From 0ec8481c10cd8277d84c7c1a785483a0a739e5a0 Mon Sep 17 00:00:00 2001 From: abranson Date: Thu, 4 Aug 2011 00:42:34 +0200 Subject: More code cleanup: Refactored Entity Proxy Subscription to handle generics better Rewrote RemoteMap to use TreeMap instead of the internal array for order. It now sorts its keys by number if they parse, else as strings. Removed a no-longer-in-progress outcome form class --- source/com/c2kernel/collection/Aggregation.java | 38 ++- .../collection/AggregationDescription.java | 28 +- .../c2kernel/collection/AggregationInstance.java | 14 +- .../com/c2kernel/collection/AggregationMember.java | 59 ++-- source/com/c2kernel/collection/Collection.java | 16 +- .../c2kernel/collection/CollectionDescription.java | 4 +- .../com/c2kernel/collection/CollectionMember.java | 10 +- .../c2kernel/collection/CollectionMemberList.java | 6 +- source/com/c2kernel/collection/Dependency.java | 63 ++-- .../com/c2kernel/collection/DependencyMember.java | 53 ++-- .../collection/Parent2ChildCollection.java | 61 ++-- .../com/c2kernel/collection/RelationshipUtils.java | 10 +- .../gui/model/AggregationVertexFactory.java | 6 +- .../gui/model/AggregationVertexOutlineCreator.java | 3 +- .../gui/view/AggregationMemberRenderer.java | 33 +- .../collection/gui/view/PropertyPanel.java | 13 +- .../collection/gui/view/SelectedMemberPanel.java | 44 ++- source/com/c2kernel/entity/C2KLocalObject.java | 8 +- source/com/c2kernel/entity/CorbaServer.java | 45 ++- source/com/c2kernel/entity/TraceableEntity.java | 86 ++--- source/com/c2kernel/entity/TraceableLocator.java | 7 +- source/com/c2kernel/entity/agent/ActiveEntity.java | 76 +++-- .../com/c2kernel/entity/agent/ActiveLocator.java | 8 +- source/com/c2kernel/entity/agent/Job.java | 17 +- source/com/c2kernel/entity/agent/JobArrayList.java | 8 +- source/com/c2kernel/entity/agent/JobList.java | 41 +-- source/com/c2kernel/entity/proxy/AgentProxy.java | 91 +++--- .../entity/proxy/DomainPathSubscriber.java | 2 +- source/com/c2kernel/entity/proxy/EntityProxy.java | 76 ++--- .../c2kernel/entity/proxy/EntityProxyManager.java | 106 +++---- .../c2kernel/entity/proxy/EntityProxyObserver.java | 6 +- source/com/c2kernel/entity/proxy/ItemProxy.java | 53 ++-- .../com/c2kernel/entity/proxy/MemberControl.java | 43 --- .../c2kernel/entity/proxy/MemberSubscription.java | 72 ++--- .../entity/proxy/ProxyClientConnection.java | 74 +++-- source/com/c2kernel/entity/proxy/ProxyMessage.java | 39 +-- .../entity/proxy/ProxyServerConnection.java | 27 +- .../com/c2kernel/entity/proxy/ProxySubscriber.java | 4 +- .../com/c2kernel/entity/transfer/TransferItem.java | 48 +-- .../com/c2kernel/entity/transfer/TransferSet.java | 40 ++- source/com/c2kernel/events/Event.java | 37 ++- source/com/c2kernel/events/History.java | 32 +- .../graph/controller/AutoScrollController.java | 6 +- .../graph/controller/DeletionController.java | 9 +- .../controller/EdgeConstructionController.java | 33 +- .../controller/MultiSelectionDragController.java | 72 +++-- .../graph/controller/StartVertexController.java | 6 +- .../controller/VertexConstructionController.java | 6 +- .../graph/layout/DefaultGraphLayoutGenerator.java | 6 +- source/com/c2kernel/graph/model/DirectedEdge.java | 2 +- source/com/c2kernel/graph/model/GraphModel.java | 60 ++-- .../c2kernel/graph/model/GraphModelManager.java | 47 +-- source/com/c2kernel/graph/model/GraphPoint.java | 4 +- source/com/c2kernel/graph/model/Graphable.java | 2 + source/com/c2kernel/graph/model/GraphableEdge.java | 2 +- .../com/c2kernel/graph/model/GraphableVertex.java | 21 +- .../graph/model/TypeNameAndConstructionInfo.java | 3 +- source/com/c2kernel/graph/model/Vertex.java | 20 +- source/com/c2kernel/graph/model/VertexFactory.java | 2 +- .../c2kernel/graph/traversal/GraphTraversal.java | 8 +- .../graph/view/DefaultDirectedEdgeRenderer.java | 6 +- .../c2kernel/graph/view/DefaultVertexRenderer.java | 3 +- source/com/c2kernel/graph/view/EditorPanel.java | 6 +- source/com/c2kernel/graph/view/EditorToolBar.java | 30 +- source/com/c2kernel/graph/view/GraphPanel.java | 16 +- source/com/c2kernel/graph/view/PropertyTable.java | 20 +- .../c2kernel/graph/view/PropertyTableModel.java | 46 +-- .../c2kernel/graph/view/SelectedVertexPanel.java | 4 +- .../c2kernel/graph/view/VertexPropertyPanel.java | 64 ++-- source/com/c2kernel/gui/Console.java | 93 +++--- source/com/c2kernel/gui/DomainKeyConsumer.java | 2 +- source/com/c2kernel/gui/DomainKeyListener.java | 2 +- source/com/c2kernel/gui/DynamicTreeBuilder.java | 41 ++- source/com/c2kernel/gui/EntityDetails.java | 41 +-- source/com/c2kernel/gui/EntityFinder.java | 52 +-- source/com/c2kernel/gui/EntityTabManager.java | 22 +- source/com/c2kernel/gui/LoginBox.java | 31 +- source/com/c2kernel/gui/Main.java | 2 +- source/com/c2kernel/gui/MainFrame.java | 43 +-- source/com/c2kernel/gui/MenuBuilder.java | 54 ++-- source/com/c2kernel/gui/TreeBrowser.java | 48 ++- source/com/c2kernel/gui/data/Node.java | 52 ++- source/com/c2kernel/gui/data/NodeAgent.java | 12 +- source/com/c2kernel/gui/data/NodeCollection.java | 18 +- source/com/c2kernel/gui/data/NodeContext.java | 16 +- source/com/c2kernel/gui/data/NodeEntity.java | 10 +- source/com/c2kernel/gui/data/NodeItem.java | 28 +- source/com/c2kernel/gui/data/NodeSubscriber.java | 2 +- .../com/c2kernel/gui/tabs/AgentPropertiesPane.java | 15 +- source/com/c2kernel/gui/tabs/CloseTabIcon.java | 3 + source/com/c2kernel/gui/tabs/CollectionPane.java | 37 ++- source/com/c2kernel/gui/tabs/DomainPathAdmin.java | 69 ++-- source/com/c2kernel/gui/tabs/EntityTabPane.java | 49 ++- source/com/c2kernel/gui/tabs/ExecutionPane.java | 47 +-- source/com/c2kernel/gui/tabs/HistoryPane.java | 73 +++-- .../gui/tabs/JTabbedPaneWithCloseIcons.java | 11 +- source/com/c2kernel/gui/tabs/JobListPane.java | 85 +++-- source/com/c2kernel/gui/tabs/PropertiesPane.java | 73 +++-- source/com/c2kernel/gui/tabs/ViewpointPane.java | 202 ++++++------ source/com/c2kernel/gui/tabs/WorkflowPane.java | 63 ++-- .../gui/tabs/collection/AggregationView.java | 7 +- .../tabs/collection/CollectionHistoryWindow.java | 44 ++- .../gui/tabs/collection/CollectionView.java | 10 +- .../gui/tabs/collection/DependencyView.java | 3 +- .../c2kernel/gui/tabs/execution/ActivityItem.java | 13 +- .../gui/tabs/execution/ActivityViewer.java | 76 ++--- .../gui/tabs/execution/DefaultExecutor.java | 8 +- .../com/c2kernel/gui/tabs/execution/Executor.java | 9 +- .../c2kernel/gui/tabs/execution/RequestButton.java | 3 +- .../gui/tabs/outcome/BasicOutcomeEditor.java | 40 ++- .../gui/tabs/outcome/form/AttributeList.java | 46 +-- .../c2kernel/gui/tabs/outcome/form/DataRecord.java | 73 +++-- .../c2kernel/gui/tabs/outcome/form/Dimension.java | 132 ++++---- .../gui/tabs/outcome/form/DimensionInstance.java | 11 +- .../gui/tabs/outcome/form/DimensionTableModel.java | 123 ++++--- .../com/c2kernel/gui/tabs/outcome/form/Field.java | 23 +- .../c2kernel/gui/tabs/outcome/form/HelpPane.java | 12 +- .../tabs/outcome/form/MultiLinePasteAdapter.java | 24 +- .../gui/tabs/outcome/form/OutcomeEditor.java | 40 +-- .../gui/tabs/outcome/form/OutcomePanel.java | 39 ++- .../gui/tabs/outcome/form/OutcomeStructure.java | 84 ++--- .../tabs/outcome/form/field/ArrayEditField.java | 41 ++- .../tabs/outcome/form/field/ArrayTableModel.java | 39 ++- .../tabs/outcome/form/field/BooleanEditField.java | 37 ++- .../gui/tabs/outcome/form/field/ComboField.java | 38 ++- .../tabs/outcome/form/field/DecimalEditField.java | 45 +-- .../tabs/outcome/form/field/FieldConstraints.java | 51 --- .../tabs/outcome/form/field/ImageEditField.java | 10 +- .../tabs/outcome/form/field/IntegerEditField.java | 39 ++- .../gui/tabs/outcome/form/field/ListOfValues.java | 6 +- .../outcome/form/field/LongStringEditField.java | 6 +- .../tabs/outcome/form/field/StringEditField.java | 62 ++-- source/com/c2kernel/lifecycle/ActivityDef.java | 18 +- source/com/c2kernel/lifecycle/ActivitySlotDef.java | 31 +- source/com/c2kernel/lifecycle/AndSplitDef.java | 7 +- .../c2kernel/lifecycle/CompositeActivityDef.java | 26 +- source/com/c2kernel/lifecycle/JoinDef.java | 5 +- source/com/c2kernel/lifecycle/LoopDef.java | 24 +- source/com/c2kernel/lifecycle/NextDef.java | 7 +- source/com/c2kernel/lifecycle/OrSplitDef.java | 1 + source/com/c2kernel/lifecycle/WfCastorHashMap.java | 2 +- source/com/c2kernel/lifecycle/WfVertexDef.java | 16 +- source/com/c2kernel/lifecycle/XOrSplitDef.java | 3 +- .../lifecycle/chooser/ActivityChooser.java | 24 +- .../lifecycle/chooser/LDAPEntryChooser.java | 17 +- .../lifecycle/chooser/LDAPFileChooser.java | 10 +- .../lifecycle/chooser/WorkflowDialogue.java | 2 +- .../lifecycle/gui/model/WfDefGraphPanel.java | 3 +- .../lifecycle/gui/model/WfEdgeDefFactory.java | 3 +- .../lifecycle/gui/model/WfVertexDefFactory.java | 5 +- .../gui/model/WfVertexDefOutlineCreator.java | 3 +- .../gui/view/ActivitySlotDefRenderer.java | 11 +- .../gui/view/CompActDefOutcomeHandler.java | 79 +++-- .../gui/view/ElemActDefOutcomeHandler.java | 53 ++-- .../lifecycle/gui/view/SplitJoinDefRenderer.java | 7 +- .../gui/view/WfDirectedEdgeDefRenderer.java | 4 +- .../lifecycle/gui/view/WfVertexDefRenderer.java | 3 +- .../com/c2kernel/lifecycle/instance/Activity.java | 36 +-- .../lifecycle/instance/AdvancementCalculator.java | 49 ++- .../com/c2kernel/lifecycle/instance/AndSplit.java | 5 +- .../lifecycle/instance/CompositeActivity.java | 77 +++-- .../c2kernel/lifecycle/instance/EventStorage.java | 6 +- .../com/c2kernel/lifecycle/instance/JobPusher.java | 9 +- source/com/c2kernel/lifecycle/instance/Join.java | 19 +- source/com/c2kernel/lifecycle/instance/Loop.java | 21 +- source/com/c2kernel/lifecycle/instance/Next.java | 3 +- .../com/c2kernel/lifecycle/instance/OrSplit.java | 10 +- .../com/c2kernel/lifecycle/instance/ParserWF.java | 21 +- source/com/c2kernel/lifecycle/instance/Split.java | 40 ++- .../com/c2kernel/lifecycle/instance/WfVertex.java | 27 +- .../com/c2kernel/lifecycle/instance/Workflow.java | 22 +- .../com/c2kernel/lifecycle/instance/XOrSplit.java | 22 +- .../instance/gui/model/WfEdgeFactory.java | 5 +- .../lifecycle/instance/gui/model/WfGraphPanel.java | 3 +- .../instance/gui/model/WfVertexFactory.java | 9 +- .../instance/gui/model/WfVertexOutlineCreator.java | 3 +- .../instance/gui/view/ActivityRenderer.java | 9 +- .../instance/gui/view/FindActDefPanel.java | 13 +- .../instance/gui/view/SplitJoinRenderer.java | 9 +- .../instance/gui/view/TransitionPanel.java | 47 +-- .../instance/gui/view/WfDirectedEdgeRenderer.java | 4 +- .../instance/gui/view/WfVertexRenderer.java | 3 +- .../instance/predefined/AddC2KObject.java | 5 +- .../instance/predefined/AddDomainPath.java | 3 +- .../predefined/AddStepsFromDescription.java | 1 + .../instance/predefined/AssignItemToSlot.java | 26 +- .../predefined/CreateItemFromDescription.java | 67 ++-- .../lifecycle/instance/predefined/Erase.java | 13 +- .../lifecycle/instance/predefined/Import.java | 21 +- .../instance/predefined/PredefinedStep.java | 25 +- .../predefined/PredefinedStepContainer.java | 10 +- .../instance/predefined/RemoveC2KObject.java | 5 +- .../instance/predefined/RemoveDomainPath.java | 3 +- .../instance/predefined/ReplaceDomainWorkflow.java | 1 + .../predefined/ServerPredefinedStepContainer.java | 5 +- .../instance/predefined/WriteProperty.java | 5 +- .../predefined/entitycreation/Aggregation.java | 10 +- .../entitycreation/AggregationMember.java | 2 +- .../predefined/entitycreation/CreateNewAgent.java | 3 +- .../predefined/entitycreation/CreateNewItem.java | 3 +- .../predefined/entitycreation/Dependency.java | 13 +- .../entitycreation/DependencyMember.java | 4 +- .../predefined/entitycreation/Geometry.java | 2 +- .../predefined/entitycreation/NewAgent.java | 19 +- .../predefined/entitycreation/NewItem.java | 47 ++- .../predefined/entitycreation/Property.java | 2 +- .../instance/stateMachine/StateMachine.java | 24 +- .../lifecycle/instance/stateMachine/States.java | 2 +- .../instance/stateMachine/Transitions.java | 4 +- .../routingHelpers/ViewpointDataHelper.java | 10 +- source/com/c2kernel/lookup/AgentPath.java | 48 +-- source/com/c2kernel/lookup/DomainPath.java | 43 +-- source/com/c2kernel/lookup/EntityPath.java | 51 +-- source/com/c2kernel/lookup/LDAPLookup.java | 119 +++---- source/com/c2kernel/lookup/LDAPLookupUtils.java | 56 ++-- source/com/c2kernel/lookup/LDAPPathSet.java | 20 +- .../com/c2kernel/lookup/LDAPPropertyManager.java | 10 +- source/com/c2kernel/lookup/LDAPRoleManager.java | 75 ++--- .../c2kernel/lookup/LegacyLDAPPropertyManager.java | 9 +- source/com/c2kernel/lookup/NextKeyManager.java | 17 +- source/com/c2kernel/lookup/Path.java | 58 ++-- source/com/c2kernel/lookup/RolePath.java | 38 ++- .../com/c2kernel/persistency/ClusterStorage.java | 46 +-- .../persistency/ClusterStorageManager.java | 111 ++++--- .../com/c2kernel/persistency/LDAPClientReader.java | 10 +- .../c2kernel/persistency/LDAPClusterStorage.java | 39 ++- source/com/c2kernel/persistency/ProxyLoader.java | 55 ++-- source/com/c2kernel/persistency/RemoteMap.java | 353 ++++++++++----------- .../c2kernel/persistency/TransactionManager.java | 111 +++---- .../c2kernel/persistency/XMLClusterStorage.java | 37 ++- .../com/c2kernel/persistency/outcome/Outcome.java | 45 +-- .../persistency/outcome/OutcomeValidator.java | 63 ++-- .../com/c2kernel/persistency/outcome/Schema.java | 2 +- .../persistency/outcome/SchemaValidator.java | 7 +- .../c2kernel/persistency/outcome/Viewpoint.java | 18 +- source/com/c2kernel/process/AbstractMain.java | 12 +- source/com/c2kernel/process/Bootstrap.java | 86 +++-- source/com/c2kernel/process/Gateway.java | 132 ++++---- source/com/c2kernel/process/ItemHTTPBridge.java | 18 +- source/com/c2kernel/process/StandardClient.java | 2 +- source/com/c2kernel/process/StandardServer.java | 39 +-- source/com/c2kernel/process/UserCodeProcess.java | 71 +++-- source/com/c2kernel/property/Property.java | 7 +- .../com/c2kernel/property/PropertyArrayList.java | 10 +- .../com/c2kernel/property/PropertyDescription.java | 12 +- .../c2kernel/property/PropertyDescriptionList.java | 21 +- source/com/c2kernel/property/PropertyUtility.java | 51 ++- source/com/c2kernel/scripting/ErrorInfo.java | 14 +- source/com/c2kernel/scripting/Parameter.java | 24 +- source/com/c2kernel/scripting/Script.java | 82 +++-- source/com/c2kernel/scripting/ScriptConsole.java | 29 +- .../scripting/ScriptingEngineException.java | 2 +- source/com/c2kernel/utils/ActDefCache.java | 33 +- source/com/c2kernel/utils/CastorArrayList.java | 8 +- source/com/c2kernel/utils/CastorXMLUtility.java | 10 +- source/com/c2kernel/utils/DateUtility.java | 6 +- source/com/c2kernel/utils/Dom4JElementParser.java | 10 +- source/com/c2kernel/utils/FileStringUtility.java | 32 +- .../com/c2kernel/utils/GTimeStampComparator.java | 9 +- source/com/c2kernel/utils/KeyValuePair.java | 24 +- source/com/c2kernel/utils/Language.java | 18 +- source/com/c2kernel/utils/LocalObjectLoader.java | 16 +- source/com/c2kernel/utils/Logger.java | 35 +- source/com/c2kernel/utils/Resource.java | 24 +- source/com/c2kernel/utils/SoftCache.java | 40 ++- source/com/c2kernel/utils/TransientCache.java | 66 ++-- source/com/c2kernel/utils/XmlElementParser.java | 32 +- .../c2kernel/utils/server/HTTPRequestHandler.java | 55 ++-- .../c2kernel/utils/server/SimpleTCPIPServer.java | 25 +- .../com/c2kernel/utils/server/SocketHandler.java | 10 +- source/com/c2kernel/utils/server/UDPListener.java | 15 +- 271 files changed, 4442 insertions(+), 3751 deletions(-) mode change 100755 => 100644 source/com/c2kernel/collection/Aggregation.java mode change 100755 => 100644 source/com/c2kernel/collection/AggregationDescription.java mode change 100755 => 100644 source/com/c2kernel/collection/AggregationInstance.java mode change 100755 => 100644 source/com/c2kernel/collection/AggregationMember.java mode change 100755 => 100644 source/com/c2kernel/collection/Collection.java mode change 100755 => 100644 source/com/c2kernel/collection/CollectionDescription.java mode change 100755 => 100644 source/com/c2kernel/collection/CollectionMember.java mode change 100755 => 100644 source/com/c2kernel/collection/Dependency.java mode change 100755 => 100644 source/com/c2kernel/collection/DependencyMember.java mode change 100755 => 100644 source/com/c2kernel/collection/Parent2ChildCollection.java mode change 100755 => 100644 source/com/c2kernel/collection/RelationshipUtils.java mode change 100755 => 100644 source/com/c2kernel/collection/gui/model/AggregationVertexFactory.java mode change 100755 => 100644 source/com/c2kernel/collection/gui/model/AggregationVertexOutlineCreator.java mode change 100755 => 100644 source/com/c2kernel/collection/gui/view/AggregationMemberRenderer.java mode change 100755 => 100644 source/com/c2kernel/collection/gui/view/PropertyPanel.java mode change 100755 => 100644 source/com/c2kernel/collection/gui/view/SelectedMemberPanel.java mode change 100755 => 100644 source/com/c2kernel/entity/C2KLocalObject.java mode change 100755 => 100644 source/com/c2kernel/entity/TraceableEntity.java mode change 100755 => 100644 source/com/c2kernel/entity/TraceableLocator.java mode change 100755 => 100644 source/com/c2kernel/entity/agent/ActiveEntity.java mode change 100755 => 100644 source/com/c2kernel/entity/agent/ActiveLocator.java mode change 100755 => 100644 source/com/c2kernel/entity/agent/Job.java mode change 100755 => 100644 source/com/c2kernel/entity/proxy/AgentProxy.java mode change 100755 => 100644 source/com/c2kernel/entity/proxy/DomainPathSubscriber.java mode change 100755 => 100644 source/com/c2kernel/entity/proxy/EntityProxyObserver.java delete mode 100755 source/com/c2kernel/entity/proxy/MemberControl.java mode change 100755 => 100644 source/com/c2kernel/entity/proxy/ProxyMessage.java mode change 100755 => 100644 source/com/c2kernel/entity/proxy/ProxyServerConnection.java mode change 100755 => 100644 source/com/c2kernel/entity/proxy/ProxySubscriber.java mode change 100755 => 100644 source/com/c2kernel/events/Event.java mode change 100755 => 100644 source/com/c2kernel/events/History.java mode change 100755 => 100644 source/com/c2kernel/graph/controller/AutoScrollController.java mode change 100755 => 100644 source/com/c2kernel/graph/controller/DeletionController.java mode change 100755 => 100644 source/com/c2kernel/graph/controller/EdgeConstructionController.java mode change 100755 => 100644 source/com/c2kernel/graph/controller/MultiSelectionDragController.java mode change 100755 => 100644 source/com/c2kernel/graph/controller/StartVertexController.java mode change 100755 => 100644 source/com/c2kernel/graph/controller/VertexConstructionController.java mode change 100755 => 100644 source/com/c2kernel/graph/model/DirectedEdge.java mode change 100755 => 100644 source/com/c2kernel/graph/model/GraphPoint.java mode change 100755 => 100644 source/com/c2kernel/graph/model/Graphable.java mode change 100755 => 100644 source/com/c2kernel/graph/model/GraphableEdge.java mode change 100755 => 100644 source/com/c2kernel/graph/model/TypeNameAndConstructionInfo.java mode change 100755 => 100644 source/com/c2kernel/graph/model/VertexFactory.java mode change 100755 => 100644 source/com/c2kernel/graph/view/DefaultDirectedEdgeRenderer.java mode change 100755 => 100644 source/com/c2kernel/graph/view/DefaultVertexRenderer.java mode change 100755 => 100644 source/com/c2kernel/graph/view/EditorPanel.java mode change 100755 => 100644 source/com/c2kernel/graph/view/GraphPanel.java mode change 100755 => 100644 source/com/c2kernel/graph/view/PropertyTable.java mode change 100755 => 100644 source/com/c2kernel/graph/view/SelectedVertexPanel.java mode change 100755 => 100644 source/com/c2kernel/gui/Console.java mode change 100755 => 100644 source/com/c2kernel/gui/DomainKeyConsumer.java mode change 100755 => 100644 source/com/c2kernel/gui/DomainKeyListener.java mode change 100755 => 100644 source/com/c2kernel/gui/DynamicTreeBuilder.java mode change 100755 => 100644 source/com/c2kernel/gui/EntityFinder.java mode change 100755 => 100644 source/com/c2kernel/gui/LoginBox.java mode change 100755 => 100644 source/com/c2kernel/gui/Main.java mode change 100755 => 100644 source/com/c2kernel/gui/TreeBrowser.java mode change 100755 => 100644 source/com/c2kernel/gui/data/NodeCollection.java mode change 100755 => 100644 source/com/c2kernel/gui/data/NodeContext.java mode change 100755 => 100644 source/com/c2kernel/gui/data/NodeSubscriber.java mode change 100755 => 100644 source/com/c2kernel/gui/tabs/AgentPropertiesPane.java mode change 100755 => 100644 source/com/c2kernel/gui/tabs/CloseTabIcon.java mode change 100755 => 100644 source/com/c2kernel/gui/tabs/CollectionPane.java mode change 100755 => 100644 source/com/c2kernel/gui/tabs/EntityTabPane.java mode change 100755 => 100644 source/com/c2kernel/gui/tabs/WorkflowPane.java mode change 100755 => 100644 source/com/c2kernel/gui/tabs/collection/AggregationView.java mode change 100755 => 100644 source/com/c2kernel/gui/tabs/collection/CollectionView.java mode change 100755 => 100644 source/com/c2kernel/gui/tabs/collection/DependencyView.java mode change 100755 => 100644 source/com/c2kernel/gui/tabs/execution/DefaultExecutor.java mode change 100755 => 100644 source/com/c2kernel/gui/tabs/execution/Executor.java mode change 100755 => 100644 source/com/c2kernel/gui/tabs/execution/RequestButton.java mode change 100755 => 100644 source/com/c2kernel/gui/tabs/outcome/BasicOutcomeEditor.java mode change 100755 => 100644 source/com/c2kernel/gui/tabs/outcome/form/DataRecord.java mode change 100755 => 100644 source/com/c2kernel/gui/tabs/outcome/form/DimensionInstance.java mode change 100755 => 100644 source/com/c2kernel/gui/tabs/outcome/form/Field.java mode change 100755 => 100644 source/com/c2kernel/gui/tabs/outcome/form/HelpPane.java mode change 100755 => 100644 source/com/c2kernel/gui/tabs/outcome/form/MultiLinePasteAdapter.java mode change 100755 => 100644 source/com/c2kernel/gui/tabs/outcome/form/OutcomeEditor.java mode change 100755 => 100644 source/com/c2kernel/gui/tabs/outcome/form/OutcomePanel.java mode change 100755 => 100644 source/com/c2kernel/gui/tabs/outcome/form/field/ArrayEditField.java mode change 100755 => 100644 source/com/c2kernel/gui/tabs/outcome/form/field/BooleanEditField.java mode change 100755 => 100644 source/com/c2kernel/gui/tabs/outcome/form/field/DecimalEditField.java delete mode 100755 source/com/c2kernel/gui/tabs/outcome/form/field/FieldConstraints.java mode change 100755 => 100644 source/com/c2kernel/gui/tabs/outcome/form/field/ImageEditField.java mode change 100755 => 100644 source/com/c2kernel/gui/tabs/outcome/form/field/IntegerEditField.java mode change 100755 => 100644 source/com/c2kernel/gui/tabs/outcome/form/field/LongStringEditField.java mode change 100755 => 100644 source/com/c2kernel/gui/tabs/outcome/form/field/StringEditField.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/ActivitySlotDef.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/CompositeActivityDef.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/JoinDef.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/LoopDef.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/NextDef.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/OrSplitDef.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/WfCastorHashMap.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/XOrSplitDef.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/chooser/ActivityChooser.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/chooser/LDAPFileChooser.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/chooser/WorkflowDialogue.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/gui/model/WfDefGraphPanel.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/gui/model/WfEdgeDefFactory.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/gui/model/WfVertexDefOutlineCreator.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/gui/view/ActivitySlotDefRenderer.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/gui/view/CompActDefOutcomeHandler.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/gui/view/ElemActDefOutcomeHandler.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/gui/view/SplitJoinDefRenderer.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/gui/view/WfDirectedEdgeDefRenderer.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/gui/view/WfVertexDefRenderer.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/instance/AndSplit.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/instance/EventStorage.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/instance/JobPusher.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/instance/Loop.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/instance/Next.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/instance/OrSplit.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/instance/WfVertex.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/instance/gui/model/WfEdgeFactory.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/instance/gui/model/WfGraphPanel.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/instance/gui/model/WfVertexOutlineCreator.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/instance/gui/view/ActivityRenderer.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/instance/gui/view/FindActDefPanel.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/instance/gui/view/SplitJoinRenderer.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/instance/gui/view/WfDirectedEdgeRenderer.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/instance/gui/view/WfVertexRenderer.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/instance/predefined/AddC2KObject.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/instance/predefined/AddDomainPath.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/instance/predefined/AddStepsFromDescription.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/instance/predefined/AssignItemToSlot.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/instance/predefined/Erase.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/instance/predefined/Import.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/instance/predefined/PredefinedStep.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/instance/predefined/PredefinedStepContainer.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/instance/predefined/RemoveC2KObject.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/instance/predefined/RemoveDomainPath.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/instance/predefined/ReplaceDomainWorkflow.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/instance/predefined/ServerPredefinedStepContainer.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/instance/predefined/WriteProperty.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/instance/predefined/entitycreation/AggregationMember.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/instance/predefined/entitycreation/CreateNewAgent.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/instance/predefined/entitycreation/CreateNewItem.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/instance/predefined/entitycreation/Dependency.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/instance/predefined/entitycreation/DependencyMember.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/instance/predefined/entitycreation/Geometry.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewAgent.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/instance/predefined/entitycreation/Property.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/instance/stateMachine/StateMachine.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/instance/stateMachine/States.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/instance/stateMachine/Transitions.java mode change 100755 => 100644 source/com/c2kernel/lifecycle/routingHelpers/ViewpointDataHelper.java mode change 100755 => 100644 source/com/c2kernel/lookup/AgentPath.java mode change 100755 => 100644 source/com/c2kernel/lookup/DomainPath.java mode change 100755 => 100644 source/com/c2kernel/lookup/LDAPLookup.java mode change 100755 => 100644 source/com/c2kernel/lookup/LDAPLookupUtils.java mode change 100755 => 100644 source/com/c2kernel/lookup/LDAPPathSet.java mode change 100755 => 100644 source/com/c2kernel/lookup/LegacyLDAPPropertyManager.java mode change 100755 => 100644 source/com/c2kernel/lookup/NextKeyManager.java mode change 100755 => 100644 source/com/c2kernel/persistency/ClusterStorage.java mode change 100755 => 100644 source/com/c2kernel/persistency/LDAPClientReader.java mode change 100755 => 100644 source/com/c2kernel/persistency/RemoteMap.java mode change 100755 => 100644 source/com/c2kernel/persistency/outcome/Outcome.java mode change 100755 => 100644 source/com/c2kernel/persistency/outcome/OutcomeValidator.java mode change 100755 => 100644 source/com/c2kernel/persistency/outcome/Schema.java mode change 100755 => 100644 source/com/c2kernel/persistency/outcome/SchemaValidator.java mode change 100755 => 100644 source/com/c2kernel/persistency/outcome/Viewpoint.java mode change 100755 => 100644 source/com/c2kernel/process/AbstractMain.java mode change 100755 => 100644 source/com/c2kernel/process/ItemHTTPBridge.java mode change 100755 => 100644 source/com/c2kernel/process/StandardServer.java mode change 100755 => 100644 source/com/c2kernel/property/Property.java mode change 100755 => 100644 source/com/c2kernel/property/PropertyDescription.java mode change 100755 => 100644 source/com/c2kernel/property/PropertyUtility.java mode change 100755 => 100644 source/com/c2kernel/scripting/Parameter.java mode change 100755 => 100644 source/com/c2kernel/scripting/ScriptingEngineException.java mode change 100755 => 100644 source/com/c2kernel/utils/DateUtility.java mode change 100755 => 100644 source/com/c2kernel/utils/Dom4JElementParser.java mode change 100755 => 100644 source/com/c2kernel/utils/GTimeStampComparator.java mode change 100755 => 100644 source/com/c2kernel/utils/KeyValuePair.java mode change 100755 => 100644 source/com/c2kernel/utils/LocalObjectLoader.java mode change 100755 => 100644 source/com/c2kernel/utils/server/SocketHandler.java mode change 100755 => 100644 source/com/c2kernel/utils/server/UDPListener.java (limited to 'source/com/c2kernel') diff --git a/source/com/c2kernel/collection/Aggregation.java b/source/com/c2kernel/collection/Aggregation.java old mode 100755 new mode 100644 index 72b8005..29cb067 --- a/source/com/c2kernel/collection/Aggregation.java +++ b/source/com/c2kernel/collection/Aggregation.java @@ -1,29 +1,31 @@ package com.c2kernel.collection; -import java.util.Iterator; import com.c2kernel.collection.gui.model.AggregationVertexOutlineCreator; -import com.c2kernel.graph.model.*; -import com.c2kernel.utils.*; +import com.c2kernel.graph.model.GraphModel; +import com.c2kernel.graph.model.GraphPoint; +import com.c2kernel.graph.model.TypeNameAndConstructionInfo; +import com.c2kernel.utils.CastorHashMap; +import com.c2kernel.utils.Language; +import com.c2kernel.utils.Logger; /** * @version $Revision: 1.59 $ $Date: 2004/08/10 07:56:08 $ * @author $Author: abranson $ */ -abstract public class Aggregation extends Parent2ChildCollection +abstract public class Aggregation extends Parent2ChildCollection { protected GraphModel mLayout = new GraphModel(new AggregationVertexOutlineCreator()); private final TypeNameAndConstructionInfo[] mVertexTypeNameAndConstructionInfo = { - new TypeNameAndConstructionInfo(Language.translate("Slot"), "AggregationMember") + new TypeNameAndConstructionInfo(Language.translate("Slot"), "AggregationMember") }; public Aggregation() { setName("Aggregation"); - mMembers = new CollectionMemberList(); } @@ -46,22 +48,22 @@ abstract public class Aggregation extends Parent2ChildCollection { for (int i=0; i { public AggregationDescription() { setName("AggregationDescription"); - mMembers = new CollectionMemberList(); } public AggregationDescription(String name) { setName(name); - mMembers = new CollectionMemberList(); } - - public Collection newInstance() + + @Override + public Aggregation newInstance() { AggregationInstance newInstance = new AggregationInstance(getName()); newInstance.setURLInfo(getURLInfo()); //for each desc member for (int i=0; i -1) { if (mClassProps == null || getProperties() == null) throw new MembershipException("ClassProps not yet set. Cannot check membership validity."); - + //for each mandatory prop check if its in the member property and has the matching value StringTokenizer sub = new StringTokenizer(mClassProps, ","); while (sub.hasMoreTokens()) { - String aClassProp = sub.nextToken(); - try { - String memberValue = (String)getProperties().get(aClassProp); - Property entityProperty = (Property)Gateway.getStorage().get(entityKey, ClusterStorage.PROPERTY+"/"+aClassProp, null); + String aClassProp = sub.nextToken(); + try { + String memberValue = (String)getProperties().get(aClassProp); + Property entityProperty = (Property)Gateway.getStorage().get(entityKey, ClusterStorage.PROPERTY+"/"+aClassProp, null); if (entityProperty == null) throw new MembershipException("Property "+aClassProp+ " does not exist for entityKey=" + entityKey ); if (entityProperty.getValue() == null || !entityProperty.getValue().equalsIgnoreCase(memberValue)) @@ -96,25 +101,27 @@ public class AggregationMember extends GraphableVertex implements CollectionMemb catch (MembershipException ex) { throw ex; } - catch (Exception ex) + catch (Exception ex) { Logger.error(ex); throw new MembershipException("Error checking properties"); } - } + } } - + mEntityKey = entityKey; mEntity = null; entityName = null; } - - public void clearEntity() { + + @Override + public void clearEntity() { mEntityKey = -1; mEntity = null; } - - public EntityProxy resolveEntity() throws ObjectNotFoundException { + + @Override + public EntityProxy resolveEntity() throws ObjectNotFoundException { if (mEntity == null) { try { EntityPath path = new EntityPath(mEntityKey); @@ -124,9 +131,9 @@ public class AggregationMember extends GraphableVertex implements CollectionMemb } } return mEntity; - + } - + public Image getImage() { if (image == null) { image = Resource.getImageResource("typeicons/"+getProperties().get("Type")+"_16.png").getImage(); @@ -147,7 +154,7 @@ public class AggregationMember extends GraphableVertex implements CollectionMemb else entityName = "Empty"; } - + return entityName; } diff --git a/source/com/c2kernel/collection/Collection.java b/source/com/c2kernel/collection/Collection.java old mode 100755 new mode 100644 index 745309c..f052ce9 --- a/source/com/c2kernel/collection/Collection.java +++ b/source/com/c2kernel/collection/Collection.java @@ -7,26 +7,26 @@ import com.c2kernel.utils.CastorHashMap; * @version $Revision: 1.13 $ $Date: 2004/05/14 15:39:39 $ * @author $Author: abranson $ */ -public interface Collection extends C2KLocalObject +public interface Collection extends C2KLocalObject { public static final short EMPTY = -1; - + public int getCounter(); public void setCounter(int count); public int size(); - public void setMembers(CollectionMemberList newMembers); + public void setMembers(CollectionMemberList newMembers); - public CollectionMemberList getMembers(); + public CollectionMemberList getMembers(); public void addMember(int entityKey, CastorHashMap props, String classProps) throws MembershipException; - + public void addMember(int entityKey) throws MembershipException; - + public void removeMember(int memberId) throws MembershipException; - + public CollectionMember getMember(int memberId) throws ObjectNotFoundException; - + } diff --git a/source/com/c2kernel/collection/CollectionDescription.java b/source/com/c2kernel/collection/CollectionDescription.java old mode 100755 new mode 100644 index 01318ed..69b569e --- a/source/com/c2kernel/collection/CollectionDescription.java +++ b/source/com/c2kernel/collection/CollectionDescription.java @@ -9,6 +9,6 @@ package com.c2kernel.collection; * All rights reserved. **************************************************************************/ -public interface CollectionDescription extends Collection { - public Collection newInstance(); +public interface CollectionDescription extends Collection { + public Collection newInstance(); } diff --git a/source/com/c2kernel/collection/CollectionMember.java b/source/com/c2kernel/collection/CollectionMember.java old mode 100755 new mode 100644 index 18b5d55..0b21e30 --- a/source/com/c2kernel/collection/CollectionMember.java +++ b/source/com/c2kernel/collection/CollectionMember.java @@ -10,7 +10,7 @@ import com.c2kernel.utils.CastorHashMap; * CollectionMember interface is the superclass of all members * This should be temporary - if we manage to rip GraphableVertex from Vertex, * then that should be the superclass. - * + * * $Revision: 1.19 $ * $Date: 2004/01/22 11:24:44 $ * @@ -22,17 +22,17 @@ public interface CollectionMember extends Serializable { public void setEntityKey(int entityKey) throws MembershipException; public int getEntityKey(); - + public void assignEntity(int entityKey) throws MembershipException; public void clearEntity(); public EntityProxy resolveEntity() throws ObjectNotFoundException; - + public void setID(int Id); public int getID(); - + public void setProperties(CastorHashMap props); public CastorHashMap getProperties(); public void setClassProps(String classProps); - public String getClassProps(); + public String getClassProps(); } diff --git a/source/com/c2kernel/collection/CollectionMemberList.java b/source/com/c2kernel/collection/CollectionMemberList.java index 3f9345e..0a4bb25 100644 --- a/source/com/c2kernel/collection/CollectionMemberList.java +++ b/source/com/c2kernel/collection/CollectionMemberList.java @@ -11,12 +11,12 @@ package com.c2kernel.collection; import com.c2kernel.utils.CastorArrayList; -public class CollectionMemberList extends CastorArrayList +public class CollectionMemberList extends CastorArrayList { public CollectionMemberList() - { + { super(); } - + } diff --git a/source/com/c2kernel/collection/Dependency.java b/source/com/c2kernel/collection/Dependency.java old mode 100755 new mode 100644 index 1b74d42..9351731 --- a/source/com/c2kernel/collection/Dependency.java +++ b/source/com/c2kernel/collection/Dependency.java @@ -1,8 +1,9 @@ package com.c2kernel.collection; -import java.util.Iterator; -import com.c2kernel.utils.*; +import com.c2kernel.utils.CastorHashMap; +import com.c2kernel.utils.KeyValuePair; +import com.c2kernel.utils.Logger; /* Dependency Object @@ -14,32 +15,30 @@ e.g.: Used for ProductDesc::Item-dependency-dependencymember-WfDesc::Item * @version $Revision: 1.15 $ $Date: 2005/04/07 08:03:21 $ * @author $Author: abranson $ */ -public class Dependency extends Parent2ChildCollection +public class Dependency extends Parent2ChildCollection { protected CastorHashMap mProperties = new CastorHashMap(); protected String mClassProps = ""; - + public Dependency() { setName("Dependency"); - mMembers = new CollectionMemberList(); } public Dependency(String name) { setName(name); - mMembers = new CollectionMemberList(); } - + public CastorHashMap getProperties() { return mProperties; } - + public void setProperties(CastorHashMap props) { mProperties = props; } - + public KeyValuePair[] getKeyValuePairs() { return mProperties.getKeyValuePairs(); @@ -48,67 +47,69 @@ public class Dependency extends Parent2ChildCollection { mProperties.setKeyValuePairs(pairs); } - + public void setClassProps(String classProps) { this.mClassProps = classProps; } - + public String getClassProps() { return mClassProps; } - public void addMember(int entityKey) throws MembershipException { + @Override + public void addMember(int entityKey) throws MembershipException { // create member object DependencyMember depMember = new DependencyMember(); depMember.setID(getCounter()); depMember.setProperties(mProperties); depMember.setClassProps(mClassProps); - + // assign entity depMember.assignEntity(entityKey); mMembers.list.add(depMember); - Logger.msg(8, "Dependency::addMember(" + entityKey + ") added to children."); + Logger.msg(8, "Dependency::addMember(" + entityKey + ") added to children."); } - public void addMember(int entityKey, CastorHashMap props, String classProps) + @Override + public void addMember(int entityKey, CastorHashMap props, String classProps) throws MembershipException { if (classProps != null && !classProps.equals(mClassProps)) throw new MembershipException("Cannot change classProps in dependency member"); DependencyMember depMember = new DependencyMember(); depMember.setID(getCounter()); - + // merge props CastorHashMap newProps = new CastorHashMap(); - for (Iterator iter = props.keySet().iterator(); iter.hasNext();) { - String key = (String)iter.next(); - newProps.put(key, props.get(key)); - + for (Object name : props.keySet()) { + String key = (String)name; + newProps.put(key, props.get(key)); + } // class props override local - for (Iterator iter = mProperties.keySet().iterator(); iter.hasNext();) { - String key = (String)iter.next(); - newProps.put(key, mProperties.get(key)); - + for (Object name : mProperties.keySet()) { + String key = (String)name; + newProps.put(key, mProperties.get(key)); + } depMember.setProperties(newProps); depMember.setClassProps(mClassProps); - + // assign entity depMember.assignEntity(entityKey); mMembers.list.add(depMember); - Logger.msg(8, "Dependency::addMember(" + entityKey + ") added to children."); + Logger.msg(8, "Dependency::addMember(" + entityKey + ") added to children."); } - - public void removeMember(int memberId) throws MembershipException { - for (Iterator iter = mMembers.list.iterator(); iter.hasNext();) { - DependencyMember element = (DependencyMember)iter.next(); + + @Override + public void removeMember(int memberId) throws MembershipException { + for (DependencyMember element : mMembers.list) { if (element.getID() == memberId) { mMembers.list.remove(element); return; } } - throw new MembershipException("Member "+memberId+" not found"); + throw new MembershipException("Member "+memberId+" not found"); } } diff --git a/source/com/c2kernel/collection/DependencyMember.java b/source/com/c2kernel/collection/DependencyMember.java old mode 100755 new mode 100644 index bb28c91..4ca2090 --- a/source/com/c2kernel/collection/DependencyMember.java +++ b/source/com/c2kernel/collection/DependencyMember.java @@ -24,7 +24,7 @@ public class DependencyMember implements CollectionMember { private int mEntityKey = -1; - private EntityProxy mEntity = null; + private EntityProxy mEntity = null; private int mId = -1; private CastorHashMap mProperties = null; private String mClassProps; @@ -40,27 +40,31 @@ public class DependencyMember implements CollectionMember } - public void setEntityKey(int entityKey) + @Override + public void setEntityKey(int entityKey) { mEntityKey = entityKey; - mEntity = null; + mEntity = null; } - public int getEntityKey() + @Override + public int getEntityKey() { return mEntityKey; } + @Override public void setProperties(CastorHashMap props) { mProperties = props; } + @Override public CastorHashMap getProperties() { return mProperties; } - + public KeyValuePair[] getKeyValuePairs() { return mProperties.getKeyValuePairs(); @@ -70,61 +74,68 @@ public class DependencyMember implements CollectionMember mProperties.setKeyValuePairs(pairs); } + @Override public int getID() { return mId; } + @Override public void setID(int id) { mId = id; } - public void setClassProps(String props) + @Override + public void setClassProps(String props) { mClassProps = props; } - public String getClassProps() + @Override + public String getClassProps() { return mClassProps; } - public void assignEntity(int entityKey) throws MembershipException + @Override + public void assignEntity(int entityKey) throws MembershipException { if (entityKey > -1) { if (mClassProps == null || getProperties() == null) throw new MembershipException("ClassProps not yet set. Cannot check membership validity."); - + //for each mandatory prop check if its in the member property and has the matching value StringTokenizer sub = new StringTokenizer(mClassProps, ","); while (sub.hasMoreTokens()) { - String aClassProp = sub.nextToken(); - try { - String memberValue = (String)getProperties().get(aClassProp); - Property entityProperty = (Property)Gateway.getStorage().get(entityKey, ClusterStorage.PROPERTY+"/"+aClassProp, null); + String aClassProp = sub.nextToken(); + try { + String memberValue = (String)getProperties().get(aClassProp); + Property entityProperty = (Property)Gateway.getStorage().get(entityKey, ClusterStorage.PROPERTY+"/"+aClassProp, null); if (entityProperty == null) throw new MembershipException("Property "+aClassProp+ " does not exist for entityKey=" + entityKey ); if (!entityProperty.getValue().equalsIgnoreCase(memberValue)) throw new MembershipException("DependencyMember::checkProperty() Values of mandatory prop "+aClassProp+" do not match " + entityProperty.getValue()+"!="+memberValue); } - catch (Exception ex) + catch (Exception ex) { Logger.error(ex); throw new MembershipException("Error checking properties"); } - } + } } - + mEntityKey = entityKey; mEntity = null; } - - public void clearEntity() { + + @Override + public void clearEntity() { mEntityKey = -1; mEntity = null; } - - public EntityProxy resolveEntity() throws ObjectNotFoundException { + + @Override + public EntityProxy resolveEntity() throws ObjectNotFoundException { if (mEntity == null) { try { EntityPath path = new EntityPath(mEntityKey); @@ -134,7 +145,7 @@ public class DependencyMember implements CollectionMember } } return mEntity; - + } diff --git a/source/com/c2kernel/collection/Parent2ChildCollection.java b/source/com/c2kernel/collection/Parent2ChildCollection.java old mode 100755 new mode 100644 index 0160444..09e9f07 --- a/source/com/c2kernel/collection/Parent2ChildCollection.java +++ b/source/com/c2kernel/collection/Parent2ChildCollection.java @@ -1,5 +1,4 @@ package com.c2kernel.collection; -import java.util.Iterator; import com.c2kernel.common.ObjectNotFoundException; import com.c2kernel.persistency.ClusterStorage; @@ -9,33 +8,36 @@ import com.c2kernel.utils.CastorHashMap; * @version $Revision: 1.23 $ $Date: 2004/05/14 15:39:39 $ * @author $Author: abranson $ */ -abstract public class Parent2ChildCollection implements Collection +abstract public class Parent2ChildCollection implements Collection { private int mCounter = -1; // Contains next available Member ID - protected CollectionMemberList mMembers = new CollectionMemberList(); + protected CollectionMemberList mMembers = new CollectionMemberList(); protected int mID = -1; protected String mName = ""; // Not checked for uniqueness protected String mURLInfo = ""; - - public int getCounter() + + @Override + public int getCounter() { if (mCounter == -1) - for (Iterator iter = mMembers.list.iterator(); iter.hasNext();) { - CollectionMember element = (CollectionMember)iter.next(); + for (Object name : mMembers.list) { + CollectionMember element = (CollectionMember)name; if (mCounter < element.getID()) mCounter = element.getID(); } return ++mCounter; } - public void setCounter(int count) + @Override + public void setCounter(int count) { mCounter = count; } - public int size() + @Override + public int size() { return mMembers.list.size(); } @@ -50,7 +52,8 @@ abstract public class Parent2ChildCollection implements Collection return mID; } - public void setName(String name) + @Override + public void setName(String name) { mName = name; } @@ -60,12 +63,14 @@ abstract public class Parent2ChildCollection implements Collection mURLInfo = urlInfo; } - public String getName() + @Override + public String getName() { return mName; } - - public String getClusterType() + + @Override + public String getClusterType() { return ClusterStorage.COLLECTION; } @@ -75,45 +80,49 @@ abstract public class Parent2ChildCollection implements Collection return mURLInfo; } - public void setMembers(CollectionMemberList newMembers) + @Override + public void setMembers(CollectionMemberList newMembers) { mMembers = newMembers; } - + public boolean contains(int entityKey) { - for (Iterator iter = mMembers.list.iterator(); iter.hasNext();) { - CollectionMember element = (CollectionMember)iter.next(); + for (Object name : mMembers.list) { + CollectionMember element = (CollectionMember)name; if (element.getEntityKey() == entityKey) return true; } return false; } - + public boolean isFull() { for (int i=0; i getMembers() { return mMembers; } - public abstract void addMember(int entityKey, CastorHashMap props, String classProps) throws MembershipException; + @Override + public abstract void addMember(int entityKey, CastorHashMap props, String classProps) throws MembershipException; } diff --git a/source/com/c2kernel/collection/RelationshipUtils.java b/source/com/c2kernel/collection/RelationshipUtils.java old mode 100755 new mode 100644 index fdd7e6b..6e35ac8 --- a/source/com/c2kernel/collection/RelationshipUtils.java +++ b/source/com/c2kernel/collection/RelationshipUtils.java @@ -19,14 +19,14 @@ public class RelationshipUtils if (entityKey == -1) return false; try { - if ( ((Aggregation) Gateway.getProxyManager().getProxy(new EntityPath(entityKey)).getObject(ClusterStorage.COLLECTION+"/Composition" )).size() > 0 ) - return true; + if ( ((Aggregation) Gateway.getProxyManager().getProxy(new EntityPath(entityKey)).getObject(ClusterStorage.COLLECTION+"/Composition" )).size() > 0 ) + return true; } - catch (Exception ex) + catch (Exception ex) { //do nothing - member has no composition, thus elementary - } - + } + return false; } diff --git a/source/com/c2kernel/collection/gui/model/AggregationVertexFactory.java b/source/com/c2kernel/collection/gui/model/AggregationVertexFactory.java old mode 100755 new mode 100644 index d99ef3c..cd4963f --- a/source/com/c2kernel/collection/gui/model/AggregationVertexFactory.java +++ b/source/com/c2kernel/collection/gui/model/AggregationVertexFactory.java @@ -17,14 +17,16 @@ public class AggregationVertexFactory implements VertexFactory private Aggregation mAggregation = null; - public void setCreationContext(Object aggregation) + @Override + public void setCreationContext(Object aggregation) { if (aggregation != null && aggregation instanceof Aggregation) mAggregation = (Aggregation)aggregation; } - public void create + @Override + public void create ( GraphModelManager graphModelManager, Point location, diff --git a/source/com/c2kernel/collection/gui/model/AggregationVertexOutlineCreator.java b/source/com/c2kernel/collection/gui/model/AggregationVertexOutlineCreator.java old mode 100755 new mode 100644 index ed19f9c..b28af2e --- a/source/com/c2kernel/collection/gui/model/AggregationVertexOutlineCreator.java +++ b/source/com/c2kernel/collection/gui/model/AggregationVertexOutlineCreator.java @@ -7,7 +7,8 @@ import com.c2kernel.graph.model.VertexOutlineCreator; public class AggregationVertexOutlineCreator implements VertexOutlineCreator { - public void setOutline(Vertex vertex) + @Override + public void setOutline(Vertex vertex) { GraphPoint centre = vertex.getCentrePoint(); int height = vertex.getHeight(); diff --git a/source/com/c2kernel/collection/gui/view/AggregationMemberRenderer.java b/source/com/c2kernel/collection/gui/view/AggregationMemberRenderer.java old mode 100755 new mode 100644 index 0d3cb03..6d41d20 --- a/source/com/c2kernel/collection/gui/view/AggregationMemberRenderer.java +++ b/source/com/c2kernel/collection/gui/view/AggregationMemberRenderer.java @@ -19,31 +19,32 @@ public class AggregationMemberRenderer implements VertexRenderer { private Aggregation mAggregation = null; - + public AggregationMemberRenderer() { } - + public void setAggregation(Aggregation agg) { mAggregation = agg; - } - - - public void draw(Graphics2D g2d, Vertex vertex) + } + + + @Override + public void draw(Graphics2D g2d, Vertex vertex) { GraphPoint centre = vertex.getCentrePoint(); GraphPoint[] outline = vertex.getOutlinePoints(); FontMetrics metrics = g2d.getFontMetrics(); - + AggregationMember memberPair = mAggregation.getMemberPair(vertex.getID()); try - { - String name = memberPair.getEntityName(); + { + String name = memberPair.getEntityName(); - g2d.drawString( name, - centre.x-metrics.stringWidth(name)/2, + g2d.drawString( name, + centre.x-metrics.stringWidth(name)/2, topYOfOutline(outline) ); g2d.drawImage @@ -54,8 +55,8 @@ public class AggregationMemberRenderer implements VertexRenderer null ); - - + + // Draw the outline of the vertex if(outline.length > 1) { @@ -69,7 +70,7 @@ public class AggregationMemberRenderer implements VertexRenderer outline[i+1].y ); } - + g2d.drawLine ( outline[outline.length-1].x, @@ -84,7 +85,7 @@ public class AggregationMemberRenderer implements VertexRenderer catch (Exception ex) { Logger.error("AggregationMemberRenderer::draw() " + ex); - } + } } @@ -104,7 +105,7 @@ public class AggregationMemberRenderer implements VertexRenderer return topY; } - + int bottomYOfOutline(GraphPoint[] outline) { int bottomY = outline[0].y; diff --git a/source/com/c2kernel/collection/gui/view/PropertyPanel.java b/source/com/c2kernel/collection/gui/view/PropertyPanel.java old mode 100755 new mode 100644 index 903ddf9..f566d70 --- a/source/com/c2kernel/collection/gui/view/PropertyPanel.java +++ b/source/com/c2kernel/collection/gui/view/PropertyPanel.java @@ -1,7 +1,7 @@ package com.c2kernel.collection.gui.view; +import com.c2kernel.collection.Aggregation; import com.c2kernel.collection.AggregationMember; -import com.c2kernel.collection.Collection; import com.c2kernel.collection.CollectionMember; import com.c2kernel.common.ObjectNotFoundException; import com.c2kernel.graph.model.Vertex; @@ -9,17 +9,18 @@ import com.c2kernel.graph.view.VertexPropertyPanel; public class PropertyPanel extends VertexPropertyPanel { - Collection mCollection; - + Aggregation mCollection; + public PropertyPanel() { super(); } - - public void setCollection(Collection collection) { + + public void setCollection(Aggregation collection) { mCollection = collection; } - public void setVertex(Vertex vert) { + @Override + public void setVertex(Vertex vert) { try { CollectionMember newMember = mCollection.getMember(vert.getID()); if (newMember instanceof AggregationMember) { diff --git a/source/com/c2kernel/collection/gui/view/SelectedMemberPanel.java b/source/com/c2kernel/collection/gui/view/SelectedMemberPanel.java old mode 100755 new mode 100644 index 5e66c1e..5b59b35 --- a/source/com/c2kernel/collection/gui/view/SelectedMemberPanel.java +++ b/source/com/c2kernel/collection/gui/view/SelectedMemberPanel.java @@ -4,7 +4,14 @@ import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; -import javax.swing.*; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JTextField; +import javax.swing.JToggleButton; import com.c2kernel.collection.AggregationMember; import com.c2kernel.collection.MembershipException; @@ -39,22 +46,23 @@ public class SelectedMemberPanel extends SelectedVertexPanel implements DomainKe SelectedMemberPanel me; AggregationMember selectedMember = null; - + public SelectedMemberPanel() { me=this; setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); - + JPanel attrs = new JPanel(new GridLayout(3,2)); attrs.add(new JLabel(Language.translate("Slot Number:"))); attrs.add(slotNumber); attrs.add(new JLabel(Language.translate("Assigned Member:"))); attrs.add(memberKey); memberKey.setEditable(false); - + add(attrs); add(Box.createVerticalStrut(10)); findButton.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent ae) { String code = memberKey.getText(); if (code == null || code.length() == 0) @@ -62,9 +70,10 @@ public class SelectedMemberPanel extends SelectedVertexPanel implements DomainKe MainFrame.itemFinder.pushNewKey(code); } }); - + changeButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { + @Override + public void actionPerformed(ActionEvent ae) { if (changeButton.getModel().isSelected()) { MainFrame.status.setText(Language.translate("Please scan or type your barcode to assign in the top field")); MainFrame.itemFinder.setConsumer(me, "Assign"); @@ -77,9 +86,10 @@ public class SelectedMemberPanel extends SelectedVertexPanel implements DomainKe } } }); - + removeButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { + @Override + public void actionPerformed(ActionEvent ae) { selectedMember.clearEntity(); selectedMember.getProperties().remove("Name"); select(selectedMember); @@ -92,11 +102,12 @@ public class SelectedMemberPanel extends SelectedVertexPanel implements DomainKe buttonBox.add(changeButton); buttonBox.add(removeButton); } - + setButtons(false); add(buttonBox); } + @Override public void select(Vertex vert) { selectedMember = (AggregationMember)vert; slotNumber.setText(String.valueOf(vert.getID())); @@ -108,10 +119,11 @@ public class SelectedMemberPanel extends SelectedVertexPanel implements DomainKe } catch (Exception e) { } memberKey.setText(name); setButtons(true); - + revalidate(); } - + + @Override public void clear() { slotNumber.setText(""); memberKey.setText(""); @@ -123,13 +135,14 @@ public class SelectedMemberPanel extends SelectedVertexPanel implements DomainKe findButton.setEnabled(state); changeButton.getModel().setSelected(false); changeButton.setEnabled(state); - removeButton.setEnabled(state); - MainFrame.itemFinder.clearConsumer(me); + removeButton.setEnabled(state); + MainFrame.itemFinder.clearConsumer(me); } /** * */ - public void push(DomainPath key) { + @Override + public void push(DomainPath key) { MainFrame.status.setText("Assigning entity "+key.getSysKey()+" to slot "+selectedMember.getID()); try { selectedMember.assignEntity(key.getSysKey()); @@ -142,7 +155,8 @@ public class SelectedMemberPanel extends SelectedVertexPanel implements DomainKe /** * */ - public void push(String name) { + @Override + public void push(String name) { JOptionPane.showMessageDialog(null, "Product is not known in this centre", "Error", JOptionPane.ERROR_MESSAGE); } diff --git a/source/com/c2kernel/entity/C2KLocalObject.java b/source/com/c2kernel/entity/C2KLocalObject.java old mode 100755 new mode 100644 index 06bf867..ec30dc1 --- a/source/com/c2kernel/entity/C2KLocalObject.java +++ b/source/com/c2kernel/entity/C2KLocalObject.java @@ -10,23 +10,23 @@ import java.io.Serializable; *
  • Outcomes - /Outcome/SchemaType/SchemaVersion/EventId *
  • Viewpoints - /ViewPoint/SchemaType/Name * - * + * * @see com.c2kernel.persistency.ClusterStorage * @see com.c2kernel.persistency.ClusterStorageManager - * + * * @author Andrew Branson * * $Revision: 1.5 $ * $Date: 2004/01/22 11:10:41 $ * * Copyright (C) 2003 CERN - European Organization for Nuclear Research - * All rights reserved. + * All rights reserved. */ public interface C2KLocalObject extends Serializable { public void setName(String name); public String getName(); - + public String getClusterType(); } diff --git a/source/com/c2kernel/entity/CorbaServer.java b/source/com/c2kernel/entity/CorbaServer.java index 883bb1b..84d2ef2 100644 --- a/source/com/c2kernel/entity/CorbaServer.java +++ b/source/com/c2kernel/entity/CorbaServer.java @@ -39,7 +39,7 @@ public class CorbaServer { public CorbaServer() throws InvalidDataException { mEntityCache = new SoftCache(50); - + // init POA try { setupPOA(); @@ -48,15 +48,16 @@ public class CorbaServer { Logger.error(ex); throw new InvalidDataException("Error initialising POA", ""); } - + new Thread(new Runnable() { - public void run() { + @Override + public void run() { Thread.currentThread().setName("ORB Invoker"); Gateway.getORB().run(); } }).start(); } - + public void close() { try { mPOAManager.deactivate(true, true); @@ -64,12 +65,12 @@ public class CorbaServer { Logger.error(ex); } } - + /************************************************************************** * Initialises the C2KRootPOA with policies which are suitable for Factory objects - **************************************************************************/ + **************************************************************************/ public void setupPOA() throws Exception { - + //Initialise the RootPOA mRootPOA = org.omg.PortableServer.POAHelper.narrow( Gateway.getORB().resolve_initial_references("RootPOA")); @@ -78,8 +79,6 @@ public class CorbaServer { mPOAManager = mRootPOA.the_POAManager(); - org.omg.CORBA.Policy[] poaPolicies; - // Create POA for use by the entities org.omg.CORBA.Policy[] policies = new org.omg.CORBA.Policy[6]; @@ -103,32 +102,32 @@ public class CorbaServer { policies ); mAgentPOA = mRootPOA.create_POA( "Agent", mRootPOA.the_POAManager(), - policies ); + policies ); //Create the locators TraceableLocator itemLocator = new TraceableLocator( mItemPOA ); - mItemPOA.set_servant_manager( itemLocator._this( Gateway.getORB() ) ); - + mItemPOA.set_servant_manager( itemLocator._this( Gateway.getORB() ) ); + ActiveLocator agentLocator = new ActiveLocator( mAgentPOA ); mAgentPOA.set_servant_manager( agentLocator._this( Gateway.getORB() ) ); - + } - + /************************************************************************** * Returns a CORBA servant for a pre-existing entity - **************************************************************************/ + **************************************************************************/ private Servant getEntity(int sysKey, org.omg.PortableServer.POA poa) throws ObjectNotFoundException { try { EntityPath entityPath = new EntityPath(sysKey); Servant entity = null; synchronized (mEntityCache) { - entity = (Servant)mEntityCache.get(entityPath); + entity = mEntityCache.get(entityPath); if (entity == null) { Logger.msg(7, "Creating new servant for "+sysKey); - - Class entityClass = Gateway.getLDAPLookup().getEntityClass(entityPath); - + + Class entityClass = Gateway.getLDAPLookup().getEntityClass(entityPath); + if (entityClass == TraceableEntity.class) { if (poa == null) poa = mItemPOA; entity = new TraceableEntity(sysKey, poa); @@ -141,12 +140,12 @@ public class CorbaServer { } } return entity; - + } catch (InvalidEntityPathException ex) { throw new ObjectNotFoundException("Invalid Entity Key", ""); - } + } } - + /************************************************************************** * Wrapper for fetching Items **************************************************************************/ @@ -186,6 +185,6 @@ public class CorbaServer { mEntityCache.put(entityPath, entity); } return entity; - + } } diff --git a/source/com/c2kernel/entity/TraceableEntity.java b/source/com/c2kernel/entity/TraceableEntity.java old mode 100755 new mode 100644 index 49bbe47..c7aff82 --- a/source/com/c2kernel/entity/TraceableEntity.java +++ b/source/com/c2kernel/entity/TraceableEntity.java @@ -11,7 +11,6 @@ package com.c2kernel.entity; -import java.util.Iterator; import com.c2kernel.common.AccessRightsException; import com.c2kernel.common.InvalidDataException; @@ -87,7 +86,8 @@ public class TraceableEntity extends ItemPOA /************************************************************************** * **************************************************************************/ - public org.omg.PortableServer.POA _default_POA() + @Override + public org.omg.PortableServer.POA _default_POA() { if(mPoa != null) return mPoa; @@ -99,7 +99,8 @@ public class TraceableEntity extends ItemPOA /************************************************************************** * **************************************************************************/ - public int getSystemKey() + @Override + public int getSystemKey() { Logger.msg(8, "TraceableEntity::getSystemKey() - " + mSystemKey); return mSystemKey; @@ -108,7 +109,8 @@ public class TraceableEntity extends ItemPOA /************************************************************************** * **************************************************************************/ - public void initialise( int agentId, + @Override + public void initialise( int agentId, String propString, String initWfString ) @@ -120,22 +122,22 @@ public class TraceableEntity extends ItemPOA synchronized (this) { Workflow lc = null; PropertyArrayList props = null; - + AgentPath agentPath; try { agentPath = new AgentPath(agentId); } catch (InvalidEntityPathException e) { throw new AccessRightsException("Invalid Agent Id:" + agentId); } - + //unmarshalling checks the validity of the received strings - + // create properties if (!propString.equals("")) { try { props = (PropertyArrayList)CastorXMLUtility.unmarshall(propString); - for (Iterator i = props.list.iterator(); i.hasNext();) { - Property thisProp = (Property)i.next(); + for (Object name : props.list) { + Property thisProp = (Property)name; mStorage.put(mSystemKey, thisProp, props); } } catch (Throwable ex) { @@ -145,10 +147,10 @@ public class TraceableEntity extends ItemPOA } mStorage.commit(props); } - + // create wf try { - if (initWfString == null || initWfString.equals("")) + if (initWfString == null || initWfString.equals("")) lc = new Workflow(new CompositeActivity()); else lc = new Workflow((CompositeActivity)CastorXMLUtility.unmarshall(initWfString)); @@ -158,14 +160,15 @@ public class TraceableEntity extends ItemPOA Logger.msg(8, "TraceableEntity::initialise("+mSystemKey+") - Workflow was invalid: "+initWfString); Logger.error(ex); } - } + } } /************************************************************************** * **************************************************************************/ //requestdata is xmlstring - public void requestAction( int agentId, + @Override + public void requestAction( int agentId, String stepPath, int transitionID, String requestData @@ -180,31 +183,31 @@ public class TraceableEntity extends ItemPOA synchronized (this) { try { - Logger.msg(1, "TraceableEntity::request("+mSystemKey+") - " + + Logger.msg(1, "TraceableEntity::request("+mSystemKey+") - " + Transitions.getTransitionName(transitionID) + " "+stepPath + " by " +agentId ); - AgentPath agent = new AgentPath(agentId); + AgentPath agent = new AgentPath(agentId); Workflow lifeCycle = (Workflow)mStorage.get(mSystemKey, ClusterStorage.LIFECYCLE+"/workflow", null); - + lifeCycle.requestAction( agent, stepPath, transitionID, requestData ); - + // store the workflow if we've changed the state of the domain wf - if (!(stepPath.startsWith("workflow/predefined"))) + if (!(stepPath.startsWith("workflow/predefined"))) mStorage.put(mSystemKey, lifeCycle, null); - + // Normal operation exceptions } catch (AccessRightsException ex) { - Logger.msg("Propagating AccessRightsException back to the calling agent"); + Logger.msg("Propagating AccessRightsException back to the calling agent"); throw ex; } catch (InvalidTransitionException ex) { - Logger.msg("Propagating InvalidTransitionException back to the calling agent"); + Logger.msg("Propagating InvalidTransitionException back to the calling agent"); throw ex; } catch (ObjectNotFoundException ex) { - Logger.msg("Propagating ObjectNotFoundException back to the calling agent"); - throw ex; + Logger.msg("Propagating ObjectNotFoundException back to the calling agent"); + throw ex; // errors } catch (ClusterStorageException ex) { Logger.error(ex); @@ -212,13 +215,13 @@ public class TraceableEntity extends ItemPOA } catch (InvalidEntityPathException ex) { Logger.error(ex); throw new AccessRightsException("Invalid Agent Id: "+agentId, ""); - } catch (InvalidDataException ex) { + } catch (InvalidDataException ex) { Logger.error(ex); - Logger.msg("Propagating InvalidDataException back to the calling agent"); + Logger.msg("Propagating InvalidDataException back to the calling agent"); throw ex; - } catch (ObjectAlreadyExistsException ex) { + } catch (ObjectAlreadyExistsException ex) { Logger.error(ex); - Logger.msg("Propagating ObjectAlreadyExistsException back to the calling agent"); + Logger.msg("Propagating ObjectAlreadyExistsException back to the calling agent"); throw ex; // non-CORBA exception hasn't been caught! } catch (Throwable ex) { @@ -226,13 +229,14 @@ public class TraceableEntity extends ItemPOA Logger.error(ex); throw new InvalidDataException("Extraordinary Exception during execution:"+ex.getClass().getName()+" - "+ex.getMessage(), ""); } - } + } } /************************************************************************** * **************************************************************************/ - public String queryLifeCycle( int agentId, + @Override + public String queryLifeCycle( int agentId, boolean filter ) throws AccessRightsException, @@ -241,7 +245,7 @@ public class TraceableEntity extends ItemPOA { synchronized (this) { Logger.msg(1, "TraceableEntity::queryLifeCycle("+mSystemKey+") - agent: " + agentId); - + try { AgentPath agent = new AgentPath(agentId); @@ -266,21 +270,22 @@ public class TraceableEntity extends ItemPOA * @param path - the path to the object required * the suffix 'all' retrieves a listing of all keys on that level * - * @return The result string in xml format + * @return The result string in xml format * except 'all' which returns a comma sep list * * @exception ObjectNotFoundException * ************************************************************************/ - public String queryData(String path) + @Override + public String queryData(String path) throws AccessRightsException, ObjectNotFoundException, PersistencyException { synchronized (this) { String result = ""; - + Logger.msg(1, "TraceableEntity::queryData("+mSystemKey+") - " + path ); - + try { // check for cluster contents query @@ -289,11 +294,11 @@ public class TraceableEntity extends ItemPOA int allPos = path.lastIndexOf("all"); String query = path.substring(0,allPos); String[] ids = mStorage.getClusterContents( mSystemKey, query ); - + for( int i=0; i iter = props.list.iterator(); while( iter.hasNext() ) - mDatabase.put( mSystemKey, (C2KLocalObject)iter.next(), props ); + mDatabase.put( mSystemKey, iter.next(), props ); } else { @@ -138,12 +145,13 @@ public class ActiveEntity extends AgentPOA return props; } - + /************************************************************************** * * **************************************************************************/ - public org.omg.PortableServer.POA _default_POA() + @Override + public org.omg.PortableServer.POA _default_POA() { if(mPOA != null) return mPOA; @@ -156,7 +164,8 @@ public class ActiveEntity extends AgentPOA * * **************************************************************************/ - public int getSystemKey() + @Override + public int getSystemKey() { return mSystemKey; } @@ -166,7 +175,8 @@ public class ActiveEntity extends AgentPOA * * **************************************************************************/ - public String queryData(String xpath) + @Override + public String queryData(String xpath) throws AccessRightsException, ObjectNotFoundException, PersistencyException @@ -203,7 +213,7 @@ public class ActiveEntity extends AgentPOA } catch (ObjectNotFoundException ex) { throw ex; - } + } catch(Throwable ex) { Logger.error("ActiveEntity::queryData("+mSystemKey+") - " + @@ -218,37 +228,39 @@ public class ActiveEntity extends AgentPOA } - + /** * Called by an activity when it reckons we need to update our joblist for it */ - - public synchronized void refreshJobList(int sysKey, String stepPath, String newJobs) { + + @Override + public synchronized void refreshJobList(int sysKey, String stepPath, String newJobs) { try { JobArrayList newJobList = (JobArrayList)CastorXMLUtility.unmarshall(newJobs); - + // get our joblist if (currentJobs == null) currentJobs = new JobList( mSystemKey, null); - + // remove old jobs for this item currentJobs.removeJobsForStep( sysKey, stepPath ); - + // merge new jobs in - for (Iterator iter = newJobList.list.iterator(); iter.hasNext();) { - Job newJob = (Job)iter.next(); + for (Object name : newJobList.list) { + Job newJob = (Job)name; Logger.msg(6, "Adding job for "+newJob.getItemSysKey()+"/"+newJob.getStepPath()+":"+newJob.getPossibleTransition()); currentJobs.addJob(newJob); } - + } catch (Throwable ex) { Logger.error("Could not refresh job list."); - Logger.error(ex); + Logger.error(ex); } - + } - - public void addRole(String roleName) throws CannotManageException, ObjectNotFoundException { + + @Override + public void addRole(String roleName) throws CannotManageException, ObjectNotFoundException { RolePath newRole = Gateway.getLDAPLookup().getRoleManager().getRolePath(roleName); try { newRole.addAgent(new AgentPath(mSystemKey)); @@ -258,11 +270,12 @@ public class ActiveEntity extends AgentPOA throw new CannotManageException("Could not update role"); } } - - public void removeRole(String roleName) throws CannotManageException, ObjectNotFoundException { + + @Override + public void removeRole(String roleName) throws CannotManageException, ObjectNotFoundException { RolePath rolePath = Gateway.getLDAPLookup().getRoleManager().getRolePath(roleName); try { - rolePath.removeAgent(new AgentPath(mSystemKey)); + rolePath.removeAgent(new AgentPath(mSystemKey)); } catch (InvalidEntityPathException e) { throw new CannotManageException("Invalid syskey for agent: "+mSystemKey, ""); } catch (ObjectCannotBeUpdated ex) { @@ -272,7 +285,8 @@ public class ActiveEntity extends AgentPOA /** * */ - protected void finalize() throws Throwable { + @Override + protected void finalize() throws Throwable { Logger.msg(7, "Agent "+mSystemKey+" reaped"); Gateway.getStorage().clearCache(mSystemKey, null); super.finalize(); diff --git a/source/com/c2kernel/entity/agent/ActiveLocator.java b/source/com/c2kernel/entity/agent/ActiveLocator.java old mode 100755 new mode 100644 index 25324ee..eb50dbf --- a/source/com/c2kernel/entity/agent/ActiveLocator.java +++ b/source/com/c2kernel/entity/agent/ActiveLocator.java @@ -45,7 +45,8 @@ public class ActiveLocator extends org.omg.PortableServer.ServantLocatorPOA /************************************************************************** * **************************************************************************/ - public org.omg.PortableServer.Servant preinvoke( + @Override + public org.omg.PortableServer.Servant preinvoke( byte[] oid, org.omg.PortableServer.POA poa, String operation, @@ -56,8 +57,6 @@ public class ActiveLocator extends org.omg.PortableServer.ServantLocatorPOA { int syskey = Integer.parseInt(new String(oid)); - org.omg.PortableServer.Servant servant; - Logger.msg(1,"==========================================================="); Logger.msg(1,"Agent called at "+new Timestamp( System.currentTimeMillis()) +": " + operation + "(" + syskey + ")." ); @@ -76,7 +75,8 @@ public class ActiveLocator extends org.omg.PortableServer.ServantLocatorPOA /************************************************************************** * **************************************************************************/ - public void postinvoke( + @Override + public void postinvoke( byte[] oid, org.omg.PortableServer.POA poa, String operation, diff --git a/source/com/c2kernel/entity/agent/Job.java b/source/com/c2kernel/entity/agent/Job.java old mode 100755 new mode 100644 index 12423d6..b5274ec --- a/source/com/c2kernel/entity/agent/Job.java +++ b/source/com/c2kernel/entity/agent/Job.java @@ -32,7 +32,7 @@ public class Job implements C2KLocalObject private int mPossibleTransition; private int mCurrentState; - + private int mTargetState; private String mStepName; @@ -61,7 +61,7 @@ public class Job implements C2KLocalObject } /*************************************************************************** - * + * **************************************************************************/ public Job(int sysKey, String path, int transition, int currState, int targState, String stepName, CastorHashMap actProps, String stepType, String agentName) { @@ -197,7 +197,8 @@ public class Job implements C2KLocalObject return mID; } - public String getName() + @Override + public String getName() { return mName; } @@ -208,7 +209,8 @@ public class Job implements C2KLocalObject mName = String.valueOf(id); } - public void setName(String name) + @Override + public void setName(String name) { mName = name; try @@ -226,7 +228,8 @@ public class Job implements C2KLocalObject item = null; } - public String getClusterType() + @Override + public String getClusterType() { return ClusterStorage.JOB; } @@ -322,7 +325,7 @@ public class Job implements C2KLocalObject /** * Returns the actType. - * + * * @return String */ public String getStepType() @@ -332,7 +335,7 @@ public class Job implements C2KLocalObject /** * Sets the actType. - * + * * @param actType * The actType to set */ diff --git a/source/com/c2kernel/entity/agent/JobArrayList.java b/source/com/c2kernel/entity/agent/JobArrayList.java index fa85368..dcb3215 100644 --- a/source/com/c2kernel/entity/agent/JobArrayList.java +++ b/source/com/c2kernel/entity/agent/JobArrayList.java @@ -17,14 +17,14 @@ public class JobArrayList extends CastorArrayList { public JobArrayList() - { + { super(); } - + public JobArrayList(ArrayList aList) - { + { super(aList); } - + } diff --git a/source/com/c2kernel/entity/agent/JobList.java b/source/com/c2kernel/entity/agent/JobList.java index 15ce0dd..f8a88ee 100644 --- a/source/com/c2kernel/entity/agent/JobList.java +++ b/source/com/c2kernel/entity/agent/JobList.java @@ -3,8 +3,6 @@ package com.c2kernel.entity.agent; import java.util.Iterator; import java.util.Vector; -import com.c2kernel.common.ObjectNotFoundException; -import com.c2kernel.lookup.InvalidEntityPathException; import com.c2kernel.persistency.ClusterStorage; import com.c2kernel.persistency.RemoteMap; import com.c2kernel.utils.Logger; @@ -15,14 +13,13 @@ import com.c2kernel.utils.Logger; * @author $Author: abranson $ $Date: 2006/03/03 13:52:21 $ * @version $Revision: 1.15 $ ***************************************************************************/ -public class JobList extends RemoteMap +public class JobList extends RemoteMap { /************************************************************************** * Empty constructor for Castor **************************************************************************/ - public JobList(int sysKey, Object locker) - throws ObjectNotFoundException, InvalidEntityPathException + public JobList(int sysKey, Object locker) { super(sysKey, ClusterStorage.JOB, locker); } @@ -43,29 +40,15 @@ public class JobList extends RemoteMap /** * Cannot be stored */ + @Override public String getClusterType() { return null; } - - public int containsJob( Job job ) - { - Iterator actMembers = keySet().iterator(); - Job j = null; - while( actMembers.hasNext() ) - { - j = (Job)actMembers.next(); - if( j.equals(job) ) - return j.getID(); - } - - return -1; - } - public Job getJob(int id) { - return (Job)get(String.valueOf(id)); - } + return get(String.valueOf(id)); + } /** @@ -73,12 +56,12 @@ public class JobList extends RemoteMap */ public void removeJobsWithSysKey( int sysKey ) { - Iterator currentMembers = values().iterator(); + Iterator currentMembers = values().iterator(); Job j = null; while( currentMembers.hasNext() ) { - j = (Job)currentMembers.next(); + j = currentMembers.next(); if( j.getItemSysKey() == sysKey ) remove( String.valueOf(j.getID()) ); @@ -89,10 +72,10 @@ public class JobList extends RemoteMap public void removeJobsForStep( int sysKey, String stepPath ) { - Iterator currentMembers = values().iterator(); + Iterator currentMembers = values().iterator(); while( currentMembers.hasNext() ) { - Job j = (Job)currentMembers.next(); + Job j = currentMembers.next(); if( j.getItemSysKey() == sysKey && j.getStepPath().equals(stepPath)) remove( String.valueOf(j.getID()) ); } @@ -104,15 +87,15 @@ public class JobList extends RemoteMap * @param string * @return */ - public Vector getJobsOfSysKey(int sysKey) + public Vector getJobsOfSysKey(int sysKey) { - Iterator currentMembers = values().iterator(); + Iterator currentMembers = values().iterator(); Job j = null; Vector jobs = new Vector(); while( currentMembers.hasNext() ) { - j = (Job)currentMembers.next(); + j = currentMembers.next(); if( j.getItemSysKey() == sysKey ) jobs.add(j); diff --git a/source/com/c2kernel/entity/proxy/AgentProxy.java b/source/com/c2kernel/entity/proxy/AgentProxy.java old mode 100755 new mode 100644 index af77031..f2e8283 --- a/source/com/c2kernel/entity/proxy/AgentProxy.java +++ b/source/com/c2kernel/entity/proxy/AgentProxy.java @@ -66,8 +66,9 @@ public class AgentProxy extends EntityProxy throw new ObjectNotFoundException(); } } - - public ManageableEntity narrow() throws ObjectNotFoundException + + @Override + public ManageableEntity narrow() throws ObjectNotFoundException { try { return AgentHelper.narrow(mIOR); @@ -85,48 +86,48 @@ public class AgentProxy extends EntityProxy ObjectNotFoundException { Logger.msg(7, "AgentProxy::initialise - started"); - + ((Agent)getEntity()).initialise( agentProps ); } - + public AgentPath getPath() { return path; } - + /** - * Executes a job on the given item using this agent. - * + * Executes a job on the given item using this agent. + * * @param item - item holding this job * @param job - the job to execute */ - public void execute(ItemProxy item, Job job) - throws AccessRightsException, - InvalidTransitionException, - ObjectNotFoundException, - InvalidDataException, + public void execute(ItemProxy item, Job job) + throws AccessRightsException, + InvalidTransitionException, + ObjectNotFoundException, + InvalidDataException, PersistencyException, ObjectAlreadyExistsException - { + { OutcomeValidator validator = null; String scriptName = job.getActPropString("ScriptName"); Date startTime = new Date(); Logger.msg(3, "AgentProxy - executing "+job.getStepPath()+" for "+path.getAgentName()); // get the outcome validator if present - if (job.isOutcomeUsed()) + if (job.isOutcomeUsed()) { - + // get schema info from act props String schemaName = job.getActPropString("SchemaType"); int schemaVersion; try { schemaVersion = Integer.parseInt(job.getActPropString("SchemaVersion")); - } catch (Exception e) { + } catch (Exception e) { throw new InvalidDataException(e.getClass().getName()+" extracing schema version", ""); } Logger.msg(5, "AgentProxy - fetching schema "+schemaName+"_"+schemaVersion+" for validation"); // retrieve schema Schema schema = LocalObjectLoader.getSchema(schemaName, schemaVersion); - + if (schema == null) throw new InvalidDataException("Job references outcome type "+schemaName+" version "+schemaVersion+" that does not exist in this centre.", ""); @@ -136,12 +137,12 @@ public class AgentProxy extends EntityProxy throw new InvalidDataException("Could not create validator: "+e.getMessage(), ""); } } - - if(scriptName != null && scriptName.length() > 0 && + + if(scriptName != null && scriptName.length() > 0 && (job.getPossibleTransition() == Transitions.DONE || job.getPossibleTransition() == Transitions.COMPLETE)) { Logger.msg(3, "AgentProxy - executing script "+scriptName); try { - + // pre-validate outcome from script if there is one if (job.getOutcomeString()!= null && validator != null) { Logger.msg(5, "AgentProxy - validating outcome before script execution"); @@ -151,10 +152,10 @@ public class AgentProxy extends EntityProxy throw new InvalidDataException(error, ""); } } - + // load script ErrorInfo scriptErrors = (ErrorInfo)callScript(item, job); - + if (scriptErrors.getFatal()) { Logger.msg(3, "AgentProxy - fatal script error"); Logger.error(scriptErrors.getErrors()); @@ -174,7 +175,7 @@ public class AgentProxy extends EntityProxy if (error.length() > 0) throw new InvalidDataException(error, ""); } - + job.setAgentId(getSystemKey()); Logger.msg(3, "AgentProxy - submitting job to item proxy"); item.requestAction(job); @@ -184,16 +185,16 @@ public class AgentProxy extends EntityProxy Logger.msg(3, "Execution took "+secsNow+" seconds"); } } - + public Object callScript(ItemProxy item, Job job) throws ScriptingEngineException { Script script = new Script(item, this, job); return script.execute(); } - + /** - * Standard execution of jobs. Note that this method should always be the one used from clients - all execution - * parameters are taken from the job where they're probably going to be correct. - * + * Standard execution of jobs. Note that this method should always be the one used from clients - all execution + * parameters are taken from the job where they're probably going to be correct. + * * @param job * @throws AccessRightsException * @throws InvalidDataException @@ -202,7 +203,7 @@ public class AgentProxy extends EntityProxy * @throws PersistencyException * @throws ObjectAlreadyExistsException */ - public void execute(Job job) + public void execute(Job job) throws AccessRightsException, InvalidDataException, InvalidTransitionException, @@ -217,8 +218,8 @@ public class AgentProxy extends EntityProxy throw new ObjectNotFoundException("Job contained invalid item sysKey: "+job.getItemSysKey(), ""); } } - - public void execute(ItemProxy item, String predefStep, C2KLocalObject obj) + + public void execute(ItemProxy item, String predefStep, C2KLocalObject obj) throws AccessRightsException, InvalidDataException, InvalidTransitionException, @@ -235,8 +236,8 @@ public class AgentProxy extends EntityProxy } execute(item, predefStep, param); } - - public void execute(ItemProxy item, String predefStep, String param) + + public void execute(ItemProxy item, String predefStep, String param) throws AccessRightsException, InvalidDataException, InvalidTransitionException, @@ -248,8 +249,8 @@ public class AgentProxy extends EntityProxy params[0] = param; execute(item, predefStep, params); } - - public void execute(ItemProxy item, String predefStep, String[] params) + + public void execute(ItemProxy item, String predefStep, String[] params) throws AccessRightsException, InvalidDataException, InvalidTransitionException, @@ -259,42 +260,42 @@ public class AgentProxy extends EntityProxy { item.requestAction(getSystemKey(), "workflow/predefined/"+predefStep, Transitions.DONE, PredefinedStep.bundleData(params)); } - + /** Wrappers for scripts */ public String marshall(Object obj) throws Exception { return CastorXMLUtility.marshall(obj); } - + public Object unmarshall(String obj) throws Exception { return CastorXMLUtility.unmarshall(obj); } - + /** Let scripts resolve items */ public ItemProxy searchItem(String name) throws ObjectNotFoundException { - Enumeration results = Gateway.getLDAPLookup().search(new DomainPath(""),name); - + Enumeration results = Gateway.getLDAPLookup().search(new DomainPath(""),name); + Path returnPath = null; if (!results.hasMoreElements()) throw new ObjectNotFoundException(name, ""); - + while(results.hasMoreElements()) { Path nextMatch = (Path)results.nextElement(); if (returnPath != null && nextMatch.getSysKey() != -1 && returnPath.getSysKey() != nextMatch.getSysKey()) throw new ObjectNotFoundException("Too many items with that name"); returnPath = nextMatch; } - + return (ItemProxy)Gateway.getProxyManager().getProxy(returnPath); } - + public ItemProxy getItem(String path) throws ObjectNotFoundException { return (getItem(new DomainPath(path))); } - + public ItemProxy getItem(DomainPath path) throws ObjectNotFoundException { return (ItemProxy)Gateway.getProxyManager().getProxy(path); } - + public ItemProxy getItemBySysKey(int sysKey) throws ObjectNotFoundException, InvalidEntityPathException { return (ItemProxy)Gateway.getProxyManager().getProxy(new EntityPath(sysKey)); } diff --git a/source/com/c2kernel/entity/proxy/DomainPathSubscriber.java b/source/com/c2kernel/entity/proxy/DomainPathSubscriber.java old mode 100755 new mode 100644 index e09178d..4089325 --- a/source/com/c2kernel/entity/proxy/DomainPathSubscriber.java +++ b/source/com/c2kernel/entity/proxy/DomainPathSubscriber.java @@ -12,7 +12,7 @@ import com.c2kernel.lookup.DomainPath; **************************************************************************/ public interface DomainPathSubscriber { - + public void pathAdded(DomainPath path); public void pathRemoved(DomainPath path); } diff --git a/source/com/c2kernel/entity/proxy/EntityProxy.java b/source/com/c2kernel/entity/proxy/EntityProxy.java index b34653f..a9f6066 100644 --- a/source/com/c2kernel/entity/proxy/EntityProxy.java +++ b/source/com/c2kernel/entity/proxy/EntityProxy.java @@ -10,14 +10,17 @@ package com.c2kernel.entity.proxy; -import java.util.*; +import java.util.HashMap; +import java.util.Iterator; import com.c2kernel.common.ObjectNotFoundException; -import com.c2kernel.entity.*; -import com.c2kernel.persistency.*; +import com.c2kernel.entity.C2KLocalObject; +import com.c2kernel.entity.ManageableEntity; +import com.c2kernel.persistency.ClusterStorageException; import com.c2kernel.process.Gateway; import com.c2kernel.property.Property; -import com.c2kernel.utils.*; +import com.c2kernel.utils.CastorXMLUtility; +import com.c2kernel.utils.Logger; /****************************************************************************** @@ -35,7 +38,7 @@ abstract public class EntityProxy implements ManageableEntity protected ManageableEntity mEntity = null; protected org.omg.CORBA.Object mIOR; protected int mSystemKey; - private HashMap mSubscriptions; + private HashMap, EntityProxyObserver> mSubscriptions; /************************************************************************** * @@ -45,7 +48,7 @@ abstract public class EntityProxy implements ManageableEntity throws ObjectNotFoundException { Logger.msg(8,"EntityProxy::EntityProxy() - Initialising '" +systemKey+ "' entity"); - + initialise( ior, systemKey); } @@ -60,7 +63,7 @@ abstract public class EntityProxy implements ManageableEntity mIOR = ior; mSystemKey = systemKey; - mSubscriptions = new HashMap(); + mSubscriptions = new HashMap, EntityProxyObserver>(); } @@ -74,14 +77,15 @@ abstract public class EntityProxy implements ManageableEntity } return mEntity; } - + abstract public ManageableEntity narrow() throws ObjectNotFoundException; - + /************************************************************************** * **************************************************************************/ //check who is using.. and if toString() is sufficient - public int getSystemKey() + @Override + public int getSystemKey() { return mSystemKey; } @@ -90,7 +94,8 @@ abstract public class EntityProxy implements ManageableEntity /************************************************************************** * **************************************************************************/ - public String queryData( String path ) + @Override + public String queryData( String path ) throws ObjectNotFoundException { @@ -114,9 +119,9 @@ abstract public class EntityProxy implements ManageableEntity } catch (Exception e) { Logger.error(e); return ""+e.getMessage()+""; - } + } } - + public String[] getContents( String path ) throws ObjectNotFoundException { try { return Gateway.getStorage().getClusterContents(mSystemKey, path.substring(0, path.length())); @@ -160,39 +165,36 @@ abstract public class EntityProxy implements ManageableEntity throw new ObjectNotFoundException(); } } - + public String getName() { try { - return getProperty("Name"); + return getProperty("Name"); } catch (ObjectNotFoundException ex) { return null; } } - + /************************************************************************** * Subscription methods **************************************************************************/ - public void subscribe (EntityProxyObserver observer, - String interest, - boolean preload) - { - MemberSubscription newSub = new MemberSubscription(this, interest, observer, preload); - synchronized (this){ - mSubscriptions.put( newSub, observer ); + public void subscribe (MemberSubscription newSub) { + + newSub.setSubject(this); + synchronized (this){ + mSubscriptions.put( newSub, newSub.getObserver() ); } new Thread(newSub).start(); - Logger.msg(7, "Subscribed "+observer.getClass().getName()+" for "+interest); + Logger.msg(7, "Subscribed "+newSub.getObserver().getClass().getName()+" for "+newSub.interest); } - - public void unsubscribe(EntityProxyObserver observer) + public void unsubscribe(EntityProxyObserver observer) { synchronized (this){ - for (Iterator e = mSubscriptions.keySet().iterator(); e.hasNext();) { - MemberSubscription thisSub = (MemberSubscription)e.next(); + for (Iterator> e = mSubscriptions.keySet().iterator(); e.hasNext();) { + MemberSubscription thisSub = e.next(); if (mSubscriptions.get( thisSub ) == observer) { e.remove(); Logger.msg(7, "Unsubscribed "+observer.getClass().getName()); @@ -200,14 +202,13 @@ abstract public class EntityProxy implements ManageableEntity } } } - + public void dumpSubscriptions(int logLevel) { if (mSubscriptions.size() == 0) return; Logger.msg(logLevel, "Subscriptions to proxy "+mSystemKey+":"); synchronized(this) { - for (Iterator iter = mSubscriptions.keySet().iterator(); iter.hasNext();) { - MemberSubscription element = (MemberSubscription)iter.next(); - EntityProxyObserver obs = element.getObserver(); + for (MemberSubscription element : mSubscriptions.keySet()) { + EntityProxyObserver obs = element.getObserver(); if (obs != null) Logger.msg(logLevel, " "+element.getObserver().getClass().getName()+" subscribed to "+element.interest); else @@ -215,14 +216,14 @@ abstract public class EntityProxy implements ManageableEntity } } } - + public void notify(ProxyMessage message) { Logger.msg(4, "EntityProxy.notify() - Received change notification for "+message.getPath()+" on "+mSystemKey); synchronized (this){ if (!message.getServer().equals(EntityProxyManager.serverName)) Gateway.getStorage().clearCache(mSystemKey, message.getPath()); - for (Iterator e = mSubscriptions.keySet().iterator(); e.hasNext();) { - MemberSubscription newSub = (MemberSubscription)e.next(); + for (Iterator> e = mSubscriptions.keySet().iterator(); e.hasNext();) { + MemberSubscription newSub = e.next(); if (newSub.getObserver() == null) { // phantom Logger.msg(4, "Removing phantom subscription to "+newSub.interest); e.remove(); @@ -232,11 +233,12 @@ abstract public class EntityProxy implements ManageableEntity } } } - + /** * If this is reaped, clear out the cache for it too. */ - protected void finalize() throws Throwable { + @Override + protected void finalize() throws Throwable { Logger.msg(7, "Proxy "+mSystemKey+" reaped"); Gateway.getStorage().clearCache(mSystemKey, null); Gateway.getProxyManager().removeProxy(mSystemKey); diff --git a/source/com/c2kernel/entity/proxy/EntityProxyManager.java b/source/com/c2kernel/entity/proxy/EntityProxyManager.java index 3224da7..8ad4576 100644 --- a/source/com/c2kernel/entity/proxy/EntityProxyManager.java +++ b/source/com/c2kernel/entity/proxy/EntityProxyManager.java @@ -10,7 +10,11 @@ package com.c2kernel.entity.proxy; -import java.util.*; +import java.util.ArrayList; +import java.util.ConcurrentModificationException; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Iterator; import com.c2kernel.common.InvalidDataException; import com.c2kernel.common.ObjectNotFoundException; @@ -25,12 +29,12 @@ import com.c2kernel.utils.SoftCache; import com.c2kernel.utils.server.SimpleTCPIPServer; -public class EntityProxyManager +public class EntityProxyManager { SoftCache proxyPool = new SoftCache(50); HashMap treeSubscribers = new HashMap(); HashMap connections = new HashMap(); - + // server objects static ArrayList proxyClients = new ArrayList(); static SimpleTCPIPServer proxyServer = null; @@ -42,8 +46,8 @@ public class EntityProxyManager public EntityProxyManager() { Logger.msg(5, "EntityProxyManager - Starting....."); - - Enumeration servers = Gateway.getLDAPLookup().searchEntities(new DomainPath("/servers")); + + Enumeration servers = Gateway.getLDAPLookup().searchEntities(new DomainPath("/servers")); while(servers.hasMoreElements()) { Path thisServerPath = (Path)servers.nextElement(); try { @@ -52,65 +56,62 @@ public class EntityProxyManager String portStr = ((Property)Gateway.getStorage().get(syskey, ClusterStorage.PROPERTY+"/ProxyPort", null)).getValue(); int remotePort = Integer.parseInt(portStr); connectToProxyServer(remoteServer, remotePort); - + } catch (Exception ex) { Logger.error("Exception retrieving proxy server connection data for "+thisServerPath); Logger.error(ex); } } } - + public void connectToProxyServer(String name, int port) { - ProxyServerConnection oldConn = (ProxyServerConnection)connections.get(name); + ProxyServerConnection oldConn = connections.get(name); if (oldConn != null) oldConn.shutdown(); connections.put(name, new ProxyServerConnection(name, port, this)); } - - + + protected void resubscribe(ProxyServerConnection conn) { synchronized (proxyPool) { - for (Iterator iter = proxyPool.keySet().iterator(); iter.hasNext();) { - Integer key = (Integer)iter.next(); + for (Integer key : proxyPool.keySet()) { ProxyMessage sub = new ProxyMessage(key.intValue(), ProxyMessage.ADDPATH, false); Logger.msg(5, "Subscribing to entity "+key); conn.sendMessage(sub); } } } - + /** * @param sub */ private void sendMessage(ProxyMessage sub) { - for (Iterator iter = connections.values().iterator(); iter.hasNext();) { - ProxyServerConnection element = (ProxyServerConnection) iter.next(); + for (ProxyServerConnection element : connections.values()) { element.sendMessage(sub); } - + } public void shutdown() { Logger.msg("EntityProxyManager.shutdown() - flagging shutdown of server connections"); - for (Iterator iter = connections.values().iterator(); iter.hasNext();) { - ProxyServerConnection element = (ProxyServerConnection) iter.next(); + for (ProxyServerConnection element : connections.values()) { element.shutdown(); } } - + protected void processMessage(ProxyMessage thisMessage) throws InvalidDataException { if (Logger.doLog(9)) Logger.msg(9, thisMessage.toString()); - + if (thisMessage.getPath().equals(ProxyMessage.PINGPATH)) // ping response return; - + if (thisMessage.getSysKey() == ProxyMessage.NA) // must be domain path info informTreeSubscribers(thisMessage.getState(), thisMessage.getPath()); else { // proper proxy message Logger.msg(5, "Received proxy message: "+thisMessage.toString()); Integer key = new Integer(thisMessage.getSysKey()); - EntityProxy relevant = (EntityProxy)proxyPool.get(key); + EntityProxy relevant = proxyPool.get(key); if (relevant == null) Logger.warning("Received proxy message for sysKey "+thisMessage.getSysKey()+" which we don't have a proxy for."); else @@ -120,18 +121,17 @@ public class EntityProxyManager Logger.error("Error caught notifying proxy listener "+relevant.toString()+" of "+thisMessage.toString()); Logger.error(ex); } - } + } } - + private void informTreeSubscribers(boolean state, String path) { DomainPath last = new DomainPath(path); DomainPath parent; boolean first = true; synchronized(treeSubscribers) { while((parent = last.getParent()) != null) { - - for (Iterator iter = treeSubscribers.keySet().iterator(); iter.hasNext();) { - DomainPathSubscriber sub = (DomainPathSubscriber)iter.next(); - DomainPath interest = (DomainPath)treeSubscribers.get(sub); + + for (DomainPathSubscriber sub : treeSubscribers.keySet()) { + DomainPath interest = treeSubscribers.get(sub); if (interest.equals(parent)) { if (state == ProxyMessage.ADDED) sub.pathAdded(last); @@ -142,26 +142,26 @@ public class EntityProxyManager last = parent; first = false; } - } + } } - + public void subscribeTree(DomainPathSubscriber sub, DomainPath interest) { synchronized(treeSubscribers) { treeSubscribers.put(sub, interest); } } - + public void unsubscribeTree(DomainPathSubscriber sub) { synchronized(treeSubscribers) { treeSubscribers.remove(sub); - } + } } /************************************************************************** * **************************************************************************/ - private EntityProxy createProxy( org.omg.CORBA.Object ior, - int systemKey, + private EntityProxy createProxy( org.omg.CORBA.Object ior, + int systemKey, boolean isItem ) throws ObjectNotFoundException { @@ -185,7 +185,7 @@ public class EntityProxyManager reportCurrentProxies(9); return ( newProxy ); } - + protected void removeProxy( int systemKey ) { ProxyMessage sub = new ProxyMessage(systemKey, ProxyMessage.DELPATH, true); @@ -210,7 +210,7 @@ public class EntityProxyManager synchronized(proxyPool) { EntityProxy newProxy; // return it if it exists - newProxy = (EntityProxy)proxyPool.get(key); + newProxy = proxyPool.get(key); if (newProxy == null) { // create a new one newProxy = createProxy(ior, systemKey, isItem ); @@ -250,14 +250,14 @@ public class EntityProxyManager Logger.msg(logLevel, "Current proxies: "); try { synchronized(proxyPool) { - Iterator i = proxyPool.keySet().iterator(); - + Iterator i = proxyPool.keySet().iterator(); + for( int count=0; i.hasNext(); count++ ) { - Integer nextProxy = (Integer)i.next(); - EntityProxy thisProxy = (EntityProxy)proxyPool.get(nextProxy); + Integer nextProxy = i.next(); + EntityProxy thisProxy = proxyPool.get(nextProxy); if (thisProxy != null) - Logger.msg(logLevel, + Logger.msg(logLevel, "" + count + ": " + proxyPool.get(nextProxy).getClass().getName() + ": " + nextProxy); @@ -267,12 +267,12 @@ public class EntityProxyManager Logger.msg(logLevel, "Proxy cache modified. Aborting."); } } - + /************************************************************************** * Static Proxy Server methods - **************************************************************************/ - + **************************************************************************/ + /** * Initialises the Proxy event UDP server listening on 'Host.Proxy.port' from c2kprops * @param c2kProps @@ -286,7 +286,7 @@ public class EntityProxyManager Logger.error("ItemServer.Proxy.port not defined in connect file. Remote proxies will not be informed of entity changes."); return; } - + // set up the proxy server try { int portNo = Integer.parseInt(port); @@ -298,40 +298,38 @@ public class EntityProxyManager Logger.error(ex); } } - + public static void sendProxyEvent(ProxyMessage message) { if (proxyServer != null && message.getPath() != null) synchronized(proxyClients) { - for (Iterator iter = proxyClients.iterator(); iter.hasNext();) { - ProxyClientConnection client = (ProxyClientConnection)iter.next(); + for (ProxyClientConnection client : proxyClients) { client.sendMessage(message); } } } - + public static void reportConnections(int logLevel) { synchronized(proxyClients) { Logger.msg(logLevel, "Currently connected proxy clients:"); - for (Iterator iter = proxyClients.iterator(); iter.hasNext();) { - ProxyClientConnection client = (ProxyClientConnection)iter.next(); + for (ProxyClientConnection client : proxyClients) { Logger.msg(logLevel, " "+client); } } } - + public static void shutdownServer() { if (proxyServer != null) { Logger.msg(1, "EntityProxyManager: Closing Server."); proxyServer.stopListening(); } } - + public static void registerProxyClient(ProxyClientConnection client) { synchronized(proxyClients) { proxyClients.add(client); } } - + public static void unRegisterProxyClient(ProxyClientConnection client) { synchronized(proxyClients) { proxyClients.remove(client); diff --git a/source/com/c2kernel/entity/proxy/EntityProxyObserver.java b/source/com/c2kernel/entity/proxy/EntityProxyObserver.java old mode 100755 new mode 100644 index 985143d..3ddb99c --- a/source/com/c2kernel/entity/proxy/EntityProxyObserver.java +++ b/source/com/c2kernel/entity/proxy/EntityProxyObserver.java @@ -4,14 +4,14 @@ import com.c2kernel.entity.C2KLocalObject; -public interface EntityProxyObserver +public interface EntityProxyObserver { /************************************************************************** * Subscribed items are broken apart and fed one by one to these methods. * Replacement after an event is done by feeding the new memberbase with the same id. * ID could be an XPath? **************************************************************************/ - public void add(C2KLocalObject contents); + public void add(V contents); /************************************************************************** * the 'type' parameter should be an indication of the type of object @@ -22,4 +22,6 @@ public interface EntityProxyObserver * the subscribe method of ItemProxy. **************************************************************************/ public void remove(String id); + + public void control(String control, String msg); } diff --git a/source/com/c2kernel/entity/proxy/ItemProxy.java b/source/com/c2kernel/entity/proxy/ItemProxy.java index 702dd26..658e0c8 100644 --- a/source/com/c2kernel/entity/proxy/ItemProxy.java +++ b/source/com/c2kernel/entity/proxy/ItemProxy.java @@ -18,7 +18,9 @@ import com.c2kernel.common.InvalidTransitionException; import com.c2kernel.common.ObjectAlreadyExistsException; import com.c2kernel.common.ObjectNotFoundException; import com.c2kernel.common.PersistencyException; -import com.c2kernel.entity.*; +import com.c2kernel.entity.Item; +import com.c2kernel.entity.ItemHelper; +import com.c2kernel.entity.ManageableEntity; import com.c2kernel.entity.agent.Job; import com.c2kernel.entity.agent.JobArrayList; import com.c2kernel.lifecycle.instance.stateMachine.Transitions; @@ -43,10 +45,11 @@ public class ItemProxy extends EntityProxy throws ObjectNotFoundException { super(ior, systemKey); - + } - public ManageableEntity narrow() throws ObjectNotFoundException + @Override + public ManageableEntity narrow() throws ObjectNotFoundException { try { return ItemHelper.narrow(mIOR); @@ -86,29 +89,29 @@ public class ItemProxy extends EntityProxy } catch (Exception e) { Logger.error(e); throw new PersistencyException("Could not store property"); - } + } } /************************************************************************** * **************************************************************************/ - protected void requestAction( Job thisJob ) - throws AccessRightsException, - InvalidTransitionException, - ObjectNotFoundException, - InvalidDataException, + protected void requestAction( Job thisJob ) + throws AccessRightsException, + InvalidTransitionException, + ObjectNotFoundException, + InvalidDataException, PersistencyException, ObjectAlreadyExistsException { - String outcome = thisJob.getOutcomeString(); + String outcome = thisJob.getOutcomeString(); // check fields that should have been filled in - if (outcome==null) - if (thisJob.isOutcomeUsed()) + if (outcome==null) + if (thisJob.isOutcomeUsed()) throw new InvalidDataException("Outcome is required.", ""); else - outcome=""; - - if (thisJob.getAgentId() == -1) - throw new InvalidDataException("No Agent specified.", ""); + outcome=""; + + if (thisJob.getAgentId() == -1) + throw new InvalidDataException("No Agent specified.", ""); Logger.msg(7, "ItemProxy - executing "+thisJob.getStepPath()+" for "+thisJob.getAgentName()); requestAction (thisJob.getAgentId(), thisJob.getStepPath(), @@ -128,7 +131,7 @@ public class ItemProxy extends EntityProxy PersistencyException, ObjectAlreadyExistsException { - ((Item)getEntity()).requestAction( agentId, + ((Item)getEntity()).requestAction( agentId, stepPath, transitionID, requestData ); @@ -139,9 +142,9 @@ public class ItemProxy extends EntityProxy **************************************************************************/ public String queryLifeCycle( int agentId, boolean filter - ) - throws AccessRightsException, - ObjectNotFoundException, + ) + throws AccessRightsException, + ObjectNotFoundException, PersistencyException { return ((Item)getEntity()).queryLifeCycle( agentId, @@ -168,15 +171,15 @@ public class ItemProxy extends EntityProxy } return thisJobList.list; } - + public ArrayList getJobList(AgentProxy agent) throws AccessRightsException, ObjectNotFoundException, PersistencyException { - return getJobList(agent.getSystemKey()); + return getJobList(agent.getSystemKey()); } - + private ArrayList getJobList(int agentId) throws AccessRightsException, ObjectNotFoundException, @@ -189,7 +192,7 @@ public class ItemProxy extends EntityProxy throws AccessRightsException, ObjectNotFoundException, PersistencyException { - + ArrayList jobList = getJobList(agentId); for (Job job : jobList) { int transition = job.getPossibleTransition(); @@ -200,7 +203,7 @@ public class ItemProxy extends EntityProxy return null; } - + public Job getJobByName(String actName, AgentProxy agent) throws AccessRightsException, ObjectNotFoundException, diff --git a/source/com/c2kernel/entity/proxy/MemberControl.java b/source/com/c2kernel/entity/proxy/MemberControl.java deleted file mode 100755 index 5f483ae..0000000 --- a/source/com/c2kernel/entity/proxy/MemberControl.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.c2kernel.entity.proxy; - -import com.c2kernel.entity.C2KLocalObject; - - -/** - * @version $Revision: 1.2 $ $Date: 2004/02/04 11:02:44 $ - * @author $Author: abranson $ - */ - -public class MemberControl implements C2KLocalObject { - - public static final int ERROR = -1; - public static final int END = -2; - public static MemberControl theEND = new MemberControl(END, null); - private int id; - private String name; - - public MemberControl(int code, String msg) { - this.setID(code); - switch (code) { - case MemberControl.ERROR: - this.setName("ERROR: The path "+msg+" was not found."); - break; - case MemberControl.END: - this.setName("END: End of preload"); - break; - default: - this.setName("Unsupported control message code: "+code); - } - } - - public String toString() { - return "MemberControl: "+this.getName(); - } - - public int getID() { return id; } - public void setID(int id) { this.id = id; } - public String getName() { return name; } - public void setName(String name) { this.name = name; } - public String getClusterType() { return null; } - -} diff --git a/source/com/c2kernel/entity/proxy/MemberSubscription.java b/source/com/c2kernel/entity/proxy/MemberSubscription.java index ba2d725..157297f 100644 --- a/source/com/c2kernel/entity/proxy/MemberSubscription.java +++ b/source/com/c2kernel/entity/proxy/MemberSubscription.java @@ -8,31 +8,33 @@ import com.c2kernel.common.ObjectNotFoundException; import com.c2kernel.entity.C2KLocalObject; import com.c2kernel.utils.Logger; -public class MemberSubscription implements Runnable { +public class MemberSubscription implements Runnable { + public static final String ERROR = "Error"; + public static final String END = "theEND"; + EntityProxy subject; String interest; // keep the subscriber by weak reference, so it is not kept from the garbage collector if no longer used - WeakReference observerReference; + WeakReference> observerReference; ArrayList contents = new ArrayList(); boolean preLoad; - public MemberSubscription(EntityProxy subject, String interest, - EntityProxyObserver observer, boolean preLoad) { + public MemberSubscription(EntityProxyObserver observer, String interest, boolean preLoad) { setObserver(observer); this.interest = interest; - this.subject = subject; this.preLoad = preLoad; } - public void run() { + @Override + public void run() { Thread.currentThread().setName("Member Subscription: "+subject.getSystemKey()+":"+interest); if (preLoad) loadChildren(); } - + private void loadChildren() { - C2KLocalObject newMember; - EntityProxyObserver observer = getObserver(); - if (observer == null) return; //reaped + C newMember; + EntityProxyObserver observer = getObserver(); + if (observer == null) return; //reaped try { // fetch contents of path String children = subject.queryData(interest+"/all"); @@ -40,22 +42,17 @@ public class MemberSubscription implements Runnable { ArrayList newContents = new ArrayList(); while (tok.hasMoreTokens()) newContents.add(tok.nextToken()); - + // look to see what's new for (String newChild: newContents) { - + // load child object try { - newMember = subject.getObject(interest+"/"+newChild); + newMember = (C)subject.getObject(interest+"/"+newChild); contents.remove(newChild); - } catch (ObjectNotFoundException ex) { - newMember = new MemberControl(MemberControl.ERROR, "Listed member "+newChild+" was not found."); - } - try { observer.add(newMember); - } catch (Throwable ex) { - Logger.error("Error publishing member to "+observer); - Logger.error(ex); + } catch (ObjectNotFoundException ex) { + observer.control(ERROR, "Listed member "+newChild+" was not found."); } } // report what's left in old contents as deleted @@ -65,24 +62,24 @@ public class MemberSubscription implements Runnable { //replace contents arraylist contents = newContents; //report that we're done - observer.add(MemberControl.theEND); + observer.control(END, null); } catch (Exception ex) { - observer.add(new MemberControl(MemberControl.ERROR, "Query on "+interest+" failed with "+ex)); - } + observer.control(ERROR, "Query on "+interest+" failed with "+ex); + } } - + public boolean isRelevant(String path) { Logger.msg(7, "Checking relevance of "+path+" to "+interest); return (path.startsWith(interest)); } - + public void update(String path, boolean deleted) { - EntityProxyObserver observer = getObserver(); + EntityProxyObserver observer = getObserver(); if (observer == null) return; //reaped Logger.msg(7, "Processing proxy message path "+path +" for "+observer+". Interest: "+interest+" Was Deleted:"+deleted); if (!path.startsWith(interest)) // doesn't concern us return; - + if (path.equals(interest)) // refresh contents loadChildren(); else { @@ -92,9 +89,9 @@ public class MemberSubscription implements Runnable { contents.remove(name); observer.remove(name); } - else { + else { try { - C2KLocalObject newMember = subject.getObject(path); + C newMember = (C)subject.getObject(path); Logger.msg(4, "Adding "+path); contents.add(name); observer.add(newMember); @@ -102,17 +99,20 @@ public class MemberSubscription implements Runnable { Logger.error("Member Subscription: could not load "+path); Logger.error(e); } - } + } } } - - public void setObserver(EntityProxyObserver observer) { - observerReference = new WeakReference(observer); + + public void setObserver(EntityProxyObserver observer) { + observerReference = new WeakReference>(observer); } - public EntityProxyObserver getObserver() { - EntityProxyObserver observer = (EntityProxyObserver)observerReference.get(); - return observer; + public void setSubject(EntityProxy subject) { + this.subject = subject; + } + + public EntityProxyObserver getObserver() { + return observerReference.get(); } } diff --git a/source/com/c2kernel/entity/proxy/ProxyClientConnection.java b/source/com/c2kernel/entity/proxy/ProxyClientConnection.java index f041012..9687f22 100644 --- a/source/com/c2kernel/entity/proxy/ProxyClientConnection.java +++ b/source/com/c2kernel/entity/proxy/ProxyClientConnection.java @@ -41,17 +41,20 @@ public class ProxyClientConnection implements SocketHandler { } - public String getName() { + @Override + public String getName() { return "Proxy Client Connection"; } - public boolean isBusy() { + @Override + public boolean isBusy() { return clientSocket != null; } - - public synchronized void setSocket(Socket newSocket) { + + @Override + public synchronized void setSocket(Socket newSocket) { try { - Logger.msg(1, "Proxy Client Connection "+thisClientId+" connect from "+newSocket.getInetAddress()+":"+newSocket.getPort()); + Logger.msg(1, "Proxy Client Connection "+thisClientId+" connect from "+newSocket.getInetAddress()+":"+newSocket.getPort()); newSocket.setSoTimeout(500); clientSocket = newSocket; response = new PrintWriter(clientSocket.getOutputStream(), true); @@ -66,11 +69,12 @@ public class ProxyClientConnection implements SocketHandler { closeSocket(); } } - + /** * Main loop. Reads proxy commands from the client and acts on them. */ - public void run() { + @Override + public void run() { Thread.currentThread().setName("Proxy Client Connection: "+clientSocket.getInetAddress()); Logger.msg(7, "ProxyClientConnection "+thisClientId+" - Setting up proxy client connection with "+clientSocket.getInetAddress()); try { @@ -87,7 +91,7 @@ public class ProxyClientConnection implements SocketHandler { } catch (InvalidDataException ex) { // invalid proxy message Logger.error("ProxyClientConnection "+thisClientId+" - Invalid proxy message: "+input); } - + } } catch (IOException ex) { if (!closing) @@ -96,68 +100,70 @@ public class ProxyClientConnection implements SocketHandler { closeSocket(); Logger.msg(1, "ProxyClientConnection "+thisClientId+" closed."); } - + private void processMessage(ProxyMessage message) throws InvalidDataException { - + // proxy disconnection if (message.getPath().equals(ProxyMessage.BYEPATH)) { Logger.msg(7, "ProxyClientConnection "+thisClientId+" disconnecting"); closeSocket(); } - + // proxy checking connection - else if (message.getPath().equals(ProxyMessage.PINGPATH)) + else if (message.getPath().equals(ProxyMessage.PINGPATH)) response.println(ProxyMessage.pingMessage); - + // new subscription to entity changes else if (message.getPath().equals(ProxyMessage.ADDPATH)) { Logger.msg(7, "ProxyClientConnection "+thisClientId+" subscribed to "+message.getSysKey()); synchronized (sysKeys) { sysKeys.add(new Integer(message.getSysKey())); - } + } } - - // remove of subscription to entity changes + + // remove of subscription to entity changes else if (message.getPath().equals(ProxyMessage.DELPATH)) { synchronized (sysKeys) { sysKeys.remove(new Integer(message.getSysKey())); - } + } Logger.msg(7, "ProxyClientConnection "+thisClientId+" unsubscribed from "+message.getSysKey()); } - + else // unknown message - Logger.error("ProxyClientConnection "+thisClientId+" - Unknown message type: "+message); - - } - + Logger.error("ProxyClientConnection "+thisClientId+" - Unknown message type: "+message); + + } + public synchronized void sendMessage(ProxyMessage message) { - if (clientSocket==null) return; // idle - boolean relevant = message.getSysKey() == ProxyMessage.NA; + if (clientSocket==null) return; // idle + boolean relevant = message.getSysKey() == ProxyMessage.NA; synchronized (sysKeys) { - for (Iterator iter = sysKeys.iterator(); iter.hasNext() && !relevant;) { - Integer thisKey = (Integer)iter.next(); + for (Iterator iter = sysKeys.iterator(); iter.hasNext() && !relevant;) { + Integer thisKey = iter.next(); if (thisKey.intValue() == message.getSysKey()) relevant = true; } } if (!relevant) return; // not for our client - + response.println(message); } - - public void shutdown() { + + @Override + public void shutdown() { if (isBusy()) { closing = true; Logger.msg("ProxyClientConnection "+thisClientId+" closing."); closeSocket(); } } - - public String toString() { + + @Override + public String toString() { if (clientSocket == null) return thisClientId+": idle"; else return thisClientId+": "+clientSocket.getInetAddress(); } - + private synchronized void closeSocket() { if (clientSocket==null) return; try { @@ -171,9 +177,9 @@ public class ProxyClientConnection implements SocketHandler { synchronized (sysKeys) { sysKeys = null; } - + clientSocket = null; } - + } diff --git a/source/com/c2kernel/entity/proxy/ProxyMessage.java b/source/com/c2kernel/entity/proxy/ProxyMessage.java old mode 100755 new mode 100644 index 66f1f34..b312a44 --- a/source/com/c2kernel/entity/proxy/ProxyMessage.java +++ b/source/com/c2kernel/entity/proxy/ProxyMessage.java @@ -18,24 +18,24 @@ import com.c2kernel.common.InvalidDataException; **************************************************************************/ public class ProxyMessage { - + // special server message paths - public static final String BYEPATH = "bye"; + public static final String BYEPATH = "bye"; public static final String ADDPATH = "add"; public static final String DELPATH = "del"; public static final String PINGPATH = "ping"; public static final boolean ADDED = false; public static final boolean DELETED = true; public static final int NA = -1; - - static ProxyMessage byeMessage = new ProxyMessage(NA, BYEPATH, ADDED); - static ProxyMessage pingMessage = new ProxyMessage(NA, PINGPATH, ADDED); - + + static ProxyMessage byeMessage = new ProxyMessage(NA, BYEPATH, ADDED); + static ProxyMessage pingMessage = new ProxyMessage(NA, PINGPATH, ADDED); + private int sysKey = NA; private String path = ""; private String server = null; private boolean state = ADDED; - + public ProxyMessage() { super(); } @@ -45,7 +45,7 @@ public class ProxyMessage { setPath(path); setState(state); } - + public ProxyMessage(String line) throws InvalidDataException, IOException { if (line == null) throw new IOException("Null proxy message"); @@ -56,10 +56,10 @@ public class ProxyMessage { path = tok.nextToken(); if (path.startsWith("-")) { state = DELETED; - path = path.substring(1); + path = path.substring(1); } } - + public ProxyMessage(DatagramPacket packet) throws InvalidDataException, IOException { this(new String(packet.getData())); } @@ -67,7 +67,7 @@ public class ProxyMessage { public int getSysKey() { return sysKey; } - + public void setSysKey(int sysKey) { this.sysKey = sysKey; } @@ -75,30 +75,31 @@ public class ProxyMessage { public String getPath() { return path; } - + public void setPath(String newPath) { this.path = newPath; } - + public boolean getState() { return state; } - + public void setState(boolean state) { this.state = state; } - - public String toString() { - return sysKey+":"+(state?"-":"")+path; + + @Override + public String toString() { + return sysKey+":"+(state?"-":"")+path; } public DatagramPacket getPacket(ProxySubscriber host) { return getPacket(host.getHost(), host.getPort()); } - + public DatagramPacket getPacket(InetAddress host, int port) { byte[] packetString = toString().getBytes(); return new DatagramPacket(packetString, packetString.length, host, port); - } + } public String getServer() { return server; diff --git a/source/com/c2kernel/entity/proxy/ProxyServerConnection.java b/source/com/c2kernel/entity/proxy/ProxyServerConnection.java old mode 100755 new mode 100644 index 191492f..6807953 --- a/source/com/c2kernel/entity/proxy/ProxyServerConnection.java +++ b/source/com/c2kernel/entity/proxy/ProxyServerConnection.java @@ -10,7 +10,11 @@ package com.c2kernel.entity.proxy; -import java.io.*; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.InterruptedIOException; +import java.io.PrintWriter; import java.net.Socket; import com.c2kernel.common.InvalidDataException; @@ -30,7 +34,7 @@ public class ProxyServerConnection extends Thread PrintWriter serverStream; boolean listening = false; static boolean isServer = false; - + /** * Create an entity proxy manager to listen for proxy events and reap unused proxies */ @@ -43,8 +47,9 @@ public class ProxyServerConnection extends Thread listening = true; start(); } - - public void run() { + + @Override + public void run() { Thread.currentThread().setName("Proxy Client Connection Listener to "+serverName+":"+serverPort); while (listening) { try { @@ -72,14 +77,14 @@ public class ProxyServerConnection extends Thread try { serverStream.close(); serverConnection.close(); - } catch (IOException e1) { } + } catch (IOException e1) { } + - serverStream = null; serverConnection = null; } } - + if (serverStream != null) { try { Logger.msg(1, "Disconnecting from proxy server on "+serverName+":"+serverPort); @@ -90,9 +95,9 @@ public class ProxyServerConnection extends Thread } catch (Exception e) { Logger.error("Error disconnecting from proxy server."); } - } + } } - + public void connect() { Logger.msg(3, "ProxyServerConnection - connecting to proxy server on "+serverName+":"+serverPort); try { @@ -111,12 +116,12 @@ public class ProxyServerConnection extends Thread serverIsActive = false; } } - + public void shutdown() { Logger.msg("Proxy Client: flagging shutdown."); listening = false; } - + /** * @param sub */ diff --git a/source/com/c2kernel/entity/proxy/ProxySubscriber.java b/source/com/c2kernel/entity/proxy/ProxySubscriber.java old mode 100755 new mode 100644 index 67d0a60..8cb85fa --- a/source/com/c2kernel/entity/proxy/ProxySubscriber.java +++ b/source/com/c2kernel/entity/proxy/ProxySubscriber.java @@ -17,9 +17,9 @@ import com.c2kernel.common.InvalidDataException; public class ProxySubscriber { - private InetAddress host; + private InetAddress host; private int port; - public ArrayList sysKeys = new ArrayList(); + public ArrayList sysKeys = new ArrayList(); public ProxySubscriber(DatagramPacket packet) throws InvalidDataException { host = packet.getAddress(); diff --git a/source/com/c2kernel/entity/transfer/TransferItem.java b/source/com/c2kernel/entity/transfer/TransferItem.java index e4e84ec..9234650 100644 --- a/source/com/c2kernel/entity/transfer/TransferItem.java +++ b/source/com/c2kernel/entity/transfer/TransferItem.java @@ -1,17 +1,23 @@ package com.c2kernel.entity.transfer; import java.io.File; -import java.util.*; +import java.util.ArrayList; +import java.util.Enumeration; import com.c2kernel.common.ObjectNotFoundException; -import com.c2kernel.entity.*; +import com.c2kernel.entity.C2KLocalObject; +import com.c2kernel.entity.TraceableEntity; import com.c2kernel.lifecycle.instance.Workflow; -import com.c2kernel.lookup.*; +import com.c2kernel.lookup.DomainPath; +import com.c2kernel.lookup.EntityPath; import com.c2kernel.persistency.ClusterStorage; import com.c2kernel.persistency.outcome.Outcome; import com.c2kernel.process.Gateway; -import com.c2kernel.property.*; -import com.c2kernel.utils.*; +import com.c2kernel.property.Property; +import com.c2kernel.property.PropertyArrayList; +import com.c2kernel.utils.CastorXMLUtility; +import com.c2kernel.utils.FileStringUtility; +import com.c2kernel.utils.Logger; public class TransferItem { public ArrayList domainPaths; @@ -31,7 +37,7 @@ public class TransferItem { this.sysKey = sysKey; domainPaths = new ArrayList(); Property name = (Property)Gateway.getStorage().get(sysKey, ClusterStorage.PROPERTY + "/Name", null); - Enumeration paths = Gateway.getLDAPLookup().search(new DomainPath(), name.getValue()); + Enumeration paths = Gateway.getLDAPLookup().search(new DomainPath(), name.getValue()); while (paths.hasMoreElements()) { DomainPath thisPath = (DomainPath)paths.nextElement(); domainPaths.add(thisPath.toString()); @@ -43,8 +49,8 @@ public class TransferItem { String[] contents = Gateway.getStorage().getClusterContents(sysKey, path); if (contents.length > 0) { FileStringUtility.createNewDir(dir.getCanonicalPath()); - for (int i = 0; i < contents.length; i++) { - exportItem(new File(dir, contents[i]), path + "/" + contents[i]); + for (String content : contents) { + exportItem(new File(dir, content), path + "/" + content); } } else { //no children, try to dump object try { @@ -66,12 +72,11 @@ public class TransferItem { } catch (Exception ex) { } - ArrayList events, outcomes, viewpoints = new ArrayList(); // retrieve objects - ArrayList objectFiles = FileStringUtility.listDir(dir.getCanonicalPath(), false, true); + ArrayList objectFiles = FileStringUtility.listDir(dir.getCanonicalPath(), false, true); ArrayList objects = new ArrayList(); - for (Iterator iter = objectFiles.iterator(); iter.hasNext();) { - String element = (String)iter.next(); + for (Object name : objectFiles) { + String element = (String)name; String xmlFile = FileStringUtility.file2String(element); C2KLocalObject newObj; String choppedPath = element.substring(dir.getCanonicalPath().length()+1, element.length()-4); @@ -88,12 +93,11 @@ public class TransferItem { EntityPath entityPath = new EntityPath(sysKey); TraceableEntity newItem = (TraceableEntity)Gateway.getCorbaServer().createEntity(entityPath); Gateway.getLDAPLookup().add(entityPath); - + PropertyArrayList props = new PropertyArrayList(); Workflow wf = null; // put objects - for (Iterator iter = objects.iterator(); iter.hasNext();) { - C2KLocalObject obj = (C2KLocalObject)iter.next(); + for (C2KLocalObject obj : objects) { if (obj instanceof Property) props.list.add((Property)obj); else if (obj instanceof Workflow) @@ -102,7 +106,7 @@ public class TransferItem { if (wf == null) throw new Exception("No workflow found in import for "+sysKey); - + // init item newItem.initialise(importAgentId, CastorXMLUtility.marshall(props), CastorXMLUtility.marshall(wf.search("workflow/domain"))); @@ -113,19 +117,17 @@ public class TransferItem { importByType(ClusterStorage.VIEWPOINT, objects); Gateway.getStorage().commit(this); // add domPaths - for (Iterator iter = domainPaths.iterator(); iter.hasNext();) { - String element = (String)iter.next(); + for (String element : domainPaths) { DomainPath newPath = new DomainPath(element, entityPath); Gateway.getLDAPLookup().add(newPath); } } - - private void importByType(String type, ArrayList objects) throws Exception { - for (Iterator iter = objects.iterator(); iter.hasNext();) { - C2KLocalObject element = (C2KLocalObject)iter.next(); + + private void importByType(String type, ArrayList objects) throws Exception { + for (C2KLocalObject element : objects) { if (element.getClusterType().equals(type)) Gateway.getStorage().put(sysKey, element, this); } - + } } \ No newline at end of file diff --git a/source/com/c2kernel/entity/transfer/TransferSet.java b/source/com/c2kernel/entity/transfer/TransferSet.java index f67ba9c..71a593a 100644 --- a/source/com/c2kernel/entity/transfer/TransferSet.java +++ b/source/com/c2kernel/entity/transfer/TransferSet.java @@ -2,7 +2,6 @@ package com.c2kernel.entity.transfer; import java.io.File; import java.util.ArrayList; -import java.util.Iterator; import com.c2kernel.lookup.EntityPath; import com.c2kernel.lookup.NextKeyManager; @@ -23,36 +22,35 @@ import com.c2kernel.utils.Logger; public class TransferSet { public ArrayList items; - + public TransferSet() { } - + public TransferSet(int[] sysKeys) { items = new ArrayList(); - for (int i = 0; i < sysKeys.length; i++) { + for (int sysKey : sysKeys) { try { - items.add(new TransferItem(sysKeys[i])); + items.add(new TransferItem(sysKey)); } catch (Exception ex) { - Logger.error("Could not add item "+sysKeys[i]); + Logger.error("Could not add item "+sysKey); Logger.error(ex); } } } - + public void exportPackage(File dir) throws Exception { if (items==null || items.size() == 0) throw new Exception("Nothing to dump"); FileStringUtility.createNewDir(dir.getAbsolutePath()); - for (Iterator iter = items.iterator(); iter.hasNext();) { - TransferItem element = (TransferItem)iter.next(); + for (TransferItem element : items) { try { element.exportItem(new File(dir, String.valueOf(element.sysKey)), "/"); } catch (Exception ex) { - Logger.error("Error dumping item "+element.sysKey); - Logger.error(ex); + Logger.error("Error dumping item "+element.sysKey); + Logger.error(ex); } } - + try { String self = CastorXMLUtility.marshall(this); FileStringUtility.string2File(new File(dir, "transferSet.xml"), self); @@ -61,10 +59,9 @@ public class TransferSet { Logger.error(ex); } } - + public void importPackage(File rootDir) { - for (Iterator iter = items.iterator(); iter.hasNext();) { - TransferItem element = (TransferItem)iter.next(); + for (TransferItem element : items) { Logger.msg(5, "Importing "+element.sysKey); try { element.importItem(new File(rootDir, String.valueOf(element.sysKey))); @@ -76,24 +73,23 @@ public class TransferSet { } checkLastKey(); } - + private void checkLastKey() - { + { // find highest key in out import set int packageLastKey = 0; - for (Iterator iter = items.iterator(); iter.hasNext();) { - TransferItem element = (TransferItem)iter.next(); + for (TransferItem element : items) { if (element.sysKey > packageLastKey) packageLastKey = element.sysKey; } - + try { // find the current last key NextKeyManager nextKeyMan = Gateway.getLDAPLookup().getNextKeyManager(); EntityPath lastKey = nextKeyMan.getLastEntityPath(); Logger.msg(1, "Last key imported was "+packageLastKey+". LDAP lastkey was "+lastKey.getSysKey()); - + if (packageLastKey > lastKey.getSysKey()) { // set new last Logger.msg(1, "Updating lastKey to "+packageLastKey); nextKeyMan.writeLastEntityKey(packageLastKey); @@ -102,6 +98,6 @@ public class TransferSet { catch (Exception ex) { Logger.error("Exception::LoadKeys::processFile() " + ex); - } + } } } diff --git a/source/com/c2kernel/events/Event.java b/source/com/c2kernel/events/Event.java old mode 100755 new mode 100644 index e3ab8b3..18310ce --- a/source/com/c2kernel/events/Event.java +++ b/source/com/c2kernel/events/Event.java @@ -54,13 +54,14 @@ public class Event implements C2KLocalObject /** * Set the Event Name, in parameter is a String */ - public void setName(String name) + @Override + public void setName(String name) { mName = name; try { mID = Integer.parseInt(name); } catch (NumberFormatException ex) { - mID = -1; + mID = -1; } } @@ -87,7 +88,7 @@ public class Event implements C2KLocalObject { mStepType = type; } - + public void setCurrentState(int state) { mCurrentState = state; @@ -100,7 +101,7 @@ public class Event implements C2KLocalObject { mAgentName = agentName; } - + public void setAgentCentre(String agentCentre) { mAgentCentre = agentCentre; @@ -146,7 +147,8 @@ public class Event implements C2KLocalObject /** * Return the Event Name */ - public String getName() + @Override + public String getName() { return mName; } @@ -174,7 +176,7 @@ public class Event implements C2KLocalObject { return mStepType; } - + public int getCurrentState() { return mCurrentState; @@ -189,7 +191,7 @@ public class Event implements C2KLocalObject return mAgentCentre+"/"+mAgentName; return mAgentName; } - + public String getAgentRole() { return mAgentRole; @@ -212,26 +214,26 @@ public class Event implements C2KLocalObject { return Event.timeToString(mTimeStamp); } - + public static String timeToString(GTimeStamp timeStamp) { StringBuffer time = new StringBuffer().append(timeStamp.mYear).append("-"); - + if (timeStamp.mMonth<10) time.append("0"); time.append(timeStamp.mMonth).append("-"); - + if (timeStamp.mDay<10) time.append("0"); time.append(timeStamp.mDay).append(" "); - + if (timeStamp.mHour<10) time.append("0"); time.append(timeStamp.mHour).append(":"); - + if (timeStamp.mMinute<10) time.append("0"); time.append(timeStamp.mMinute).append(":"); - + if (timeStamp.mSecond<10) time.append("0"); time.append(timeStamp.mSecond); - - return time.toString(); + + return time.toString(); } public void setTimeString(String time) throws Exception @@ -259,11 +261,11 @@ public class Event implements C2KLocalObject } - + static public GTimeStamp getGMT() { java.util.Calendar now = Calendar.getInstance(); - + return new GTimeStamp( now.get(Calendar.YEAR), now.get(Calendar.MONTH)+1, now.get(Calendar.DAY_OF_MONTH), @@ -275,6 +277,7 @@ public class Event implements C2KLocalObject /** * @see com.c2kernel.entity.C2KLocalObject#getClusterType() */ + @Override public String getClusterType() { return ClusterStorage.HISTORY; } diff --git a/source/com/c2kernel/events/History.java b/source/com/c2kernel/events/History.java old mode 100755 new mode 100644 index bc806dd..a964a72 --- a/source/com/c2kernel/events/History.java +++ b/source/com/c2kernel/events/History.java @@ -1,8 +1,6 @@ package com.c2kernel.events; -import com.c2kernel.common.ObjectNotFoundException; -import com.c2kernel.lookup.InvalidEntityPathException; import com.c2kernel.persistency.ClusterStorage; import com.c2kernel.persistency.RemoteMap; import com.c2kernel.utils.Logger; @@ -14,19 +12,18 @@ import com.c2kernel.utils.Logger; * $Date: 2004/07/21 09:55:11 $ * * Copyright (C) 2003 CERN - European Organization for Nuclear Research - * All rights reserved. + * All rights reserved. */ -public class History extends RemoteMap { - +public class History extends RemoteMap { + int lastID = -1; - public History(int sysKey, Object locker) - throws ObjectNotFoundException, InvalidEntityPathException { + public History(int sysKey, Object locker) { super(sysKey, ClusterStorage.HISTORY, locker); } - public Event addEvent(String agentName, String agentRole, + public Event addEvent(String agentName, String agentRole, int stepTransitionId, String stepName, String stepPath, @@ -45,8 +42,8 @@ public class History extends RemoteMap { newEvent.setTimeStamp(Event.getGMT()); return storeNewEvent(newEvent); } - - public Event addEvent(String agentName, String agentRole, + + public Event addEvent(String agentName, String agentRole, int stepTransitionId, String stepName, String stepPath, @@ -66,27 +63,28 @@ public class History extends RemoteMap { newEvent.setTimeString(timeString); return storeNewEvent(newEvent); } - + private Event storeNewEvent(Event newEvent) { synchronized (this) { int newEventID = getLastId()+1; newEvent.setID(newEventID); if (put(newEvent.getName(), newEvent) != null) { lastID = newEventID; - return newEvent; + return newEvent; } else { Logger.error("History.addEvent() - Event storage failed!"); return null; } - } + } } - + public Event getEvent(int id) { - return (Event)get(String.valueOf(id)); + return get(String.valueOf(id)); } - - public Object remove(Object key) { + + @Override + public Event remove(Object key) { // forbidden return null; } diff --git a/source/com/c2kernel/graph/controller/AutoScrollController.java b/source/com/c2kernel/graph/controller/AutoScrollController.java old mode 100755 new mode 100644 index d1e0d8d..aa04609 --- a/source/com/c2kernel/graph/controller/AutoScrollController.java +++ b/source/com/c2kernel/graph/controller/AutoScrollController.java @@ -20,7 +20,8 @@ public class AutoScrollController implements MouseMotionListener } - public void mouseDragged(MouseEvent me) + @Override + public void mouseDragged(MouseEvent me) { Point mousePoint = null; @@ -33,7 +34,8 @@ public class AutoScrollController implements MouseMotionListener } - public void mouseMoved(MouseEvent me) + @Override + public void mouseMoved(MouseEvent me) { } } diff --git a/source/com/c2kernel/graph/controller/DeletionController.java b/source/com/c2kernel/graph/controller/DeletionController.java old mode 100755 new mode 100644 index 38e8347..44ea990 --- a/source/com/c2kernel/graph/controller/DeletionController.java +++ b/source/com/c2kernel/graph/controller/DeletionController.java @@ -47,7 +47,8 @@ public class DeletionController extends KeyAdapter implements Observer, ActionLi // Invoked by the graph model - public void update(Observable o, Object arg) + @Override + public void update(Observable o, Object arg) { SelectionChangedEvent event = null; DirectedEdge selectedEdge = null; @@ -69,7 +70,8 @@ public class DeletionController extends KeyAdapter implements Observer, ActionLi // Invoked by the graph panel - public void keyPressed(KeyEvent e) + @Override + public void keyPressed(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_DELETE && mGraphModelManager.isEditable()) { @@ -79,7 +81,8 @@ public class DeletionController extends KeyAdapter implements Observer, ActionLi // Invoked by the delete button - public void actionPerformed(ActionEvent ae) + @Override + public void actionPerformed(ActionEvent ae) { if(mGraphModelManager != null && mGraphModelManager.isEditable()) { diff --git a/source/com/c2kernel/graph/controller/EdgeConstructionController.java b/source/com/c2kernel/graph/controller/EdgeConstructionController.java old mode 100755 new mode 100644 index fdf52bf..00ea45b --- a/source/com/c2kernel/graph/controller/EdgeConstructionController.java +++ b/source/com/c2kernel/graph/controller/EdgeConstructionController.java @@ -3,7 +3,6 @@ package com.c2kernel.graph.controller; import java.awt.Point; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; -import java.awt.event.MouseMotionListener; import com.c2kernel.graph.model.GraphModelManager; import com.c2kernel.graph.model.GraphPoint; @@ -12,7 +11,7 @@ import com.c2kernel.graph.view.EditorModeListener; import com.c2kernel.graph.view.EditorToolBar; -public class EdgeConstructionController extends MouseAdapter implements MouseMotionListener, EditorModeListener +public class EdgeConstructionController extends MouseAdapter implements EditorModeListener { private GraphModelManager mGraphModelManager = null; private EditorToolBar mEditorToolBar = null; @@ -49,7 +48,8 @@ public class EdgeConstructionController extends MouseAdapter implements MouseMot private Action mSetOriginVertex = new Action() { - public void doIt(Object data) + @Override + public void doIt(Object data) { if(mGraphModelManager != null) { @@ -61,7 +61,8 @@ public class EdgeConstructionController extends MouseAdapter implements MouseMot private Action mSetEndPoint = new Action() { - public void doIt(Object data) + @Override + public void doIt(Object data) { if(mGraphModelManager != null) { @@ -73,7 +74,8 @@ public class EdgeConstructionController extends MouseAdapter implements MouseMot private Action mClearEdge = new Action() { - public void doIt(Object data) + @Override + public void doIt(Object data) { if(mGraphModelManager != null) { @@ -86,7 +88,8 @@ public class EdgeConstructionController extends MouseAdapter implements MouseMot private Action mCreateEdge = new Action() { - public void doIt(Object data) + @Override + public void doIt(Object data) { if((mGraphModelManager != null) && (mEditorToolBar != null) && mGraphModelManager.isEditable()) { @@ -170,7 +173,8 @@ public class EdgeConstructionController extends MouseAdapter implements MouseMot } - public void editorModeChanged(String idOfNewMode) + @Override + public void editorModeChanged(String idOfNewMode) { if(idOfNewMode.equals("Edge")) { @@ -183,7 +187,8 @@ public class EdgeConstructionController extends MouseAdapter implements MouseMot } - public void mousePressed(MouseEvent me) + @Override + public void mousePressed(MouseEvent me) { Vertex vertex = null; Point mousePoint = null; @@ -203,7 +208,8 @@ public class EdgeConstructionController extends MouseAdapter implements MouseMot } - public void mouseReleased(MouseEvent me) + @Override + public void mouseReleased(MouseEvent me) { Vertex vertex = null; Point mousePoint = null; @@ -227,18 +233,21 @@ public class EdgeConstructionController extends MouseAdapter implements MouseMot } - public void mouseExited(MouseEvent me) + @Override + public void mouseExited(MouseEvent me) { } - public void mouseDragged(MouseEvent me) + @Override + public void mouseDragged(MouseEvent me) { processEvent(kDrag, me.getPoint()); } - public void mouseMoved(MouseEvent me) + @Override + public void mouseMoved(MouseEvent me) { } } diff --git a/source/com/c2kernel/graph/controller/MultiSelectionDragController.java b/source/com/c2kernel/graph/controller/MultiSelectionDragController.java old mode 100755 new mode 100644 index 8e9a2b3..eda5c1c --- a/source/com/c2kernel/graph/controller/MultiSelectionDragController.java +++ b/source/com/c2kernel/graph/controller/MultiSelectionDragController.java @@ -6,7 +6,6 @@ import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; -import java.awt.event.MouseMotionListener; import com.c2kernel.graph.model.DirectedEdge; import com.c2kernel.graph.model.ElasticBand; @@ -20,7 +19,7 @@ import com.c2kernel.graph.view.EditorModeListener; public class MultiSelectionDragController extends MouseAdapter -implements EditorModeListener, MouseMotionListener, KeyListener +implements EditorModeListener, KeyListener { private class ResizeInf { @@ -90,7 +89,8 @@ implements EditorModeListener, MouseMotionListener, KeyListener protected Action mStoreResizeInf = new Action() { - public void doIt(Object data) + @Override + public void doIt(Object data) { Point mousePoint = (Point)data; GraphPoint centre = null; @@ -110,8 +110,9 @@ implements EditorModeListener, MouseMotionListener, KeyListener protected Action mResizeVertex = new Action() { - public void doIt(Object data) - { + @Override + public void doIt(Object data) + { Point mousePoint = (Point)data; int resizeX = 0; int resizeY = 0; @@ -186,7 +187,8 @@ implements EditorModeListener, MouseMotionListener, KeyListener protected Action mSelectEdge = new Action() { - public void doIt(Object data) + @Override + public void doIt(Object data) { Selection selection = new Selection((DirectedEdge)data, null, 0, 0, 0, 0); @@ -197,7 +199,8 @@ implements EditorModeListener, MouseMotionListener, KeyListener protected Action mSelectVertexAndStoreDisp = new Action() { - public void doIt(Object data) + @Override + public void doIt(Object data) { VertexAndDisp vertexAndDisp = (VertexAndDisp)data; GraphPoint centrePoint = vertexAndDisp.mVertex.getCentrePoint(); @@ -218,7 +221,8 @@ implements EditorModeListener, MouseMotionListener, KeyListener protected Action mStoreDisp = new Action() { - public void doIt(Object data) + @Override + public void doIt(Object data) { mDispForSelection = (DispForSelection)data; } @@ -227,7 +231,8 @@ implements EditorModeListener, MouseMotionListener, KeyListener protected Action mToggleVertex = new Action() { - public void doIt(Object data) + @Override + public void doIt(Object data) { Vertex vertex = (Vertex)data; @@ -245,7 +250,8 @@ implements EditorModeListener, MouseMotionListener, KeyListener protected Action mSelectAll = new Action() { - public void doIt(Object data) + @Override + public void doIt(Object data) { mGraphModelManager.getModel().selectAll(); } @@ -254,7 +260,8 @@ implements EditorModeListener, MouseMotionListener, KeyListener protected Action mCreateBand = new Action() { - public void doIt(Object data) + @Override + public void doIt(Object data) { Point fixedCorner = (Point)data; @@ -265,7 +272,8 @@ implements EditorModeListener, MouseMotionListener, KeyListener protected Action mMoveSelection = new Action() { - public void doIt(Object data) + @Override + public void doIt(Object data) { Point mousePoint = (Point)data; int topLeftX = mousePoint.x - mDispForSelection.mXDisp; @@ -279,7 +287,8 @@ implements EditorModeListener, MouseMotionListener, KeyListener protected Action mResizeBand = new Action() { - public void doIt(Object data) + @Override + public void doIt(Object data) { mGraphModelManager.getModel().resizeElasticBand((Point)data); } @@ -288,7 +297,8 @@ implements EditorModeListener, MouseMotionListener, KeyListener protected Action mSelectContents = new Action() { - public void doIt(Object data) + @Override + public void doIt(Object data) { mGraphModelManager.getModel().selectContentsOfElasticBand(); } @@ -296,7 +306,8 @@ implements EditorModeListener, MouseMotionListener, KeyListener protected Action mZoomIn = new Action() { - public void doIt(Object data) // data is the clicked vertex + @Override + public void doIt(Object data) // data is the clicked vertex { // Need to get child graph model out of the vertex before we can zoom in if (data instanceof Vertex) { @@ -372,7 +383,8 @@ implements EditorModeListener, MouseMotionListener, KeyListener } - public void editorModeChanged(String idOfNewMode) + @Override + public void editorModeChanged(String idOfNewMode) { if(idOfNewMode.equals("Select")) { @@ -385,7 +397,8 @@ implements EditorModeListener, MouseMotionListener, KeyListener } - public void mousePressed(MouseEvent me) + @Override + public void mousePressed(MouseEvent me) { int modifiers = me.getModifiers(); @@ -402,7 +415,8 @@ implements EditorModeListener, MouseMotionListener, KeyListener } } - public void mouseClicked(MouseEvent me) + @Override + public void mouseClicked(MouseEvent me) { if (me.getClickCount() == 2) { // want double click Point clickedSpot = me.getPoint(); @@ -513,24 +527,28 @@ implements EditorModeListener, MouseMotionListener, KeyListener } - public void mouseReleased(MouseEvent me) + @Override + public void mouseReleased(MouseEvent me) { processEvent(kRelease, null); } - public void mouseMoved(MouseEvent me) + @Override + public void mouseMoved(MouseEvent me) { } - public void mouseDragged(MouseEvent e) + @Override + public void mouseDragged(MouseEvent e) { processEvent(kDrag, e.getPoint()); } - public void keyPressed(KeyEvent e) + @Override + public void keyPressed(KeyEvent e) { if((e.getKeyCode() == KeyEvent.VK_A) && e.isControlDown()) { @@ -539,13 +557,15 @@ implements EditorModeListener, MouseMotionListener, KeyListener } - public void keyReleased(KeyEvent e) + @Override + public void keyReleased(KeyEvent e) { } - public void keyTyped(KeyEvent e) + @Override + public void keyTyped(KeyEvent e) { - } - + } + } diff --git a/source/com/c2kernel/graph/controller/StartVertexController.java b/source/com/c2kernel/graph/controller/StartVertexController.java old mode 100755 new mode 100644 index 0dc959c..3984cb7 --- a/source/com/c2kernel/graph/controller/StartVertexController.java +++ b/source/com/c2kernel/graph/controller/StartVertexController.java @@ -44,7 +44,8 @@ public class StartVertexController implements Observer, ActionListener } - public void update(Observable o, Object arg) + @Override + public void update(Observable o, Object arg) { SelectionChangedEvent event = null; Vertex[] selectedVertices = null; @@ -67,7 +68,8 @@ public class StartVertexController implements Observer, ActionListener } - public void actionPerformed(ActionEvent ae) + @Override + public void actionPerformed(ActionEvent ae) { if(mGraphModelManager != null) { diff --git a/source/com/c2kernel/graph/controller/VertexConstructionController.java b/source/com/c2kernel/graph/controller/VertexConstructionController.java old mode 100755 new mode 100644 index d351b0a..1eb91f6 --- a/source/com/c2kernel/graph/controller/VertexConstructionController.java +++ b/source/com/c2kernel/graph/controller/VertexConstructionController.java @@ -28,13 +28,15 @@ public class VertexConstructionController extends MouseAdapter implements Editor } - public void editorModeChanged(String idOfNewMode) + @Override + public void editorModeChanged(String idOfNewMode) { mCreatingVertices = idOfNewMode.equals("Vertex"); } - public void mouseClicked(MouseEvent me) + @Override + public void mouseClicked(MouseEvent me) { if(mCreatingVertices && (mGraphModelManager != null) && (mEditorToolBar != null) && mGraphModelManager.isEditable()) { diff --git a/source/com/c2kernel/graph/layout/DefaultGraphLayoutGenerator.java b/source/com/c2kernel/graph/layout/DefaultGraphLayoutGenerator.java index 4b429fa..8ab91ef 100644 --- a/source/com/c2kernel/graph/layout/DefaultGraphLayoutGenerator.java +++ b/source/com/c2kernel/graph/layout/DefaultGraphLayoutGenerator.java @@ -60,7 +60,7 @@ public class DefaultGraphLayoutGenerator { } private static void calculateRowMidPoints(Vector> rowVector, int[] midPoints, IntegerWrapper valueOfLargestMidPoint) { - Vector rowsVertices = null; + Vector rowsVertices = null; int rowsWidth = 0; int i = 0; for (i = 0; i < midPoints.length; i++) { @@ -75,7 +75,7 @@ public class DefaultGraphLayoutGenerator { private static void fillInVertexLocations(GraphModel graphModel, Vector> rowVector, IntegerWrapper valueOfLargestMidPoint, int[] midPoints) { - Vector rowsVertices = null; + Vector rowsVertices = null; Vertex vertex = null; int rowIndex = 0; int column = 0; @@ -85,7 +85,7 @@ public class DefaultGraphLayoutGenerator { rowsVertices = rowVector.elementAt(rowIndex); rowsLeftMargin = mLeftMargin + valueOfLargestMidPoint.mValue - midPoints[rowIndex]; for (column = 0; column < rowsVertices.size(); column++) { - vertex = (Vertex)rowsVertices.elementAt(column); + vertex = rowsVertices.elementAt(column); point.x = rowsLeftMargin + column * mHorzGap; point.y = mTopMargin + rowIndex * mVertGap; vertex.moveAbsolute(point); diff --git a/source/com/c2kernel/graph/model/DirectedEdge.java b/source/com/c2kernel/graph/model/DirectedEdge.java old mode 100755 new mode 100644 index 3848373..830d70d --- a/source/com/c2kernel/graph/model/DirectedEdge.java +++ b/source/com/c2kernel/graph/model/DirectedEdge.java @@ -51,7 +51,7 @@ public abstract class DirectedEdge implements Serializable public boolean containsPoint(GraphPoint p) - { + { int midX = mOriginPoint.x + (mTerminusPoint.x - mOriginPoint.x)/2; int midY = mOriginPoint.y + (mTerminusPoint.y - mOriginPoint.y)/2; int minX = midX - 10; diff --git a/source/com/c2kernel/graph/model/GraphModel.java b/source/com/c2kernel/graph/model/GraphModel.java index e9ae02f..47f368d 100644 --- a/source/com/c2kernel/graph/model/GraphModel.java +++ b/source/com/c2kernel/graph/model/GraphModel.java @@ -6,7 +6,23 @@ import java.io.Serializable; import java.util.Hashtable; import java.util.Vector; -import com.c2kernel.graph.event.*; +import com.c2kernel.graph.event.ClearedEvent; +import com.c2kernel.graph.event.EdgeRemovedEvent; +import com.c2kernel.graph.event.EdgesChangedEvent; +import com.c2kernel.graph.event.ElasticBandResizedEvent; +import com.c2kernel.graph.event.ElasticBandSetEvent; +import com.c2kernel.graph.event.ForcedNotifyEvent; +import com.c2kernel.graph.event.GraphModelEvent; +import com.c2kernel.graph.event.GraphModelResizedEvent; +import com.c2kernel.graph.event.NewEdgeEndPointChangedEvent; +import com.c2kernel.graph.event.SelectionChangedEvent; +import com.c2kernel.graph.event.SelectionMovedEvent; +import com.c2kernel.graph.event.StartVertexIdChangedEvent; +import com.c2kernel.graph.event.VertexAddedEvent; +import com.c2kernel.graph.event.VertexCreatedEvent; +import com.c2kernel.graph.event.VertexMovedEvent; +import com.c2kernel.graph.event.VertexRemovedEvent; +import com.c2kernel.graph.event.VerticesChangedEvent; import com.c2kernel.utils.Logger; public class GraphModel implements Serializable{ @@ -153,7 +169,7 @@ public class GraphModel implements Serializable{ public Vertex getStartVertex() { return resolveVertex(getStartVertexId()); } - + /** * @return Returns the mParentVertex. */ @@ -165,13 +181,13 @@ public class GraphModel implements Serializable{ */ public void setContainingVertex(GraphableVertex vertex) { mContainingVertex = vertex; - } + } public void setVertices(Vertex[] vertices) { mVertexHashtable = new Hashtable(); - for (int i = 0; i < vertices.length; i++) { - mVertexHashtable.put(String.valueOf(vertices[i].getID()), vertices[i]); - checkSize(vertices[i]); + for (Vertex vertice : vertices) { + mVertexHashtable.put(String.valueOf(vertice.getID()), vertice); + checkSize(vertice); } setChanged(); @@ -190,8 +206,8 @@ public class GraphModel implements Serializable{ public void setEdges(DirectedEdge[] edges) { mEdgeHashtable = new Hashtable(); - for (int i = 0; i < edges.length; i++) { - mEdgeHashtable.put(String.valueOf(edges[i].getID()), edges[i]); + for (DirectedEdge edge : edges) { + mEdgeHashtable.put(String.valueOf(edge.getID()), edge); } setChanged(); notifyObservers(mEdgesChangedEvent); @@ -229,11 +245,11 @@ public class GraphModel implements Serializable{ return null; } else { - smallestVertex = (Vertex)vertexVector.elementAt(0); + smallestVertex = vertexVector.elementAt(0); sizeOfSmallestVertex = smallestVertex.getHeight() * smallestVertex.getWidth(); // Determine the smallest vertex for (i = 1; i < numVerticesFound; i++) { - vertex = (Vertex)vertexVector.elementAt(i); + vertex = vertexVector.elementAt(i); sizeOfVertex = vertex.getHeight() * vertex.getWidth(); if (sizeOfVertex < sizeOfSmallestVertex) { smallestVertex = vertex; @@ -245,7 +261,7 @@ public class GraphModel implements Serializable{ } public Vertex getVertexById(int id) { - return (Vertex)mVertexHashtable.get(String.valueOf(id)); + return mVertexHashtable.get(String.valueOf(id)); } public DirectedEdge getEdge(GraphPoint p) { @@ -302,7 +318,7 @@ public class GraphModel implements Serializable{ if (mVertexOutlineCreator == null) { Logger.msg(1,"You cannot add a vertex with no outline creator"); return -1; - + } mVertexHashtable.put(String.valueOf(mNextId), v); placeVertex(v, location); @@ -316,7 +332,7 @@ public class GraphModel implements Serializable{ if (mVertexOutlineCreator != null) { mVertexOutlineCreator.setOutline(v); } - setChanged(); + setChanged(); notifyObservers(mVertexAddedEvent); checkSize(v); } @@ -420,11 +436,11 @@ public class GraphModel implements Serializable{ } public Vertex resolveVertex(int id) { - return (Vertex)mVertexHashtable.get(String.valueOf(id)); + return mVertexHashtable.get(String.valueOf(id)); } public DirectedEdge resolveEdge(int id) { - return (DirectedEdge)mEdgeHashtable.get(String.valueOf(id)); + return mEdgeHashtable.get(String.valueOf(id)); } public DirectedEdge[] getInEdges(Vertex v) { @@ -641,7 +657,7 @@ public class GraphModel implements Serializable{ verticesInside.add(allVertices[i]); } } - + // Select the vertices found within the elastic band polygon if (verticesInside.size() == 0) { mSelection.mTopLeftX = 0; @@ -651,15 +667,15 @@ public class GraphModel implements Serializable{ mSelection.mEdge = null; if (mContainingVertex != null) verticesInside.add(mContainingVertex); - else + else mSelection.mVertices = null; } - + if (verticesInside.size() > 0) { mSelection.mEdge = null; mSelection.mVertices = new Vertex[verticesInside.size()]; for (i = 0; i < verticesInside.size(); i++) { - mSelection.mVertices[i] = (Vertex)verticesInside.elementAt(i); + mSelection.mVertices[i] = verticesInside.elementAt(i); } updateSelectionCorners(); } @@ -679,8 +695,8 @@ public class GraphModel implements Serializable{ mSelection.mTopLeftY = centrePoint.y; mSelection.mBottomRightX = centrePoint.x; mSelection.mBottomRightY = centrePoint.y; - for (int i = 0; i < mSelection.mVertices.length; i++) { - vertex = mSelection.mVertices[i]; + for (Vertex mVertice : mSelection.mVertices) { + vertex = mVertice; centrePoint = vertex.getCentrePoint(); if (centrePoint.x < mSelection.mTopLeftX) { mSelection.mTopLeftX = centrePoint.x; @@ -825,7 +841,7 @@ public class GraphModel implements Serializable{ } public void setGraphModelCastorData(GraphModelCastorData data) { - Class vertexOutlineCreatorClass = null; + Class vertexOutlineCreatorClass = null; int i = 0; // Create the vertex outline creator if (data.mClassNameOfVertexOutlineCreator.equals("")) { diff --git a/source/com/c2kernel/graph/model/GraphModelManager.java b/source/com/c2kernel/graph/model/GraphModelManager.java index 3146c24..68d47e0 100644 --- a/source/com/c2kernel/graph/model/GraphModelManager.java +++ b/source/com/c2kernel/graph/model/GraphModelManager.java @@ -23,7 +23,7 @@ public class GraphModelManager extends Observable private Stack mParentModels = new Stack(); private ArrayList mParentIds = new ArrayList(); private boolean mEditable = true; - + // Calling this constructor does not create a vertex outline creator // which is required by the method addVertexAndCreateId() public GraphModelManager() @@ -31,7 +31,7 @@ public class GraphModelManager extends Observable mGraphModel = new GraphModel(); mGraphModel.setManager(this); } - + public GraphModelManager(GraphModel newModel) { newModel.setManager(this); mGraphModel = newModel; @@ -41,8 +41,8 @@ public class GraphModelManager extends Observable mParentModels.clear(); //zoom back to where we were - for (Iterator iter = mParentIds.iterator(); iter.hasNext();) { - Integer parentId = (Integer) iter.next(); + for (Iterator iter = mParentIds.iterator(); iter.hasNext();) { + Integer parentId = iter.next(); GraphableVertex childModelVertex = (GraphableVertex)newModel.getVertexById(parentId.intValue()); if (childModelVertex == null) { // we've been deleted, stay here Logger.msg(7, "Didn't find "+parentId+" in new model tree. Stopping here."); @@ -54,17 +54,17 @@ public class GraphModelManager extends Observable Logger.msg(7, "Pushing model and switching to "+parentId); newModel = childModelVertex.getChildGraphModel(); } - } + } setModel(newModel); } - + public void setModel(GraphModel newModel) { // reset transient data newModel.mSelection = new Selection(null, null, 0, 0, 0, 0); newModel.mNewEdgeOriginVertex = null; newModel.mNewEdgeEndPoint = null; - // copy factories over + // copy factories over newModel.setExternalEdgeFactory(mEdgeFactory); newModel.setExternalVertexFactory(mVertexFactory); newModel.setVertexOutlineCreator(mVertexOutlineCreator); @@ -72,12 +72,12 @@ public class GraphModelManager extends Observable newModel.setManager(this); mGraphModel.setManager(null); mGraphModel = newModel; - + // notify setChanged(); notifyObservers(mEntireModelChangedEvent); } - + public void zoomIn(Vertex child) { GraphModel childModel = child.getChildGraphModel(); if (childModel != null) { @@ -87,53 +87,54 @@ public class GraphModelManager extends Observable Logger.msg(7, "ZoomIn - Stack size: "+mParentModels.size()+" ids:"+mParentIds.size()); } } - + public void zoomOut() { if (!mParentModels.empty()) { - setModel((GraphModel)mParentModels.pop()); + setModel(mParentModels.pop()); mParentIds.remove(mParentIds.size()-1); } Logger.msg(7, "ZoomOut - Stack size: "+mParentModels.size()+" ids:"+mParentIds.size()); - + } - + public void forceNotify() { setChanged(); notifyObservers(mForcedNotifyEvent); } - + public GraphModel getModel() { return mGraphModel; } - + public void setExternalEdgeFactory(EdgeFactory newEdgeFactory) { mEdgeFactory = newEdgeFactory; mGraphModel.setExternalEdgeFactory(newEdgeFactory); - } + } public void setExternalVertexFactory(VertexFactory newVertexFactory) { mVertexFactory = newVertexFactory; mGraphModel.setExternalVertexFactory(newVertexFactory); - } + } public void setVertexOutlineCreator(VertexOutlineCreator newVertexOutlineCreator) { mVertexOutlineCreator = newVertexOutlineCreator; mGraphModel.setVertexOutlineCreator(newVertexOutlineCreator); - } - - protected void setChanged() { + } + + @Override + protected void setChanged() { super.setChanged(); } - + protected void notifyObservers(GraphModelEvent ev) { super.notifyObservers(ev); } - + public void setEditable(boolean editable) { mEditable = editable; } - + public boolean isEditable() { return mEditable; } diff --git a/source/com/c2kernel/graph/model/GraphPoint.java b/source/com/c2kernel/graph/model/GraphPoint.java old mode 100755 new mode 100644 index c1c6ccc..f2aa165 --- a/source/com/c2kernel/graph/model/GraphPoint.java +++ b/source/com/c2kernel/graph/model/GraphPoint.java @@ -6,11 +6,11 @@ public class GraphPoint implements Serializable{ public int x; public int y; - + public GraphPoint() { x=0; y=0; } - + public GraphPoint(int x, int y) { this.x = x; this.y = y; diff --git a/source/com/c2kernel/graph/model/Graphable.java b/source/com/c2kernel/graph/model/Graphable.java old mode 100755 new mode 100644 index 5dde105..ed55271 --- a/source/com/c2kernel/graph/model/Graphable.java +++ b/source/com/c2kernel/graph/model/Graphable.java @@ -42,10 +42,12 @@ abstract public class Graphable extends Vertex { this.parent = parent; } + @Override public GraphModel getChildGraphModel() { return children; } + @Override public Object getCreationContext() { return this; } diff --git a/source/com/c2kernel/graph/model/GraphableEdge.java b/source/com/c2kernel/graph/model/GraphableEdge.java old mode 100755 new mode 100644 index a6d9a63..23499be --- a/source/com/c2kernel/graph/model/GraphableEdge.java +++ b/source/com/c2kernel/graph/model/GraphableEdge.java @@ -64,7 +64,7 @@ public abstract class GraphableEdge extends DirectedEdge public KeyValuePair[] getKeyValuePairs() { return mProperties.getKeyValuePairs(); } - + public void setKeyValuePairs(KeyValuePair[] pairs) { mProperties.setKeyValuePairs(pairs); } diff --git a/source/com/c2kernel/graph/model/GraphableVertex.java b/source/com/c2kernel/graph/model/GraphableVertex.java index 6efd298..fc04743 100644 --- a/source/com/c2kernel/graph/model/GraphableVertex.java +++ b/source/com/c2kernel/graph/model/GraphableVertex.java @@ -4,6 +4,7 @@ package com.c2kernel.graph.model; * @author $Author: abranson $ */ import java.awt.Point; + import com.c2kernel.utils.CastorHashMap; import com.c2kernel.utils.KeyValuePair; public abstract class GraphableVertex extends Vertex @@ -52,10 +53,12 @@ public abstract class GraphableVertex extends Vertex throw new ExceptionInInitializerError(); this.parent = parent; } + @Override public GraphModel getChildGraphModel() { return mChildrenGraphModel; } + @Override public Object getCreationContext() { return this; @@ -134,9 +137,9 @@ public abstract class GraphableVertex extends Vertex ids = ids.substring(getPath().length() + 1); else return null; - - for (int i = 0; i < graphables.length; i++) { - GraphableVertex grap = graphables[i].search(ids); + + for (GraphableVertex graphable : graphables) { + GraphableVertex grap = graphable.search(ids); if (grap != null) return grap; } } @@ -201,17 +204,18 @@ public abstract class GraphableVertex extends Vertex DirectedEdge[] edges = mChildrenGraphModel.getEdges(); GraphableVertex[] graphables = this.getLayoutableChildren(); if (graphables != null) - for (int i = 0; i < graphables.length; i++) - graphables[i].setParent(this); + for (GraphableVertex graphable : graphables) + graphable.setParent(this); if (edges != null) - for (int i = 0; i < edges.length; i++) - ((GraphableEdge) edges[i]).setParent(this); + for (DirectedEdge edge : edges) + ((GraphableEdge) edge).setParent(this); childrenGraph.setContainingVertex(this); } /** * @see com.c2kernel.graph.model.Vertex#getCentrePoint() */ + @Override public GraphPoint getCentrePoint() { if (!getIsLayoutable()) @@ -221,6 +225,7 @@ public abstract class GraphableVertex extends Vertex /** * @see com.c2kernel.graph.model.Vertex#getInEdgeIds() */ + @Override public int[] getInEdgeIds() { if (!getIsLayoutable()) @@ -230,6 +235,7 @@ public abstract class GraphableVertex extends Vertex /** * @see com.c2kernel.graph.model.Vertex#getOutEdgeIds() */ + @Override public int[] getOutEdgeIds() { if (!getIsLayoutable()) @@ -239,6 +245,7 @@ public abstract class GraphableVertex extends Vertex /** * @see com.c2kernel.graph.model.Vertex#getOutlinePoints() */ + @Override public GraphPoint[] getOutlinePoints() { if (!getIsLayoutable()) diff --git a/source/com/c2kernel/graph/model/TypeNameAndConstructionInfo.java b/source/com/c2kernel/graph/model/TypeNameAndConstructionInfo.java old mode 100755 new mode 100644 index 6443064..e5b6c3d --- a/source/com/c2kernel/graph/model/TypeNameAndConstructionInfo.java +++ b/source/com/c2kernel/graph/model/TypeNameAndConstructionInfo.java @@ -16,7 +16,8 @@ public class TypeNameAndConstructionInfo implements Serializable } - public String toString() + @Override + public String toString() { return mName; } diff --git a/source/com/c2kernel/graph/model/Vertex.java b/source/com/c2kernel/graph/model/Vertex.java index a9a5238..ccef437 100644 --- a/source/com/c2kernel/graph/model/Vertex.java +++ b/source/com/c2kernel/graph/model/Vertex.java @@ -198,7 +198,7 @@ public class Vertex implements Serializable } - private int[] integerVectorToIntArray(Vector vector) + private static int[] integerVectorToIntArray(Vector vector) { int[] array = new int[vector.size()]; Integer integer = null; @@ -206,7 +206,7 @@ public class Vertex implements Serializable for(i=0; i vector) { Vertex[] vertices = new Vertex[vector.size()]; int i = 0; @@ -77,7 +77,7 @@ public class GraphTraversal for(i=0; i 0)) return Math.PI; diff --git a/source/com/c2kernel/graph/view/DefaultVertexRenderer.java b/source/com/c2kernel/graph/view/DefaultVertexRenderer.java old mode 100755 new mode 100644 index 6f57185..e9b92d0 --- a/source/com/c2kernel/graph/view/DefaultVertexRenderer.java +++ b/source/com/c2kernel/graph/view/DefaultVertexRenderer.java @@ -24,7 +24,8 @@ public class DefaultVertexRenderer implements VertexRenderer } - public void draw(Graphics2D g2d, Vertex vertex) + @Override + public void draw(Graphics2D g2d, Vertex vertex) { GraphPoint[] outlinePoints = vertex.getOutlinePoints(); GraphPoint centrePoint = vertex.getCentrePoint(); diff --git a/source/com/c2kernel/graph/view/EditorPanel.java b/source/com/c2kernel/graph/view/EditorPanel.java old mode 100755 new mode 100644 index 78fb5c9..fb25b68 --- a/source/com/c2kernel/graph/view/EditorPanel.java +++ b/source/com/c2kernel/graph/view/EditorPanel.java @@ -10,7 +10,11 @@ import com.c2kernel.graph.controller.AutoScrollController; import com.c2kernel.graph.controller.EdgeConstructionController; import com.c2kernel.graph.controller.MultiSelectionDragController; import com.c2kernel.graph.controller.VertexConstructionController; -import com.c2kernel.graph.model.*; +import com.c2kernel.graph.model.EdgeFactory; +import com.c2kernel.graph.model.GraphModelManager; +import com.c2kernel.graph.model.TypeNameAndConstructionInfo; +import com.c2kernel.graph.model.VertexFactory; +import com.c2kernel.graph.model.VertexOutlineCreator; public class EditorPanel extends JPanel { // Graph Model diff --git a/source/com/c2kernel/graph/view/EditorToolBar.java b/source/com/c2kernel/graph/view/EditorToolBar.java index e01056f..cc7ab41 100644 --- a/source/com/c2kernel/graph/view/EditorToolBar.java +++ b/source/com/c2kernel/graph/view/EditorToolBar.java @@ -50,6 +50,7 @@ public class EditorToolBar extends Box implements Printable { mModeId = modeId; } + @Override public void actionPerformed(ActionEvent ae) { notifyListeners(mModeId); @@ -185,6 +186,7 @@ public class EditorToolBar extends Box implements Printable // user select a vertex type from the vertex type box mVertexTypeBox.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent ae) { mVertexModeButton.setSelected(true); @@ -195,6 +197,7 @@ public class EditorToolBar extends Box implements Printable // user select an edge type from the edge type box mEdgeTypeBox.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent ae) { mEdgeModeButton.setSelected(true); @@ -203,6 +206,7 @@ public class EditorToolBar extends Box implements Printable }); mPrintButton.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent ae) { PrinterJob _monJob = PrinterJob.getPrinterJob(); @@ -222,10 +226,11 @@ public class EditorToolBar extends Box implements Printable Class.forName("java.awt.datatransfer.DataFlavor").getDeclaredField("imageFlavor"); mCopyButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) + @Override + public void actionPerformed(ActionEvent ae) { try - { + { Image i = createImage(mGraphPanel.getWidth(),mGraphPanel.getHeight()); Graphics g = i.getGraphics(); mGraphPanel.paintComponent(g); @@ -242,7 +247,7 @@ public class EditorToolBar extends Box implements Printable mCopyButton.setEnabled(false); } } - + protected class ImageTransferable implements Transferable, ClipboardOwner { Image image; int width,height; @@ -255,19 +260,22 @@ public class EditorToolBar extends Box implements Printable javaImg = new DataFlavor("image/x-java-image; class=java.awt.Image", "AWT Image"); } catch (Exception ex){ } } - public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException { + @Override + public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException { if (!isDataFlavorSupported(flavor) || image == null) { throw new UnsupportedFlavorException(flavor); } return image; } - public boolean isDataFlavorSupported(DataFlavor flavor) { + @Override + public boolean isDataFlavorSupported(DataFlavor flavor) { boolean result = in(flavor, getTransferDataFlavors()); return result; } - - public DataFlavor[] getTransferDataFlavors() { + + @Override + public DataFlavor[] getTransferDataFlavors() { return new DataFlavor[] { javaImg }; } protected boolean in(DataFlavor flavor, DataFlavor[] flavors) { @@ -277,18 +285,19 @@ public class EditorToolBar extends Box implements Printable } return f < flavors.length; } - public void lostOwnership(Clipboard clipboard, Transferable contents) { + @Override + public void lostOwnership(Clipboard clipboard, Transferable contents) { image = null; } } - + protected void notifyListeners(String newModeId) { int i = 0; EditorModeListener listener = null; for (i = 0; i < mListenerVector.size(); i++) { - listener = (EditorModeListener) mListenerVector.elementAt(i); + listener = mListenerVector.elementAt(i); listener.editorModeChanged(newModeId); } } @@ -318,6 +327,7 @@ public class EditorToolBar extends Box implements Printable { return this; } + @Override public int print(Graphics g, PageFormat pf, int i) throws PrinterException { if (i >= 1) diff --git a/source/com/c2kernel/graph/view/GraphPanel.java b/source/com/c2kernel/graph/view/GraphPanel.java old mode 100755 new mode 100644 index 9db481e..5edd070 --- a/source/com/c2kernel/graph/view/GraphPanel.java +++ b/source/com/c2kernel/graph/view/GraphPanel.java @@ -41,6 +41,7 @@ public class GraphPanel extends JPanel implements Observer // is pressed on the graph panel addMouseListener(new MouseAdapter() { + @Override public void mousePressed(MouseEvent me) { requestFocus(); @@ -51,6 +52,7 @@ public class GraphPanel extends JPanel implements Observer { mGraphModelManager = graphModelManager; } + @Override public void update(Observable o, Object arg) { if (arg instanceof GraphModelResizedEvent || arg instanceof EntireModelChangedEvent) @@ -60,6 +62,7 @@ public class GraphPanel extends JPanel implements Observer } repaint(); } + @Override public void paintComponent(Graphics g) { Graphics2D g2d = (Graphics2D) g; @@ -111,7 +114,7 @@ public class GraphPanel extends JPanel implements Observer drawVertexHighlight(g2d, selection.mVertices[i], 5); } // Draw the resize pads if there is one and only one vertex selected - if (selection.mVertices.length == 1 && + if (selection.mVertices.length == 1 && selection.mVertices[0] != mGraphModelManager.getModel().getContainingVertex()) { vertexCentre = selection.mVertices[0].getCentrePoint(); @@ -189,7 +192,7 @@ public class GraphPanel extends JPanel implements Observer outlinePoints[0].y); } // Draws the specifed line the specified distance away from the specified centre point - private void drawShiftedLine(int dist, Graphics2D g2d, GraphPoint centrePoint, int x1, int y1, int x2, int y2) + private static void drawShiftedLine(int dist, Graphics2D g2d, GraphPoint centrePoint, int x1, int y1, int x2, int y2) { if (x1 > centrePoint.x) x1 += dist; @@ -225,6 +228,7 @@ public class GraphPanel extends JPanel implements Observer g2d.drawLine(maxX, maxY, minX, maxY); g2d.drawLine(minX, maxY, minX, minY); } + @Override public void printComponent(Graphics g) { super.paintComponent(g); @@ -232,12 +236,6 @@ public class GraphPanel extends JPanel implements Observer DirectedEdge[] edges = null; Vertex[] vertices = null; Vertex startVertex = null; - Selection selection = null; - ElasticBand elasticBand = null; - Vertex newEdgeOriginVertex = null; - GraphPoint newEdgeOriginPoint = null; - Point newEdgeEndPoint = null; - GraphPoint vertexCentre = null; int i = 0; g.setColor(Color.white); g2d.fillRect(0,0,getWidth(),getHeight()); @@ -266,7 +264,7 @@ public class GraphPanel extends JPanel implements Observer } } } - + protected void superPaint(Graphics g) { super.paintComponent(g); diff --git a/source/com/c2kernel/graph/view/PropertyTable.java b/source/com/c2kernel/graph/view/PropertyTable.java old mode 100755 new mode 100644 index e067e68..c1257aa --- a/source/com/c2kernel/graph/view/PropertyTable.java +++ b/source/com/c2kernel/graph/view/PropertyTable.java @@ -13,26 +13,28 @@ public class PropertyTable extends JTable } - public TableCellRenderer getCellRenderer(int row, int column) { + @Override + public TableCellRenderer getCellRenderer(int row, int column) { + - return getDefaultRenderer(getCellClass(row, column)); } - public TableCellEditor getCellEditor(int row, int column) { - + @Override +public TableCellEditor getCellEditor(int row, int column) { + return getDefaultEditor(getCellClass(row, column)); } - - private Class getCellClass(int row, int column) { - Class cellClass = String.class; - + + private Class getCellClass(int row, int column) { + Class cellClass = String.class; + try { cellClass = dataModel.getValueAt(row, column).getClass(); } catch (NullPointerException ex) { } - + return cellClass; } } diff --git a/source/com/c2kernel/graph/view/PropertyTableModel.java b/source/com/c2kernel/graph/view/PropertyTableModel.java index 22ba4f3..b1e69b1 100644 --- a/source/com/c2kernel/graph/view/PropertyTableModel.java +++ b/source/com/c2kernel/graph/view/PropertyTableModel.java @@ -1,6 +1,9 @@ package com.c2kernel.graph.view; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; import javax.swing.JOptionPane; import javax.swing.event.TableModelEvent; @@ -23,26 +26,30 @@ public class PropertyTableModel extends AbstractTableModel { HashMap sourceMap = new HashMap(); ArrayList sortedNameList = new ArrayList(); boolean isEditable = false; - + public PropertyTableModel() { super(); } - public int getColumnCount() + @Override + public int getColumnCount() { return mColumnNames.length; } - public String getColumnName(int col) + @Override + public String getColumnName(int col) { return mColumnNames[col]; } - public int getRowCount() + @Override + public int getRowCount() { synchronized (sourceMap) { return sourceMap.size(); } } - public Object getValueAt(int rowIndex, int colIndex) + @Override + public Object getValueAt(int rowIndex, int colIndex) { synchronized (sourceMap) { String rowName = sortedNameList.get(rowIndex); @@ -52,18 +59,19 @@ public class PropertyTableModel extends AbstractTableModel { return sourceMap.get(rowName); } } - - public void setValueAt(Object value, int rowIndex, int colIndex) + + @Override + public void setValueAt(Object value, int rowIndex, int colIndex) { synchronized (sourceMap) { if (colIndex == 0) return; String rowName = sortedNameList.get(rowIndex); - Class oldElement = sourceMap.get(rowName).getClass(); + Class oldElement = sourceMap.get(rowName).getClass(); if (oldElement == Float.class && value.getClass() == String.class) try { value = Float.valueOf((String)value); } catch (Exception ex) { } - if (value.getClass() != oldElement) + if (value.getClass() != oldElement) JOptionPane.showMessageDialog(null, "This property should contain a "+oldElement.getName()+" not a "+value.getClass().getName(), "Incorrect datatype", JOptionPane.ERROR_MESSAGE); else { sourceMap.put(rowName, value); @@ -71,24 +79,26 @@ public class PropertyTableModel extends AbstractTableModel { } } } - + public void setMap(HashMap props) { synchronized (sourceMap) { sourceMap = props; sortedNameList = new ArrayList(props.size()); - for (Iterator keys = props.keySet().iterator(); keys.hasNext();) - sortedNameList.add(keys.next()); - + for (String string : props.keySet()) + sortedNameList.add(string); + Collections.sort(sortedNameList, new Comparator() { - public int compare(String o1, String o2) { + @Override + public int compare(String o1, String o2) { return (o1.compareToIgnoreCase(o2)); } }); } fireTableChanged(new TableModelEvent(this)); } - - public boolean isCellEditable(int row, int col) + + @Override + public boolean isCellEditable(int row, int col) { return col==1 && isEditable; } @@ -112,7 +122,7 @@ public class PropertyTableModel extends AbstractTableModel { */ public void addProperty(String text, Object object) { sourceMap.put(text,object); - setMap(sourceMap); + setMap(sourceMap); } /** diff --git a/source/com/c2kernel/graph/view/SelectedVertexPanel.java b/source/com/c2kernel/graph/view/SelectedVertexPanel.java old mode 100755 new mode 100644 index 18658dd..966f527 --- a/source/com/c2kernel/graph/view/SelectedVertexPanel.java +++ b/source/com/c2kernel/graph/view/SelectedVertexPanel.java @@ -16,12 +16,12 @@ import com.c2kernel.graph.model.Vertex; public abstract class SelectedVertexPanel extends JPanel { - + public SelectedVertexPanel() { super(); } public abstract void select(Vertex vert); - + public abstract void clear(); } diff --git a/source/com/c2kernel/graph/view/VertexPropertyPanel.java b/source/com/c2kernel/graph/view/VertexPropertyPanel.java index dd5fbd2..2cc03c2 100644 --- a/source/com/c2kernel/graph/view/VertexPropertyPanel.java +++ b/source/com/c2kernel/graph/view/VertexPropertyPanel.java @@ -10,13 +10,24 @@ import java.util.HashMap; import java.util.Observable; import java.util.Observer; -import javax.swing.*; +import javax.swing.Box; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextField; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import com.c2kernel.graph.event.EntireModelChangedEvent; import com.c2kernel.graph.event.SelectionChangedEvent; -import com.c2kernel.graph.model.*; +import com.c2kernel.graph.model.DirectedEdge; +import com.c2kernel.graph.model.GraphModelManager; +import com.c2kernel.graph.model.GraphableEdge; +import com.c2kernel.graph.model.GraphableVertex; +import com.c2kernel.graph.model.Vertex; import com.c2kernel.gui.tabs.EntityTabPane; import com.c2kernel.utils.Language; import com.c2kernel.utils.Logger; @@ -47,7 +58,7 @@ public class VertexPropertyPanel extends JPanel implements Observer, TableModelL String[] typeOptions = { "String", "Boolean", "Integer", "Float" }; String[] typeInitVal = { "", "false", "0", "0.0"}; SelectedVertexPanel mSelPanel; - + public VertexPropertyPanel() { super(); setLayout(gridbag); @@ -60,7 +71,8 @@ public class VertexPropertyPanel extends JPanel implements Observer, TableModelL * */ - public void update(Observable o, Object arg) { + @Override + public void update(Observable o, Object arg) { Vertex[] selectedVertices = null; DirectedEdge selectedEdge = null; // If the selection has changed @@ -87,14 +99,15 @@ public class VertexPropertyPanel extends JPanel implements Observer, TableModelL clear(); } } - - public void tableChanged(TableModelEvent e) { + + @Override + public void tableChanged(TableModelEvent e) { if (mGraphModelManager!=null) mGraphModelManager.forceNotify(); } - + public void setVertex(Vertex vert) { if (vert.getName().equals("domain")) selObjName.setText("Domain Workflow"); @@ -109,7 +122,7 @@ public class VertexPropertyPanel extends JPanel implements Observer, TableModelL delPropButton.setEnabled(isEditable); } } - + public void setEdge(DirectedEdge edge) { selObjName.setText(edge.getName()); String className = edge.getClass().getName(); @@ -121,7 +134,7 @@ public class VertexPropertyPanel extends JPanel implements Observer, TableModelL } if (mSelPanel != null) mSelPanel.clear(); } - + public void clear() { selObjName.setText(""); selObjClass.setText("Nothing Selected"); @@ -130,7 +143,7 @@ public class VertexPropertyPanel extends JPanel implements Observer, TableModelL addPropButton.setEnabled(false); delPropButton.setEnabled(false); } - + /** * @param isEditable The isEditable to set. */ @@ -139,12 +152,12 @@ public class VertexPropertyPanel extends JPanel implements Observer, TableModelL isEditable = editable; newPropBox.setVisible(editable); } - + public void setGraphModelManager(GraphModelManager manager) { mGraphModelManager = manager; manager.addObserver(this); } - + public void createLayout(SelectedVertexPanel selPanel) { GridBagConstraints c = new GridBagConstraints(); @@ -155,30 +168,30 @@ public class VertexPropertyPanel extends JPanel implements Observer, TableModelL c.anchor = GridBagConstraints.NORTHWEST; c.ipadx = 5; c.ipady = 5; - + selObjName = new JLabel(); selObjName.setFont(EntityTabPane.titleFont); gridbag.setConstraints(selObjName, c); - add(selObjName); - + add(selObjName); + c.gridy++; selObjClass = new JLabel(); gridbag.setConstraints(selObjClass, c); add(selObjClass); - + c.gridy++; JLabel title = new JLabel("Properties"); title.setFont(EntityTabPane.titleFont); gridbag.setConstraints(title, c); - add(title); - + add(title); + c.gridy++; c.fill = GridBagConstraints.BOTH; c.weighty = 2; JScrollPane scroll = new JScrollPane(mPropertyTable); gridbag.setConstraints(scroll, c); add(scroll); - + newPropBox = Box.createHorizontalBox(); newPropBox.add(new JLabel(Language.translate("New :"))); newPropBox.add(Box.createHorizontalGlue()); @@ -195,13 +208,13 @@ public class VertexPropertyPanel extends JPanel implements Observer, TableModelL delPropButton.addActionListener(this); newPropBox.add(addPropButton); newPropBox.add(delPropButton); - + c.gridy++; c.weighty=0; c.fill= GridBagConstraints.HORIZONTAL; gridbag.setConstraints(newPropBox, c); add(newPropBox); - + if (selPanel != null) { c.gridy++; mSelPanel = selPanel; @@ -209,8 +222,9 @@ public class VertexPropertyPanel extends JPanel implements Observer, TableModelL add(mSelPanel); } } - - public void actionPerformed(ActionEvent e) { + + @Override + public void actionPerformed(ActionEvent e) { if (e.getSource() == addPropButton) { if (newPropName.getText().length() < 1) { JOptionPane.showMessageDialog(this, "Enter a name for the new property", "Cannot add property", JOptionPane.ERROR_MESSAGE); @@ -225,8 +239,8 @@ public class VertexPropertyPanel extends JPanel implements Observer, TableModelL try { Class newPropClass = Class.forName("java.lang."+typeOptions[newPropType.getSelectedIndex()]); - Class[] params = {String.class}; - Constructor init = newPropClass.getConstructor(params); + Class[] params = {String.class}; + Constructor init = newPropClass.getConstructor(params); Object[] initParams = { typeInitVal[newPropType.getSelectedIndex()] }; mPropertyModel.addProperty(newPropName.getText(), init.newInstance(initParams)); } catch (Exception ex) { diff --git a/source/com/c2kernel/gui/Console.java b/source/com/c2kernel/gui/Console.java old mode 100755 new mode 100644 index 370413a..a16e6f6 --- a/source/com/c2kernel/gui/Console.java +++ b/source/com/c2kernel/gui/Console.java @@ -6,12 +6,22 @@ import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; -import java.io.*; +import java.io.BufferedReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.InterruptedIOException; +import java.io.PrintWriter; import java.net.Socket; -import java.util.Iterator; import java.util.Properties; -import javax.swing.*; +import javax.swing.Box; +import javax.swing.JButton; +import javax.swing.JFileChooser; +import javax.swing.JFrame; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.JTextField; import com.c2kernel.process.Gateway; import com.c2kernel.utils.FileStringUtility; @@ -32,12 +42,12 @@ public class Console extends JFrame { JScrollPane scroll; JTextField input; JButton sendButton; - JButton toFileButton; + JButton toFileButton; FileWriter logFile; ConsoleConnection connection; JFileChooser scriptLoader = new JFileChooser(); static int bufferSize = Integer.parseInt(Gateway.getProperty("Console.bufferSize", "200")); - + public Console(String host, int port) { super("Cristal Console - "+host); GridBagLayout gridbag = new GridBagLayout(); @@ -48,13 +58,15 @@ public class Console extends JFrame { setSize(400, 600); sendButton = new JButton("Send"); sendButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { + @Override + public void actionPerformed(ActionEvent e) { submit(); } }); JButton clearButton = new JButton("Clear"); clearButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { + @Override + public void actionPerformed(ActionEvent e) { synchronized (output) { output.setText(""); } @@ -62,7 +74,8 @@ public class Console extends JFrame { }); toFileButton = new JButton("Save"); toFileButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { + @Override + public void actionPerformed(ActionEvent e) { if (logFile == null) { int returnValue = scriptLoader.showSaveDialog(null); switch (returnValue) @@ -93,8 +106,8 @@ public class Console extends JFrame { } } }); - - + + input.addKeyListener(new EnterListener(this)); scroll = new JScrollPane(output); @@ -104,7 +117,7 @@ public class Console extends JFrame { c.weightx=1.0;c.weighty=1.0; gridbag.setConstraints(scroll, c); getContentPane().add(scroll); - + Box inputBox = Box.createHorizontalBox(); inputBox.add(input); inputBox.add(Box.createHorizontalStrut(5)); @@ -115,47 +128,50 @@ public class Console extends JFrame { c.weighty=0; gridbag.setConstraints(inputBox, c); getContentPane().add(inputBox); - + try { Properties utilProps = FileStringUtility.loadConfigFile( Resource.getDomainResourceURL("ScriptUtils.conf").toString()); Box utilBox = Box.createHorizontalBox(); - for (Iterator utilIter = utilProps.keySet().iterator(); utilIter.hasNext();) { - String name = (String) utilIter.next(); + for (Object name2 : utilProps.keySet()) { + String name = (String) name2; String value = utilProps.getProperty(name); JButton newUtil = new JButton(name); newUtil.setActionCommand(value); newUtil.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { + @Override + public void actionPerformed(ActionEvent e) { processUtil(e.getActionCommand()); } }); utilBox.add(newUtil); utilBox.add(Box.createHorizontalStrut(5)); } - + c.gridy++; gridbag.setConstraints(utilBox, c); getContentPane().add(utilBox); } catch (Exception ex) { // no domain utils } - - + + validate(); connection = new ConsoleConnection(host, port, this); new Thread(connection).start(); addWindowListener(new java.awt.event.WindowAdapter() { - public void windowClosing(java.awt.event.WindowEvent evt) { + @Override + public void windowClosing(java.awt.event.WindowEvent evt) { if (connection!=null) connection.shutdown(); dispose(); } }); } - - public void setVisible(boolean visible) { + + @Override + public void setVisible(boolean visible) { super.setVisible(visible); if (visible) input.requestFocus(); } - + public void processUtil(String command) { int replace; String text = input.getText(); @@ -164,12 +180,12 @@ public class Console extends JFrame { } connection.sendCommand(command); } - + public void submit() { connection.sendCommand(input.getText()); input.setText(""); } - + public void print(String line) { synchronized (output) { String currentText = output.getText()+line+"\n"; @@ -187,8 +203,9 @@ public class Console extends JFrame { } } } - - public void disable() { + + @Override + public void disable() { synchronized (output) { output.append("Lost connection"); } @@ -196,14 +213,15 @@ public class Console extends JFrame { input.setEnabled(false); sendButton.setEnabled(false); } - + private class EnterListener extends KeyAdapter { Console parent; public EnterListener(Console parent) { this.parent = parent; } - public void keyPressed(KeyEvent e) { + @Override + public void keyPressed(KeyEvent e) { if (e.getKeyCode()==10) { parent.submit(); } @@ -213,16 +231,17 @@ public class Console extends JFrame { private class ConsoleConnection implements Runnable { String host; int port; Console parent; boolean keepConnected = true; Socket conn; PrintWriter consoleOutput; BufferedReader consoleInput; - - + + public ConsoleConnection(String host, int port, Console parent) { Thread.currentThread().setName("Console Client to "+host+":"+port); this.host = host; this.port = port; this.parent = parent; } - - public void run() { + + @Override + public void run() { connect(); while (keepConnected) { try { @@ -239,20 +258,20 @@ public class Console extends JFrame { keepConnected = false; } } - + try { conn.close(); } catch (IOException ex) { } } - + public void sendCommand(String command) { consoleOutput.println(command); } - + public void shutdown() { keepConnected = false; } - + public void connect() { parent.print("Connecting to "+host+":"+port); try { @@ -262,7 +281,7 @@ public class Console extends JFrame { consoleOutput = new PrintWriter(conn.getOutputStream(), true); consoleInput = new BufferedReader(new InputStreamReader(conn.getInputStream())); } catch (Exception ex) { - + } } } diff --git a/source/com/c2kernel/gui/DomainKeyConsumer.java b/source/com/c2kernel/gui/DomainKeyConsumer.java old mode 100755 new mode 100644 index 9eb878c..18847cc --- a/source/com/c2kernel/gui/DomainKeyConsumer.java +++ b/source/com/c2kernel/gui/DomainKeyConsumer.java @@ -10,7 +10,7 @@ import com.c2kernel.lookup.DomainPath; public interface DomainKeyConsumer { public void push(DomainPath key); - + public void push(String name); } diff --git a/source/com/c2kernel/gui/DomainKeyListener.java b/source/com/c2kernel/gui/DomainKeyListener.java old mode 100755 new mode 100644 index 5c1575b..df18e72 --- a/source/com/c2kernel/gui/DomainKeyListener.java +++ b/source/com/c2kernel/gui/DomainKeyListener.java @@ -21,7 +21,7 @@ public interface DomainKeyListener { // return 25x25 icon for enable/disable button public ImageIcon getIcon(); - + // tooltip for the button public String getDescription(); } diff --git a/source/com/c2kernel/gui/DynamicTreeBuilder.java b/source/com/c2kernel/gui/DynamicTreeBuilder.java old mode 100755 new mode 100644 index 29a62dc..a72c156 --- a/source/com/c2kernel/gui/DynamicTreeBuilder.java +++ b/source/com/c2kernel/gui/DynamicTreeBuilder.java @@ -7,6 +7,7 @@ import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import com.c2kernel.gui.data.Node; +import com.c2kernel.gui.data.NodeItem; import com.c2kernel.gui.data.NodeSubscriber; import com.c2kernel.lookup.Path; import com.c2kernel.utils.Language; @@ -33,7 +34,7 @@ public class DynamicTreeBuilder implements NodeSubscriber { private DefaultMutableTreeNode loading; private static ImageIcon loadIcon = Resource.getImageResource("loading.gif"); private static ImageIcon pauseIcon = Resource.getImageResource("reload.gif"); - + /** * The newly created DynamicTreeBuilder records its parent node - the one for which it will build child nodes for. * @param nodeClicked The Parent Tree Node that will be populated. @@ -67,7 +68,8 @@ public class DynamicTreeBuilder implements NodeSubscriber { /** * Used by the JTree to find the text representation of the node. */ - public String toString() { + @Override + public String toString() { switch (state) { case IDLE: return Language.translate("Initializing Tree Node Loader"); @@ -80,9 +82,9 @@ public class DynamicTreeBuilder implements NodeSubscriber { default: return ""; } - + } - + public ImageIcon getIcon() { if (state == LOADING) return loadIcon; @@ -94,19 +96,21 @@ public class DynamicTreeBuilder implements NodeSubscriber { return loading; } - public void add(Node newNode) { + @Override + public void add(Node newNode) { Logger.msg(2, "DynamicTreeBuilder.add() - Received item for tree. Name: "+newNode); - + // have we inserted the node yet? SwingUtilities.invokeLater(new TreeAddThread(newNode)); } - + class TreeAddThread implements Runnable { Node newNode; TreeAddThread(Node newNode) { this.newNode = newNode; } - public void run() { + @Override + public void run() { boolean inserted = false; DefaultMutableTreeNode newTreeNode = newNode.getTreeNode(); // loop though all children unless we have done the insertion @@ -133,21 +137,23 @@ public class DynamicTreeBuilder implements NodeSubscriber { if (!inserted) treeModel.insertNodeInto(newTreeNode, parent, parent.getChildCount()); } - + } - + class TreeRemoveThread implements Runnable { DefaultMutableTreeNode oldNode; TreeRemoveThread(DefaultMutableTreeNode oldNode) { this.oldNode = oldNode; } - - public void run() { + + @Override + public void run() { treeModel.removeNodeFromParent(oldNode); } } - - public void end(boolean more) { + + @Override + public void end(boolean more) { if (more) { state = PARTIAL; } @@ -158,9 +164,10 @@ public class DynamicTreeBuilder implements NodeSubscriber { SwingUtilities.invokeLater(new TreeRemoveThread(loading)); } } - } - - public void remove(Path path) { + } + + @Override + public void remove(Path path) { synchronized (treeModel) { for (int i=0; i requiredTabs = myEntity.getTabs(); + + for (Object name2 : requiredTabs) { + String tabName = (String)name2; if (tabName != null) { //create class instances and initialise - Class myClass = null; + Class myClass = null; //look up the required TabbedPane try { myClass = Class.forName(this.getClass().getPackage().getName() + ".tabs." + tabName + "Pane"); @@ -69,7 +72,7 @@ public class EntityDetails extends JPanel implements ChangeListener, Runnable { Logger.msg(0, "ItemDetails. - Instantiation Error! " + e); } catch (IllegalAccessException e) { Logger.msg(0, "ItemDetails. - Illegal Method Access Error! Class was probably not a ItemTabPane: " + e); - } + } if (componentToAdd == null) componentToAdd = new EntityTabPane(tabName, null); componentToAdd.setParent(this); @@ -94,12 +97,13 @@ public class EntityDetails extends JPanel implements ChangeListener, Runnable { } - public void stateChanged(javax.swing.event.ChangeEvent p1) { + @Override + public void stateChanged(javax.swing.event.ChangeEvent p1) { initialisePane((EntityTabPane)myTabbedPane.getSelectedComponent()); } public void initialisePane(EntityTabPane pane) { - Boolean isInit = (Boolean)childPanes.get(pane); + Boolean isInit = childPanes.get(pane); if (isInit.booleanValue() == false) { Logger.msg(4,"Initialising "+pane.getTabName()); pane.initForEntity(myEntity); @@ -155,18 +159,18 @@ public class EntityDetails extends JPanel implements ChangeListener, Runnable { public void discardTabs() { myTabbedPane.removeChangeListener(this); myTabbedPane.removeAll(); - for (Iterator iter = childPanes.keySet().iterator(); iter.hasNext();) { - EntityTabPane element = (EntityTabPane)iter.next(); + for (Iterator iter = childPanes.keySet().iterator(); iter.hasNext();) { + EntityTabPane element = iter.next(); element.destroy(); iter.remove(); } } - + public int getSysKey() { return myEntity.getSysKey(); } - + public void closeTab() { desktopManager.remove(myEntity.getSysKey()); Logger.msg(5,"Remove master Tab :"+myEntity.getType()+ " SysKey "+myEntity.getSysKey()); @@ -177,7 +181,7 @@ public class EntityDetails extends JPanel implements ChangeListener, Runnable { if (e.getActionCommand().equals("close")) closeTab(); } - + public void runCommand(String tab, String command) { if (initialized) { int tabIndex = findTab(tab); @@ -185,7 +189,7 @@ public class EntityDetails extends JPanel implements ChangeListener, Runnable { if (tabIndex == -1) { Logger.error("Tab "+tab+" not found for command "+command); return; - } + } EntityTabPane startPane = (EntityTabPane)myTabbedPane.getComponentAt(tabIndex); myTabbedPane.setSelectedIndex(tabIndex); initialisePane(startPane); @@ -198,7 +202,7 @@ public class EntityDetails extends JPanel implements ChangeListener, Runnable { startCommand = command; } } - + protected int findTab(String tabName) { for (int i=0; i< myTabbedPane.getTabCount(); i++) { EntityTabPane thisPane = (EntityTabPane)myTabbedPane.getComponentAt(i); @@ -207,7 +211,7 @@ public class EntityDetails extends JPanel implements ChangeListener, Runnable { } return -1; } - + public void refresh() { @@ -215,7 +219,8 @@ public class EntityDetails extends JPanel implements ChangeListener, Runnable { /** * */ - protected void finalize() throws Throwable { + @Override + protected void finalize() throws Throwable { Logger.msg(7, "EntityDetails "+myEntity.getSysKey()+" reaped"); super.finalize(); } diff --git a/source/com/c2kernel/gui/EntityFinder.java b/source/com/c2kernel/gui/EntityFinder.java old mode 100755 new mode 100644 index 6f23a5d..18038c9 --- a/source/com/c2kernel/gui/EntityFinder.java +++ b/source/com/c2kernel/gui/EntityFinder.java @@ -10,7 +10,14 @@ import java.io.IOException; import java.util.Enumeration; import java.util.StringTokenizer; -import javax.swing.*; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JTextField; +import javax.swing.JToggleButton; import com.c2kernel.lookup.DomainPath; import com.c2kernel.lookup.LDAPLookup; @@ -28,7 +35,7 @@ public class EntityFinder extends Box implements Runnable { LDAPLookup lookup = Gateway.getLDAPLookup(); DomainKeyConsumer defaultConsumer = null; DomainKeyConsumer currentConsumer = null; - Enumeration matches; + Enumeration matches; Path rootNode = MainFrame.userNode.getPath(); static protected ImageIcon mFindIcon = null; @@ -54,7 +61,7 @@ public class EntityFinder extends Box implements Runnable { inputField.setText(key); runSearch(); } - + public void setDefaultConsumer(DomainKeyConsumer newConsumer) { defaultConsumer = newConsumer; currentConsumer = newConsumer; @@ -64,43 +71,46 @@ public class EntityFinder extends Box implements Runnable { currentConsumer = newConsumer; findButton.setText(label); } - + public void clearConsumer(DomainKeyConsumer oldConsumer) { if (currentConsumer == oldConsumer) { currentConsumer = defaultConsumer; findButton.setText(""); } } - + private void initPanel() { JLabel search = new JLabel(" "+Language.translate("Search")+":"); add(search); add(Box.createHorizontalStrut(7)); - + inputField = new JTextField(20); add(inputField); add(Box.createHorizontalStrut(5)); inputField.addActionListener( new ActionListener() { - public void actionPerformed(ActionEvent e) { + @Override + public void actionPerformed(ActionEvent e) { pushNewKey(inputField.getText()); } }); - + findButton = new JButton(mFindIcon);//(Language.translate("Find")); findButton.setMargin(new Insets(2, 5, 2, 5)); findButton.addActionListener( new ActionListener() { - public void actionPerformed(ActionEvent e) { + @Override + public void actionPerformed(ActionEvent e) { pushNewKey(inputField.getText()); } }); add(findButton); add(Box.createHorizontalStrut(5)); - findNextButton = new JButton(mNextIcon);//(Language.translate("Next")); + findNextButton = new JButton(mNextIcon);//(Language.translate("Next")); findNextButton.setMargin(new Insets(2, 5, 2, 5)); findNextButton.addActionListener( new ActionListener() { - public void actionPerformed(ActionEvent e) { + @Override + public void actionPerformed(ActionEvent e) { MainFrame.status.setText("Navigating to next match"); nextMatch(); } @@ -118,7 +128,7 @@ public class EntityFinder extends Box implements Runnable { String listenerName = tok.nextToken(); Logger.msg(6, "ItemFinder() - creating a " + listenerName); try { - Class listenerClass = Class.forName(listenerName); + Class listenerClass = Class.forName(listenerName); DomainKeyListener newListener = (DomainKeyListener)listenerClass.newInstance(); newListener.init(); newListener.setConsumer(this); JToggleButton listenerButton = new JToggleButton(newListener.getIcon(), false); @@ -139,19 +149,20 @@ public class EntityFinder extends Box implements Runnable { Thread searcher = new Thread(this); searcher.start(); } - - public void run() { + + @Override + public void run() { Thread.currentThread().setName("Entity Search"); MainFrame.status.setText("Searching. Please Wait"); findButton.setEnabled(false); findNextButton.setEnabled(false); String searchTerm = inputField.getText(); if (searchTerm.length() == 0) return; // don't allow null searches - findNextButton.setEnabled(false); + findNextButton.setEnabled(false); matches = lookup.search(rootNode,inputField.getText()); if (!matches.hasMoreElements()) { MainFrame.status.setText("No results"); currentConsumer.push(searchTerm); // for subscribers who don't care if it exists - findButton.setEnabled(true); + findButton.setEnabled(true); return; } MainFrame.status.setText("Selecting first match."); @@ -161,7 +172,7 @@ public class EntityFinder extends Box implements Runnable { void nextMatch() { findButton.setEnabled(false); findNextButton.setEnabled(false); - DomainPath nextMatch = (DomainPath)matches.nextElement(); + DomainPath nextMatch = (DomainPath)matches.nextElement(); try { currentConsumer.push(nextMatch); @@ -171,8 +182,8 @@ public class EntityFinder extends Box implements Runnable { //case the item searched is not found ! } findButton.setEnabled(true); - findNextButton.setToolTipText("Click to show next match"); - if (matches.hasMoreElements()) findNextButton.setEnabled(true); + findNextButton.setToolTipText("Click to show next match"); + if (matches.hasMoreElements()) findNextButton.setEnabled(true); } private class ListenerButtonListener implements ItemListener { @@ -184,7 +195,8 @@ public class EntityFinder extends Box implements Runnable { this.listenerButton = listenerButton; } - public void itemStateChanged(ItemEvent e) { + @Override + public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { // Switch on try { diff --git a/source/com/c2kernel/gui/EntityTabManager.java b/source/com/c2kernel/gui/EntityTabManager.java index 1e01ad0..b465570 100644 --- a/source/com/c2kernel/gui/EntityTabManager.java +++ b/source/com/c2kernel/gui/EntityTabManager.java @@ -2,7 +2,6 @@ package com.c2kernel.gui; import java.awt.GridLayout; import java.util.ArrayList; import java.util.HashMap; -import java.util.Iterator; import javax.swing.BorderFactory; import javax.swing.JPanel; @@ -21,7 +20,7 @@ import com.c2kernel.utils.Logger; public class EntityTabManager extends JPanel { private MainFrame mMainframe; - + protected HashMap openItems = new HashMap(); protected JTabbedPaneWithCloseIcons tabbedPane = new JTabbedPaneWithCloseIcons(); //JTabbedPane tabbedPane = new JTabbedPane(); @@ -50,11 +49,11 @@ public class EntityTabManager extends JPanel // get currently selected item to set location tabbedPane.addTab(thisEntity.getName(), thisEntity.getIcon(), requestedDetails, Integer.toString(thisEntity.getSysKey())); - - + + } else { //opened window but different nodeitem - requestedDetails = (EntityDetails)openItems.get(new Integer(thisEntity.getSysKey())); + requestedDetails = openItems.get(new Integer(thisEntity.getSysKey())); } tabbedPane.setSelectedComponent(requestedDetails); return requestedDetails; @@ -64,24 +63,23 @@ public class EntityTabManager extends JPanel this.myMenuBuilder = myMenuBuilder; } - public void remove(int sysKey) { + @Override + public void remove(int sysKey) { Integer sysKeyObj = new Integer(sysKey); if (!openItems.containsKey(sysKeyObj)) return; - EntityDetails tabToClose = (EntityDetails)openItems.get(sysKeyObj); + EntityDetails tabToClose = openItems.get(sysKeyObj); tabbedPane.remove(tabToClose); tabToClose.discardTabs(); openItems.remove(sysKeyObj); } - + public void closeAll(boolean keepOpen) { ArrayList toRemove = new ArrayList(); - for (Iterator iter = openItems.keySet().iterator(); iter.hasNext();) { - Integer element = (Integer) iter.next(); + for (Integer element : openItems.keySet()) { if (keepOpen && openItems.get(element).equals(tabbedPane.getSelectedComponent())) continue; toRemove.add(element); } - for (Iterator iter = toRemove.iterator(); iter.hasNext();) { - Integer element = (Integer) iter.next(); + for (Integer element : toRemove) { remove(element.intValue()); } } diff --git a/source/com/c2kernel/gui/LoginBox.java b/source/com/c2kernel/gui/LoginBox.java old mode 100755 new mode 100644 index f813cef..415469b --- a/source/com/c2kernel/gui/LoginBox.java +++ b/source/com/c2kernel/gui/LoginBox.java @@ -8,11 +8,23 @@ package com.c2kernel.gui; * @author not attributable * @version 1.0 */ -import java.awt.*; +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; -import javax.swing.*; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JPasswordField; +import javax.swing.JTextField; import javax.swing.border.EmptyBorder; import com.c2kernel.common.InvalidDataException; @@ -150,7 +162,7 @@ public class LoginBox extends JFrame { OK.setText(Language.translate("OK")); OK.addActionListener(new Frame2_OK_actionAdapter(this)); OK.setPreferredSize(new Dimension(80,30)); - + Cancel.setActionCommand("Cancel"); Cancel.setText(Language.translate("Cancel")); Cancel.addActionListener(new Frame2_Cancel_actionAdapter(this)); @@ -183,7 +195,7 @@ public class LoginBox extends JFrame { c.weightx=0; c.weighty=1; getContentPane().add(passwordLabel,c); - + initBasicConstraints(c,3,1,1,1); c.anchor=GridBagConstraints.SOUTH; c.fill = GridBagConstraints.HORIZONTAL; @@ -225,7 +237,7 @@ public class LoginBox extends JFrame { msgPane.add(errorLabel); msgPane.add(Box.createGlue()); getContentPane().add(msgPane,c); - + ((JPanel)getContentPane()).setBorder(new EmptyBorder(0,0,0,5)); pack(); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); @@ -284,7 +296,8 @@ class Frame2_Cancel_actionAdapter implements java.awt.event.ActionListener { Frame2_Cancel_actionAdapter(LoginBox adaptee) { this.adaptee = adaptee; } - public void actionPerformed(ActionEvent e) { + @Override +public void actionPerformed(ActionEvent e) { adaptee.Cancel_actionPerformed(e); } } @@ -295,7 +308,8 @@ class Frame2_OK_actionAdapter implements java.awt.event.ActionListener { Frame2_OK_actionAdapter(LoginBox adaptee) { this.adaptee = adaptee; } - public void actionPerformed(ActionEvent e) { + @Override +public void actionPerformed(ActionEvent e) { adaptee.OK_actionPerformed(e); } } @@ -306,7 +320,8 @@ class LoginBox_this_keyAdapter extends java.awt.event.KeyAdapter { LoginBox_this_keyAdapter(LoginBox adaptee) { this.adaptee = adaptee; } - public void keyPressed(KeyEvent e) { + @Override +public void keyPressed(KeyEvent e) { adaptee.this_keyPressed(e); } } \ No newline at end of file diff --git a/source/com/c2kernel/gui/Main.java b/source/com/c2kernel/gui/Main.java old mode 100755 new mode 100644 index 4c77d63..5a9209e --- a/source/com/c2kernel/gui/Main.java +++ b/source/com/c2kernel/gui/Main.java @@ -20,7 +20,7 @@ public class Main extends StandardClient Logger.initConsole("GUI"); MainFrame client = new MainFrame(); client.showLogin(); - + } catch( Exception ex ) { diff --git a/source/com/c2kernel/gui/MainFrame.java b/source/com/c2kernel/gui/MainFrame.java index e561f1f..589e0b4 100644 --- a/source/com/c2kernel/gui/MainFrame.java +++ b/source/com/c2kernel/gui/MainFrame.java @@ -14,10 +14,10 @@ import java.net.URL; import java.util.Properties; import java.util.StringTokenizer; -import javax.swing.*; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JComboBox; +import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSplitPane; @@ -53,15 +53,17 @@ public class MainFrame extends javax.swing.JFrame { public static boolean isAdmin; int splitPanePos; public static final JFileChooser xmlChooser; - + static { xmlChooser = new JFileChooser(); xmlChooser.addChoosableFileFilter( new javax.swing.filechooser.FileFilter() { - public String getDescription() { + @Override + public String getDescription() { return "XML Files"; } - public boolean accept(File f) { + @Override + public boolean accept(File f) { if (f.isDirectory() || (f.isFile() && f.getName().endsWith(".xml"))) { return true; } @@ -72,7 +74,7 @@ public class MainFrame extends javax.swing.JFrame { /** Creates new gui client for Cristal2 */ public MainFrame() { - + // Load gui preferences try { FileInputStream prefsfile = @@ -82,7 +84,7 @@ public class MainFrame extends javax.swing.JFrame { } catch (IOException e) { Logger.msg(2, "Creating new preference file"); } - + // set look & feel from pref try { String lf = getPref("Style", null); @@ -92,9 +94,9 @@ public class MainFrame extends javax.swing.JFrame { SwingUtilities.updateComponentTreeUI(this); } catch (Exception e) { e.printStackTrace(); - } + } } - + public void showLogin() { // Log in logoURL = Gateway.getProperty("Logo"); @@ -108,7 +110,7 @@ public class MainFrame extends javax.swing.JFrame { } catch (java.net.MalformedURLException m) { imageHolder = Resource.getImageResource(logoURL); } - + LoginBox login = new LoginBox( 5, @@ -116,19 +118,19 @@ public class MainFrame extends javax.swing.JFrame { getPref("lastUser."+Gateway.getCentreId(), null), bottomMessage, imageHolder, this); - + login.setVisible(true); } - + public void mainFrameShow() { prefs.setProperty("lastUser."+Gateway.getCentreId(), userAgent.getName()); isAdmin = userAgent.getPath().hasRole("Admin"); GridBagLayout gridbag = new GridBagLayout(); getContentPane().setLayout(gridbag); - + this.setTitle( userAgent.getName()+"@"+Gateway.getProperty("Name") + " - " + Language.translate("Cristal 2")); - + String iconFile = Gateway.getProperty("AppIcon"); if (iconFile != null) this.setIconImage(Resource.getImageResource(iconFile).getImage()); @@ -137,7 +139,8 @@ public class MainFrame extends javax.swing.JFrame { Resource.getImageResource("loading.gif"); // close listener addWindowListener(new java.awt.event.WindowAdapter() { - public void windowClosing(java.awt.event.WindowEvent evt) { + @Override + public void windowClosing(java.awt.event.WindowEvent evt) { exitForm(); } }); @@ -167,7 +170,7 @@ public class MainFrame extends javax.swing.JFrame { getContentPane().add(itemFinder); // register the browser as the key consumer itemFinder.setDefaultConsumer(treeBrowser); - + c.gridy++; c.weightx = 1.0; c.weighty = 1.0; @@ -266,13 +269,13 @@ public class MainFrame extends javax.swing.JFrame { getSplitPanel().validate(); } - public static JComboBox getExecutionPlugins() { + public static JComboBox getExecutionPlugins() { JComboBox plugins = new JComboBox(); // create execution selector Executor defaultExecutor = new DefaultExecutor(); plugins.addItem(defaultExecutor); plugins.setSelectedIndex(0); - + // load execution plugins String pluginList = Gateway.getProperty("Executors"); if (pluginList != null) { @@ -280,9 +283,9 @@ public class MainFrame extends javax.swing.JFrame { while (tok.hasMoreTokens()) { String pluginName = tok.nextToken(); try { - Class pluginClass = Class.forName(pluginName); - Executor domainExecutor = (Executor)pluginClass.newInstance(); - plugins.addItem(domainExecutor); + Class pluginClass = Class.forName(pluginName); + Executor domainExecutor = (Executor)pluginClass.newInstance(); + plugins.addItem(domainExecutor); } catch (Exception ex) { Logger.error("Could not load the executor plugin "+pluginName); } diff --git a/source/com/c2kernel/gui/MenuBuilder.java b/source/com/c2kernel/gui/MenuBuilder.java index bf27287..6d1bfbc 100644 --- a/source/com/c2kernel/gui/MenuBuilder.java +++ b/source/com/c2kernel/gui/MenuBuilder.java @@ -5,7 +5,22 @@ import java.awt.event.ItemListener; import java.util.Enumeration; import java.util.HashMap; -import javax.swing.*; +import javax.swing.Box; +import javax.swing.ButtonGroup; +import javax.swing.Icon; +import javax.swing.JCheckBoxMenuItem; +import javax.swing.JDialog; +import javax.swing.JEditorPane; +import javax.swing.JLabel; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; +import javax.swing.JRadioButtonMenuItem; +import javax.swing.JScrollPane; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; +import javax.swing.UIManager.LookAndFeelInfo; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import javax.swing.text.html.HTMLEditorKit; @@ -34,11 +49,11 @@ public class MenuBuilder extends JMenuBar implements ActionListener, ItemListene protected JMenu prefMenu; protected JMenu helpMenu; protected HashMap availableMenus = new HashMap(); - + public MenuBuilder() {} - - /** Creates new DynamicMenuBuilder */ + + /** Creates new DynamicMenuBuilder */ public MenuBuilder(MainFrame parentFrame) { myParentFrame = parentFrame; @@ -63,14 +78,14 @@ public class MenuBuilder extends JMenuBar implements ActionListener, ItemListene addServerConsoles(); ButtonGroup styleButtonGroup = new ButtonGroup(); - for (int i = 0; i < availableViews.length; i++) - addMenuItem(availableViews[i].getName(), "style", styleButtonGroup, 0); - + for (LookAndFeelInfo availableView : availableViews) + addMenuItem(availableView.getName(), "style", styleButtonGroup, 0); + addMenuItem(Language.translate("Tree Browser"), "preferences", null, MainFrame.getPref("ShowTree", "true").equals("true")?2:1); addMenuItem(Language.translate("Outcome Field Help"), "preferences", null, MainFrame.getPref("ShowHelp", "true").equals("true")?2:1); addMenuItem(Language.translate("Graph Properties"), "preferences", null, MainFrame.getPref("ShowProps", "true").equals("true")?2:1); addMenuItem(Language.translate("About"), "help", null, 0); - + add(fileMenu); add(consoleMenu); add(styleMenu); @@ -78,10 +93,10 @@ public class MenuBuilder extends JMenuBar implements ActionListener, ItemListene add(helpMenu); } /** - * + * */ private void addServerConsoles() { - Enumeration servers = Gateway.getLDAPLookup().searchEntities(new DomainPath("/servers")); + Enumeration servers = Gateway.getLDAPLookup().searchEntities(new DomainPath("/servers")); while(servers.hasMoreElements()) { Path thisServerPath = (Path)servers.nextElement(); try { @@ -117,7 +132,7 @@ public class MenuBuilder extends JMenuBar implements ActionListener, ItemListene myItem = new JCheckBoxMenuItem(itemName, checkBox == 2); } myItem.addActionListener(this); - JMenu myMenu = (JMenu) availableMenus.get(menuName); + JMenu myMenu = availableMenus.get(menuName); myMenu.add(myItem); } } @@ -133,6 +148,7 @@ public class MenuBuilder extends JMenuBar implements ActionListener, ItemListene return -1; } //listens for events performed on the menu items + @Override public void actionPerformed(java.awt.event.ActionEvent e) { String s = e.getActionCommand(); @@ -180,7 +196,7 @@ public class MenuBuilder extends JMenuBar implements ActionListener, ItemListene { Logger.error(ex); } - } + } else Logger.msg(1, "MenuBuilder.actionPerformed() - No action associated with the event received"); } @@ -189,7 +205,7 @@ public class MenuBuilder extends JMenuBar implements ActionListener, ItemListene { JOptionPane myPane = new JOptionPane(); Box about = Box.createVerticalBox(); - + String aboutInfo; try { @@ -201,7 +217,7 @@ public class MenuBuilder extends JMenuBar implements ActionListener, ItemListene } JLabel title = new JLabel(aboutInfo); about.add(title); - + about.add(new JLabel("Domain version: "+Resource.getDomainVersion())); about.add(new JLabel("Kernel version: "+Resource.getKernelVersion())); // get license info @@ -210,7 +226,7 @@ public class MenuBuilder extends JMenuBar implements ActionListener, ItemListene if (domlictxt != null) lictxt.append(domlictxt); lictxt.append(Resource.getTextResource("textFiles/license.html")); - + JEditorPane license = new JEditorPane(); license.setEditable(false); license.setEditorKit(new HTMLEditorKit()); @@ -220,7 +236,7 @@ public class MenuBuilder extends JMenuBar implements ActionListener, ItemListene JScrollPane scroll = new JScrollPane(license); scroll.setPreferredSize(new Dimension(300,200)); license.setCaretPosition(0); - + about.add(scroll); myPane.setMessage(about); myPane.setMessageType(JOptionPane.INFORMATION_MESSAGE); @@ -232,7 +248,8 @@ public class MenuBuilder extends JMenuBar implements ActionListener, ItemListene dialog.setVisible(true); } - public void hyperlinkUpdate(HyperlinkEvent e) { + @Override +public void hyperlinkUpdate(HyperlinkEvent e) { try { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler "+e.getURL().toString()); @@ -240,7 +257,8 @@ public class MenuBuilder extends JMenuBar implements ActionListener, ItemListene Logger.exceptionDialog(ex); } } - + + @Override public void itemStateChanged(java.awt.event.ItemEvent e) { } diff --git a/source/com/c2kernel/gui/TreeBrowser.java b/source/com/c2kernel/gui/TreeBrowser.java old mode 100755 new mode 100644 index ccee681..72cf738 --- a/source/com/c2kernel/gui/TreeBrowser.java +++ b/source/com/c2kernel/gui/TreeBrowser.java @@ -5,10 +5,19 @@ import java.awt.Dimension; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; -import javax.swing.*; +import javax.swing.ImageIcon; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTree; +import javax.swing.ToolTipManager; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeExpansionListener; -import javax.swing.tree.*; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.DefaultTreeCellRenderer; +import javax.swing.tree.DefaultTreeModel; +import javax.swing.tree.TreePath; +import javax.swing.tree.TreeSelectionModel; import com.c2kernel.gui.data.Node; import com.c2kernel.gui.data.NodeEntity; @@ -20,7 +29,7 @@ import com.c2kernel.utils.Logger; * @version $Revision: 1.31 $ $Date: 2006/01/17 07:49:44 $ * @author $Author: abranson $ */ - + // must put in top level list of loaded items, so we don't have duplicates public class TreeBrowser extends JPanel implements DomainKeyConsumer { @@ -39,10 +48,12 @@ public class TreeBrowser extends JPanel implements DomainKeyConsumer tree.setToggleClickCount(3); // need three clicks to expand a branch tree.addTreeExpansionListener( new TreeExpansionListener() { - public void treeCollapsed(TreeExpansionEvent e) { + @Override + public void treeCollapsed(TreeExpansionEvent e) { //REVISIT: possible reaping here if things are getting heavy } - public void treeExpanded(TreeExpansionEvent e) { + @Override + public void treeExpanded(TreeExpansionEvent e) { TreePath p = e.getPath(); // find the clicked tree node DefaultMutableTreeNode nodeClicked = (DefaultMutableTreeNode)p.getLastPathComponent(); @@ -71,7 +82,8 @@ public class TreeBrowser extends JPanel implements DomainKeyConsumer loading.start(); } - public void push(DomainPath target) { + @Override + public void push(DomainPath target) { Logger.debug("Opening tree node "+target); String[] components = target.getPath(); Node currentNode = userRoot; @@ -109,15 +121,16 @@ public class TreeBrowser extends JPanel implements DomainKeyConsumer MainFrame.status.setText("Done"); } } - - public void push(String name) { + + @Override + public void push(String name) { // only interested in real paths - JOptionPane.showMessageDialog(null, "'"+name+"' was not found.", + JOptionPane.showMessageDialog(null, "'"+name+"' was not found.", "No results", JOptionPane.INFORMATION_MESSAGE); } - - private void dumpPath(TreePath selPath, int logLevel) { + + private static void dumpPath(TreePath selPath, int logLevel) { if (selPath == null) { Logger.msg(logLevel, "TreeBrowser.dumpPath() - selPath null"); return; } for (int i =0; i nodes = childNodes.values().iterator(); nodes.hasNext();) { + newNode = nodes.next(); Logger.msg("subscribeNode target.add("+newNode.name+")"); target.add(newNode); } } } } - + public void loadMore() { Thread loading = new Thread(this); loading.start(); @@ -128,62 +128,58 @@ public abstract class Node implements Runnable { public void add(Node newNode) { synchronized(childNodes) { childNodes.put(newNode.getPath(), newNode); - for (Iterator e = subscribers.iterator(); e.hasNext();) { - NodeSubscriber thisSub = (NodeSubscriber)e.next(); - + for (NodeSubscriber thisSub : subscribers) { thisSub.add(newNode); } } } - + public void remove(Path oldPath) { synchronized(childNodes) { childNodes.remove(oldPath); - for (Iterator e = subscribers.iterator(); e.hasNext();) { - NodeSubscriber thisSub = (NodeSubscriber)e.next(); + for (NodeSubscriber thisSub : subscribers) { thisSub.remove(oldPath); } } } - + public void removeAllChildren() { synchronized(childNodes) { - Path thisPath; while (childNodes.keySet().iterator().hasNext()) { - remove((Path)childNodes.keySet().iterator().next()); + remove(childNodes.keySet().iterator().next()); } } } public Node getChildNode(Path itsPath) { - for (Iterator i = childNodes.keySet().iterator(); i.hasNext();) { - Object next = i.next(); - if ( next.equals(itsPath) ) return (Node)childNodes.get(next); + for (Iterator i = childNodes.keySet().iterator(); i.hasNext();) { + Object next = i.next(); + if ( next.equals(itsPath) ) return childNodes.get(next); } return null; } // end of current batch public void end(boolean more) { - for (Iterator e = subscribers.iterator(); e.hasNext();) { - NodeSubscriber thisSub = (NodeSubscriber)e.next(); + for (NodeSubscriber thisSub : subscribers) { thisSub.end(more); } } - public void run() { + @Override + public void run() { Thread.currentThread().setName("Node Loader: "+name); loadChildren(); } public abstract void loadChildren(); - + public void refresh() { removeAllChildren(); loadChildren(); } - + // Getters and Setters public int getSysKey() { return sysKey; } @@ -198,8 +194,9 @@ public abstract class Node implements Runnable { public Path getPath() { return binding; } public DynamicTreeBuilder getTreeBuilder() { return loader; } - - public String toString() { + + @Override + public String toString() { if (this.name.length() > 0) { return this.name; } @@ -214,7 +211,7 @@ public abstract class Node implements Runnable { public String getIconName() { return iconName; } - + public void setIcon(String icon) { iconName = icon; this.icon = Resource.getImageResource("typeicons/"+icon+"_16.png"); @@ -224,6 +221,7 @@ public abstract class Node implements Runnable { JPopupMenu popup = new JPopupMenu(); JMenuItem menuItem = new JMenuItem(Language.translate("Refresh")); menuItem.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { if (isExpandable) refresh(); } diff --git a/source/com/c2kernel/gui/data/NodeAgent.java b/source/com/c2kernel/gui/data/NodeAgent.java index 138b576..9f6cdad 100644 --- a/source/com/c2kernel/gui/data/NodeAgent.java +++ b/source/com/c2kernel/gui/data/NodeAgent.java @@ -18,14 +18,16 @@ public class NodeAgent extends NodeEntity { super(path, desktop); } - public void loadChildren() { + @Override + public void loadChildren() { } - - public ArrayList getTabs() { + + @Override + public ArrayList getTabs() { ArrayList requiredTabs = super.getTabs(); requiredTabs.add("AgentProperties"); requiredTabs.add("JobList"); - return requiredTabs; - } + return requiredTabs; + } } diff --git a/source/com/c2kernel/gui/data/NodeCollection.java b/source/com/c2kernel/gui/data/NodeCollection.java old mode 100755 new mode 100644 index 3b02098..f55f8cd --- a/source/com/c2kernel/gui/data/NodeCollection.java +++ b/source/com/c2kernel/gui/data/NodeCollection.java @@ -16,7 +16,7 @@ import com.c2kernel.utils.Logger; public class NodeCollection extends Node { ItemProxy parent; - Parent2ChildCollection thisCollection; + Parent2ChildCollection thisCollection; String path; public NodeCollection(ItemProxy parent, String name, EntityTabManager desktop) { @@ -28,19 +28,20 @@ public class NodeCollection extends Node { this.makeExpandable(); } - public void loadChildren() { + @Override + public void loadChildren() { Logger.msg(8, "NodeCollection::loadChildren()"); try { - thisCollection = (Parent2ChildCollection)parent.getObject("Collection/"+name); + thisCollection = (Parent2ChildCollection)parent.getObject("Collection/"+name); } catch (ObjectNotFoundException ex) { end(false); - return; + return; } - + this.type = thisCollection.getClass().getName(); int lastDot = this.type.lastIndexOf('.'); if (lastDot > -1) this.type = this.type.substring(lastDot+1); - ArrayList collectionMembers = thisCollection.getMembers().list; + ArrayList collectionMembers = thisCollection.getMembers().list; for (int i=0; i children; public NodeContext(Path path, EntityTabManager desktop) { super(path, desktop); @@ -22,7 +22,8 @@ public class NodeContext extends Node implements DomainPathSubscriber { } - public void loadChildren() { + @Override + public void loadChildren() { if (children == null) { Gateway.getProxyManager().subscribeTree(this, (DomainPath)binding); children = binding.getChildren(); @@ -38,16 +39,19 @@ public class NodeContext extends Node implements DomainPathSubscriber { } end(children.hasMoreElements()); } - - public void pathAdded(DomainPath path) { + + @Override + public void pathAdded(DomainPath path) { add(newNode(path)); } - public void refresh() { + @Override + public void refresh() { children = null; super.refresh(); } - public void pathRemoved(DomainPath path) { + @Override + public void pathRemoved(DomainPath path) { remove(path); } diff --git a/source/com/c2kernel/gui/data/NodeEntity.java b/source/com/c2kernel/gui/data/NodeEntity.java index 8c05afd..cce4f68 100644 --- a/source/com/c2kernel/gui/data/NodeEntity.java +++ b/source/com/c2kernel/gui/data/NodeEntity.java @@ -56,11 +56,13 @@ public abstract class NodeEntity extends Node { /** * */ - public JPopupMenu getPopupMenu() { + @Override + public JPopupMenu getPopupMenu() { JPopupMenu popup = super.getPopupMenu(); JMenuItem openItem = new JMenuItem(Language.translate("Open")); openItem.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { + @Override + public void actionPerformed(ActionEvent e) { openItem(); } }); @@ -68,11 +70,11 @@ public abstract class NodeEntity extends Node { popup.add(openItem); return popup; } - + public void openItem() { desktop.add(this); } - + public ArrayList getTabs() { ArrayList requiredTabs = new ArrayList(); return requiredTabs; diff --git a/source/com/c2kernel/gui/data/NodeItem.java b/source/com/c2kernel/gui/data/NodeItem.java index 84cba97..30f7ce3 100644 --- a/source/com/c2kernel/gui/data/NodeItem.java +++ b/source/com/c2kernel/gui/data/NodeItem.java @@ -3,7 +3,6 @@ package com.c2kernel.gui.data; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; -import java.util.Iterator; import java.util.StringTokenizer; import javax.swing.JMenuItem; @@ -31,10 +30,11 @@ public class NodeItem extends NodeEntity { makeExpandable(); } catch (Exception e) { Logger.error(e); - } + } } - public void loadChildren() { + @Override + public void loadChildren() { try { String collections = myEntity.queryData("Collection/all"); StringTokenizer tok = new StringTokenizer(collections, ","); @@ -47,16 +47,16 @@ public class NodeItem extends NodeEntity { Logger.error(e); } } - + + @Override public JPopupMenu getPopupMenu() { JPopupMenu popup = super.getPopupMenu(); popup.addSeparator(); try { - ArrayList jobList = ((ItemProxy)myEntity).getJobList(MainFrame.userAgent); + ArrayList jobList = ((ItemProxy)myEntity).getJobList(MainFrame.userAgent); ArrayList already = new ArrayList(); if (jobList.size() > 0) { - for (Iterator e = jobList.iterator(); e.hasNext();) { - Job thisJob = (Job)e.next(); + for (Job thisJob : jobList) { String stepName = thisJob.getStepName(); if (already.contains(stepName)) continue; @@ -64,12 +64,13 @@ public class NodeItem extends NodeEntity { JMenuItem menuItem = new JMenuItem(stepName); menuItem.setActionCommand(stepName); menuItem.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { + @Override + public void actionPerformed(ActionEvent e) { execute(e.getActionCommand()); } }); popup.add(menuItem); - + } } else { @@ -85,13 +86,14 @@ public class NodeItem extends NodeEntity { return popup; } - + public void execute(String stepName) { EntityDetails thisDetail = desktop.add(this); thisDetail.runCommand("Execution", stepName); } - public ArrayList getTabs() { + @Override + public ArrayList getTabs() { ArrayList requiredTabs = super.getTabs(); requiredTabs.add("Properties"); @@ -99,12 +101,12 @@ public class NodeItem extends NodeEntity { String collNames = myEntity.queryData(ClusterStorage.COLLECTION+"/all"); if (collNames.length() > 0) requiredTabs.add("Collection"); - } catch (Exception e) { } + } catch (Exception e) { } requiredTabs.add("Execution"); requiredTabs.add("History"); requiredTabs.add("Viewpoint"); requiredTabs.add("Workflow"); return requiredTabs; - + } } diff --git a/source/com/c2kernel/gui/data/NodeSubscriber.java b/source/com/c2kernel/gui/data/NodeSubscriber.java old mode 100755 new mode 100644 index ae2ab44..70af660 --- a/source/com/c2kernel/gui/data/NodeSubscriber.java +++ b/source/com/c2kernel/gui/data/NodeSubscriber.java @@ -8,6 +8,6 @@ public interface NodeSubscriber { public void add(Node newNode); public void remove(Path path); - + public void end(boolean more); } diff --git a/source/com/c2kernel/gui/tabs/AgentPropertiesPane.java b/source/com/c2kernel/gui/tabs/AgentPropertiesPane.java old mode 100755 new mode 100644 index b859c44..f0ae533 --- a/source/com/c2kernel/gui/tabs/AgentPropertiesPane.java +++ b/source/com/c2kernel/gui/tabs/AgentPropertiesPane.java @@ -22,7 +22,7 @@ public class AgentPropertiesPane extends EntityTabPane { JTextField newPassword; JTextField newPasswordConfirm; JButton changePassword; - + public AgentPropertiesPane() { super("Properties", "Agent Details"); initPanel(); @@ -38,13 +38,14 @@ public class AgentPropertiesPane extends EntityTabPane { c.gridy++; gridbag.setConstraints(roleScroll, c); add(roleScroll); - - JLabel passHeader = new JLabel("Change password"); - + + //JLabel passHeader = new JLabel("Change password"); + //TODO: Finish agent admin page } - - public void run() { - + + @Override + public void run() { + } } diff --git a/source/com/c2kernel/gui/tabs/CloseTabIcon.java b/source/com/c2kernel/gui/tabs/CloseTabIcon.java old mode 100755 new mode 100644 index ca2bf0b..a117df4 --- a/source/com/c2kernel/gui/tabs/CloseTabIcon.java +++ b/source/com/c2kernel/gui/tabs/CloseTabIcon.java @@ -29,6 +29,7 @@ class CloseTabIcon implements Icon width = 16; height = 16; } + @Override public void paintIcon(Component c, Graphics g, int x, int y) { this.x_pos = x; @@ -52,10 +53,12 @@ class CloseTabIcon implements Icon fileIcon.paintIcon(c, g, x + width, y_p); } } + @Override public int getIconWidth() { return width + (fileIcon != null ? fileIcon.getIconWidth() : 0); } + @Override public int getIconHeight() { return height; diff --git a/source/com/c2kernel/gui/tabs/CollectionPane.java b/source/com/c2kernel/gui/tabs/CollectionPane.java old mode 100755 new mode 100644 index 92492fc..7511a97 --- a/source/com/c2kernel/gui/tabs/CollectionPane.java +++ b/source/com/c2kernel/gui/tabs/CollectionPane.java @@ -6,9 +6,9 @@ import javax.swing.JTabbedPane; import com.c2kernel.collection.Aggregation; import com.c2kernel.collection.Collection; import com.c2kernel.collection.Dependency; -import com.c2kernel.entity.C2KLocalObject; import com.c2kernel.entity.proxy.EntityProxyObserver; import com.c2kernel.entity.proxy.ItemProxy; +import com.c2kernel.entity.proxy.MemberSubscription; import com.c2kernel.gui.tabs.collection.AggregationView; import com.c2kernel.gui.tabs.collection.CollectionView; import com.c2kernel.gui.tabs.collection.DependencyView; @@ -19,24 +19,20 @@ import com.c2kernel.utils.Logger; * @version $Revision: 1.36 $ $Date: 2005/10/06 06:51:15 $ * @author $Author: abranson $ */ -public class CollectionPane extends EntityTabPane implements EntityProxyObserver +public class CollectionPane extends EntityTabPane implements EntityProxyObserver> { - JTabbedPane collTabs; - + JTabbedPane collTabs; + public CollectionPane() { super("Collection", "Item Collection"); createLayout(); } - public void add(C2KLocalObject contents) + @Override + public void add(Collection contents) { Logger.msg(5, "Got "+contents.getName()+": "+contents.getClass().getName()); - if (!(contents instanceof Collection)) - { - // ignore member control objects - return; - } Logger.msg(7, "Looking for existing "+contents.getName()); CollectionView thisCollView = findTabForCollName(contents.getName()); if (thisCollView == null){ @@ -52,14 +48,15 @@ public class CollectionPane extends EntityTabPane implements EntityProxyObserver thisCollView.setItem((ItemProxy)sourceEntity.getEntity()); collTabs.add(contents.getName(), thisCollView); } - thisCollView.setCollection((Collection)contents); + thisCollView.setCollection(contents); } - public void remove(String id) + @Override + public void remove(String id) { - + } - + private CollectionView findTabForCollName(String collName) { CollectionView thisCollView = null; for (int i = 0; i < collTabs.getTabCount(); i++) { @@ -85,16 +82,24 @@ public class CollectionPane extends EntityTabPane implements EntityProxyObserver add(collTabs); } + @Override public void run() { Thread.currentThread().setName("Collection Loader"); - sourceEntity.getEntity().subscribe(this, ClusterStorage.COLLECTION, true); + sourceEntity.getEntity().subscribe(new MemberSubscription>(this, ClusterStorage.COLLECTION, true)); } - + + @Override public void reload() { Gateway.getStorage().clearCache(sourceEntity.getSysKey(), ClusterStorage.COLLECTION); collTabs.removeAll(); initForEntity(sourceEntity); } + + @Override + public void control(String control, String msg) { + // TODO Auto-generated method stub + + } } diff --git a/source/com/c2kernel/gui/tabs/DomainPathAdmin.java b/source/com/c2kernel/gui/tabs/DomainPathAdmin.java index 2e81121..408a32c 100644 --- a/source/com/c2kernel/gui/tabs/DomainPathAdmin.java +++ b/source/com/c2kernel/gui/tabs/DomainPathAdmin.java @@ -5,7 +5,12 @@ import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Enumeration; -import javax.swing.*; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JOptionPane; +import javax.swing.JScrollPane; +import javax.swing.JTable; import javax.swing.table.AbstractTableModel; import com.c2kernel.entity.proxy.ItemProxy; @@ -30,10 +35,10 @@ public class DomainPathAdmin extends Box implements ActionListener { DomainPathTableModel model; JButton addButton; JButton removeButton; - + public DomainPathAdmin() { super(BoxLayout.Y_AXIS); - + model = new DomainPathTableModel(this); table = new JTable(model); add(new JScrollPane(table)); @@ -47,19 +52,20 @@ public class DomainPathAdmin extends Box implements ActionListener { buttonBox.add(removeButton); buttonBox.add(Box.createHorizontalGlue()); add(buttonBox); - + addButton.setActionCommand("add"); addButton.addActionListener(this); removeButton.setActionCommand("remove"); - removeButton.addActionListener(this); + removeButton.addActionListener(this); } - + public void setEntity(ItemProxy entity) { this.entity = entity; model.loadPaths(); } - public void actionPerformed(ActionEvent e) { + @Override +public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("add")) { String newPath = JOptionPane.showInputDialog(this, "Enter new path,", "Add Domain Path", JOptionPane.PLAIN_MESSAGE); addDomainPath(new DomainPath(newPath)); @@ -73,23 +79,23 @@ public class DomainPathAdmin extends Box implements ActionListener { } } } - + public boolean removeDomainPath(DomainPath oldPath) { return alterDomainPath(oldPath, "Remove"); } - + public boolean addDomainPath(DomainPath newPath) { return alterDomainPath(newPath, "Add"); - } - + } + public boolean alterDomainPath(DomainPath path, String action) { - if (JOptionPane.showConfirmDialog(this, - action+" "+path+"?", - action+" Domain Path", + if (JOptionPane.showConfirmDialog(this, + action+" "+path+"?", + action+" Domain Path", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) return false; - + String[] params = new String[1]; params[0] = path.toString(); try { @@ -100,7 +106,7 @@ public class DomainPathAdmin extends Box implements ActionListener { } return true; } - + private class DomainPathTableModel extends AbstractTableModel { ArrayList domPaths; DomainPathAdmin parent; @@ -108,10 +114,10 @@ public class DomainPathAdmin extends Box implements ActionListener { this.parent = parent; domPaths = new ArrayList(); } - + public void loadPaths() { domPaths.clear(); - for (Enumeration currentPaths = Gateway.getLDAPLookup().search(new DomainPath(), entity.getName()); currentPaths.hasMoreElements();) { + for (Enumeration currentPaths = Gateway.getLDAPLookup().search(new DomainPath(), entity.getName()); currentPaths.hasMoreElements();) { DomainPath thisPath = (DomainPath)currentPaths.nextElement(); if (thisPath.getSysKey() == entity.getSystemKey()) domPaths.add(thisPath); @@ -120,10 +126,11 @@ public class DomainPathAdmin extends Box implements ActionListener { } public DomainPath getPath(int rowIndex) { - return (DomainPath)domPaths.get(rowIndex); + return domPaths.get(rowIndex); } - public void setValueAt(Object aValue, int rowIndex, int columnIndex) { - DomainPath oldPath = (DomainPath)domPaths.get(rowIndex); + @Override + public void setValueAt(Object aValue, int rowIndex, int columnIndex) { + DomainPath oldPath = domPaths.get(rowIndex); DomainPath newPath = new DomainPath((String)aValue); boolean success = parent.addDomainPath(newPath); if (success) @@ -133,28 +140,34 @@ public class DomainPathAdmin extends Box implements ActionListener { fireTableDataChanged(); } } - - public Class getColumnClass(int columnIndex) { + + @Override + public Class getColumnClass(int columnIndex) { return String.class; } - public int getColumnCount() { + @Override + public int getColumnCount() { return 1; } - public String getColumnName(int column) { + @Override + public String getColumnName(int column) { return "Path"; } - public int getRowCount() { + @Override + public int getRowCount() { return domPaths.size(); } - public Object getValueAt(int rowIndex, int columnIndex) { + @Override + public Object getValueAt(int rowIndex, int columnIndex) { return domPaths.get(rowIndex).toString(); } - public boolean isCellEditable(int rowIndex, int columnIndex) { + @Override + public boolean isCellEditable(int rowIndex, int columnIndex) { return true; } } diff --git a/source/com/c2kernel/gui/tabs/EntityTabPane.java b/source/com/c2kernel/gui/tabs/EntityTabPane.java old mode 100755 new mode 100644 index f6fae14..5a374dd --- a/source/com/c2kernel/gui/tabs/EntityTabPane.java +++ b/source/com/c2kernel/gui/tabs/EntityTabPane.java @@ -4,12 +4,23 @@ * Created on March 22, 2001, 11:39 AM */ package com.c2kernel.gui.tabs; -import java.awt.*; +import java.awt.Color; +import java.awt.Cursor; +import java.awt.Font; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; -import javax.swing.*; +import javax.swing.Box; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JToggleButton; +import javax.swing.SwingConstants; import com.c2kernel.entity.proxy.EntityProxyObserver; import com.c2kernel.gui.EntityDetails; @@ -93,10 +104,11 @@ public class EntityTabPane extends JPanel implements Runnable { refreshButton.setToolTipText(Language.translate("Refresh")); refreshButton.setMargin(new Insets(0, 0, 0, 0)); refreshButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - setCursor(new Cursor(Cursor.WAIT_CURSOR)); + @Override + public void actionPerformed(ActionEvent e) { + setCursor(new Cursor(Cursor.WAIT_CURSOR)); reload(); - setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); + setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } }); String defaultStartTab = MainFrame.getPref("DefaultStartTab", "Properties"); @@ -108,7 +120,8 @@ public class EntityTabPane extends JPanel implements Runnable { defaultStart.setSelected(tabName.equals(defaultStartTab)); defaultStart.setActionCommand(tabName); defaultStart.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { + @Override + public void actionPerformed(ActionEvent e) { if (((JToggleButton)e.getSource()).isSelected()) MainFrame.setPref("DefaultStartTab", e.getActionCommand()); } @@ -122,11 +135,12 @@ public class EntityTabPane extends JPanel implements Runnable { this.add(titleBox); } public void initForEntity(NodeEntity sourceEntity) { - this.sourceEntity = sourceEntity; + this.sourceEntity = sourceEntity; Thread loader = new Thread(this); loader.start(); } - public void run() { + @Override + public void run() { Thread.currentThread().setName("Default Entity Pane Builder"); getGridBagConstraints(); c.gridx = 0; @@ -145,23 +159,24 @@ public class EntityTabPane extends JPanel implements Runnable { } public void runCommand(String command) { } - + public void destroy() { - if (sourceEntity != null && this instanceof EntityProxyObserver) { - sourceEntity.getEntity().unsubscribe((EntityProxyObserver)this); + if (sourceEntity != null && this instanceof EntityProxyObserver) { + sourceEntity.getEntity().unsubscribe((EntityProxyObserver)this); } parent = null; } - - protected void finalize() throws Throwable { + + @Override + protected void finalize() throws Throwable { Logger.msg(7, "Reaping "+getClass().getName()); } - + static public OutcomeHandler getOutcomeHandler(String schema, int version) { String ohClassName = Gateway.getProperty("OutcomeHandler."+schema+"."+version); try { if (ohClassName != null && ohClassName.length() > 0) { - Class ohClass = Class.forName(ohClassName); + Class ohClass = Class.forName(ohClassName); return (OutcomeHandler) ohClass.newInstance(); } } catch (Exception ex) { @@ -170,7 +185,7 @@ public class EntityTabPane extends JPanel implements Runnable { ohClassName = Gateway.getProperty("OutcomeHandler.*"); try { if (ohClassName != null && ohClassName.length() > 0) { - Class ohClass = Class.forName(ohClassName); + Class ohClass = Class.forName(ohClassName); return (OutcomeHandler) ohClass.newInstance(); } } catch (Exception ex) { @@ -178,5 +193,5 @@ public class EntityTabPane extends JPanel implements Runnable { Logger.error(ex); } return new OutcomePanel(); - } + } } diff --git a/source/com/c2kernel/gui/tabs/ExecutionPane.java b/source/com/c2kernel/gui/tabs/ExecutionPane.java index 0685fa9..96b1129 100644 --- a/source/com/c2kernel/gui/tabs/ExecutionPane.java +++ b/source/com/c2kernel/gui/tabs/ExecutionPane.java @@ -7,22 +7,25 @@ import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.util.ArrayList; import java.util.Iterator; + import javax.swing.Box; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; -import com.c2kernel.entity.C2KLocalObject; + import com.c2kernel.entity.agent.Job; import com.c2kernel.entity.proxy.EntityProxyObserver; import com.c2kernel.entity.proxy.ItemProxy; +import com.c2kernel.entity.proxy.MemberSubscription; import com.c2kernel.gui.MainFrame; import com.c2kernel.gui.tabs.execution.ActivityItem; import com.c2kernel.gui.tabs.execution.ActivityViewer; +import com.c2kernel.lifecycle.instance.Workflow; import com.c2kernel.persistency.ClusterStorage; import com.c2kernel.utils.Language; import com.c2kernel.utils.Logger; -public class ExecutionPane extends EntityTabPane implements EntityProxyObserver { +public class ExecutionPane extends EntityTabPane implements EntityProxyObserver { ArrayList jobList = null; Object jobLock = new Object(); @@ -47,7 +50,7 @@ public class ExecutionPane extends EntityTabPane implements EntityProxyObserver c.anchor = GridBagConstraints.CENTER; c.fill = GridBagConstraints.BOTH; gridbag.setConstraints(view, c); - + add(view); // create activity selection box activityBox.add(new JLabel(Language.translate("Select Activity") + ": ")); @@ -55,16 +58,18 @@ public class ExecutionPane extends EntityTabPane implements EntityProxyObserver activitySelector.setEditable(false); activityBox.add(activitySelector); activitySelector.addItemListener(new ItemListener() { - public void itemStateChanged(ItemEvent selection) { + @Override + public void itemStateChanged(ItemEvent selection) { if (selection.getStateChange() == ItemEvent.SELECTED) { selectActivity(selection.getItem()); } } }); } - public void run() { + @Override + public void run() { Thread.currentThread().setName("Execution Pane Builder"); - sourceEntity.getEntity().subscribe(this, ClusterStorage.LIFECYCLE, false); + sourceEntity.getEntity().subscribe(new MemberSubscription(this, ClusterStorage.LIFECYCLE, false)); loadJobList(); init = true; if (autoRun != null) { @@ -80,8 +85,7 @@ public class ExecutionPane extends EntityTabPane implements EntityProxyObserver try { jobList = ((ItemProxy)sourceEntity.getEntity()).getJobList(MainFrame.userAgent); activitySelector.addItem(emptyAct); - for (Iterator e = jobList.iterator(); e.hasNext();) { - Job thisJob = (Job)e.next(); + for (Job thisJob : jobList) { Logger.msg(7, "ExecutionPane - loadJobList " + thisJob.isOutcomeUsed() + "|" + thisJob.getSchemaType() + "|" + thisJob.getSchemaVersion() + "|"); ActivityItem newAct = new ActivityItem(thisJob); if (activities.contains(newAct)) { @@ -117,7 +121,8 @@ public class ExecutionPane extends EntityTabPane implements EntityProxyObserver revalidate(); updateUI(); } - public void reload() { + @Override + public void reload() { loadJobList(); } private void addActivity(ActivityItem newAct) { @@ -145,10 +150,10 @@ public class ExecutionPane extends EntityTabPane implements EntityProxyObserver updateUI(); currentActView.init(); } - public void runCommand(String command) { + @Override + public void runCommand(String command) { if (init) { - for (Iterator iter = activities.iterator(); iter.hasNext();) { - ActivityItem act = (ActivityItem)iter.next(); + for (ActivityItem act : activities) { if (act.name.equals(command)) { selectActivity(act); } @@ -159,7 +164,8 @@ public class ExecutionPane extends EntityTabPane implements EntityProxyObserver /** * when the workflow changes, reload this pane. */ - public void add(C2KLocalObject contents) { + @Override + public void add(Workflow contents) { if (!formIsActive) reload(); else { // look to see if this form is now invalid @@ -170,13 +176,12 @@ public class ExecutionPane extends EntityTabPane implements EntityProxyObserver return; } // compare to currently editing jobs - ArrayList currentActJobs = currentActView.getActivity().getJobs(); + ArrayList currentActJobs = currentActView.getActivity().getJobs(); boolean allValid = true; - for (Iterator iter = currentActJobs.iterator(); iter.hasNext() && allValid;) { + for (Iterator iter = currentActJobs.iterator(); iter.hasNext() && allValid;) { Job thisJob = (Job)iter.next(); boolean stillValid = false; - for (Iterator iter2 = jobList.iterator(); iter2.hasNext();) { - Job newJob = (Job)iter2.next(); + for (Job newJob : jobList) { if (thisJob.equals(newJob)) { stillValid = true; break; @@ -192,6 +197,12 @@ public class ExecutionPane extends EntityTabPane implements EntityProxyObserver /** * Not pertinent for this one */ - public void remove(String id) { + @Override + public void remove(String id) { } + @Override + public void control(String control, String msg) { + // TODO Auto-generated method stub + + } } diff --git a/source/com/c2kernel/gui/tabs/HistoryPane.java b/source/com/c2kernel/gui/tabs/HistoryPane.java index be7f8b2..5b3d536 100644 --- a/source/com/c2kernel/gui/tabs/HistoryPane.java +++ b/source/com/c2kernel/gui/tabs/HistoryPane.java @@ -21,8 +21,8 @@ import javax.swing.JTable; import javax.swing.table.AbstractTableModel; import com.c2kernel.common.ObjectNotFoundException; -import com.c2kernel.entity.C2KLocalObject; import com.c2kernel.entity.proxy.EntityProxyObserver; +import com.c2kernel.entity.proxy.MemberSubscription; import com.c2kernel.events.Event; import com.c2kernel.events.History; import com.c2kernel.lifecycle.instance.stateMachine.Transitions; @@ -36,7 +36,7 @@ import com.c2kernel.utils.Logger; * @version $Revision: 1.22 $ $Date: 2005/04/26 06:48:13 $ * @author $Author: abranson $ */ -public class HistoryPane extends EntityTabPane implements ActionListener, EntityProxyObserver { +public class HistoryPane extends EntityTabPane implements ActionListener, EntityProxyObserver { History history; HistoryTableModel model; @@ -47,7 +47,7 @@ public class HistoryPane extends EntityTabPane implements ActionListener, Entity JButton endButton = new JButton(">>"); public static final int SIZE = 30; int currentSize = SIZE; - + public HistoryPane() { super("History", "Event History"); initPanel(); @@ -56,18 +56,18 @@ public class HistoryPane extends EntityTabPane implements ActionListener, Entity Box navBox = Box.createHorizontalBox(); navBox.add(startButton); navBox.add(prevButton); navBox.add(nextButton); navBox.add(endButton); - + // setup buttons //startButton.setEnabled(false); nextButton.setEnabled(false); //prevButton.setEnabled(false); endButton.setEnabled(false); startButton.setActionCommand("start"); startButton.addActionListener(this); prevButton.setActionCommand("prev"); - prevButton.addActionListener(this); + prevButton.addActionListener(this); nextButton.setActionCommand("next"); - nextButton.addActionListener(this); + nextButton.addActionListener(this); endButton.setActionCommand("end"); - endButton.addActionListener(this); + endButton.addActionListener(this); getGridBagConstraints(); c.gridx = 0; c.gridy = 1; c.anchor = GridBagConstraints.NORTHWEST; @@ -76,27 +76,29 @@ public class HistoryPane extends EntityTabPane implements ActionListener, Entity gridbag.setConstraints(navBox, c); add(navBox); - + // Create table eventTable = new JTable(); JScrollPane eventScroll= new JScrollPane(eventTable); c.weightx = 1.0; c.weighty = 1.0; - c.fill = GridBagConstraints.BOTH; c.gridy++; + c.fill = GridBagConstraints.BOTH; c.gridy++; gridbag.setConstraints(eventScroll, c); add(eventScroll); - + } - public void reload() { + @Override + public void reload() { history.clear(); jumpToEnd(); } - public void run() { + @Override + public void run() { Thread.currentThread().setName("History Pane Builder"); try { history = (History)sourceEntity.getEntity().getObject(ClusterStorage.HISTORY); - sourceEntity.getEntity().subscribe(this, ClusterStorage.HISTORY, false); + sourceEntity.getEntity().subscribe(new MemberSubscription(this, ClusterStorage.HISTORY, false)); } catch (ObjectNotFoundException e) { Logger.error(e); } @@ -104,7 +106,7 @@ public class HistoryPane extends EntityTabPane implements ActionListener, Entity eventTable.setModel(model); jumpToEnd(); } - + public void jumpToEnd() { int lastEvent = history.getLastId(); int firstEvent = 0; currentSize = SIZE; @@ -113,28 +115,31 @@ public class HistoryPane extends EntityTabPane implements ActionListener, Entity Logger.msg(5, "HistoryPane.run() - init table start "+firstEvent+" for "+currentSize); model.setView(firstEvent, currentSize); } - - public void add(C2KLocalObject contents) { + + @Override + public void add(Event contents) { jumpToEnd(); } - public void remove(String id) { + @Override + public void remove(String id) { // don't have to deal with this normally - } - + } + + @Override public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("end")) { jumpToEnd(); return; } - + int lastEvent = history.getLastId(); int startEvent = model.getStartId(); if (e.getActionCommand().equals("start")) { currentSize = SIZE; startEvent = 0; } - + else if (e.getActionCommand().equals("prev")) { currentSize = SIZE; startEvent-=currentSize; @@ -151,19 +156,19 @@ public class HistoryPane extends EntityTabPane implements ActionListener, Entity } model.setView(startEvent, currentSize); - } - + } + private class HistoryTableModel extends AbstractTableModel { Event[] event; Integer[] ids; int loaded = 0; int startId = 0; - + public HistoryTableModel() { event = new Event[0]; ids = new Integer[0]; - } - + } + public int getStartId() { return startId; } @@ -182,6 +187,7 @@ public class HistoryPane extends EntityTabPane implements ActionListener, Entity /** * @see javax.swing.table.TableModel#getColumnClass(int) */ + @Override public Class getColumnClass(int columnIndex) { switch(columnIndex) { case 0: @@ -194,6 +200,7 @@ public class HistoryPane extends EntityTabPane implements ActionListener, Entity /** * @see javax.swing.table.TableModel#getColumnCount() */ + @Override public int getColumnCount() { return 6; } @@ -201,6 +208,7 @@ public class HistoryPane extends EntityTabPane implements ActionListener, Entity /** * @see javax.swing.table.TableModel#getColumnName(int) */ + @Override public String getColumnName(int columnIndex) { switch(columnIndex) { case 0: return Language.translate("ID"); @@ -216,6 +224,7 @@ public class HistoryPane extends EntityTabPane implements ActionListener, Entity /** * @see javax.swing.table.TableModel#getRowCount() */ + @Override public int getRowCount() { return loaded; } @@ -223,6 +232,7 @@ public class HistoryPane extends EntityTabPane implements ActionListener, Entity /** * @see javax.swing.table.TableModel#getValueAt(int, int) */ + @Override public Object getValueAt(int rowIndex, int columnIndex) { if (event.length <= rowIndex || event[rowIndex] == null) return ""; @@ -234,8 +244,8 @@ public class HistoryPane extends EntityTabPane implements ActionListener, Entity case 3: return event[rowIndex].getTimeString(); case 4: return event[rowIndex].getAgentName(); case 5: return event[rowIndex].getAgentRole(); - default: return ""; - } + default: return ""; + } } catch (Exception e) { return null; } @@ -244,10 +254,17 @@ public class HistoryPane extends EntityTabPane implements ActionListener, Entity /** * @see javax.swing.table.TableModel#isCellEditable(int, int) */ + @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return false; } } + @Override + public void control(String control, String msg) { + // TODO Auto-generated method stub + + } + } diff --git a/source/com/c2kernel/gui/tabs/JTabbedPaneWithCloseIcons.java b/source/com/c2kernel/gui/tabs/JTabbedPaneWithCloseIcons.java index 1629672..8f047ca 100644 --- a/source/com/c2kernel/gui/tabs/JTabbedPaneWithCloseIcons.java +++ b/source/com/c2kernel/gui/tabs/JTabbedPaneWithCloseIcons.java @@ -14,13 +14,13 @@ import com.c2kernel.gui.EntityDetails; /** * @author Developpement - * + * * Allows a close icone in JTabbePane */ public class JTabbedPaneWithCloseIcons extends JTabbedPane implements MouseListener, ChangeListener { /** - * + * */ public JTabbedPaneWithCloseIcons() { @@ -31,6 +31,7 @@ public class JTabbedPaneWithCloseIcons extends JTabbedPane implements MouseListe /** * @see javax.swing.JTabbedPane#addTab(String, Icon, Component, String) */ + @Override public void addTab(String title, Icon arg2, Component component, String arg3) { super.addTab(title, new CloseTabIcon(arg2), component, arg3); @@ -38,6 +39,7 @@ public class JTabbedPaneWithCloseIcons extends JTabbedPane implements MouseListe /** * @see java.awt.event.MouseListener#mouseClicked(MouseEvent) */ + @Override public void mouseClicked(MouseEvent e) { int tabNumber = getUI().tabForCoordinate(this, e.getX(), e.getY()); @@ -60,27 +62,32 @@ public class JTabbedPaneWithCloseIcons extends JTabbedPane implements MouseListe /** * @see java.awt.event.MouseListener#mouseEntered(MouseEvent) */ + @Override public void mouseEntered(MouseEvent e) { } /** * @see java.awt.event.MouseListener#mouseExited(MouseEvent) */ + @Override public void mouseExited(MouseEvent e) { } /** * @see java.awt.event.MouseListener#mousePressed(MouseEvent) */ + @Override public void mousePressed(MouseEvent e) { } /** * @see java.awt.event.MouseListener#mouseReleased(MouseEvent) */ + @Override public void mouseReleased(MouseEvent e) { } + @Override public void stateChanged(ChangeEvent e) { if (getSelectedComponent()!= null) diff --git a/source/com/c2kernel/gui/tabs/JobListPane.java b/source/com/c2kernel/gui/tabs/JobListPane.java index b9ff0e5..619a589 100644 --- a/source/com/c2kernel/gui/tabs/JobListPane.java +++ b/source/com/c2kernel/gui/tabs/JobListPane.java @@ -25,10 +25,10 @@ import javax.swing.JTable; import javax.swing.table.AbstractTableModel; import com.c2kernel.common.ObjectNotFoundException; -import com.c2kernel.entity.C2KLocalObject; import com.c2kernel.entity.agent.Job; import com.c2kernel.entity.agent.JobList; import com.c2kernel.entity.proxy.EntityProxyObserver; +import com.c2kernel.entity.proxy.MemberSubscription; import com.c2kernel.gui.MainFrame; import com.c2kernel.lifecycle.instance.stateMachine.Transitions; import com.c2kernel.persistency.ClusterStorage; @@ -43,7 +43,7 @@ import com.c2kernel.utils.Logger; * @version $Revision: 1.4 $ $Date: 2004/10/21 08:02:21 $ * @author $Author: abranson $ */ -public class JobListPane extends EntityTabPane implements ActionListener, EntityProxyObserver { +public class JobListPane extends EntityTabPane implements ActionListener, EntityProxyObserver { JobList joblist; JoblistTableModel model; @@ -54,7 +54,7 @@ public class JobListPane extends EntityTabPane implements ActionListener, Entity JButton endButton = new JButton(">>"); public static final int SIZE = 30; int currentSize = SIZE; - + public JobListPane() { super("Job List", "Agent Job List"); initPanel(); @@ -63,18 +63,18 @@ public class JobListPane extends EntityTabPane implements ActionListener, Entity Box navBox = Box.createHorizontalBox(); navBox.add(startButton); navBox.add(prevButton); navBox.add(nextButton); navBox.add(endButton); - + // setup buttons //startButton.setEnabled(false); nextButton.setEnabled(false); //prevButton.setEnabled(false); endButton.setEnabled(false); startButton.setActionCommand("start"); startButton.addActionListener(this); prevButton.setActionCommand("prev"); - prevButton.addActionListener(this); + prevButton.addActionListener(this); nextButton.setActionCommand("next"); - nextButton.addActionListener(this); + nextButton.addActionListener(this); endButton.setActionCommand("end"); - endButton.addActionListener(this); + endButton.addActionListener(this); getGridBagConstraints(); c.gridx = 0; c.gridy = 1; c.anchor = GridBagConstraints.NORTHWEST; @@ -83,29 +83,31 @@ public class JobListPane extends EntityTabPane implements ActionListener, Entity gridbag.setConstraints(navBox, c); add(navBox); - + // Create table eventTable = new JTable(); JScrollPane eventScroll= new JScrollPane(eventTable); c.weightx = 1.0; c.weighty = 1.0; - c.fill = GridBagConstraints.BOTH; c.gridy++; + c.fill = GridBagConstraints.BOTH; c.gridy++; gridbag.setConstraints(eventScroll, c); add(eventScroll); - + // detect double clicked jobs eventTable.addMouseListener(new JobListMouseListener()); } - public void reload() { + @Override + public void reload() { joblist.clear(); jumpToEnd(); } - public void run() { + @Override + public void run() { Thread.currentThread().setName("Joblist Pane Builder"); try { joblist = (JobList)sourceEntity.getEntity().getObject(ClusterStorage.JOB); - sourceEntity.getEntity().subscribe(this, ClusterStorage.JOB, false); + sourceEntity.getEntity().subscribe(new MemberSubscription(this, ClusterStorage.JOB, false)); } catch (ObjectNotFoundException e) { Logger.error(e); } @@ -113,8 +115,8 @@ public class JobListPane extends EntityTabPane implements ActionListener, Entity eventTable.setModel(model); jumpToEnd(); } - - + + public void jumpToEnd() { int lastEvent = joblist.getLastId(); int firstEvent = 0; currentSize = SIZE; @@ -124,27 +126,30 @@ public class JobListPane extends EntityTabPane implements ActionListener, Entity model.setView(firstEvent, currentSize); } - public void add(C2KLocalObject contents) { + @Override + public void add(Job contents) { reload(); } - public void remove(String id) { + @Override + public void remove(String id) { reload(); - } - + } + + @Override public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("end")) { jumpToEnd(); return; } - + int lastEvent = joblist.getLastId(); int startEvent = model.getStartId(); if (e.getActionCommand().equals("start")) { currentSize = SIZE; startEvent = 0; } - + else if (e.getActionCommand().equals("prev")) { currentSize = SIZE; startEvent-=currentSize; @@ -161,20 +166,20 @@ public class JobListPane extends EntityTabPane implements ActionListener, Entity } model.setView(startEvent, currentSize); - } - + } + private class JoblistTableModel extends AbstractTableModel { Job[] job; Integer[] ids; String[] itemNames; int loaded = 0; int startId = 0; - + public JoblistTableModel(JobList joblist) { job = new Job[0]; ids = new Integer[0]; - } - + } + public int getStartId() { return startId; } @@ -185,12 +190,11 @@ public class JobListPane extends EntityTabPane implements ActionListener, Entity itemNames = new String[size]; this.startId = startId; int count = 0; - for (Iterator i = joblist.keySet().iterator(); i.hasNext();) { + for (Iterator i = joblist.keySet().iterator(); i.hasNext();) { Integer thisJobId = new Integer((String)i.next()); if (count >= startId) { int idx = count-startId; ids[idx] = thisJobId; - Job thisJob = joblist.getJob(thisJobId.intValue()); job[idx] = joblist.getJob(thisJobId.intValue()); itemNames[idx] = "Item Not Found"; try { @@ -198,7 +202,7 @@ public class JobListPane extends EntityTabPane implements ActionListener, Entity } catch (Exception ex) { Logger.error(ex); } - + } count++; loaded = count-startId; @@ -209,6 +213,7 @@ public class JobListPane extends EntityTabPane implements ActionListener, Entity /** * @see javax.swing.table.TableModel#getColumnClass(int) */ + @Override public Class getColumnClass(int columnIndex) { switch(columnIndex) { case 0: @@ -221,6 +226,7 @@ public class JobListPane extends EntityTabPane implements ActionListener, Entity /** * @see javax.swing.table.TableModel#getColumnCount() */ + @Override public int getColumnCount() { return 4; } @@ -228,6 +234,7 @@ public class JobListPane extends EntityTabPane implements ActionListener, Entity /** * @see javax.swing.table.TableModel#getColumnName(int) */ + @Override public String getColumnName(int columnIndex) { switch(columnIndex) { case 0: return Language.translate("ID"); @@ -241,6 +248,7 @@ public class JobListPane extends EntityTabPane implements ActionListener, Entity /** * @see javax.swing.table.TableModel#getRowCount() */ + @Override public int getRowCount() { return loaded; } @@ -248,6 +256,7 @@ public class JobListPane extends EntityTabPane implements ActionListener, Entity /** * @see javax.swing.table.TableModel#getValueAt(int, int) */ + @Override public Object getValueAt(int rowIndex, int columnIndex) { if (job.length <= rowIndex || job[rowIndex] == null) return ""; @@ -257,8 +266,8 @@ public class JobListPane extends EntityTabPane implements ActionListener, Entity case 1: return itemNames[rowIndex]; case 2: return job[rowIndex].getStepName(); case 3: return Transitions.getTransitionName(job[rowIndex].getPossibleTransition()); - default: return ""; - } + default: return ""; + } } catch (Exception e) { return null; } @@ -267,10 +276,11 @@ public class JobListPane extends EntityTabPane implements ActionListener, Entity /** * @see javax.swing.table.TableModel#isCellEditable(int, int) */ + @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return false; } - + public Job getJobAtRow(int rowIndex) { return job[rowIndex]; } @@ -279,7 +289,8 @@ public class JobListPane extends EntityTabPane implements ActionListener, Entity private class JobListMouseListener extends MouseAdapter { - public void mouseClicked(MouseEvent e) { + @Override + public void mouseClicked(MouseEvent e) { super.mouseClicked(e); if (e.getClickCount() == 2) { Job selectedJob = model.getJobAtRow(eventTable.getSelectedRow()); @@ -289,7 +300,13 @@ public class JobListPane extends EntityTabPane implements ActionListener, Entity Logger.error(ex); JOptionPane.showMessageDialog(null, "No Item Found", "Job references an unknown item", JOptionPane.ERROR_MESSAGE); } - } + } } } + + @Override + public void control(String control, String msg) { + // TODO Auto-generated method stub + + } } diff --git a/source/com/c2kernel/gui/tabs/PropertiesPane.java b/source/com/c2kernel/gui/tabs/PropertiesPane.java index 6b21804..2411296 100644 --- a/source/com/c2kernel/gui/tabs/PropertiesPane.java +++ b/source/com/c2kernel/gui/tabs/PropertiesPane.java @@ -17,11 +17,16 @@ import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.HashMap; -import javax.swing.*; +import javax.swing.Box; +import javax.swing.JButton; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.SwingConstants; -import com.c2kernel.entity.C2KLocalObject; import com.c2kernel.entity.proxy.EntityProxyObserver; import com.c2kernel.entity.proxy.ItemProxy; +import com.c2kernel.entity.proxy.MemberSubscription; import com.c2kernel.gui.MainFrame; import com.c2kernel.gui.data.NodeAgent; import com.c2kernel.persistency.ClusterStorage; @@ -36,7 +41,7 @@ import com.c2kernel.utils.Logger; * @version $Revision: 1.44 $ $Date: 2005/08/31 07:21:20 $ * @author $Author: abranson $ */ -public class PropertiesPane extends EntityTabPane implements EntityProxyObserver, ActionListener { +public class PropertiesPane extends EntityTabPane implements EntityProxyObserver, ActionListener { Box propertyBox; boolean subbed = false; @@ -66,15 +71,15 @@ public class PropertiesPane extends EntityTabPane implements EntityProxyObserver domTitle.setForeground(headingColor); gridbag.setConstraints(domTitle, c); add(domTitle); - + c.gridy++; c.fill = GridBagConstraints.BOTH; c.weighty=1.0; domAdmin = new DomainPathAdmin(); gridbag.setConstraints(domAdmin, c); - add(domAdmin); - - + add(domAdmin); + + if ("true".equals(Gateway.getProperty("EnableItemErase"))) { c.gridy++; c.fill = GridBagConstraints.NONE; @@ -87,13 +92,15 @@ public class PropertiesPane extends EntityTabPane implements EntityProxyObserver } } - public void reload() { + @Override + public void reload() { Gateway.getStorage().clearCache(sourceEntity.getSysKey(), ClusterStorage.PROPERTY); loadedProps = new HashMap(); initForEntity(sourceEntity); } - public void run() { + @Override + public void run() { Thread.currentThread().setName("Property Pane Builder"); if (sourceEntity instanceof NodeAgent) { remove(domAdmin); @@ -104,16 +111,15 @@ public class PropertiesPane extends EntityTabPane implements EntityProxyObserver propertyBox.removeAll(); propertyBox.add(Box.createGlue()); revalidate(); - sourceEntity.getEntity().subscribe(this, ClusterStorage.PROPERTY, true); - + sourceEntity.getEntity().subscribe(new MemberSubscription(this, ClusterStorage.PROPERTY, true)); + } /** * */ - public void add(C2KLocalObject contents) { - if (!(contents instanceof Property)) return; - Property newProp = (Property) contents; - JLabel propLabel = (JLabel)loadedProps.get(newProp.getName()); + @Override + public void add(Property newProp) { + JLabel propLabel = loadedProps.get(newProp.getName()); if (propLabel == null) { // new prop JPanel summaryPanel = new JPanel(new GridLayout(0,2)); summaryPanel.add(new JLabel(Language.translate(newProp.getName()) + ":")); @@ -126,9 +132,10 @@ public class PropertiesPane extends EntityTabPane implements EntityProxyObserver editButton.setMargin(new Insets(0,0,0,0)); editButton.setActionCommand(newProp.getName()); editButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e){ - String oldVal = ((JLabel)loadedProps.get(e.getActionCommand())).getText(); - String newVal = (String)JOptionPane.showInputDialog(null, "Enter new value for "+e.getActionCommand(), "Edit Property", + @Override + public void actionPerformed(ActionEvent e){ + String oldVal = loadedProps.get(e.getActionCommand()).getText(); + String newVal = (String)JOptionPane.showInputDialog(null, "Enter new value for "+e.getActionCommand(), "Edit Property", JOptionPane.QUESTION_MESSAGE, null, null, oldVal); if (newVal!=null && !(newVal.equals(oldVal))) { try { @@ -151,23 +158,25 @@ public class PropertiesPane extends EntityTabPane implements EntityProxyObserver revalidate(); } - public void remove(String id) { + @Override + public void remove(String id) { String propName = id.substring(id.lastIndexOf("/")+1); - JLabel propbox = (JLabel)loadedProps.get(propName); - if (propbox!= null) propbox.setText("DELETED"); - revalidate(); + JLabel propbox = loadedProps.get(propName); + if (propbox!= null) propbox.setText("DELETED"); + revalidate(); } - public void actionPerformed(ActionEvent e) { + @Override + public void actionPerformed(ActionEvent e) { String[] params; String predefStep; - - if (JOptionPane.showConfirmDialog(this, - "Are you sure?", - e.getActionCommand(), + + if (JOptionPane.showConfirmDialog(this, + "Are you sure?", + e.getActionCommand(), JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) return; - + if (e.getActionCommand().equals("Erase Item")) { params = new String[0]; predefStep = "Erase"; @@ -176,10 +185,16 @@ public class PropertiesPane extends EntityTabPane implements EntityProxyObserver return; try { - MainFrame.userAgent.execute((ItemProxy)sourceEntity.getEntity(), predefStep, params); + MainFrame.userAgent.execute((ItemProxy)sourceEntity.getEntity(), predefStep, params); } catch (Exception ex) { Logger.exceptionDialog(ex); } } + @Override + public void control(String control, String msg) { + // TODO Auto-generated method stub + + } + } diff --git a/source/com/c2kernel/gui/tabs/ViewpointPane.java b/source/com/c2kernel/gui/tabs/ViewpointPane.java index 31e18c3..a0f63ab 100644 --- a/source/com/c2kernel/gui/tabs/ViewpointPane.java +++ b/source/com/c2kernel/gui/tabs/ViewpointPane.java @@ -27,6 +27,7 @@ import com.c2kernel.common.ObjectNotFoundException; import com.c2kernel.entity.C2KLocalObject; import com.c2kernel.entity.proxy.EntityProxyObserver; import com.c2kernel.entity.proxy.ItemProxy; +import com.c2kernel.entity.proxy.MemberSubscription; import com.c2kernel.events.Event; import com.c2kernel.gui.MainFrame; import com.c2kernel.gui.tabs.outcome.OutcomeException; @@ -39,15 +40,15 @@ import com.c2kernel.utils.Language; import com.c2kernel.utils.LocalObjectLoader; import com.c2kernel.utils.Logger; -public class ViewpointPane extends EntityTabPane implements ItemListener, ActionListener, EntityProxyObserver { - +public class ViewpointPane extends EntityTabPane implements ItemListener, ActionListener, EntityProxyObserver { + JComboBox schemas; JComboBox views; JComboBox events; JLabel eventDetails; JButton exportButton; JButton viewButton; - + ArrayList schemaList; ArrayList viewpointList; ArrayList eventList; @@ -55,11 +56,11 @@ public class ViewpointPane extends EntityTabPane implements ItemListener, Action Outcome currentOutcome = null; OutcomeHandler thisOutcome; boolean suspendSelection = false; - + JPanel dataView = new JPanel(new GridLayout(1,1)); - + public ViewpointPane() { - + super("Data Viewer", "Outcome Browser"); initialize(); } @@ -96,14 +97,14 @@ public class ViewpointPane extends EntityTabPane implements ItemListener, Action viewBox.add(views); viewBox.add(Box.createHorizontalGlue()); views.addItemListener(this); - + gridbag.setConstraints(viewBox, c); this.add(viewBox); - - // Set up event details box + + // Set up event details box c.gridy++; - Box eventBox = Box.createHorizontalBox(); - + Box eventBox = Box.createHorizontalBox(); + label = new JLabel(Language.translate("Event")+":", SwingConstants.LEFT); eventBox.add(label); eventBox.add(Box.createHorizontalStrut(7)); @@ -112,29 +113,29 @@ public class ViewpointPane extends EntityTabPane implements ItemListener, Action eventBox.add(events); eventBox.add(Box.createHorizontalStrut(7)); events.addItemListener(this); - + eventDetails = new JLabel(); eventBox.add(eventDetails); eventBox.add(Box.createHorizontalGlue()); - + if (MainFrame.isAdmin) { viewButton = new JButton(Language.translate("Write View")); viewButton.setMargin(new Insets(0, 0, 0, 0)); viewButton.setActionCommand("setview"); - eventBox.add(viewButton); + eventBox.add(viewButton); eventBox.add(Box.createHorizontalStrut(14)); viewButton.addActionListener(this); } - + exportButton = new JButton(Language.translate("Export")); exportButton.setMargin(new Insets(0, 0, 0, 0)); exportButton.setActionCommand("export"); exportButton.addActionListener(this); eventBox.add(exportButton); - + gridbag.setConstraints(eventBox, c); this.add(eventBox); - + // data pane c.gridx = 0; c.gridy = 3; c.anchor = GridBagConstraints.NORTHWEST; c.fill = GridBagConstraints.BOTH; @@ -143,24 +144,26 @@ public class ViewpointPane extends EntityTabPane implements ItemListener, Action this.add(dataView); } - public void reload() { + @Override + public void reload() { // reset boxes schemas.removeAllItems(); - views.removeAllItems(); - events.removeAllItems(); + views.removeAllItems(); + events.removeAllItems(); eventDetails.setText(""); - + clearView(); - + // reload initForEntity(sourceEntity); } - public void run() { + @Override + public void run() { Thread.currentThread().setName("Viewpoint Pane Builder"); //Local object subscriptions - sourceEntity.getEntity().subscribe(this, ClusterStorage.VIEWPOINT, false); - sourceEntity.getEntity().subscribe(this, ClusterStorage.OUTCOME, false); + sourceEntity.getEntity().subscribe(new MemberSubscription(this, ClusterStorage.VIEWPOINT, false)); + sourceEntity.getEntity().subscribe(new MemberSubscription(this, ClusterStorage.OUTCOME, false)); clearView(); schemas.addItem("--"); currentSchema = null; @@ -168,7 +171,7 @@ public class ViewpointPane extends EntityTabPane implements ItemListener, Action try { String outcomeTypes = sourceEntity.getEntity().queryData(ClusterStorage.VIEWPOINT+"/all"); StringTokenizer tok = new StringTokenizer(outcomeTypes, ","); - for (int i = 0; tok.countTokens() > 0; i++) { + while (tok.hasMoreTokens()) { String thisType = tok.nextToken(); schemas.addItem(thisType); schemaList.add(thisType); @@ -178,13 +181,14 @@ public class ViewpointPane extends EntityTabPane implements ItemListener, Action } } - public void itemStateChanged(ItemEvent e) { - + @Override + public void itemStateChanged(ItemEvent e) { + Object selectedItem = e.getItem(); - if (e.getStateChange() == ItemEvent.DESELECTED) return; + if (e.getStateChange() == ItemEvent.DESELECTED) return; if (suspendSelection) return; if (e.getItem().equals("--")) return; - + if (e.getItemSelectable() == schemas) switchSchema((String)selectedItem); else if (e.getItemSelectable() == views) @@ -196,13 +200,13 @@ public class ViewpointPane extends EntityTabPane implements ItemListener, Action public void switchSchema(String schemaName) { clearView(); suspendSelection = true; - views.removeAllItems(); + views.removeAllItems(); events.removeAllItems(); viewpointList = new ArrayList(); eventList = new ArrayList(); currentSchema = schemaName; - + try { // populate views String viewNames = sourceEntity.getEntity().queryData(ClusterStorage.VIEWPOINT+"/"+schemaName+"/all"); @@ -217,7 +221,7 @@ public class ViewpointPane extends EntityTabPane implements ItemListener, Action lastView = thisView; viewpointList.add(thisView); } - + String ocVersions = sourceEntity.getEntity().queryData(ClusterStorage.OUTCOME+"/"+schemaName+"/all"); tok = new StringTokenizer(ocVersions, ","); while(tok.hasMoreTokens()) { @@ -227,40 +231,39 @@ public class ViewpointPane extends EntityTabPane implements ItemListener, Action while(tok2.hasMoreTokens()) { int eventId = Integer.parseInt(tok2.nextToken()); EventItem newEvent = new EventItem(eventId, schemaVersion); - for (Iterator iter = viewpointList.iterator(); iter.hasNext();) { - Viewpoint thisView = (Viewpoint)iter.next(); + for (Viewpoint thisView : viewpointList) { if (thisView.getEventId() == eventId) newEvent.addView(thisView.getName()); } eventList.add(newEvent); } Collections.sort(eventList, new Comparator() { - public int compare(EventItem o1, EventItem o2) { + @Override + public int compare(EventItem o1, EventItem o2) { return o1.compareTo(o2); } }); - for (Iterator iter = eventList.iterator(); iter.hasNext();) - events.addItem(iter.next()); + for (EventItem eventItem : eventList) + events.addItem(eventItem); } - + if (lastView != null) { suspendSelection = false; views.setSelectedItem(lastView); switchView(lastView); } - + } catch (Exception e) { Logger.error(e); - JOptionPane.showMessageDialog(this, - "The data structures of this item are incorrect.\nPlease contact your administrator.", + JOptionPane.showMessageDialog(this, + "The data structures of this item are incorrect.\nPlease contact your administrator.", "Viewpoint Error" , JOptionPane.ERROR_MESSAGE); } suspendSelection = false; } - + public void switchView(Viewpoint newView) { - for (Iterator iter = eventList.iterator(); iter.hasNext();) { - EventItem thisEvent = (EventItem)iter.next(); + for (EventItem thisEvent : eventList) { if (thisEvent.eventId == newView.getEventId()) { suspendSelection = true; events.setSelectedItem(thisEvent); @@ -270,7 +273,7 @@ public class ViewpointPane extends EntityTabPane implements ItemListener, Action } } } - + public void showEvent(EventItem thisEvent) { eventDetails.setText(thisEvent.getEventDesc()); try { @@ -278,13 +281,13 @@ public class ViewpointPane extends EntityTabPane implements ItemListener, Action ClusterStorage.OUTCOME+"/"+currentSchema+"/"+thisEvent.schemaVersion+"/"+thisEvent.eventId)); } catch (Exception ex) { Logger.error(ex); - JOptionPane.showMessageDialog(this, - "Could not retrieve requested outcome.\nPlease contact your administrator.", + JOptionPane.showMessageDialog(this, + "Could not retrieve requested outcome.\nPlease contact your administrator.", "Viewpoint Error" , JOptionPane.ERROR_MESSAGE); } } - - public void setView(Outcome data) throws OutcomeException { + + public void setView(Outcome data) { Logger.msg(6, "ViewpointPane: got outcome type: "+data.getSchemaType()+" version: "+data.getSchemaVersion()); String schema; currentOutcome = data; @@ -295,7 +298,7 @@ public class ViewpointPane extends EntityTabPane implements ItemListener, Action thisOutcome = EntityTabPane.getOutcomeHandler(data.getSchemaType(), data.getSchemaVersion()); thisOutcome.setDescription(schema); thisOutcome.setOutcome(data.getData()); - thisOutcome.setReadOnly(true); + thisOutcome.setReadOnly(true); Thread builder = new Thread(thisOutcome); builder.start(); dataView.add(thisOutcome.getPanel()); @@ -308,21 +311,22 @@ public class ViewpointPane extends EntityTabPane implements ItemListener, Action error = "Outcome was not valid. See log for details: "+ex.getMessage(); Logger.error(ex); } - + dataView.add(new JLabel(error)); } - + public void clearView() { dataView.removeAll(); exportButton.setEnabled(false); if (viewButton!=null) viewButton.setEnabled(false); } - - public void actionPerformed(ActionEvent e) { + + @Override + public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("export") && currentOutcome != null) saveOutcomeToFile(); if (e.getActionCommand().equals("setview") && currentOutcome != null) - overrideView(); + overrideView(); } private void saveOutcomeToFile() { @@ -333,7 +337,7 @@ public class ViewpointPane extends EntityTabPane implements ItemListener, Action File targetFile = MainFrame.xmlChooser.getSelectedFile(); if (!(targetFile.getAbsolutePath().endsWith(".xml"))) targetFile = new File(targetFile.getAbsolutePath()+".xml"); - + Logger.msg(2, "ViewpointPane.actionPerformed() - Exporting outcome to file " + targetFile.getName()); try { thisOutcome.export(targetFile); @@ -343,28 +347,28 @@ public class ViewpointPane extends EntityTabPane implements ItemListener, Action Logger.exceptionDialog(ex); } } - + } - + private void overrideView() { Viewpoint oldView = (Viewpoint)views.getSelectedItem(); EventItem newEvent = (EventItem)events.getSelectedItem(); - + if (oldView.getEventId() == newEvent.eventId) { - JOptionPane.showMessageDialog(this, - "View '"+oldView.getName()+"' is already set to event "+newEvent.eventId, + JOptionPane.showMessageDialog(this, + "View '"+oldView.getName()+"' is already set to event "+newEvent.eventId, "Viewpoint Already Set" , JOptionPane.ERROR_MESSAGE); return; } - - if (JOptionPane.showConfirmDialog(this, + + if (JOptionPane.showConfirmDialog(this, "Are you sure you want to set the '"+oldView.getName()+ - "' view to event " + newEvent.eventId+ "?", - "Overwrite view", + "' view to event " + newEvent.eventId+ "?", + "Overwrite view", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) return; - + oldView.setEventId(newEvent.eventId); try { String[] predefParams = new String[1]; @@ -373,17 +377,18 @@ public class ViewpointPane extends EntityTabPane implements ItemListener, Action } catch (Exception e) { Logger.error(e); Logger.exceptionDialog(e); - } + } } - public void add(C2KLocalObject contents) { + @Override + public void add(C2KLocalObject contents) { if (contents instanceof Viewpoint) addViewpoint((Viewpoint)contents); else if (contents instanceof Outcome) addOutcome((Outcome)contents); } - + public void addViewpoint(Viewpoint newView) { String schemaName = newView.getSchemaName(); Logger.msg(3, "Viewpoint "+newView.getName()+" now points to "+newView.getEventId()); @@ -393,21 +398,19 @@ public class ViewpointPane extends EntityTabPane implements ItemListener, Action return; } - + if (!(schemaName.equals(schemas.getSelectedItem()))) return; - - for (Iterator iter = eventList.iterator(); iter.hasNext();) { - EventItem thisEvent = (EventItem)iter.next(); + + for (EventItem thisEvent : eventList) { if (thisEvent.eventId == newView.getEventId()) thisEvent.addView(newView.getName()); else thisEvent.removeView(newView.getName()); } - + boolean isSelected = false; - for (Iterator iter = viewpointList.iterator(); iter.hasNext();) { - Viewpoint thisView = (Viewpoint)iter.next(); + for (Viewpoint thisView : viewpointList) { if (thisView.getName().equals(newView.getName())) { isSelected = thisView.equals(views.getSelectedItem()); views.removeItem(thisView); @@ -415,15 +418,15 @@ public class ViewpointPane extends EntityTabPane implements ItemListener, Action break; } } - + views.addItem(newView); viewpointList.add(newView); if (isSelected) { views.setSelectedItem(newView); } - + } - + public void addOutcome(Outcome contents) { if (!(contents.getSchemaType().equals(currentSchema))) // not interested return; @@ -433,21 +436,22 @@ public class ViewpointPane extends EntityTabPane implements ItemListener, Action events.addItem(newEvent); } - public void remove(String id) { + @Override + public void remove(String id) { // we don't really remove viewpoints } - - class EventItem implements Comparable { + + class EventItem implements Comparable { public int eventId; public int schemaVersion; public ArrayList viewNames = new ArrayList(); public String viewList = ""; - + public EventItem(int eventId, int schemaVersion) { this.eventId = eventId; this.schemaVersion = schemaVersion; } - + public void addView(String viewName) { if (!(viewNames.contains(viewName))) { viewNames.add(viewName); @@ -459,29 +463,30 @@ public class ViewpointPane extends EntityTabPane implements ItemListener, Action viewNames.remove(viewName); buildViewLabel(); } - + private void buildViewLabel() { if (viewNames.size() == 0) { viewList = ""; return; } - + StringBuffer newLabel = new StringBuffer(" ("); - for (Iterator iter = viewNames.iterator(); iter.hasNext();) { - String viewName = (String)iter.next(); + for (Iterator iter = viewNames.iterator(); iter.hasNext();) { + String viewName = iter.next(); newLabel.append(viewName); if (iter.hasNext()) newLabel.append(", "); } - + viewList = newLabel.append(")").toString(); } - - public String toString() { + + @Override + public String toString() { return eventId+viewList; - + } - + public String getEventDesc() { try { Event myEvent = (Event)sourceEntity.getEntity().getObject(ClusterStorage.HISTORY+"/"+eventId); @@ -494,7 +499,8 @@ public class ViewpointPane extends EntityTabPane implements ItemListener, Action } } - public int compareTo(Object o) { + @Override + public int compareTo(Object o) { if (o instanceof EventItem) { EventItem other = (EventItem)o; if (other.eventId < eventId) return 1; @@ -503,4 +509,10 @@ public class ViewpointPane extends EntityTabPane implements ItemListener, Action return 0; } } + + @Override + public void control(String control, String msg) { + // TODO Auto-generated method stub + + } } diff --git a/source/com/c2kernel/gui/tabs/WorkflowPane.java b/source/com/c2kernel/gui/tabs/WorkflowPane.java old mode 100755 new mode 100644 index 7b664ba..6bccd08 --- a/source/com/c2kernel/gui/tabs/WorkflowPane.java +++ b/source/com/c2kernel/gui/tabs/WorkflowPane.java @@ -9,9 +9,9 @@ import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JSplitPane; -import com.c2kernel.entity.C2KLocalObject; import com.c2kernel.entity.proxy.EntityProxyObserver; import com.c2kernel.entity.proxy.ItemProxy; +import com.c2kernel.entity.proxy.MemberSubscription; import com.c2kernel.graph.layout.DefaultGraphLayoutGenerator; import com.c2kernel.graph.model.EdgeFactory; import com.c2kernel.graph.model.Selection; @@ -30,8 +30,12 @@ import com.c2kernel.lifecycle.instance.gui.view.WfDirectedEdgeRenderer; import com.c2kernel.lifecycle.instance.gui.view.WfVertexRenderer; import com.c2kernel.persistency.ClusterStorage; import com.c2kernel.process.Gateway; -import com.c2kernel.utils.*; -public class WorkflowPane extends EntityTabPane implements EntityProxyObserver +import com.c2kernel.utils.CastorXMLUtility; +import com.c2kernel.utils.FileStringUtility; +import com.c2kernel.utils.Language; +import com.c2kernel.utils.Logger; +import com.c2kernel.utils.Resource; +public class WorkflowPane extends EntityTabPane implements EntityProxyObserver { // Only for the purpose of loading and saving protected Workflow mWorkflow = null; @@ -49,7 +53,7 @@ public class WorkflowPane extends EntityTabPane implements EntityProxyObserver protected EditorPanel mEditorPanel; // Objects to view/modify the properties of the selected activity protected VertexPropertyPanel mPropertyPanel; - protected JSplitPane mSplitPane; + protected JSplitPane mSplitPane; // Graph editor panel // Objects to view/modify the properties of the selected activity @@ -64,26 +68,28 @@ public class WorkflowPane extends EntityTabPane implements EntityProxyObserver mLoadButton.setToolTipText(Language.translate("Load")); mSaveButton.setToolTipText(Language.translate("Save")); mOtherToolBarButtons = new JButton[] { mZoomOutButton, mLayoutButton, mLoadButton, mSaveButton }; - + } - + protected void createListeners() { /** - * + * */ mLoadButton.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent ae) { loadWorkflow(); } }); /** - * + * */ mSaveButton.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent ae) { setCursor(new Cursor(Cursor.WAIT_CURSOR)); @@ -92,20 +98,22 @@ public class WorkflowPane extends EntityTabPane implements EntityProxyObserver } }); /** - * + * */ mLayoutButton.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent ae) { DefaultGraphLayoutGenerator.layoutGraph(mEditorPanel.mGraphModelManager.getModel()); } }); /** - * + * */ mZoomOutButton.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent ae) { mEditorPanel.mGraphModelManager.zoomOut(); @@ -114,7 +122,7 @@ public class WorkflowPane extends EntityTabPane implements EntityProxyObserver } /** * Return a single ref on mEditorPanel - * + * * @return EditorPanel */ public EditorPanel getEditorPanel() @@ -140,16 +148,13 @@ public class WorkflowPane extends EntityTabPane implements EntityProxyObserver } return mSplitPane; } - public void add(C2KLocalObject contents) + @Override + public void add(Workflow contents) { - if (contents instanceof Workflow) - { - mWorkflow = (Workflow) contents; - addActivity((CompositeActivity) mWorkflow.search("workflow/domain")); - } - else if (contents instanceof CompositeActivity) - addActivity((CompositeActivity) contents); + mWorkflow = contents; + addActivity((CompositeActivity) mWorkflow.search("workflow/domain")); } + @Override public void remove(String id) { } @@ -163,6 +168,7 @@ public class WorkflowPane extends EntityTabPane implements EntityProxyObserver mEditorPanel.enterSelectMode(); mWfVertexFactory.setCreationContext(cAct); } + @Override public void run() { Thread.currentThread().setName("Workflow Pane Builder"); @@ -175,9 +181,10 @@ public class WorkflowPane extends EntityTabPane implements EntityProxyObserver mEditorPanel.setEditable(MainFrame.isAdmin); init = true; } - sourceEntity.getEntity().subscribe(this, ClusterStorage.LIFECYCLE, true); + sourceEntity.getEntity().subscribe(new MemberSubscription(this, ClusterStorage.LIFECYCLE, true)); transPanel.setItem((ItemProxy) sourceEntity.getEntity()); } + @Override public void reload() { Gateway.getStorage().clearCache(sourceEntity.getSysKey(), ClusterStorage.LIFECYCLE); @@ -235,9 +242,9 @@ public class WorkflowPane extends EntityTabPane implements EntityProxyObserver catch (Exception e) { Logger.error(e); - } + } } - + public VertexPropertyPanel getPropertyPanel() { if (mPropertyPanel == null) { @@ -249,7 +256,7 @@ public class WorkflowPane extends EntityTabPane implements EntityProxyObserver } return mPropertyPanel; } - + public void setNewPropertyPanel() { String wfPanelClass = Gateway.getProperty("WfPropertyPanel"); @@ -257,7 +264,7 @@ public class WorkflowPane extends EntityTabPane implements EntityProxyObserver { try { - Class panelClass = Class.forName(wfPanelClass); + Class panelClass = Class.forName(wfPanelClass); mPropertyPanel = (VertexPropertyPanel) panelClass.newInstance(); return; } @@ -269,5 +276,11 @@ public class WorkflowPane extends EntityTabPane implements EntityProxyObserver } mPropertyPanel = new VertexPropertyPanel(); } - + + @Override + public void control(String control, String msg) { + // TODO Auto-generated method stub + + } + } diff --git a/source/com/c2kernel/gui/tabs/collection/AggregationView.java b/source/com/c2kernel/gui/tabs/collection/AggregationView.java old mode 100755 new mode 100644 index 8a97c6c..3291906 --- a/source/com/c2kernel/gui/tabs/collection/AggregationView.java +++ b/source/com/c2kernel/gui/tabs/collection/AggregationView.java @@ -47,7 +47,8 @@ public class AggregationView extends CollectionView mEditorPanel.setEditable(MainFrame.isAdmin); } - public void setCollection(Collection contents) + @Override + public void setCollection(Collection contents) { thisColl = contents; Aggregation agg = (Aggregation)thisColl; @@ -70,6 +71,7 @@ public class AggregationView extends CollectionView { mSaveButton.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent ae) { saveCollection(); @@ -77,10 +79,11 @@ public class AggregationView extends CollectionView }); mHistoryButton.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent ae) { new CollectionHistoryWindow(item, thisColl); } - }); + }); } } diff --git a/source/com/c2kernel/gui/tabs/collection/CollectionHistoryWindow.java b/source/com/c2kernel/gui/tabs/collection/CollectionHistoryWindow.java index bb71cd8..7cb2753 100644 --- a/source/com/c2kernel/gui/tabs/collection/CollectionHistoryWindow.java +++ b/source/com/c2kernel/gui/tabs/collection/CollectionHistoryWindow.java @@ -12,10 +12,10 @@ import javax.swing.table.AbstractTableModel; import com.c2kernel.collection.Collection; import com.c2kernel.common.ObjectNotFoundException; -import com.c2kernel.entity.C2KLocalObject; import com.c2kernel.entity.proxy.EntityProxy; import com.c2kernel.entity.proxy.EntityProxyObserver; import com.c2kernel.entity.proxy.ItemProxy; +import com.c2kernel.entity.proxy.MemberSubscription; import com.c2kernel.events.Event; import com.c2kernel.gui.MainFrame; import com.c2kernel.lifecycle.instance.predefined.PredefinedStep; @@ -32,8 +32,8 @@ public class CollectionHistoryWindow extends JFrame { JTable historyTable; HistoryTableModel historyModel; - - public CollectionHistoryWindow(ItemProxy item, Collection coll) throws HeadlessException { + + public CollectionHistoryWindow(ItemProxy item, Collection coll) throws HeadlessException { super("Collection History"); historyModel = new HistoryTableModel(item, coll); historyTable = new JTable(historyModel); @@ -44,23 +44,25 @@ public class CollectionHistoryWindow extends JFrame { this.validate(); this.show(); } - - private class HistoryTableModel extends AbstractTableModel implements EntityProxyObserver { + + private class HistoryTableModel extends AbstractTableModel implements EntityProxyObserver { ItemProxy item; ArrayList collEvents, collEventData; - Collection coll; - public HistoryTableModel(ItemProxy item, Collection coll) { + Collection coll; + public HistoryTableModel(ItemProxy item, Collection coll) { this.item = item; this.coll = coll; collEvents = new ArrayList(); collEventData = new ArrayList(); - item.subscribe(this, ClusterStorage.HISTORY, true); + item.subscribe(new MemberSubscription(this, ClusterStorage.HISTORY, true)); } + @Override public int getColumnCount() { return 4; } - + + @Override public String getColumnName(int columnIndex) { switch(columnIndex) { case 0: return Language.translate("Date"); @@ -69,10 +71,12 @@ public class CollectionHistoryWindow extends JFrame { case 3: return Language.translate("Child"); default: return ""; } - } + } + @Override public int getRowCount() { return collEvents.size(); } + @Override public Object getValueAt(int rowIndex, int columnIndex) { Event ev = (Event)collEvents.get(rowIndex); switch (columnIndex) { @@ -109,9 +113,8 @@ public class CollectionHistoryWindow extends JFrame { public Object getEventData(int row) { return collEventData.get(row); } - public void add(C2KLocalObject contents) { - if (!(contents instanceof Event)) return; - Event thisEv = (Event)contents; + @Override + public void add(Event thisEv) { if (thisEv.getStepName().equals("AssignItemToSlot") || thisEv.getStepName().equals("AddC2KObject")) { String[] params; try { @@ -134,16 +137,22 @@ public class CollectionHistoryWindow extends JFrame { if (obj instanceof Collection) collEventData.add(obj); else return; - + } } else return; collEvents.add(thisEv); fireTableRowsInserted(collEvents.size()-1, collEvents.size()-1); } + @Override public void remove(String id) { } + @Override + public void control(String control, String msg) { + // TODO Auto-generated method stub + + } } - + private class HistoryTableListener extends MouseAdapter { ItemProxy item; @@ -151,12 +160,13 @@ public class CollectionHistoryWindow extends JFrame { this.item = item; } + @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount()==2) { int row = historyTable.getSelectedRow(); Object data = historyModel.getEventData(row); if (data instanceof Collection) { - showColl((Collection)data); + showColl((Collection)data); } else { String[] params = (String[])data; @@ -167,7 +177,7 @@ public class CollectionHistoryWindow extends JFrame { } } } - public void showColl(Collection coll) { + public void showColl(Collection coll) { JFrame newFrame = new JFrame(); AggregationView newView = new AggregationView(); newView.setCollection(coll); diff --git a/source/com/c2kernel/gui/tabs/collection/CollectionView.java b/source/com/c2kernel/gui/tabs/collection/CollectionView.java old mode 100755 new mode 100644 index 62a598c..8a97af5 --- a/source/com/c2kernel/gui/tabs/collection/CollectionView.java +++ b/source/com/c2kernel/gui/tabs/collection/CollectionView.java @@ -19,19 +19,19 @@ import com.c2kernel.utils.Logger; public abstract class CollectionView extends JPanel { - protected Collection thisColl; + protected Collection thisColl; protected ItemProxy item; public CollectionView() { super(); } - + public void setItem(ItemProxy entity) { this.item = entity; } - - public abstract void setCollection(Collection coll); - + + public abstract void setCollection(Collection coll); + protected void saveCollection() { try diff --git a/source/com/c2kernel/gui/tabs/collection/DependencyView.java b/source/com/c2kernel/gui/tabs/collection/DependencyView.java old mode 100755 new mode 100644 index 4465d6a..14e2af0 --- a/source/com/c2kernel/gui/tabs/collection/DependencyView.java +++ b/source/com/c2kernel/gui/tabs/collection/DependencyView.java @@ -19,7 +19,8 @@ public class DependencyView extends CollectionView createLayout(); } - public void setCollection(Collection contents) + @Override + public void setCollection(Collection contents) { thisColl = contents; } diff --git a/source/com/c2kernel/gui/tabs/execution/ActivityItem.java b/source/com/c2kernel/gui/tabs/execution/ActivityItem.java index ba5e76b..6a8f2f7 100644 --- a/source/com/c2kernel/gui/tabs/execution/ActivityItem.java +++ b/source/com/c2kernel/gui/tabs/execution/ActivityItem.java @@ -9,7 +9,7 @@ public class ActivityItem { public int state; public String name; ArrayList jobs = new ArrayList(); - + public ActivityItem() { stepPath = ""; state = -1; @@ -27,7 +27,7 @@ public class ActivityItem { jobs.add(newJob); } - public ArrayList getJobs() { + public ArrayList getJobs() { return jobs; } @@ -35,16 +35,19 @@ public class ActivityItem { return stepPath; } - public String toString() { + @Override + public String toString() { return name+(state>-1?" ("+States.getStateName(state)+")":""); } - public boolean equals(Object other) { + @Override + public boolean equals(Object other) { if (other instanceof ActivityItem) return hashCode() == ((ActivityItem)other).hashCode(); return false; } - + + @Override public int hashCode() { return stepPath.hashCode(); } diff --git a/source/com/c2kernel/gui/tabs/execution/ActivityViewer.java b/source/com/c2kernel/gui/tabs/execution/ActivityViewer.java index b0417f4..b6ef7f8 100644 --- a/source/com/c2kernel/gui/tabs/execution/ActivityViewer.java +++ b/source/com/c2kernel/gui/tabs/execution/ActivityViewer.java @@ -8,7 +8,6 @@ import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.util.ArrayList; -import java.util.Iterator; import javax.swing.Box; import javax.swing.JButton; @@ -34,7 +33,7 @@ import com.c2kernel.utils.LocalObjectLoader; import com.c2kernel.utils.Logger; public class ActivityViewer extends JPanel implements Runnable { - + ItemProxy item; Box outcomeButtons = Box.createHorizontalBox(); OutcomeHandler outcomePanel; @@ -43,8 +42,8 @@ public class ActivityViewer extends JPanel implements Runnable { ArrayList requestButtons = new ArrayList(); JLabel noOutcome = new JLabel(Language.translate("No outcome data is required for this activity")); ExecutionPane parent; - JLabel status; - JComboBox executors; + JLabel status; + JComboBox executors; JButton saveButton = new JButton("Save"); JButton loadButton = new JButton("Load"); GridBagLayout gridbag = new GridBagLayout(); @@ -53,10 +52,12 @@ public class ActivityViewer extends JPanel implements Runnable { static { chooser.addChoosableFileFilter( new javax.swing.filechooser.FileFilter() { - public String getDescription() { + @Override + public String getDescription() { return "XML Files"; } - public boolean accept(File f) { + @Override + public boolean accept(File f) { if (f.isDirectory() || (f.isFile() && f.getName().endsWith(".xml"))) { return true; } @@ -64,13 +65,13 @@ public class ActivityViewer extends JPanel implements Runnable { } }); } - + public ActivityViewer (ActivityItem newAct, ItemProxy item, ExecutionPane parent){ thisAct = newAct; this.item = item; this.parent = parent; setLayout(gridbag); - + GridBagConstraints c = new GridBagConstraints(); c.gridx=0; c.gridy=1; c.weightx=1.0; c.weighty=0.0; c.insets = new Insets(5,5,5,5); @@ -82,17 +83,17 @@ public class ActivityViewer extends JPanel implements Runnable { actTitle.setFont(EntityTabPane.titleFont); gridbag.setConstraints(actTitle, c); add(actTitle); - - Job firstJob = (Job)(thisAct.getJobs().get(0)); + + Job firstJob = (thisAct.getJobs().get(0)); // desc String desc = firstJob.getDescription(); if (desc != null && desc.length() > 0) { Box descBox = Box.createHorizontalBox(); - + String chopDesc = null; if(desc.length() >= 40) chopDesc = desc.substring(0,40); else chopDesc = desc; - + descBox.add(new JLabel("Description: "+chopDesc)); if (desc.length()>chopDesc.length()) { descBox.add(new JLabel(" ...")); @@ -101,7 +102,8 @@ public class ActivityViewer extends JPanel implements Runnable { descButton.setMargin(new Insets(0,0,0,0)); descButton.setActionCommand(desc); descButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { + @Override + public void actionPerformed(ActionEvent e) { JTextArea descArea = new JTextArea(e.getActionCommand()); descArea.setLineWrap(true); descArea.setWrapStyleWord(true); @@ -118,8 +120,8 @@ public class ActivityViewer extends JPanel implements Runnable { add(descBox); } - -// agentid + +// agentid String roleName = firstJob.getAgentRole(); if (roleName!= null && roleName.length()>0) { c.gridy++; @@ -127,12 +129,12 @@ public class ActivityViewer extends JPanel implements Runnable { gridbag.setConstraints(role, c); add(role); } - + c.gridy++; c.anchor = GridBagConstraints.EAST; gridbag.setConstraints(outcomeButtons, c); add(outcomeButtons); - + executors = MainFrame.getExecutionPlugins(); if (executors.getItemCount() > 1) { c.gridx++; @@ -142,12 +144,12 @@ public class ActivityViewer extends JPanel implements Runnable { } c.gridy++; - + status = new JLabel(Language.translate("Waiting for request")); status.setFont(EntityTabPane.titleFont); gridbag.setConstraints(status, c); add(status); - + c.gridx++; Box fileBox = Box.createHorizontalBox(); fileBox.add(saveButton); fileBox.add(Box.createHorizontalGlue()); fileBox.add(loadButton); @@ -158,8 +160,8 @@ public class ActivityViewer extends JPanel implements Runnable { c.gridx--; c.gridwidth = 2; boolean outcomeEmpty = true; - for (Iterator e = thisAct.getJobs().iterator(); e.hasNext();) { - Job thisJob = (Job)e.next(); + for (Object name2 : thisAct.getJobs()) { + Job thisJob = (Job)name2; RequestButton newButton = new RequestButton(thisJob, this); requestButtons.add(newButton); outcomeButtons.add(newButton); @@ -191,7 +193,8 @@ public class ActivityViewer extends JPanel implements Runnable { if (outcomePanel == null) newButton.setEnabled(false); else { saveButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { + @Override + public void actionPerformed(ActionEvent e) { String output; try { output = outcomePanel.getOutcome(); @@ -200,7 +203,7 @@ public class ActivityViewer extends JPanel implements Runnable { File targetFile = chooser.getSelectedFile(); if (!(targetFile.getAbsolutePath().endsWith(".xml"))) targetFile = new File(targetFile.getAbsolutePath()+".xml"); - + Logger.msg(2, "ExecutionPane - Exporting outcome to file " + targetFile.getName()); FileStringUtility.string2File(targetFile, output); } @@ -211,14 +214,15 @@ public class ActivityViewer extends JPanel implements Runnable { } }); saveButton.setEnabled(true); - + loadButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { + @Override + public void actionPerformed(ActionEvent e) { try { int returnVal = chooser.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { File targetFile = chooser.getSelectedFile(); - + Logger.msg(2, "ViewpointPane.actionPerformed() - Reading outcome from file " + targetFile.getName()); String outcome = FileStringUtility.file2String(targetFile); outcomePanel.setOutcome(outcome); @@ -230,7 +234,7 @@ public class ActivityViewer extends JPanel implements Runnable { } } }); - loadButton.setEnabled(true); + loadButton.setEnabled(true); } } } @@ -243,15 +247,15 @@ public class ActivityViewer extends JPanel implements Runnable { add(outcomeView); } - + public void init() { if (outcomePanel != null) new Thread(outcomePanel).start(); } - + public void execute(Job thisJob) { try{ - if (thisJob.isOutcomeUsed() && thisJob.getSchemaType().length() > 0) + if (thisJob.isOutcomeUsed() && thisJob.getSchemaType().length() > 0) thisJob.setOutcome(outcomePanel.getOutcome()); executingJob = thisJob; new Thread(this).start(); @@ -260,11 +264,12 @@ public class ActivityViewer extends JPanel implements Runnable { } } - + /** * Submits the job to the database */ - public void run() { + @Override + public void run() { Thread.currentThread().setName("Activity Execution"); enableAllButtons(false); try { @@ -277,15 +282,14 @@ public class ActivityViewer extends JPanel implements Runnable { } enableAllButtons(true); } - + private void enableAllButtons(boolean enabled) { - for (Iterator iter = requestButtons.iterator(); iter.hasNext();) { - RequestButton thisButton = (RequestButton)iter.next(); + for (RequestButton thisButton : requestButtons) { thisButton.setEnabled(enabled); } } - + public ActivityItem getActivity() { return thisAct; } diff --git a/source/com/c2kernel/gui/tabs/execution/DefaultExecutor.java b/source/com/c2kernel/gui/tabs/execution/DefaultExecutor.java old mode 100755 new mode 100644 index ea05568..378cc2e --- a/source/com/c2kernel/gui/tabs/execution/DefaultExecutor.java +++ b/source/com/c2kernel/gui/tabs/execution/DefaultExecutor.java @@ -16,18 +16,20 @@ import com.c2kernel.utils.Language; **************************************************************************/ public class DefaultExecutor implements Executor { - + public DefaultExecutor() { super(); } - public void execute(Job job, JLabel status) throws Exception { + @Override + public void execute(Job job, JLabel status) throws Exception { status.setText(Language.translate("Requesting, please wait.")); MainFrame.userAgent.execute(job); status.setText(Language.translate("Execution complete. Waiting for joblist update.")); } - public String toString() { + @Override + public String toString() { return "Normal"; } } diff --git a/source/com/c2kernel/gui/tabs/execution/Executor.java b/source/com/c2kernel/gui/tabs/execution/Executor.java old mode 100755 new mode 100644 index dd185b4..6fbde17 --- a/source/com/c2kernel/gui/tabs/execution/Executor.java +++ b/source/com/c2kernel/gui/tabs/execution/Executor.java @@ -14,8 +14,9 @@ import com.c2kernel.entity.agent.Job; **************************************************************************/ public interface Executor { - - public String toString(); - - public void execute(Job job, JLabel status) throws Exception; + + @Override + public String toString(); + + public void execute(Job job, JLabel status) throws Exception; } diff --git a/source/com/c2kernel/gui/tabs/execution/RequestButton.java b/source/com/c2kernel/gui/tabs/execution/RequestButton.java old mode 100755 new mode 100644 index 0e11a7f..e1372a2 --- a/source/com/c2kernel/gui/tabs/execution/RequestButton.java +++ b/source/com/c2kernel/gui/tabs/execution/RequestButton.java @@ -27,7 +27,8 @@ import com.c2kernel.lifecycle.instance.stateMachine.Transitions; addActionListener(this); } - public void actionPerformed(ActionEvent event) { + @Override + public void actionPerformed(ActionEvent event) { parent.execute(myJob); } } diff --git a/source/com/c2kernel/gui/tabs/outcome/BasicOutcomeEditor.java b/source/com/c2kernel/gui/tabs/outcome/BasicOutcomeEditor.java old mode 100755 new mode 100644 index 451b393..5ab5245 --- a/source/com/c2kernel/gui/tabs/outcome/BasicOutcomeEditor.java +++ b/source/com/c2kernel/gui/tabs/outcome/BasicOutcomeEditor.java @@ -29,7 +29,7 @@ public class BasicOutcomeEditor extends JPanel implements OutcomeHandler { PlainDocument doc; JTextArea textarea; boolean unsaved; - + public BasicOutcomeEditor() { super(); this.setLayout(new GridLayout(1,1)); @@ -39,14 +39,18 @@ public class BasicOutcomeEditor extends JPanel implements OutcomeHandler { textarea.setFont(Font.decode("monospaced")); add(new JScrollPane(textarea)); doc.addDocumentListener(new DocumentListener() { - public void changedUpdate(DocumentEvent e) { unsaved = true; } - public void insertUpdate(DocumentEvent e) { unsaved = true; } - public void removeUpdate(DocumentEvent e) { unsaved = true; } - + @Override + public void changedUpdate(DocumentEvent e) { unsaved = true; } + @Override + public void insertUpdate(DocumentEvent e) { unsaved = true; } + @Override + public void removeUpdate(DocumentEvent e) { unsaved = true; } + }); } - public void setOutcome(String outcome) throws InvalidOutcomeException { + @Override + public void setOutcome(String outcome) throws InvalidOutcomeException { try { doc.insertString(0, outcome, null); unsaved = false; @@ -55,14 +59,17 @@ public class BasicOutcomeEditor extends JPanel implements OutcomeHandler { } } - public void setDescription(String description) throws InvalidSchemaException { } + @Override + public void setDescription(String description) throws InvalidSchemaException { } - public void setReadOnly(boolean readOnly) { + @Override + public void setReadOnly(boolean readOnly) { textarea.setEditable(!readOnly); } - public JPanel getPanel() throws OutcomeNotInitialisedException { + @Override + public JPanel getPanel() throws OutcomeNotInitialisedException { return this; } @@ -70,7 +77,8 @@ public class BasicOutcomeEditor extends JPanel implements OutcomeHandler { * */ - public String getOutcome() throws OutcomeException { + @Override + public String getOutcome() throws OutcomeException { try { return doc.getText(0, doc.getLength()); } catch (Exception ex) { @@ -82,18 +90,22 @@ public class BasicOutcomeEditor extends JPanel implements OutcomeHandler { * */ - public void run() { + @Override + public void run() { } - public boolean isUnsaved() { + @Override + public boolean isUnsaved() { return unsaved; } - - public void saved() { + + @Override + public void saved() { unsaved = false; } + @Override public void export(File targetFile) throws Exception { FileStringUtility.string2File(targetFile, getOutcome()); } diff --git a/source/com/c2kernel/gui/tabs/outcome/form/AttributeList.java b/source/com/c2kernel/gui/tabs/outcome/form/AttributeList.java index 015bd9a..3d6cc6e 100644 --- a/source/com/c2kernel/gui/tabs/outcome/form/AttributeList.java +++ b/source/com/c2kernel/gui/tabs/outcome/form/AttributeList.java @@ -26,7 +26,7 @@ public class AttributeList extends JPanel { ElementDecl model; Element myElement; boolean readOnly; - static Font labelFont; + static Font labelFont; public AttributeList(ElementDecl model, boolean readOnly, HelpPane helpPane) { super(); @@ -44,7 +44,7 @@ public class AttributeList extends JPanel { // simple types have no attributes return; } - + ComplexType content = (ComplexType)model.getType(); // place on panel @@ -53,9 +53,9 @@ public class AttributeList extends JPanel { c.anchor = GridBagConstraints.NORTHWEST; c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1.0; c.weighty = 1.0; c.gridx = 0; - c.ipadx = 5; c.ipady = 0; + c.ipadx = 5; c.ipady = 0; - for (Enumeration fields = content.getAttributeDecls(); fields.hasMoreElements();) { + for (Enumeration fields = content.getAttributeDecls(); fields.hasMoreElements();) { c.gridy = 0; thisDecl = (AttributeDecl)fields.nextElement(); Logger.msg(8, "Includes Attribute "+thisDecl.getName()); @@ -70,11 +70,11 @@ public class AttributeList extends JPanel { // read help String helpText; String doc = OutcomeStructure.extractHelp(thisDecl); - if (doc.length() > 0) + if (doc.length() > 0) helpText = doc.toString(); else helpText = "No help is available for this attribute"; - + c.gridy++; @@ -91,7 +91,7 @@ public class AttributeList extends JPanel { entry.setToolTipText(e.getMessage()); gridbag.setConstraints(entry, c); this.add(entry); - } + } c.gridx++; @@ -100,26 +100,25 @@ public class AttributeList extends JPanel { public void setInstance(Element data) throws StructuralException { this.myElement = data; - for (Iterator e = attrSet.iterator(); e.hasNext();) { - StringEditField thisField = (StringEditField)e.next(); + for (StringEditField thisField : attrSet) { Logger.msg(8, "Populating Attribute "+thisField.getName()); Attr thisAttr = myElement.getAttributeNode(thisField.getName()); - if (thisAttr == null) + if (thisAttr == null) thisAttr = newAttribute(myElement, (AttributeDecl)thisField.getModel()); thisField.setData(thisAttr); } } - + public Attr newAttribute(Element parent, AttributeDecl attr) { - + parent.setAttribute(attr.getName(), attr.getFixedValue()!=null?attr.getFixedValue():attr.getDefaultValue()); return parent.getAttributeNode(attr.getName()); } - + public String validateAttributes() { if (model.getType().isComplexType()) { ComplexType content = (ComplexType)model.getType(); - for (Enumeration fields = content.getAttributeDecls(); fields.hasMoreElements();) { + for (Enumeration fields = content.getAttributeDecls(); fields.hasMoreElements();) { AttributeDecl thisDecl = (AttributeDecl)fields.nextElement(); String attrVal = myElement.getAttribute(thisDecl.getName()); if (attrVal.length() == 0 && thisDecl.isOptional()) { @@ -129,20 +128,20 @@ public class AttributeList extends JPanel { } return null; } - + public void initNew(Element parent) { AttributeDecl thisDecl; StringEditField thisField; Attr thisAttr; this.myElement = parent; - + if (model.getType().isSimpleType()) return; // no attributes in simple types - + ComplexType content = (ComplexType)model.getType(); - - for (Iterator e = attrSet.iterator(); e.hasNext();) { - thisField = (StringEditField)e.next(); - + + for (Iterator e = attrSet.iterator(); e.hasNext();) { + thisField = e.next(); + thisDecl = content.getAttributeDecl(thisField.getName()); thisAttr = newAttribute(myElement, thisDecl); // add into parent - fill in field @@ -151,8 +150,9 @@ public class AttributeList extends JPanel { } catch (Exception ex) { } // impossible name mismatch } } - public void grabFocus() { + @Override + public void grabFocus() { if (attrSet.size() > 0) - ((StringEditField)attrSet.get(0)).grabFocus(); + attrSet.get(0).grabFocus(); } } diff --git a/source/com/c2kernel/gui/tabs/outcome/form/DataRecord.java b/source/com/c2kernel/gui/tabs/outcome/form/DataRecord.java old mode 100755 new mode 100644 index 9d0b633..7477ecd --- a/source/com/c2kernel/gui/tabs/outcome/form/DataRecord.java +++ b/source/com/c2kernel/gui/tabs/outcome/form/DataRecord.java @@ -4,7 +4,6 @@ import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.util.ArrayList; -import java.util.Iterator; import javax.swing.JLabel; import javax.swing.JTabbedPane; @@ -26,7 +25,7 @@ public class DataRecord extends OutcomeStructure implements ChangeListener { AttributeList myAttributes; JTabbedPane DRPanel = null; boolean deferred; - ArrayList deferredChildren = new ArrayList(); + ArrayList deferredChildren = new ArrayList(); Document parentDoc; GridBagConstraints position; GridBagLayout gridbag; @@ -36,7 +35,7 @@ public class DataRecord extends OutcomeStructure implements ChangeListener { this.deferred = deferred; if (!deferred) setupPanel(); } - + public synchronized void activate() { deferred = false; try { @@ -84,7 +83,8 @@ public class DataRecord extends OutcomeStructure implements ChangeListener { } } - public void addStructure(OutcomeStructure newElement) throws OutcomeException { + @Override + public void addStructure(OutcomeStructure newElement) throws OutcomeException { super.addStructure(newElement); if (newElement == null) return; if (newElement instanceof DataRecord) { @@ -127,7 +127,7 @@ public class DataRecord extends OutcomeStructure implements ChangeListener { position.gridy--; position.gridheight=2; position.weightx=0; - position.fill=GridBagConstraints.NONE; + position.fill=GridBagConstraints.NONE; gridbag.setConstraints(newField.getAttributes(), position); this.add(newField.getAttributes()); position.gridx=0; @@ -135,7 +135,7 @@ public class DataRecord extends OutcomeStructure implements ChangeListener { position.gridy++; } else { - position.fill=GridBagConstraints.HORIZONTAL; + position.fill=GridBagConstraints.HORIZONTAL; position.gridwidth=3; position.weightx=1.0; position.gridy++; @@ -146,48 +146,49 @@ public class DataRecord extends OutcomeStructure implements ChangeListener { } } - public void addInstance(Element myElement, Document parentDoc) throws OutcomeException { + @Override + public void addInstance(Element myElement, Document parentDoc) throws OutcomeException { Logger.msg(8, "Accepting DR "+myElement.getTagName()); if (this.myElement != null) throw new CardinalException("DataRecord "+this.getName()+" cannot repeat."); this.myElement = myElement; this.parentDoc = parentDoc; - + if (!deferred) populateInstance(); } - + public void populateInstance() throws OutcomeException { myAttributes.setInstance(myElement); - + NodeList childElements = myElement.getChildNodes(); - + for (int i=0; i 0) myAttributes.grabFocus(); else if (order.size()> 0) - ((OutcomeStructure)subStructure.get(order.get(0))).grabFocus(); + subStructure.get(order.get(0)).grabFocus(); } } diff --git a/source/com/c2kernel/gui/tabs/outcome/form/Dimension.java b/source/com/c2kernel/gui/tabs/outcome/form/Dimension.java index 8de306b..c91c5df 100644 --- a/source/com/c2kernel/gui/tabs/outcome/form/Dimension.java +++ b/source/com/c2kernel/gui/tabs/outcome/form/Dimension.java @@ -1,6 +1,6 @@ package com.c2kernel.gui.tabs.outcome.form; -import java.awt.*; import java.awt.FlowLayout; +import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; @@ -11,7 +11,15 @@ import java.awt.event.FocusListener; import java.util.ArrayList; import java.util.Iterator; -import javax.swing.*; +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.JButton; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JTabbedPane; +import javax.swing.JTable; +import javax.swing.ListSelectionModel; import javax.swing.border.EtchedBorder; import javax.swing.table.JTableHeader; @@ -38,7 +46,7 @@ public class Dimension extends OutcomeStructure implements ActionListener { Box tableBox; ArrayList instances = new ArrayList(); // stores DimensionInstances if tabs ArrayList elements = new ArrayList(); // stores current children - + JButton addButton; JButton delButton; @@ -61,17 +69,17 @@ public class Dimension extends OutcomeStructure implements ActionListener { position.insets = new Insets(0,0,0,0); // TODO: an element or attribute of the dimension can be flagged as an index, so it can be used as a title for a tab - + // set up the border setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(EtchedBorder.LOWERED), model.getName())); - + msg = new JLabel("No elements"); msg.setFont(new Font("SansSerif", Font.ITALIC, msg.getFont().getSize())); gridbag.setConstraints(msg, position); add(msg); position.gridy++; - + // decide whether a table or tabs try { tableModel = new DimensionTableModel(model, readOnly); @@ -90,10 +98,10 @@ public class Dimension extends OutcomeStructure implements ActionListener { gridbag.setConstraints(tableBox, position); add(tableBox); tableBox.setVisible(false); - + } catch (StructuralException e) { // use tabs - Logger.msg(8, "DIM "+model.getName()+" - Will be tabs: "+e.getMessage()); + Logger.msg(8, "DIM "+model.getName()+" - Will be tabs: "+e.getMessage()); mode = TABS; tabs = new JTabbedPane(); gridbag.setConstraints(tabs, position); @@ -101,7 +109,7 @@ public class Dimension extends OutcomeStructure implements ActionListener { tabs.setVisible(false); } if (!readOnly) { - JPanel rowAdjust = new JPanel(new FlowLayout()); + JPanel rowAdjust = new JPanel(new FlowLayout()); addButton = new JButton("+"); addButton.setActionCommand("add"); addButton.addActionListener(this); @@ -113,19 +121,20 @@ public class Dimension extends OutcomeStructure implements ActionListener { delButton.setEnabled(false); rowAdjust.add(delButton); - + position.gridy++; position.weighty=0; position.weightx=0; gridbag.setConstraints(rowAdjust, position); this.add(rowAdjust); } - + } - + public void setParentElement(Element parent) { this.parent = parent; } - public void addInstance(Element myElement, Document parentDoc) throws OutcomeException { + @Override + public void addInstance(Element myElement, Document parentDoc) throws OutcomeException { if (Logger.doLog(6)) Logger.msg(6, "DIM - adding instance "+ (elements.size()+1) +" for "+myElement.getTagName()); if (parent == null) setParentElement((Element)myElement.getParentNode()); @@ -134,24 +143,24 @@ public class Dimension extends OutcomeStructure implements ActionListener { tableModel.addInstance(myElement, -1); elements.add(myElement); } - else { + else { DimensionInstance target; elements.add(myElement); if (instances.size() < elements.size()) target = newInstance(); else - target = (DimensionInstance)instances.get(elements.size()-1); + target = instances.get(elements.size()-1); target.addInstance(myElement, parentDoc); } checkButtons(); } - + public int getChildCount() { return elements.size(); } public DimensionInstance newInstance() { - DimensionInstance newInstance = null; + DimensionInstance newInstance = null; try { newInstance = new DimensionInstance(model, readOnly, helpPane, deferChild); instances.add(newInstance); @@ -166,37 +175,38 @@ public class Dimension extends OutcomeStructure implements ActionListener { } return newInstance; } - - public String validateStructure() { + + @Override + public String validateStructure() { if (mode == TABLE) return table.validateStructure(); else { StringBuffer errors = new StringBuffer(); - for (Iterator iter = instances.iterator(); iter.hasNext();) { - OutcomeStructure element = (OutcomeStructure)iter.next(); + for (Iterator iter = instances.iterator(); iter.hasNext();) { + OutcomeStructure element = iter.next(); errors.append(element.validateStructure()); } - return errors.toString(); + return errors.toString(); } } - + public void checkButtons() { // check if data visible boolean dataVisible = elements.size() > 0; if (mode == TABS) tabs.setVisible(dataVisible); else tableBox.setVisible(dataVisible); msg.setVisible(!dataVisible); - + if (readOnly) return; - + if (elements.size() <= model.getMinOccurs() || elements.size() == 0) { - delButton.setEnabled(false); + delButton.setEnabled(false); delButton.setToolTipText("Minimum row count of "+model.getMinOccurs()+" reached."); } else { - delButton.setEnabled(true); + delButton.setEnabled(true); delButton.setToolTipText(null); } - + if (elements.size() < model.getMaxOccurs() || model.getMaxOccurs() == Particle.UNBOUNDED) { addButton.setEnabled(true); addButton.setToolTipText(null); @@ -205,8 +215,9 @@ public class Dimension extends OutcomeStructure implements ActionListener { addButton.setToolTipText("Maximum row count of "+model.getMaxOccurs()+" reached."); } } - - public Element initNew(Document parent) { + + @Override + public Element initNew(Document parent) { Element newElement; if (mode == TABLE) { @@ -220,19 +231,20 @@ public class Dimension extends OutcomeStructure implements ActionListener { if (instances.size() < elements.size()+1) newTab = newInstance(); else - newTab = (DimensionInstance)instances.get(elements.size()-1); + newTab = instances.get(elements.size()-1); newElement = newTab.initNew(parent); elements.add(newElement); - checkButtons(); + checkButtons(); return newElement; } } - - public void actionPerformed(ActionEvent e) { + + @Override + public void actionPerformed(ActionEvent e) { int index; if (mode == TABS) index = tabs.getSelectedIndex(); else { - index = table.getSelectedRow(); + index = table.getSelectedRow(); if (index == -1) index = tableModel.getRowCount(); } try { @@ -246,16 +258,16 @@ public class Dimension extends OutcomeStructure implements ActionListener { JOptionPane.showMessageDialog(null, ex.getMessage(), "Table error", JOptionPane.ERROR_MESSAGE); } } - + public void addRow(int index) throws CardinalException { - if (elements.size() == model.getMaxOccurs()) + if (elements.size() == model.getMaxOccurs()) throw new CardinalException("Maximum size of table reached"); - + if (mode == TABLE) { Element newRow = tableModel.initNew(parent.getOwnerDocument(), index); elements.add(index, newRow); try { - Element following = (Element)elements.get(index+1); + Element following = elements.get(index+1); parent.insertBefore(newRow, following); } catch (IndexOutOfBoundsException ex) { parent.appendChild(newRow); @@ -268,9 +280,9 @@ public class Dimension extends OutcomeStructure implements ActionListener { parent.appendChild(newTab); } checkButtons(); - - } - + + } + public void removeRow(int index) throws CardinalException { if (elements.size() <= model.getMinOccurs()) throw new CardinalException("Minimum size of table reached"); @@ -284,12 +296,12 @@ public class Dimension extends OutcomeStructure implements ActionListener { } } else { - Element elementToGo = (Element)elements.get(index); + Element elementToGo = elements.get(index); parent.removeChild(elementToGo); instances.remove(index); tabs.remove(index); for (int i = index; i 0) { table.changeSelection(0, 0, false, false); @@ -371,7 +389,7 @@ public class Dimension extends OutcomeStructure implements ActionListener { table.requestFocus(); } else if (instances.size()> 0) - ((DimensionInstance)instances.get(0)).grabFocus(); + instances.get(0).grabFocus(); } } diff --git a/source/com/c2kernel/gui/tabs/outcome/form/DimensionInstance.java b/source/com/c2kernel/gui/tabs/outcome/form/DimensionInstance.java old mode 100755 new mode 100644 index 07fbe1b..649886b --- a/source/com/c2kernel/gui/tabs/outcome/form/DimensionInstance.java +++ b/source/com/c2kernel/gui/tabs/outcome/form/DimensionInstance.java @@ -9,7 +9,7 @@ public class DimensionInstance extends DataRecord { Dimension parentDimension; int tabNumber; String tabName = null; - + public DimensionInstance(ElementDecl model, boolean readOnly , HelpPane help, boolean deferred) throws OutcomeException { super(model, readOnly, help, deferred); } @@ -17,14 +17,15 @@ public class DimensionInstance extends DataRecord { public void setTabNumber(int tabNumber) { this.tabNumber=tabNumber; } - + public void setParent(Dimension parent) { this.parentDimension = parent; } - - public String getName() { + + @Override + public String getName() { //TODO appinfo for picking out attributes or child elements for tab name - if (tabName == null) + if (tabName == null) return Integer.toString(tabNumber); else return tabName; diff --git a/source/com/c2kernel/gui/tabs/outcome/form/DimensionTableModel.java b/source/com/c2kernel/gui/tabs/outcome/form/DimensionTableModel.java index 1a606fb..45bdbc8 100644 --- a/source/com/c2kernel/gui/tabs/outcome/form/DimensionTableModel.java +++ b/source/com/c2kernel/gui/tabs/outcome/form/DimensionTableModel.java @@ -4,15 +4,29 @@ import java.util.Enumeration; import javax.swing.table.AbstractTableModel; -import org.exolab.castor.xml.schema.*; -import org.w3c.dom.*; +import org.exolab.castor.xml.schema.Annotated; +import org.exolab.castor.xml.schema.AttributeDecl; +import org.exolab.castor.xml.schema.ComplexType; +import org.exolab.castor.xml.schema.ContentModelGroup; +import org.exolab.castor.xml.schema.ElementDecl; +import org.exolab.castor.xml.schema.Group; +import org.exolab.castor.xml.schema.Order; +import org.exolab.castor.xml.schema.Particle; +import org.exolab.castor.xml.schema.SimpleType; +import org.exolab.castor.xml.schema.SimpleTypesFactory; +import org.exolab.castor.xml.schema.XMLType; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.w3c.dom.Text; import com.c2kernel.gui.tabs.outcome.OutcomeException; import com.c2kernel.utils.Language; import com.c2kernel.utils.Logger; public class DimensionTableModel extends AbstractTableModel { - + ElementDecl model; ArrayList columnHeadings = new ArrayList(); ArrayList> columnClasses = new ArrayList>(); @@ -25,7 +39,7 @@ public class DimensionTableModel extends AbstractTableModel { public DimensionTableModel(ElementDecl model, boolean readOnly) throws StructuralException { XMLType modelContent = model.getType(); - + this.model = model; this.readOnly = readOnly; // use text node for simple types @@ -47,7 +61,7 @@ public class DimensionTableModel extends AbstractTableModel { addColumn(model.getName(), baseType, typeCode, new Boolean(model.getFixedValue() != null)); } // process attributes - for (Enumeration e = elementType.getAttributeDecls(); e.hasMoreElements();) { + for (Enumeration e = elementType.getAttributeDecls(); e.hasMoreElements();) { AttributeDecl thisAttr = (AttributeDecl)e.nextElement(); addColumn(thisAttr.getName(), thisAttr, thisAttr.getSimpleType().getTypeCode(), new Boolean(thisAttr.isFixed())); } @@ -63,30 +77,30 @@ public class DimensionTableModel extends AbstractTableModel { columnDecls.add(decl); columnClasses.add(OutcomeStructure.getJavaClass(typeCode)); colReadOnly.add(readOnly); - + // read help String helpText; if (decl instanceof SimpleType) helpText = OutcomeStructure.extractHelp(model); else helpText = OutcomeStructure.extractHelp(decl); - - if (helpText.length() == 0) + + if (helpText.length() == 0) helpText = ""+Language.translate("No help is available for this cell")+""; - + colHelp.add(helpText); } public void enumerateElements(ContentModelGroup group) throws StructuralException { - for (Enumeration childElements = group.enumerate(); childElements.hasMoreElements(); ) { + for (Enumeration childElements = group.enumerate(); childElements.hasMoreElements(); ) { Particle thisParticle = (Particle)childElements.nextElement(); String extraHeader = ""; if (thisParticle instanceof Group) { Group thisGroup = (Group)thisParticle; Order order = thisGroup.getOrder(); - if (order == Order.sequence || order == Order.all) + if (order == Order.sequence || order == Order.all) enumerateElements(thisGroup); else // we only support sequences in data structures such as these throw new StructuralException("Element "+thisGroup.getName()+". Expecting sequence or all. Got "+thisGroup.getOrder()); @@ -101,9 +115,9 @@ public class DimensionTableModel extends AbstractTableModel { if (elementType.getParticleCount() > 0 || thisElement.getMaxOccurs() > 1) throw new StructuralException("Too deep for a table"); - for (Enumeration attrs = elementType.getAttributeDecls(); attrs.hasMoreElements();) { + for (Enumeration attrs = elementType.getAttributeDecls(); attrs.hasMoreElements();) { AttributeDecl thisAttr = (AttributeDecl)attrs.nextElement(); - if (!thisAttr.isFixed()) + if (!thisAttr.isFixed()) throw new StructuralException("Non-fixed attributes of child elements not supported in tables."); else extraHeader=extraHeader+" ("+thisAttr.getName()+":"+(thisAttr.getFixedValue()!=null?thisAttr.getFixedValue():thisAttr.getDefaultValue())+")"; @@ -118,7 +132,7 @@ public class DimensionTableModel extends AbstractTableModel { else typeCode = ((SimpleType)thisElement.getType()).getTypeCode(); } - + //add to list addColumn(thisElement.getName()+extraHeader, thisElement, typeCode, new Boolean(thisElement.getFixedValue() != null)); } @@ -139,35 +153,35 @@ public class DimensionTableModel extends AbstractTableModel { if (childElement.hasChildNodes()) { Node thisNode = childElement.getFirstChild(); if (thisNode.getNodeType() == Node.TEXT_NODE) - newRow[i] = OutcomeStructure.getTypedValue(((Text)thisNode).getData(), (Class)columnClasses.get(i)); + newRow[i] = OutcomeStructure.getTypedValue(((Text)thisNode).getData(), columnClasses.get(i)); else throw new StructuralException("First child of Field " + thisElementDecl.getName() + " was not Text. (NodeType:"+thisNode.getNodeType()+")"); } else { // create text node - newRow[i] = this.setupDefaultElement(thisElementDecl, childElement, (Class)columnClasses.get(i)); + newRow[i] = this.setupDefaultElement(thisElementDecl, childElement, columnClasses.get(i)); } break; case 0: // element is missing - create it Element newElement = myElement.getOwnerDocument().createElement(thisElementDecl.getName()); myElement.appendChild(newElement); //TODO: not in the right place in sequence. should insert it - newRow[i] = setupDefaultElement(thisElementDecl, newElement, (Class)columnClasses.get(i)); - break; + newRow[i] = setupDefaultElement(thisElementDecl, newElement, columnClasses.get(i)); + break; default: throw new CardinalException("Element "+thisElementDecl.getName()+" appeared more than once."); } } else if (columnDecls.get(i) instanceof AttributeDecl) { //attribute AttributeDecl thisAttrDecl = (AttributeDecl)columnDecls.get(i); - newRow[i] = OutcomeStructure.getTypedValue(myElement.getAttribute(thisAttrDecl.getName()), (Class)columnClasses.get(i)); + newRow[i] = OutcomeStructure.getTypedValue(myElement.getAttribute(thisAttrDecl.getName()), columnClasses.get(i)); } - else { // first child node + else { // first child node Node thisNode = myElement.getFirstChild(); if (thisNode == null) { thisNode = myElement.getOwnerDocument().createTextNode(""); myElement.appendChild(thisNode); } if (thisNode.getNodeType() == Node.TEXT_NODE || thisNode.getNodeType() == Node.CDATA_SECTION_NODE) - newRow[i] = OutcomeStructure.getTypedValue(((Text)thisNode).getData(), (Class)columnClasses.get(i)); + newRow[i] = OutcomeStructure.getTypedValue(((Text)thisNode).getData(), columnClasses.get(i)); else throw new StructuralException("First child of Column " + myElement.getTagName() + " was not Text"); } @@ -176,31 +190,37 @@ public class DimensionTableModel extends AbstractTableModel { rows.add(index, newRow); fireTableRowsInserted(index, index); } - public Class getColumnClass(int columnIndex) { + @Override + public Class getColumnClass(int columnIndex) { return columnClasses.get(columnIndex); } - public String getColumnName(int columnIndex) { - return (String)columnHeadings.get(columnIndex); + @Override + public String getColumnName(int columnIndex) { + return columnHeadings.get(columnIndex); } - public int getRowCount() { + @Override + public int getRowCount() { return rows.size(); } - public int getColumnCount() { + @Override + public int getColumnCount() { return columnHeadings.size(); } - public boolean isCellEditable(int rowIndex, int columnIndex) { - boolean isReadOnly = readOnly || ((Boolean)colReadOnly.get(columnIndex)).booleanValue(); + @Override + public boolean isCellEditable(int rowIndex, int columnIndex) { + boolean isReadOnly = readOnly || colReadOnly.get(columnIndex).booleanValue(); return !isReadOnly; } - public void setValueAt(Object aValue, int rowIndex, int columnIndex) { - Object[] thisRow = (Object[])rows.get(rowIndex); + @Override + public void setValueAt(Object aValue, int rowIndex, int columnIndex) { + Object[] thisRow = rows.get(rowIndex); thisRow[columnIndex]=aValue; - Element myElement = (Element)elements.get(rowIndex); + Element myElement = elements.get(rowIndex); // update node if (columnDecls.get(columnIndex) instanceof ElementDecl) { // sub element ElementDecl thisDecl = (ElementDecl)columnDecls.get(columnIndex); @@ -213,7 +233,7 @@ public class DimensionTableModel extends AbstractTableModel { AttributeDecl thisDecl = (AttributeDecl) columnDecls.get(columnIndex); myElement.setAttribute(thisDecl.getName(), aValue.toString()); } - else { // first child node + else { // first child node Text textNode = (Text)myElement.getFirstChild(); textNode.setData(aValue.toString()); } @@ -221,14 +241,14 @@ public class DimensionTableModel extends AbstractTableModel { } public Element removeRow(int rowIndex) { - Element elementToGo = (Element)elements.get(rowIndex); + Element elementToGo = elements.get(rowIndex); elements.remove(rowIndex); rows.remove(rowIndex); fireTableRowsDeleted(rowIndex,rowIndex); return elementToGo; } - - public Object setupDefaultElement(ElementDecl thisDecl, Element parent, Class type) { + + public Object setupDefaultElement(ElementDecl thisDecl, Element parent, Class type) { Object newValue; String defaultValue = thisDecl.getFixedValue(); if (defaultValue == null) @@ -237,13 +257,13 @@ public class DimensionTableModel extends AbstractTableModel { newValue = ""; else newValue = OutcomeStructure.getTypedValue(defaultValue, type); - + Text newNode = parent.getOwnerDocument().createTextNode(newValue.toString()); parent.appendChild(newNode); // fixed attributes try { ComplexType content = (ComplexType)thisDecl.getType(); - for (Enumeration attrs = content.getAttributeDecls(); attrs.hasMoreElements();) { + for (Enumeration attrs = content.getAttributeDecls(); attrs.hasMoreElements();) { AttributeDecl thisAttr = (AttributeDecl)attrs.nextElement(); parent.setAttribute(thisAttr.getName(), thisAttr.getFixedValue()!=null?thisAttr.getFixedValue():thisAttr.getDefaultValue()); } @@ -251,16 +271,17 @@ public class DimensionTableModel extends AbstractTableModel { return newValue; } - public Object getValueAt(int rowIndex, int columnIndex) { - Object[] thisRow = (Object[])rows.get(rowIndex); + @Override + public Object getValueAt(int rowIndex, int columnIndex) { + Object[] thisRow = rows.get(rowIndex); if (!(getColumnClass(columnIndex).equals(thisRow[columnIndex].getClass()))) Logger.warning(thisRow[columnIndex]+" should be "+getColumnClass(columnIndex)+" is a "+thisRow[columnIndex].getClass().getName()); return thisRow[columnIndex]; } - + public String validateStructure() { // remove empty rows for (int j=0; j < rows.size(); j++) { - Object[] elems = (Object[])rows.get(j); + Object[] elems = rows.get(j); boolean empty = true; for (int i = 0; i < elems.length && empty; i++) empty &= OutcomeStructure.isEmpty(elems[i]); @@ -272,37 +293,37 @@ public class DimensionTableModel extends AbstractTableModel { } return null; } - + public Element initNew(Document parent, int index) { if (index == -1) index = elements.size(); Object[] newRow = new Object[columnHeadings.size()]; Element myElement = parent.createElement(model.getName()); for (int i=0; i"+Language.translate("Help")+""; - + public HelpPane() { super(); setEditable(false); @@ -25,24 +25,24 @@ public class HelpPane extends JEditorPane { setContentType("text/html"); setPreferredSize(new java.awt.Dimension(200,400)); } - + public void setHelp(String title, String helpText) { setText(header+"

    "+title+"


    "+toHTML(helpText)); } - + /** * Unfortunately JEditorPane will only display HTML3.2, whereas to embed HTML in an xsd we must * use XHTML so it will be valid XML. This method does a quick and dirty removal of stuff that * the JEditorPane cannot display - * + * * @param xhtml * @return */ public static String toHTML(String xhtml) { int startPos, endPos; //remove xml header - while((startPos = xhtml.indexOf("")) != -1) { xhtml = xhtml.substring(0,startPos)+xhtml.substring(endPos+2); } diff --git a/source/com/c2kernel/gui/tabs/outcome/form/MultiLinePasteAdapter.java b/source/com/c2kernel/gui/tabs/outcome/form/MultiLinePasteAdapter.java old mode 100755 new mode 100644 index d9f6b55..3c5da27 --- a/source/com/c2kernel/gui/tabs/outcome/form/MultiLinePasteAdapter.java +++ b/source/com/c2kernel/gui/tabs/outcome/form/MultiLinePasteAdapter.java @@ -1,12 +1,19 @@ package com.c2kernel.gui.tabs.outcome.form; -import java.awt.*; -import java.awt.event.*; -import javax.swing.*; +import java.awt.Toolkit; +import java.awt.datatransfer.Clipboard; +import java.awt.datatransfer.DataFlavor; +import java.awt.datatransfer.StringSelection; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.KeyEvent; +import java.util.StringTokenizer; -import com.c2kernel.utils.Logger; +import javax.swing.JComponent; +import javax.swing.JOptionPane; +import javax.swing.JTable; +import javax.swing.KeyStroke; -import java.awt.datatransfer.*; -import java.util.*; +import com.c2kernel.utils.Logger; /** * ExcelAdapter enables Copy-Paste Clipboard functionality on JTables. * The clipboard data format used by the adapter is compatible with @@ -64,7 +71,8 @@ public class MultiLinePasteAdapter implements ActionListener { * Paste is done by aligning the upper left corner of the selection with the * 1st element in the current selection of the JTable. */ - public void actionPerformed(ActionEvent e) { + @Override + public void actionPerformed(ActionEvent e) { if (e.getActionCommand().compareTo("Copy") == 0) { StringBuffer sbf = new StringBuffer(); // Check to ensure we have selected only a contiguous block of @@ -127,7 +135,7 @@ public class MultiLinePasteAdapter implements ActionListener { } catch (Exception ex) { Logger.exceptionDialog(ex); } - + } } } diff --git a/source/com/c2kernel/gui/tabs/outcome/form/OutcomeEditor.java b/source/com/c2kernel/gui/tabs/outcome/form/OutcomeEditor.java old mode 100755 new mode 100644 index 10c3542..7809480 --- a/source/com/c2kernel/gui/tabs/outcome/form/OutcomeEditor.java +++ b/source/com/c2kernel/gui/tabs/outcome/form/OutcomeEditor.java @@ -27,14 +27,14 @@ class OutcomeEditor extends JFrame implements ActionListener { JFileChooser chooser; OutcomePanel outcome; OutcomeValidator thisValid; - + public OutcomeEditor(File schema, File instance, boolean readOnly) { URL schemaURL = null; URL instanceURL = null; schemaFile = schema; instanceFile = instance; this.readOnly = readOnly; - + try { chooser = new JFileChooser(); chooser.setCurrentDirectory(new File(new File(".").getCanonicalPath())); @@ -47,12 +47,13 @@ class OutcomeEditor extends JFrame implements ActionListener { this.setTitle("Outcome Editor"); GridBagLayout gridbag = new GridBagLayout(); getContentPane().setLayout(gridbag); - + addWindowListener( new java.awt.event.WindowAdapter() { - public void windowClosing(java.awt.event.WindowEvent evt) { + @Override + public void windowClosing(java.awt.event.WindowEvent evt) { System.exit(0); - } + } } ); // select files if url is empty @@ -64,12 +65,12 @@ class OutcomeEditor extends JFrame implements ActionListener { System.exit(1); } } - + try { schemaURL = schemaFile.toURL(); - } catch (Exception e) { + } catch (Exception e) { System.out.println("Invalid schema URL"); - System.exit(1); + System.exit(1); } if (instanceFile == null) { // prompt for schema @@ -79,7 +80,7 @@ class OutcomeEditor extends JFrame implements ActionListener { try { instanceURL = instanceFile.toURL(); } catch (Exception e) { } - + try { if (instanceFile != null && instanceFile.exists()) outcome = new OutcomePanel(schemaURL, instanceURL, readOnly); @@ -93,14 +94,14 @@ class OutcomeEditor extends JFrame implements ActionListener { thisValid = OutcomeValidator.getValidator(thisSchema); } catch (Exception e) { e.printStackTrace(); System.exit(0);} - - + + GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.anchor = GridBagConstraints.NORTHWEST; c.fill = GridBagConstraints.BOTH; c.weightx = 1.0; c.weighty = 1.0; - c.gridwidth = 2; c.ipadx = 5; c.ipady = 5; + c.gridwidth = 2; c.ipadx = 5; c.ipady = 5; gridbag.setConstraints(outcome, c); this.getContentPane().add(outcome); @@ -111,7 +112,7 @@ class OutcomeEditor extends JFrame implements ActionListener { gridbag.setConstraints(saveButton, c); this.getContentPane().add(saveButton); if (readOnly) saveButton.setEnabled(false); - + JButton saveAsButton = new JButton("Save As"); saveAsButton.setActionCommand("saveas"); saveAsButton.addActionListener(this); @@ -165,18 +166,19 @@ class OutcomeEditor extends JFrame implements ActionListener { new OutcomeEditor(schema, instance, readOnly); } - public void actionPerformed(ActionEvent e) { + @Override + public void actionPerformed(ActionEvent e) { if (e.getActionCommand().indexOf("save") == 0) { String output; output = outcome.getOutcome(); - + String errors = thisValid.validate(output); if (errors != null && errors.length() > 0) { int choice = JOptionPane.showConfirmDialog(null, errors+"\n\nSave anyway?", "Errors validating document", JOptionPane.YES_NO_OPTION); if (choice != JOptionPane.YES_OPTION) return; } - + if (instanceFile == null || e.getActionCommand().equals("saveas")) { instanceFile = getFile("Choose Instance File", "xml"); if (instanceFile == null) { @@ -200,11 +202,13 @@ class OutcomeEditor extends JFrame implements ActionListener { this.extension = extension; } - public String getDescription() { + @Override + public String getDescription() { return extension.toUpperCase()+" Files"; } - public boolean accept(File f) { + @Override + public boolean accept(File f) { if ((f.isFile() && f.getName().endsWith(extension.toLowerCase())) || f.isDirectory()) { return true; } diff --git a/source/com/c2kernel/gui/tabs/outcome/form/OutcomePanel.java b/source/com/c2kernel/gui/tabs/outcome/form/OutcomePanel.java old mode 100755 new mode 100644 index 4bb7347..6d20183 --- a/source/com/c2kernel/gui/tabs/outcome/form/OutcomePanel.java +++ b/source/com/c2kernel/gui/tabs/outcome/form/OutcomePanel.java @@ -89,7 +89,7 @@ public class OutcomePanel extends JPanel implements OutcomeHandler splitPane.setDividerSize(9); pane = splitPane; } - + GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; @@ -165,8 +165,9 @@ public class OutcomePanel extends JPanel implements OutcomeHandler this.setOutcome(outcomeURL); } - // Parse from Strings - public void setOutcome(String outcome) throws InvalidOutcomeException + // Parse from Strings + @Override + public void setOutcome(String outcome) throws InvalidOutcomeException { try @@ -179,7 +180,8 @@ public class OutcomePanel extends JPanel implements OutcomeHandler } } - public void setDescription(String schema) throws InvalidSchemaException + @Override + public void setDescription(String schema) throws InvalidSchemaException { if (schema == null) throw new InvalidSchemaException("Null schema supplied"); @@ -194,7 +196,8 @@ public class OutcomePanel extends JPanel implements OutcomeHandler } - public void setReadOnly(boolean readOnly) + @Override + public void setReadOnly(boolean readOnly) { this.readOnly = readOnly; } @@ -218,7 +221,8 @@ public class OutcomePanel extends JPanel implements OutcomeHandler } } - public void run() + @Override + public void run() { Thread.currentThread().setName("Outcome Panel Builder"); try @@ -271,7 +275,7 @@ public class OutcomePanel extends JPanel implements OutcomeHandler ElementDecl rootElementDecl = null; docElement = (outcomeDOM == null) ? null : outcomeDOM.getDocumentElement(); - for (Enumeration globalElements = schemaSOM.getElementDecls(); globalElements.hasMoreElements();) + for (Enumeration globalElements = schemaSOM.getElementDecls(); globalElements.hasMoreElements();) { rootElementDecl = (ElementDecl) globalElements.nextElement(); // REVISIT: We don't detect which is the most likely root element if there is more than one root decl @@ -284,7 +288,7 @@ public class OutcomePanel extends JPanel implements OutcomeHandler if (rootElementDecl == null) throw new InvalidSchemaException("No root elements defined"); documentRoot = new DataRecord(rootElementDecl, readOnly, help, false); - + Logger.msg(5, "Finished structure. Populating..."); if (docElement == null) { @@ -302,7 +306,7 @@ public class OutcomePanel extends JPanel implements OutcomeHandler outcomeTab.addTab(rootElementDecl.getName(), documentRoot); outcomeTab.setSelectedIndex(0); - scrollpane.setViewportView(outcomeTab); + scrollpane.setViewportView(outcomeTab); panelBuilt = true; revalidate(); @@ -311,12 +315,14 @@ public class OutcomePanel extends JPanel implements OutcomeHandler documentRoot.grabFocus(); } - public JPanel getPanel() throws OutcomeNotInitialisedException + @Override + public JPanel getPanel() throws OutcomeNotInitialisedException { return this; } - public String getOutcome() + @Override + public String getOutcome() { if (useForm) { @@ -348,14 +354,17 @@ public class OutcomePanel extends JPanel implements OutcomeHandler return serializedDoc; } - public boolean isUnsaved() { + @Override + public boolean isUnsaved() { return unsaved; } - - public void saved() { + + @Override + public void saved() { unsaved = false; } - + + @Override public void export(File targetFile) throws Exception { FileStringUtility.string2File(targetFile, getOutcome()); } diff --git a/source/com/c2kernel/gui/tabs/outcome/form/OutcomeStructure.java b/source/com/c2kernel/gui/tabs/outcome/form/OutcomeStructure.java index a535da6..aee09df 100644 --- a/source/com/c2kernel/gui/tabs/outcome/form/OutcomeStructure.java +++ b/source/com/c2kernel/gui/tabs/outcome/form/OutcomeStructure.java @@ -4,7 +4,6 @@ import java.math.BigInteger; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; -import java.util.Iterator; import javax.swing.ImageIcon; import javax.swing.JPanel; @@ -49,11 +48,11 @@ public abstract class OutcomeStructure extends JPanel { subStructure = new HashMap(); Logger.msg(8, "Creating " + model.getName() + " structure as " + this.getClass().getName().substring(this.getClass().getName().lastIndexOf('.') + 1)); - + String doc = extractHelp(model); if (doc.length() > 0) help = doc; } - + public boolean getReadOnly() { return readOnly; } @@ -69,21 +68,21 @@ public abstract class OutcomeStructure extends JPanel { public OutcomeStructure createStructure(ElementDecl model, boolean readOnly, HelpPane help) throws OutcomeException { XMLType elementType = model.getType(); ComplexType elementComplexType; - + if (model.getMaxOccurs() == 0) return null; - + // if more than one can occur - dimension - if (model.getMaxOccurs() > 1 - || model.getMaxOccurs() == Particle.UNBOUNDED - || model.getMinOccurs() == 0) + if (model.getMaxOccurs() > 1 + || model.getMaxOccurs() == Particle.UNBOUNDED + || model.getMinOccurs() == 0) return new Dimension(model, readOnly, help); - + // must have a type from now on if (elementType == null) throw new StructuralException("Element "+model.getName()+" is elementary yet has no type."); // simple types will be fields if (elementType instanceof SimpleType) return new Field(model, readOnly, help); - + // otherwise is a complex type try { elementComplexType = (ComplexType)elementType; @@ -91,10 +90,10 @@ public abstract class OutcomeStructure extends JPanel { catch (ClassCastException e) { throw new StructuralException("Unknown XMLType for element " + model.getName()); } - + //when no element children - field if (elementComplexType.getParticleCount() == 0) return new Field(model, readOnly, help); - + //everything else is a data record return new DataRecord(model, readOnly, help, deferChild); } @@ -113,11 +112,11 @@ public abstract class OutcomeStructure extends JPanel { enumerateElements((ComplexType)base); } - for (Enumeration elements = group.enumerate(); elements.hasMoreElements(); ) { + for (Enumeration elements = group.enumerate(); elements.hasMoreElements(); ) { Particle thisParticle = (Particle)elements.nextElement(); if (thisParticle instanceof Group) { Group thisGroup = (Group)thisParticle; - if (thisGroup instanceof ModelGroup) { + if (thisGroup instanceof ModelGroup) { // HACK: Castor strangeness - model groups don't seem to resolve their own references. If fixed, this will still work ModelGroup thisModel = (ModelGroup)thisGroup; if (thisModel.hasReference()) thisGroup = thisModel.getReference(); @@ -152,39 +151,39 @@ public abstract class OutcomeStructure extends JPanel { public Element getElement() { return myElement; } - - public String getName() { + + @Override + public String getName() { if (model == null) return null; return model.getName(); } - + public ElementDecl getModel() { return model; } - + public String getHelp() { return help; } - + public String validateStructure() { StringBuffer errors = new StringBuffer(); - for (Iterator iter = subStructure.values().iterator(); iter.hasNext();) { - OutcomeStructure element = (OutcomeStructure)iter.next(); + for (OutcomeStructure element : subStructure.values()) { errors.append(element.validateStructure()); } return errors.toString(); } - + public abstract Element initNew(Document parent); - + public static String extractHelp(Annotated model) { - Enumeration e = model.getAnnotations(); + Enumeration e = model.getAnnotations(); StringBuffer doc = new StringBuffer(); if (e.hasMoreElements()) { // look for HTML Annotation note = (Annotation)e.nextElement(); - for (Enumeration g = note.getDocumentation(); g.hasMoreElements();) { + for (Enumeration g = note.getDocumentation(); g.hasMoreElements();) { Documentation thisDoc = (Documentation)g.nextElement(); - for (Enumeration h = thisDoc.getObjects(); h.hasMoreElements();) { + for (Enumeration h = thisDoc.getObjects(); h.hasMoreElements();) { AnyNode node = (AnyNode)h.nextElement(); String line = node.toString(); if (line.length() == 0) @@ -193,21 +192,22 @@ public abstract class OutcomeStructure extends JPanel { doc.append(line).append("\n"); } } - } + } } - + return doc.toString(); } - - public abstract void grabFocus(); - public static Class getJavaClass(int typeCode) { + @Override + public abstract void grabFocus(); + + public static Class getJavaClass(int typeCode) { switch (typeCode) { - + // boolean case SimpleTypesFactory.BOOLEAN_TYPE: return Boolean.class; - + // integers case SimpleTypesFactory.INTEGER_TYPE: case SimpleTypesFactory.NON_POSITIVE_INTEGER_TYPE: @@ -216,7 +216,7 @@ public abstract class OutcomeStructure extends JPanel { case SimpleTypesFactory.POSITIVE_INTEGER_TYPE: case SimpleTypesFactory.INT_TYPE: case SimpleTypesFactory.UNSIGNED_INT_TYPE: - case SimpleTypesFactory.SHORT_TYPE: + case SimpleTypesFactory.SHORT_TYPE: case SimpleTypesFactory.UNSIGNED_SHORT_TYPE: case SimpleTypesFactory.LONG_TYPE: case SimpleTypesFactory.UNSIGNED_LONG_TYPE: @@ -228,19 +228,19 @@ public abstract class OutcomeStructure extends JPanel { case SimpleTypesFactory.DOUBLE_TYPE: case SimpleTypesFactory.DECIMAL_TYPE: return BigDecimal.class; - + // images case SimpleTypesFactory.BASE64BINARY_TYPE: case SimpleTypesFactory.HEXBINARY_TYPE: return ImageIcon.class; - - // everything else is a string for now + + // everything else is a string for now default: return String.class; } } - - public static Object getTypedValue(String value, Class type) { + + public static Object getTypedValue(String value, Class type) { try { if (type.equals(Boolean.class)) if (value == null || value.equals("")) @@ -250,7 +250,7 @@ public abstract class OutcomeStructure extends JPanel { else if (type.equals(BigInteger.class)) if (value == null || value.equals("")) return new BigInteger("0"); - else + else return new BigInteger(value); else if (type.equals(BigDecimal.class)) if (value == null || value.equals("")) @@ -262,10 +262,10 @@ public abstract class OutcomeStructure extends JPanel { } return value==null?"":value; } - + public static boolean isEmpty(Object value) { if (value == null) return true; - + if (value instanceof String) { if (((String)value).length() == 0) return true; } diff --git a/source/com/c2kernel/gui/tabs/outcome/form/field/ArrayEditField.java b/source/com/c2kernel/gui/tabs/outcome/form/field/ArrayEditField.java old mode 100755 new mode 100644 index e7dc8bc..742d1b4 --- a/source/com/c2kernel/gui/tabs/outcome/form/field/ArrayEditField.java +++ b/source/com/c2kernel/gui/tabs/outcome/form/field/ArrayEditField.java @@ -25,7 +25,7 @@ import com.c2kernel.utils.Language; **************************************************************************/ public class ArrayEditField extends StringEditField implements ActionListener { - + Box arrayBox; Box expandBox; Box editBox; @@ -34,20 +34,20 @@ public class ArrayEditField extends StringEditField implements ActionListener { JButton expandButton; JButton contractButton; JButton addButton; - JButton removeButton; + JButton removeButton; ArrayTableModel arrayModel; JLabel arrayLabel = new JLabel("Array"); boolean panelShown = false; boolean readOnly = false; - + public ArrayEditField(SimpleType type) { - arrayBox = Box.createVerticalBox(); + arrayBox = Box.createVerticalBox(); arrayBox.add(arrayLabel); arrayButton = new JButton(Language.translate("Show")); arrayButton.addActionListener(this); arrayButton.setActionCommand("toggle"); arrayBox.add(arrayButton); - + expandBox = Box.createHorizontalBox(); expandButton = new JButton(">>"); expandButton.setToolTipText("Increase the number of columns displaying this array"); @@ -58,15 +58,15 @@ public class ArrayEditField extends StringEditField implements ActionListener { contractButton.setToolTipText("Decrease the number of columns displaying this array"); contractButton.addActionListener(this); contractButton.setActionCommand("contract"); - + expandBox.add(contractButton); expandBox.add(Box.createHorizontalGlue()); expandBox.add(expandButton); - + arrayModel = new ArrayTableModel(type); if (arrayModel.getColumnCount() < 2) contractButton.setEnabled(false); arrayView = new JScrollPane(new JTable(arrayModel)); - + editBox = Box.createHorizontalBox(); addButton = new JButton("+"); addButton.setToolTipText("Add a field to the end of this array"); @@ -75,7 +75,7 @@ public class ArrayEditField extends StringEditField implements ActionListener { removeButton = new JButton("-"); removeButton.setToolTipText("Remove the last field from this array"); removeButton.addActionListener(this); - removeButton.setActionCommand("remove"); + removeButton.setActionCommand("remove"); editBox.add(addButton); editBox.add(Box.createHorizontalGlue()); editBox.add(removeButton); @@ -83,32 +83,37 @@ public class ArrayEditField extends StringEditField implements ActionListener { /** * */ - public String getDefaultValue() { + @Override + public String getDefaultValue() { return ""; } /** * */ - public String getText() { + @Override + public String getText() { return arrayModel.getData(); } /** * */ - public void setText(String text) { + @Override + public void setText(String text) { arrayModel.setData(text); arrayLabel.setText("Array ("+arrayModel.getArrayLength()+" values)"); } /** * */ - public Component getControl() { + @Override + public Component getControl() { return arrayBox; } /** * */ - public void actionPerformed(ActionEvent e) { + @Override + public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("toggle")) { arrayBox.removeAll(); if (panelShown) { @@ -122,7 +127,7 @@ public class ArrayEditField extends StringEditField implements ActionListener { arrayBox.add(Box.createVerticalStrut(7)); arrayBox.add(arrayButton); arrayBox.add(Box.createVerticalStrut(7)); - arrayBox.add(expandBox); + arrayBox.add(expandBox); arrayBox.add(Box.createVerticalStrut(7)); arrayBox.add(arrayView); if (!readOnly) arrayBox.add(editBox); @@ -138,7 +143,7 @@ public class ArrayEditField extends StringEditField implements ActionListener { else if (e.getActionCommand().equals("remove")) { arrayModel.removeField(); arrayLabel.setText("Array ("+arrayModel.getArrayLength()+" values)"); - } + } else { int currentCols = arrayModel.getColumnCount(); if (e.getActionCommand().equals("extend")) @@ -154,10 +159,12 @@ public class ArrayEditField extends StringEditField implements ActionListener { /** * */ - public JTextComponent makeTextField() { + @Override + public JTextComponent makeTextField() { // not used by array return null; } + @Override public void setEditable(boolean editable) { readOnly = !editable; arrayModel.setReadOnly(!readOnly); diff --git a/source/com/c2kernel/gui/tabs/outcome/form/field/ArrayTableModel.java b/source/com/c2kernel/gui/tabs/outcome/form/field/ArrayTableModel.java index c7934c0..341c33a 100644 --- a/source/com/c2kernel/gui/tabs/outcome/form/field/ArrayTableModel.java +++ b/source/com/c2kernel/gui/tabs/outcome/form/field/ArrayTableModel.java @@ -23,10 +23,10 @@ import com.c2kernel.utils.Language; public class ArrayTableModel extends AbstractTableModel { ArrayList contents = new ArrayList(); - Class type; + Class type; int numCols = 1; boolean readOnly = false; - + public ArrayTableModel(SimpleType type) { super(); this.type = OutcomeStructure.getJavaClass(type.getTypeCode()); @@ -35,7 +35,7 @@ public class ArrayTableModel extends AbstractTableModel { public void setReadOnly(boolean readOnly) { this.readOnly = readOnly; } - + public void setData(String data) { contents.clear(); StringTokenizer tok = new StringTokenizer(data); @@ -43,16 +43,16 @@ public class ArrayTableModel extends AbstractTableModel { contents.add(OutcomeStructure.getTypedValue(tok.nextToken(), type)); fireTableStructureChanged(); } - + public String getData() { if (contents.size() == 0) return ""; - Iterator iter = contents.iterator(); + Iterator iter = contents.iterator(); StringBuffer result = new StringBuffer(iter.next().toString()); while (iter.hasNext()) result.append(" ").append(iter.next().toString()); return result.toString(); } - + public void addField() { contents.add(OutcomeStructure.getTypedValue("", type)); fireTableStructureChanged(); @@ -62,45 +62,52 @@ public class ArrayTableModel extends AbstractTableModel { contents.remove(contents.size()-1); fireTableStructureChanged(); } - - public Class getColumnClass(int columnIndex) { + + @Override + public Class getColumnClass(int columnIndex) { return type; } - public int getColumnCount() { + @Override + public int getColumnCount() { return numCols; } - + public int getArrayLength() { return contents.size(); } - + public void setColumnCount(int newCols) { numCols = newCols; fireTableStructureChanged(); } - public String getColumnName(int column) { + @Override + public String getColumnName(int column) { return Language.translate("Value"); } - public int getRowCount() { + @Override + public int getRowCount() { return (contents.size()/numCols)+1; } - public Object getValueAt(int arg0, int arg1) { + @Override + public Object getValueAt(int arg0, int arg1) { int index = arg1+(arg0 * numCols); if (index >= contents.size()) return null; return contents.get(arg1+(arg0 * numCols)); } - public boolean isCellEditable(int rowIndex, int columnIndex) { + @Override + public boolean isCellEditable(int rowIndex, int columnIndex) { if (columnIndex+(rowIndex*numCols) > contents.size()-1) return false; return !readOnly; } - public void setValueAt(Object aValue, int rowIndex, int columnIndex) { + @Override + public void setValueAt(Object aValue, int rowIndex, int columnIndex) { contents.set(columnIndex+(rowIndex*numCols), aValue); } } diff --git a/source/com/c2kernel/gui/tabs/outcome/form/field/BooleanEditField.java b/source/com/c2kernel/gui/tabs/outcome/form/field/BooleanEditField.java old mode 100755 new mode 100644 index 5776f73..c831eb4 --- a/source/com/c2kernel/gui/tabs/outcome/form/field/BooleanEditField.java +++ b/source/com/c2kernel/gui/tabs/outcome/form/field/BooleanEditField.java @@ -17,51 +17,58 @@ import com.c2kernel.utils.Logger; * All rights reserved. **************************************************************************/ public class BooleanEditField extends StringEditField { - + JCheckBox checkbox; - + public BooleanEditField() { checkbox = new JCheckBox(); checkbox.setSelected(false); checkbox.addFocusListener(this); } - - public String getText() { + + @Override + public String getText() { return String.valueOf(checkbox.isSelected()); } - public void setText(String text) { + @Override + public void setText(String text) { boolean newState = false; try { newState = Boolean.valueOf(text).booleanValue(); } catch (Exception ex) { Logger.error("Invalid value for checkbox: "+text); } - checkbox.setSelected(newState); + checkbox.setSelected(newState); } - public void setEditable(boolean editable) { + @Override + public void setEditable(boolean editable) { super.setEditable(editable); checkbox.setEnabled(editable); } - public Component getControl() { + @Override + public Component getControl() { return checkbox; } - - public String getDefaultValue() { + + @Override + public String getDefaultValue() { return "false"; - } - + } + /** don't reserve the item finder for a boolean */ - public void focusGained(FocusEvent e) { + @Override + public void focusGained(FocusEvent e) { helpPane.setHelp(name, helpText); } - + /** * */ - public JTextComponent makeTextField() { + @Override + public JTextComponent makeTextField() { // not used by boolean return null; } diff --git a/source/com/c2kernel/gui/tabs/outcome/form/field/ComboField.java b/source/com/c2kernel/gui/tabs/outcome/form/field/ComboField.java index 303a870..ef56046 100644 --- a/source/com/c2kernel/gui/tabs/outcome/form/field/ComboField.java +++ b/source/com/c2kernel/gui/tabs/outcome/form/field/ComboField.java @@ -19,9 +19,9 @@ import com.c2kernel.scripting.Script; import com.c2kernel.utils.Logger; /******************************************************************************* - * + * * $Revision: 1.4 $ $Date: 2005/08/16 13:59:56 $ - * + * * Copyright (C) 2003 CERN - European Organization for Nuclear Research All * rights reserved. ******************************************************************************/ @@ -40,28 +40,33 @@ public class ComboField extends StringEditField { this.listNode = listNode; createLOV(); } - - public String getDefaultValue() { + + @Override + public String getDefaultValue() { if (vals.getDefaultKey() != null) return vals.get(vals.getDefaultKey()).toString(); else return ""; } - public String getText() { + @Override + public String getText() { return vals.get(comboModel.getSelectedItem()).toString(); } - public JTextComponent makeTextField() { + @Override + public JTextComponent makeTextField() { // not used by this control return null; } - public void setText(String text) { + @Override + public void setText(String text) { comboModel.setSelectedItem(text); } - public Component getControl() { + @Override + public Component getControl() { return comboField; } @@ -76,12 +81,12 @@ public class ComboField extends StringEditField { if (lovType.equals("PathList")) populateLOVFromLDAP(param); } - + // handle enumerations // TODO: should be ANDed with above results if (content.hasFacet(Facet.ENUMERATION)) { //ListOfValues andList = new ListOfValues(); - Enumeration enums = content.getFacets(Facet.ENUMERATION); + Enumeration enums = content.getFacets(Facet.ENUMERATION); while (enums.hasMoreElements()) { Facet thisEnum = (Facet)enums.nextElement(); vals.put(thisEnum.getValue(), thisEnum.getValue(), false); @@ -99,8 +104,8 @@ public class ComboField extends StringEditField { */ private void populateLOVFromLDAP(String param) { // TODO '/root/path;prop=val;prop=val' - - + + } private void populateLOVFromScript(String scriptName) { @@ -116,12 +121,14 @@ public class ComboField extends StringEditField { } } - public void setDecl(AttributeDecl model) throws StructuralException { + @Override + public void setDecl(AttributeDecl model) throws StructuralException { super.setDecl(model); createLOV(); } - public void setDecl(ElementDecl model) throws StructuralException { + @Override + public void setDecl(ElementDecl model) throws StructuralException { super.setDecl(model); createLOV(); } @@ -130,7 +137,8 @@ public class ComboField extends StringEditField { * */ - public void setEditable(boolean editable) { + @Override + public void setEditable(boolean editable) { comboField.setEditable(editable); } } \ No newline at end of file diff --git a/source/com/c2kernel/gui/tabs/outcome/form/field/DecimalEditField.java b/source/com/c2kernel/gui/tabs/outcome/form/field/DecimalEditField.java old mode 100755 new mode 100644 index d77dff3..fabaed8 --- a/source/com/c2kernel/gui/tabs/outcome/form/field/DecimalEditField.java +++ b/source/com/c2kernel/gui/tabs/outcome/form/field/DecimalEditField.java @@ -26,44 +26,50 @@ public class DecimalEditField extends StringEditField { field.setToolTipText("This field must contains a decimal number e.g. 3.14159265"); } - public String getText() { + @Override + public String getText() { return field.getText(); } - public void setText(String text) { + @Override + public void setText(String text) { field.setText(text); } - - public String getDefaultValue() { + + @Override + public String getDefaultValue() { return "0.0"; - } - - public JTextComponent makeTextField() { + } + + @Override + public JTextComponent makeTextField() { return new DecimalTextField(); } - + private class DecimalTextField extends JTextField { public DecimalTextField() { super(); setHorizontalAlignment(RIGHT); } - protected Document createDefaultModel() { + @Override + protected Document createDefaultModel() { return new Decimal(); } } - + private class Decimal extends PlainDocument { BigDecimal currentVal = new BigDecimal(0.0); - public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { + @Override + public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { if (str == null || str.equals("")) { return; } - + String proposedResult = null; if (getLength() == 0) { @@ -73,23 +79,24 @@ public class DecimalEditField extends StringEditField { currentBuffer.insert(offs, str); proposedResult = currentBuffer.toString(); } - + try { currentVal = parse(proposedResult); super.insertString(offs, str, a); } catch (Exception e) { Toolkit.getDefaultToolkit().beep(); } - + } - public void remove(int offs, int len) throws BadLocationException { + @Override + public void remove(int offs, int len) throws BadLocationException { String currentText = this.getText(0, getLength()); String beforeOffset = currentText.substring(0, offs); String afterOffset = currentText.substring(len + offs, currentText.length()); String proposedResult = beforeOffset + afterOffset; - + if (proposedResult.length() == 0) { // empty is ok super.remove(offs, len); return; @@ -97,17 +104,17 @@ public class DecimalEditField extends StringEditField { try { currentVal = parse(proposedResult); super.remove(offs, len); - } catch (Exception e) { + } catch (Exception e) { Toolkit.getDefaultToolkit().beep(); } - } + } public BigDecimal parse(String proposedResult) throws NumberFormatException { BigDecimal value = new BigDecimal(0); if ( proposedResult.length() != 0) { - value = new BigDecimal(proposedResult); + value = new BigDecimal(proposedResult); } return value; } diff --git a/source/com/c2kernel/gui/tabs/outcome/form/field/FieldConstraints.java b/source/com/c2kernel/gui/tabs/outcome/form/field/FieldConstraints.java deleted file mode 100755 index d09cd91..0000000 --- a/source/com/c2kernel/gui/tabs/outcome/form/field/FieldConstraints.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.c2kernel.gui.tabs.outcome.form.field; - -import java.util.Enumeration; - -import org.exolab.castor.types.AnyNode; -import org.exolab.castor.xml.schema.Annotation; -import org.exolab.castor.xml.schema.AppInfo; -import org.exolab.castor.xml.schema.XMLType; - -/************************************************************************** - * - * $Revision: 1.1 $ - * $Date: 2005/04/26 06:48:12 $ - * - * Copyright (C) 2003 CERN - European Organization for Nuclear Research - * All rights reserved. - **************************************************************************/ - -public class FieldConstraints { - - XMLType content; - ListOfValues lov; - int rows = 1; - - public FieldConstraints(XMLType content) { - this.content = content; - Enumeration e = content.getAnnotations(); - while (e.hasMoreElements()) { - Annotation note = (Annotation)e.nextElement(); - for (Enumeration f = note.getAppInfo(); f.hasMoreElements();) { - addAppInfo((AppInfo)f.nextElement()); - } - } - } - - private void addAppInfo(AppInfo element) { - Enumeration e = element.getObjects(); - while (e.hasMoreElements()) { - AnyNode node = (AnyNode)e.nextElement(); - - } - } - - public ListOfValues getLOV() { - return lov; - } - - public int getRows() { - return rows; - } -} diff --git a/source/com/c2kernel/gui/tabs/outcome/form/field/ImageEditField.java b/source/com/c2kernel/gui/tabs/outcome/form/field/ImageEditField.java old mode 100755 new mode 100644 index b0bb079..716a073 --- a/source/com/c2kernel/gui/tabs/outcome/form/field/ImageEditField.java +++ b/source/com/c2kernel/gui/tabs/outcome/form/field/ImageEditField.java @@ -31,15 +31,17 @@ public class ImageEditField extends StringEditField { static JFileChooser chooser = new JFileChooser(); static { chooser.addChoosableFileFilter(new javax.swing.filechooser.FileFilter() { + @Override public String getDescription() { return "Image Files"; } + @Override public boolean accept(File f) { return (f.isDirectory() || (f.isFile() && (f.getName() .endsWith(".gif") || f.getName().endsWith(".jpg") - || f.getName().endsWith(".jpeg") + || f.getName().endsWith(".jpeg") || f.getName().endsWith(".png")))); } }); @@ -51,6 +53,7 @@ public class ImageEditField extends StringEditField { imagePanel = Box.createVerticalBox(); browseButton = new JButton("Browse"); browseButton.addActionListener(new ActionListener() { + @Override public void actionPerformed(ActionEvent e) { int returnVal = chooser.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { @@ -77,18 +80,22 @@ public class ImageEditField extends StringEditField { imagePanel.add(browseButton); } + @Override public String getDefaultValue() { return ""; } + @Override public Component getControl() { return imagePanel; } + @Override public String getText() { return encodedImage == null ? "" : encodedImage; } + @Override public void setText(String text) { encodedImage = text; if (text != null && text.length() > 0) { @@ -98,6 +105,7 @@ public class ImageEditField extends StringEditField { } } + @Override public void setEditable(boolean editable) { browseButton.setVisible(false); } diff --git a/source/com/c2kernel/gui/tabs/outcome/form/field/IntegerEditField.java b/source/com/c2kernel/gui/tabs/outcome/form/field/IntegerEditField.java old mode 100755 new mode 100644 index 7c858a4..e2c3df4 --- a/source/com/c2kernel/gui/tabs/outcome/form/field/IntegerEditField.java +++ b/source/com/c2kernel/gui/tabs/outcome/form/field/IntegerEditField.java @@ -19,44 +19,50 @@ import javax.swing.text.PlainDocument; * All rights reserved. **************************************************************************/ public class IntegerEditField extends StringEditField { - + public IntegerEditField() { super(); field.setToolTipText("This field must contains a whole number e.g. 3"); } - public String getText() { + @Override + public String getText() { return field.getText(); } - public void setText(String text) { + @Override + public void setText(String text) { field.setText(text); } - public String getDefaultValue() { + @Override + public String getDefaultValue() { return "0"; } - - public JTextComponent makeTextField() { + + @Override + public JTextComponent makeTextField() { return new IntegerTextField(); } - + private class IntegerTextField extends JTextField { public IntegerTextField() { super(); setHorizontalAlignment(RIGHT); } - protected Document createDefaultModel() { + @Override + protected Document createDefaultModel() { return new IntegerDocument(); } } - + private class IntegerDocument extends PlainDocument { BigInteger currentVal = new BigInteger("0"); - public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { + @Override + public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { if (str == null || str.equals("")) { return; @@ -71,17 +77,18 @@ public class IntegerEditField extends StringEditField { currentBuffer.insert(offs, str); proposedResult = currentBuffer.toString(); } - + try { currentVal = parse(proposedResult); super.insertString(offs, str, a); } catch (Exception e) { Toolkit.getDefaultToolkit().beep(); } - + } - public void remove(int offs, int len) throws BadLocationException { + @Override + public void remove(int offs, int len) throws BadLocationException { String currentText = this.getText(0, getLength()); String beforeOffset = currentText.substring(0, offs); @@ -95,17 +102,17 @@ public class IntegerEditField extends StringEditField { try { currentVal = parse(proposedResult); super.remove(offs, len); - } catch (Exception e) { + } catch (Exception e) { Toolkit.getDefaultToolkit().beep(); } - } + } public BigInteger parse(String proposedResult) throws NumberFormatException { BigInteger value = new BigInteger("0"); if ( proposedResult.length() != 0) { - value = new BigInteger(proposedResult); + value = new BigInteger(proposedResult); } return value; } diff --git a/source/com/c2kernel/gui/tabs/outcome/form/field/ListOfValues.java b/source/com/c2kernel/gui/tabs/outcome/form/field/ListOfValues.java index 3204766..f95c5c9 100644 --- a/source/com/c2kernel/gui/tabs/outcome/form/field/ListOfValues.java +++ b/source/com/c2kernel/gui/tabs/outcome/form/field/ListOfValues.java @@ -18,14 +18,14 @@ public class ListOfValues extends HashMap { public ListOfValues() { super(); } - + public String put(String key, String value, boolean isDefaultKey) { if (isDefaultKey) defaultKey = key; return (String)super.put(key, value); } - + public String getDefaultKey() { return defaultKey; } - + } diff --git a/source/com/c2kernel/gui/tabs/outcome/form/field/LongStringEditField.java b/source/com/c2kernel/gui/tabs/outcome/form/field/LongStringEditField.java old mode 100755 new mode 100644 index b782c65..140d7f2 --- a/source/com/c2kernel/gui/tabs/outcome/form/field/LongStringEditField.java +++ b/source/com/c2kernel/gui/tabs/outcome/form/field/LongStringEditField.java @@ -26,10 +26,12 @@ public class LongStringEditField extends StringEditField { field.setToolTipText(Language.translate("This field can contain any string.")); } - public JTextComponent makeTextField() { + @Override + public JTextComponent makeTextField() { return new JTextArea(); } - public Component getControl() { + @Override + public Component getControl() { if (bigScroller == null) { bigScroller = new JScrollPane(field); } diff --git a/source/com/c2kernel/gui/tabs/outcome/form/field/StringEditField.java b/source/com/c2kernel/gui/tabs/outcome/form/field/StringEditField.java old mode 100755 new mode 100644 index 310ee2e..a9b55a4 --- a/source/com/c2kernel/gui/tabs/outcome/form/field/StringEditField.java +++ b/source/com/c2kernel/gui/tabs/outcome/form/field/StringEditField.java @@ -42,33 +42,33 @@ public class StringEditField implements FocusListener, DomainKeyConsumer { HelpPane helpPane; String helpText; protected JTextComponent field; - + boolean isValid = true; boolean editable = true; String name; - - public StringEditField() { + + public StringEditField() { field = makeTextField(); if (field != null) field.addFocusListener(this); } - + private static StringEditField getFieldForType(SimpleType type) { // handle lists special - if (type instanceof ListType) + if (type instanceof ListType) return new ArrayEditField(type.getBuiltInBaseType()); // is a combobox if (type.hasFacet(Facet.ENUMERATION)) return new ComboField(type, null); //find LOVscript - Enumeration e = type.getAnnotations(); + Enumeration e = type.getAnnotations(); while (e.hasMoreElements()) { Annotation note = (Annotation)e.nextElement(); - for (Enumeration f = note.getAppInfo(); f.hasMoreElements();) { + for (Enumeration f = note.getAppInfo(); f.hasMoreElements();) { AppInfo thisAppInfo = (AppInfo)f.nextElement(); - for (Enumeration g = thisAppInfo.getObjects(); g.hasMoreElements();) { + for (Enumeration g = thisAppInfo.getObjects(); g.hasMoreElements();) { AnyNode appInfoNode = (AnyNode)g.nextElement(); if (appInfoNode.getLocalName().equals("ScriptList") || appInfoNode.getLocalName().equals("LDAPList")) { @@ -82,12 +82,12 @@ public class StringEditField implements FocusListener, DomainKeyConsumer { if (type.getLength()!=null) length = type.getLength().longValue(); else if (type.getMaxLength()!=null) length = type.getMaxLength().longValue(); else if (type.getMinLength()!=null) length = type.getMinLength().longValue(); - + // find base type if derived if (!(type.isBuiltInType())) - type = type.getBuiltInBaseType(); + type = type.getBuiltInBaseType(); // else derive the class - Class contentClass = OutcomeStructure.getJavaClass(type.getTypeCode()); + Class contentClass = OutcomeStructure.getJavaClass(type.getTypeCode()); // disable list edits for the moment if (contentClass.equals(Boolean.class)) return new BooleanEditField(); @@ -96,7 +96,7 @@ public class StringEditField implements FocusListener, DomainKeyConsumer { else if (contentClass.equals(BigDecimal.class)) return new DecimalEditField(); else if (contentClass.equals(ImageIcon.class)) - return new ImageEditField(); + return new ImageEditField(); else if (length > 60) return new LongStringEditField(); else return new StringEditField(); @@ -107,7 +107,7 @@ public class StringEditField implements FocusListener, DomainKeyConsumer { newField.setDecl(model); return newField; } - + public static StringEditField getEditField(ElementDecl model) throws StructuralException { try { XMLType baseType = model.getType(); @@ -120,7 +120,7 @@ public class StringEditField implements FocusListener, DomainKeyConsumer { throw new StructuralException("No type defined in model"); } } - + public void setDecl(AttributeDecl model) throws StructuralException { this.model=model; this.content=model.getSimpleType(); @@ -132,7 +132,7 @@ public class StringEditField implements FocusListener, DomainKeyConsumer { this.model=model; this.name = model.getName(); XMLType type = model.getType(); - + // derive base type if (type.isSimpleType()) this.content = (SimpleType)type; @@ -141,9 +141,9 @@ public class StringEditField implements FocusListener, DomainKeyConsumer { if (this.content == null) throw new StructuralException("No declared base type of element"); - // + // if (model.getFixedValue() != null) setEditable(false); - + } public void setData(Attr newData) throws StructuralException { @@ -178,26 +178,28 @@ public class StringEditField implements FocusListener, DomainKeyConsumer { public Node getData() { return data; } - + public String getDefaultValue() { return ""; } - + public void setHelp(HelpPane helpPane, String helpText) { this.helpPane = helpPane; this.helpText = helpText; } - public void focusLost(FocusEvent e) { + @Override + public void focusLost(FocusEvent e) { if (MainFrame.itemFinder != null) MainFrame.itemFinder.clearConsumer(this); updateNode(); } - public void focusGained(FocusEvent e) { + @Override + public void focusGained(FocusEvent e) { helpPane.setHelp(name, helpText); if (editable && MainFrame.itemFinder != null) - MainFrame.itemFinder.setConsumer(this, "Insert"); + MainFrame.itemFinder.setConsumer(this, "Insert"); } public void updateNode() { @@ -213,23 +215,25 @@ public class StringEditField implements FocusListener, DomainKeyConsumer { /** * Read domkey from barcode input */ - public void push(DomainPath key) { + @Override + public void push(DomainPath key) { setText(key.getName()); } /** * Read string from barcode input */ - public void push(String key) { + @Override + public void push(String key) { setText(key); } - + public void setEditable(boolean editable) { this.editable = editable; if (field != null) field.setEditable(editable); } - + public String getText() { return field.getText(); } @@ -237,15 +241,15 @@ public class StringEditField implements FocusListener, DomainKeyConsumer { public void setText(String text) { field.setText(text); } - + public JTextComponent makeTextField() { return new JTextField(); } - + public Component getControl() { return field; } - + public void grabFocus() { getControl().requestFocus(); } diff --git a/source/com/c2kernel/lifecycle/ActivityDef.java b/source/com/c2kernel/lifecycle/ActivityDef.java index 42385a4..235275f 100644 --- a/source/com/c2kernel/lifecycle/ActivityDef.java +++ b/source/com/c2kernel/lifecycle/ActivityDef.java @@ -33,6 +33,7 @@ public class ActivityDef extends WfVertexDef implements C2KLocalObject /** * @see com.c2kernel.graph.model.Vertex#setID(int) */ + @Override public void setID(int id) { mId = id; @@ -42,6 +43,7 @@ public class ActivityDef extends WfVertexDef implements C2KLocalObject /** * @see com.c2kernel.graph.model.Vertex#getID() */ + @Override public int getID() { return mId; @@ -49,6 +51,7 @@ public class ActivityDef extends WfVertexDef implements C2KLocalObject /** * @see com.c2kernel.graph.model.Vertex#setName(java.lang.String) */ + @Override public void setName(String n) { mName = n; @@ -56,11 +59,12 @@ public class ActivityDef extends WfVertexDef implements C2KLocalObject /** * @see com.c2kernel.graph.model.Vertex#getName() */ + @Override public String getName() { return mName; } - + public void setVersion(String v) { mVersion = v; @@ -71,17 +75,18 @@ public class ActivityDef extends WfVertexDef implements C2KLocalObject public String getVersion() { return mVersion; - } + } /** * @see com.c2kernel.lifecycle.WfVertexDef#getErrors() */ + @Override public String getErrors() { return super.getErrors(); } /** * Method linkToSlot. - * + * * @param actSl * @param name */ @@ -95,6 +100,7 @@ public class ActivityDef extends WfVertexDef implements C2KLocalObject /** * @see com.c2kernel.lifecycle.WfVertexDef#verify() */ + @Override public boolean verify() { return true; @@ -102,6 +108,7 @@ public class ActivityDef extends WfVertexDef implements C2KLocalObject /** * @see com.c2kernel.entity.C2KLocalObject#getClusterType() */ + @Override public String getClusterType() { return null; @@ -113,14 +120,15 @@ public class ActivityDef extends WfVertexDef implements C2KLocalObject /* * (non-Javadoc) - * + * * @see com.c2kernel.lifecycle.commonInterface.ActType#getDescName() */ public String getDescName() { return getName(); } - + + @Override public WfVertex instantiate() throws ObjectNotFoundException, InvalidDataException{ return instantiate(getName()); } diff --git a/source/com/c2kernel/lifecycle/ActivitySlotDef.java b/source/com/c2kernel/lifecycle/ActivitySlotDef.java old mode 100755 new mode 100644 index 10f6778..74d8305 --- a/source/com/c2kernel/lifecycle/ActivitySlotDef.java +++ b/source/com/c2kernel/lifecycle/ActivitySlotDef.java @@ -14,10 +14,10 @@ import com.c2kernel.utils.LocalObjectLoader; public class ActivitySlotDef extends WfVertexDef { private String activityDef; - + /** * Method setActivityDef. - * + * * @param oActivityDef */ public void setActivityDef(String oActivityDef) @@ -26,7 +26,7 @@ public class ActivitySlotDef extends WfVertexDef } /** * Method getActivityDef. - * + * * @return String */ public String getActivityDef() @@ -42,7 +42,7 @@ public class ActivitySlotDef extends WfVertexDef getProperties().put("Version", "last"); } - public ActivityDef getTheActivityDef() throws ObjectNotFoundException, InvalidDataException + public ActivityDef getTheActivityDef() throws ObjectNotFoundException, InvalidDataException { ActivityDef actDef = LocalObjectLoader.getActDef(getActivityDef(), getActVersion()); if (actDef instanceof CompositeActivityDef) @@ -53,6 +53,7 @@ public class ActivitySlotDef extends WfVertexDef * @see com.c2kernel.lifecycle.WfVertexDef#verify() */ /** launch the verification of the ActivityDef */ + @Override public boolean verify() { mErrors.removeAllElements(); @@ -87,10 +88,9 @@ public class ActivitySlotDef extends WfVertexDef Vertex[] outV = getOutGraphables(); Vertex[] anteVertices = GraphTraversal.getTraversal(getParent().getChildrenGraphModel(), this, GraphTraversal.kUp, false); boolean errInLoop = false; - for (int i = 0; i < outV.length; i++) - { - for (int j = 0; j < anteVertices.length; j++) - if (!loop() && outV[i].getID() == anteVertices[j].getID()) + for (Vertex element : outV) { + for (Vertex anteVertice : anteVertices) + if (!loop() && element.getID() == anteVertice.getID()) errInLoop = true; } if (errInLoop) @@ -103,7 +103,7 @@ public class ActivitySlotDef extends WfVertexDef } /** * Method getNextWfVertices. - * + * * @return WfVertexDef[] */ public WfVertexDef[] getNextWfVertices() @@ -122,21 +122,21 @@ public class ActivitySlotDef extends WfVertexDef } /** * Method getInfo. - * + * * @return CastorHashMap */ public void configureInstance(Activity act) { KeyValuePair[] k = getProperties().getKeyValuePairs(); - for (int i = 0; i < k.length; i++) - act.getProperties().put(k[i].getKey(), k[i].getValue()); + for (KeyValuePair element : k) + act.getProperties().put(element.getKey(), element.getValue()); act.setCentrePoint(getCentrePoint()); act.setOutlinePoints(getOutlinePoints()); act.setInEdgeIds(getInEdgeIds()); act.setOutEdgeIds(getOutEdgeIds()); act.setName(getActName()); act.setID(getID()); - } + } public String getActName() { @@ -145,8 +145,9 @@ public class ActivitySlotDef extends WfVertexDef public String getActVersion() { return (String) getProperties().get("Version"); - } - + } + + @Override public WfVertex instantiate() throws ObjectNotFoundException, InvalidDataException { Activity newActivity = (Activity)getTheActivityDef().instantiate(); configureInstance(newActivity); diff --git a/source/com/c2kernel/lifecycle/AndSplitDef.java b/source/com/c2kernel/lifecycle/AndSplitDef.java index 80c27df..af87b18 100644 --- a/source/com/c2kernel/lifecycle/AndSplitDef.java +++ b/source/com/c2kernel/lifecycle/AndSplitDef.java @@ -26,6 +26,7 @@ public class AndSplitDef extends WfVertexDef /** * @see com.c2kernel.lifecycle.WfVertexDef#verify() */ + @Override public boolean verify() { mErrors.removeAllElements(); @@ -81,8 +82,9 @@ public class AndSplitDef extends WfVertexDef } return err; } - - public boolean loop() + + @Override + public boolean loop() { boolean loop2 = false; if (!loopTested) @@ -102,6 +104,7 @@ public class AndSplitDef extends WfVertexDef return loop2; } + @Override public WfVertex instantiate() { AndSplit newSplit = new AndSplit(); configureInstance(newSplit); diff --git a/source/com/c2kernel/lifecycle/CompositeActivityDef.java b/source/com/c2kernel/lifecycle/CompositeActivityDef.java old mode 100755 new mode 100644 index a46cc50..86b6f88 --- a/source/com/c2kernel/lifecycle/CompositeActivityDef.java +++ b/source/com/c2kernel/lifecycle/CompositeActivityDef.java @@ -51,7 +51,7 @@ public class CompositeActivityDef extends ActivityDef /** * Method addNextDef. - * + * * @param origin * @param terminus * @return NextDef @@ -64,7 +64,7 @@ public class CompositeActivityDef extends ActivityDef } /** * Method addExistingActivityDef. - * + * * @param actDef * @param point */ @@ -78,7 +78,7 @@ public class CompositeActivityDef extends ActivityDef } /** * Method newChild. - * + * * @param Name * @param Type * @param location @@ -149,13 +149,15 @@ public class CompositeActivityDef extends ActivityDef } /** * Method instantiateAct. - * + * * @return CompositeActivity */ + @Override public WfVertex instantiate() throws ObjectNotFoundException, InvalidDataException { return instantiate(getName()); } - + + @Override public WfVertex instantiate(String name) throws ObjectNotFoundException, InvalidDataException { CompositeActivity cAct = new CompositeActivity(); @@ -186,18 +188,17 @@ public class CompositeActivityDef extends ActivityDef /** * Method hasGoodNumberOfActivity. - * + * * @return boolean */ - + public boolean hasGoodNumberOfActivity() { int endingAct = 0; GraphableVertex[] graphableVertices = this.getLayoutableChildren(); if (graphableVertices != null) - for (int i = 0; i < graphableVertices.length; i++) - { - WfVertexDef vertex = (WfVertexDef) graphableVertices[i]; + for (GraphableVertex graphableVertice : graphableVertices) { + WfVertexDef vertex = (WfVertexDef) graphableVertice; if (getChildrenGraphModel().getOutEdges(vertex).length == 0) endingAct++; } @@ -209,17 +210,18 @@ public class CompositeActivityDef extends ActivityDef /** * @see com.c2kernel.graph.model.GraphableVertex#getPath() */ + @Override public String getPath() { if (getParent() == null) return getName(); return super.getPath(); } - + //deprecated public String[] getCastorNonLayoutableChildren() { return new String[0]; } - + public void setCastorNonLayoutableChildren(String[] dummy) { } } diff --git a/source/com/c2kernel/lifecycle/JoinDef.java b/source/com/c2kernel/lifecycle/JoinDef.java old mode 100755 new mode 100644 index 71bc95c..95e2ec4 --- a/source/com/c2kernel/lifecycle/JoinDef.java +++ b/source/com/c2kernel/lifecycle/JoinDef.java @@ -18,6 +18,7 @@ public class JoinDef extends WfVertexDef /** * @see com.c2kernel.lifecycle.WfVertexDef#verify() */ + @Override public boolean verify() { mErrors.removeAllElements(); @@ -52,11 +53,13 @@ public class JoinDef extends WfVertexDef } return true; } + @Override public boolean isJoin() { return true; } - + + @Override public WfVertex instantiate() { Join newJoin = new Join(); configureInstance(newJoin); diff --git a/source/com/c2kernel/lifecycle/LoopDef.java b/source/com/c2kernel/lifecycle/LoopDef.java old mode 100755 new mode 100644 index bee97c5..36108ad --- a/source/com/c2kernel/lifecycle/LoopDef.java +++ b/source/com/c2kernel/lifecycle/LoopDef.java @@ -26,6 +26,7 @@ public class LoopDef extends XOrSplitDef /** * @see com.c2kernel.lifecycle.WfVertexDef#loop() */ + @Override public boolean loop() { return true; @@ -34,6 +35,7 @@ public class LoopDef extends XOrSplitDef /** * @see com.c2kernel.lifecycle.WfVertexDef#verify() */ + @Override public boolean verify() { if (!super.verify()) return false; @@ -43,11 +45,11 @@ public class LoopDef extends XOrSplitDef int k = 0; int l = 0; Vertex[] brothers = getParent().getChildren(); - for (int i = 0; i < brothers.length; i++) - if (brothers[i] instanceof LoopDef) l++; - for (int i = 0; i < nexts.length; i++) - for (int j = 0; j < anteVertices.length; j++) - if (nexts[i].equals(anteVertices[j])) + for (Vertex brother : brothers) + if (brother instanceof LoopDef) l++; + for (Vertex next : nexts) + for (Vertex anteVertice : anteVertices) + if (next.equals(anteVertice)) k++; if (k != 1 && !(l>1)) { @@ -60,15 +62,17 @@ public class LoopDef extends XOrSplitDef // } return true; } - - public boolean isLoop() { + + @Override + public boolean isLoop() { return true; - } - + } + + @Override public WfVertex instantiate() { Loop newLoop = new Loop(); configureInstance(newLoop); return newLoop; } - + } diff --git a/source/com/c2kernel/lifecycle/NextDef.java b/source/com/c2kernel/lifecycle/NextDef.java old mode 100755 new mode 100644 index 6bddabf..d196066 --- a/source/com/c2kernel/lifecycle/NextDef.java +++ b/source/com/c2kernel/lifecycle/NextDef.java @@ -16,7 +16,7 @@ public class NextDef extends GraphableEdge } /** * Method verify. - * + * * @return boolean */ public boolean verify() @@ -25,7 +25,7 @@ public class NextDef extends GraphableEdge } /** * Method NextDef. - * + * * @param pre * @param nex */ @@ -47,6 +47,7 @@ public class NextDef extends GraphableEdge pre.getProperties().put("LastNum", String.valueOf(num + 1)); } } + @Override public boolean containsPoint(GraphPoint p) { GraphPoint originPoint = getOriginPoint(); @@ -80,7 +81,7 @@ public class NextDef extends GraphableEdge int maxY = midPoint.y + 10; return (p.x >= minX) && (p.x <= maxX) && (p.y >= minY) && (p.y <= maxY); } - + public Next instantiate() { Next next = new Next(); next.setID(getID()); diff --git a/source/com/c2kernel/lifecycle/OrSplitDef.java b/source/com/c2kernel/lifecycle/OrSplitDef.java old mode 100755 new mode 100644 index 14931a1..df68f22 --- a/source/com/c2kernel/lifecycle/OrSplitDef.java +++ b/source/com/c2kernel/lifecycle/OrSplitDef.java @@ -15,6 +15,7 @@ public class OrSplitDef extends AndSplitDef super(); } + @Override public WfVertex instantiate() { OrSplit newSplit = new OrSplit(); configureInstance(newSplit); diff --git a/source/com/c2kernel/lifecycle/WfCastorHashMap.java b/source/com/c2kernel/lifecycle/WfCastorHashMap.java old mode 100755 new mode 100644 index 1e6a308..7d88ea9 --- a/source/com/c2kernel/lifecycle/WfCastorHashMap.java +++ b/source/com/c2kernel/lifecycle/WfCastorHashMap.java @@ -28,6 +28,6 @@ public class WfCastorHashMap extends CastorHashMap put("SchemaVersion", ""); put("ScriptName", ""); put("ScriptVersion", ""); - put("Viewpoint", ""); + put("Viewpoint", ""); } } diff --git a/source/com/c2kernel/lifecycle/WfVertexDef.java b/source/com/c2kernel/lifecycle/WfVertexDef.java index 221f6ae..6a46bee 100644 --- a/source/com/c2kernel/lifecycle/WfVertexDef.java +++ b/source/com/c2kernel/lifecycle/WfVertexDef.java @@ -29,11 +29,11 @@ public abstract class WfVertexDef extends GraphableVertex } public abstract WfVertex instantiate() throws ObjectNotFoundException, InvalidDataException; - + public void configureInstance(WfVertex newVertex) { KeyValuePair[] k = getProperties().getKeyValuePairs(); - for (int i = 0; i < k.length; i++) - newVertex.getProperties().put(k[i].getKey(), k[i].getValue()); + for (KeyValuePair element : k) + newVertex.getProperties().put(element.getKey(), element.getValue()); newVertex.setID(getID()); if (getIsLayoutable()) { newVertex.setInEdgeIds(getInEdgeIds()); @@ -42,17 +42,17 @@ public abstract class WfVertexDef extends GraphableVertex newVertex.setOutlinePoints(getOutlinePoints()); } } - + /** * Method verify. - * + * * @return boolean */ public abstract boolean verify(); /** * Method getErrors. - * + * * @return String */ public String getErrors() @@ -60,12 +60,12 @@ public abstract class WfVertexDef extends GraphableVertex if (mErrors.size() == 0) return "No error"; else - return (String) mErrors.elementAt(0); + return mErrors.elementAt(0); } /** * Method loop. - * + * * @return boolean */ public boolean loop() diff --git a/source/com/c2kernel/lifecycle/XOrSplitDef.java b/source/com/c2kernel/lifecycle/XOrSplitDef.java old mode 100755 new mode 100644 index 550fb88..73c578f --- a/source/com/c2kernel/lifecycle/XOrSplitDef.java +++ b/source/com/c2kernel/lifecycle/XOrSplitDef.java @@ -19,7 +19,8 @@ public class XOrSplitDef extends AndSplitDef { super(); } - + + @Override public WfVertex instantiate() { XOrSplit newSplit = new XOrSplit(); configureInstance(newSplit); diff --git a/source/com/c2kernel/lifecycle/chooser/ActivityChooser.java b/source/com/c2kernel/lifecycle/chooser/ActivityChooser.java old mode 100755 new mode 100644 index f79dedf..4b0ae4c --- a/source/com/c2kernel/lifecycle/chooser/ActivityChooser.java +++ b/source/com/c2kernel/lifecycle/chooser/ActivityChooser.java @@ -1,6 +1,6 @@ /* * Created on 1 sept. 2003 - * + * * To change the template for this generated file go to Window>Preferences>Java>Code Generation>Code and Comments */ package com.c2kernel.lifecycle.chooser; @@ -22,15 +22,13 @@ import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; -import com.c2kernel.lifecycle.ActivityDef; import com.c2kernel.utils.Language; -import com.c2kernel.utils.LocalObjectLoader; import com.c2kernel.utils.Logger; import com.c2kernel.utils.Resource; /** * @author Developpement - * + * * To change the template for this generated type comment go to * Window>Preferences>Java>Code Generation>Code and Comments */ @@ -52,9 +50,9 @@ public class ActivityChooser extends JFrame private JLabel label = null; - HashMap mhashmap = null; + HashMap mhashmap = null; - public ActivityChooser(String message, String title, Image img, WorkflowDialogue parent, HashMap hashmap) + public ActivityChooser(String message, String title, Image img, WorkflowDialogue parent, HashMap hashmap) { super(title); mMessage = message; @@ -93,7 +91,7 @@ public class ActivityChooser extends JFrame { Logger.error(mExc); } - } + } return mLDAPFileChooserActivity; } @@ -101,14 +99,9 @@ public class ActivityChooser extends JFrame { getJButtonOK().addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) + @Override + public void actionPerformed(ActionEvent e) { - try - { - ActivityDef act = LocalObjectLoader.getActDef(mLDAPFileChooserActivity.getEntryName(), "last"); - } catch (Exception ex) - { - } Logger.debug(5, "mLDAPFileChooserActivity.getEntryName()" + mLDAPFileChooserActivity.getEntryName()); setCursor(new Cursor(Cursor.WAIT_CURSOR)); mParent.loadThisWorkflow(mLDAPFileChooserActivity.getEntryName(), mhashmap); @@ -118,7 +111,8 @@ public class ActivityChooser extends JFrame }); getJButtonCancel().addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) + @Override + public void actionPerformed(ActionEvent e) { close(); } diff --git a/source/com/c2kernel/lifecycle/chooser/LDAPEntryChooser.java b/source/com/c2kernel/lifecycle/chooser/LDAPEntryChooser.java index e8143be..d86c0a0 100644 --- a/source/com/c2kernel/lifecycle/chooser/LDAPEntryChooser.java +++ b/source/com/c2kernel/lifecycle/chooser/LDAPEntryChooser.java @@ -17,10 +17,10 @@ import com.c2kernel.utils.Logger; public class LDAPEntryChooser extends JComboBox { - + DomainPath mDomainPath = null; ArrayList allItems = new ArrayList(); - + public LDAPEntryChooser(DomainPath domPath, boolean editable) { super(); @@ -28,12 +28,12 @@ public class LDAPEntryChooser extends JComboBox mDomainPath = domPath; initialise(); } - + private void initialise() { try { - Enumeration children = Gateway.getLDAPLookup().searchAliases(mDomainPath); + Enumeration children = Gateway.getLDAPLookup().searchAliases(mDomainPath); while (children.hasMoreElements()) { DomainPath domPath = (DomainPath)children.nextElement(); @@ -44,13 +44,13 @@ public class LDAPEntryChooser extends JComboBox { Logger.exceptionDialog(ex); } - + Collections.sort(allItems); addItem(""); for (String element : allItems) { addItem(element); } - + } public void reload() @@ -58,8 +58,9 @@ public class LDAPEntryChooser extends JComboBox removeAllItems(); initialise(); } - - public synchronized Dimension getSize() + + @Override + public synchronized Dimension getSize() { if ("1".equals(Gateway.getProperty("ResizeCombo"))) return new Dimension(super.getSize().width<400?400:super.getSize().width,super.getSize().height); diff --git a/source/com/c2kernel/lifecycle/chooser/LDAPFileChooser.java b/source/com/c2kernel/lifecycle/chooser/LDAPFileChooser.java old mode 100755 new mode 100644 index 08f4387..9843d61 --- a/source/com/c2kernel/lifecycle/chooser/LDAPFileChooser.java +++ b/source/com/c2kernel/lifecycle/chooser/LDAPFileChooser.java @@ -22,7 +22,7 @@ public class LDAPFileChooser extends JPanel public static String SCHEMA_CHOOSER = "Schema"; public static String ACTIVITY_CHOOSER = "Activity"; private String chooserMode = null; - private HashMap mHashList = null; + private HashMap mHashList = null; public LDAPEntryChooser mLec; private boolean mEditable = false; DomainPath domainPath; @@ -83,7 +83,7 @@ public class LDAPFileChooser extends JPanel public void setSelectedItem(String name, String version) { Logger.debug(5,"setSelectedItem " + name + " " + version); - if (name == null||name.equals("-1")) name=""; + if (name == null||name.equals("-1")) name=""; mLec.setSelectedItem(name); } @@ -106,13 +106,15 @@ public class LDAPFileChooser extends JPanel mLec.setEditable(b); } - public void updateUI() + @Override + public void updateUI() { if (mLec!=null) mLec.updateUI(); super.updateUI(); } - public void setEnabled(boolean enabled) + @Override + public void setEnabled(boolean enabled) { mLec.setEnabled(enabled); } diff --git a/source/com/c2kernel/lifecycle/chooser/WorkflowDialogue.java b/source/com/c2kernel/lifecycle/chooser/WorkflowDialogue.java old mode 100755 new mode 100644 index 8453ad2..2ddd489 --- a/source/com/c2kernel/lifecycle/chooser/WorkflowDialogue.java +++ b/source/com/c2kernel/lifecycle/chooser/WorkflowDialogue.java @@ -16,5 +16,5 @@ import java.util.HashMap; */ public interface WorkflowDialogue { - public void loadThisWorkflow(String name, HashMap hashMap); + public void loadThisWorkflow(String name, HashMap hashMap); } diff --git a/source/com/c2kernel/lifecycle/gui/model/WfDefGraphPanel.java b/source/com/c2kernel/lifecycle/gui/model/WfDefGraphPanel.java old mode 100755 new mode 100644 index 973fcbf..e0f4f65 --- a/source/com/c2kernel/lifecycle/gui/model/WfDefGraphPanel.java +++ b/source/com/c2kernel/lifecycle/gui/model/WfDefGraphPanel.java @@ -18,6 +18,7 @@ public class WfDefGraphPanel extends GraphPanel super(d,v); } // Draws the highlight of the specified edge + @Override protected void drawEdgeHighlight(Graphics2D g2d, DirectedEdge edge) { GraphPoint originPoint = edge.getOriginPoint(); @@ -49,7 +50,7 @@ public class WfDefGraphPanel extends GraphPanel int minX = midPoint.x - 10; int minY = midPoint.y - 10; int maxX = midPoint.x + 10; - int maxY = midPoint.y + 10; + int maxY = midPoint.y + 10; g2d.drawLine(minX, minY, maxX, minY); g2d.drawLine(maxX, minY, maxX, maxY); g2d.drawLine(maxX, maxY, minX, maxY); diff --git a/source/com/c2kernel/lifecycle/gui/model/WfEdgeDefFactory.java b/source/com/c2kernel/lifecycle/gui/model/WfEdgeDefFactory.java old mode 100755 new mode 100644 index d6fd41c..6e6727a --- a/source/com/c2kernel/lifecycle/gui/model/WfEdgeDefFactory.java +++ b/source/com/c2kernel/lifecycle/gui/model/WfEdgeDefFactory.java @@ -8,6 +8,7 @@ import com.c2kernel.lifecycle.NextDef; import com.c2kernel.lifecycle.WfVertexDef; public class WfEdgeDefFactory implements EdgeFactory { + @Override public void create( GraphModelManager graphModelManager, Vertex origin, @@ -20,7 +21,7 @@ public class WfEdgeDefFactory implements EdgeFactory graphModelManager.getModel().addEdgeAndCreateId(nextDef, origin, terminus); } } - private boolean validCreation(GraphModelManager graphModelManager, Vertex origin, Vertex terminus) + private static boolean validCreation(GraphModelManager graphModelManager, Vertex origin, Vertex terminus) { DirectedEdge[] connectingEdgesAToB = graphModelManager.getModel().getConnectingEdges(origin.getID(), terminus.getID()); DirectedEdge[] connectingEdgesBToA = graphModelManager.getModel().getConnectingEdges(terminus.getID(), origin.getID()); diff --git a/source/com/c2kernel/lifecycle/gui/model/WfVertexDefFactory.java b/source/com/c2kernel/lifecycle/gui/model/WfVertexDefFactory.java index 2ef9508..da59efd 100644 --- a/source/com/c2kernel/lifecycle/gui/model/WfVertexDefFactory.java +++ b/source/com/c2kernel/lifecycle/gui/model/WfVertexDefFactory.java @@ -20,6 +20,7 @@ import com.c2kernel.utils.Resource; public class WfVertexDefFactory implements VertexFactory, WorkflowDialogue { protected CompositeActivityDef mCompositeActivityDef = null; + @Override public void create(GraphModelManager graphModelManager, Point location, TypeNameAndConstructionInfo typeNameAndConstructionInfo) { String vertexTypeId = null; @@ -46,7 +47,8 @@ public class WfVertexDefFactory implements VertexFactory, WorkflowDialogue mCompositeActivityDef.newChild("", vertexTypeId, location); } } - public void loadThisWorkflow(String newName, HashMap hashMap) + @Override + public void loadThisWorkflow(String newName, HashMap hashMap) { String vertexTypeId = (String) hashMap.get("P1"); Point location = (Point) hashMap.get("P2"); @@ -86,6 +88,7 @@ public class WfVertexDefFactory implements VertexFactory, WorkflowDialogue mCompositeActivityDef.newChild(newName, vertexTypeId, location); } } + @Override public void setCreationContext(Object newContext) { if (newContext != null && newContext instanceof CompositeActivityDef) diff --git a/source/com/c2kernel/lifecycle/gui/model/WfVertexDefOutlineCreator.java b/source/com/c2kernel/lifecycle/gui/model/WfVertexDefOutlineCreator.java old mode 100755 new mode 100644 index 3727f35..63d3b2f --- a/source/com/c2kernel/lifecycle/gui/model/WfVertexDefOutlineCreator.java +++ b/source/com/c2kernel/lifecycle/gui/model/WfVertexDefOutlineCreator.java @@ -12,7 +12,8 @@ public class WfVertexDefOutlineCreator implements VertexOutlineCreator private final int mSplitJoinWidth = 60; private final int mSplitJoinHeight = 25; - public void setOutline(Vertex vertex) + @Override + public void setOutline(Vertex vertex) { GraphPoint centrePoint = vertex.getCentrePoint(); GraphPoint[] outlinePoints = new GraphPoint[ 4 ]; diff --git a/source/com/c2kernel/lifecycle/gui/view/ActivitySlotDefRenderer.java b/source/com/c2kernel/lifecycle/gui/view/ActivitySlotDefRenderer.java old mode 100755 new mode 100644 index 5746673..c4309ee --- a/source/com/c2kernel/lifecycle/gui/view/ActivitySlotDefRenderer.java +++ b/source/com/c2kernel/lifecycle/gui/view/ActivitySlotDefRenderer.java @@ -19,7 +19,8 @@ public class ActivitySlotDefRenderer implements VertexRenderer private Paint mTextPaint = Color.black; - public void draw( Graphics2D g2d, Vertex vertex) + @Override + public void draw( Graphics2D g2d, Vertex vertex) { ActivitySlotDef activitySlotDef = ( ActivitySlotDef )vertex; boolean hasError = activitySlotDef.verify(); @@ -28,12 +29,12 @@ public class ActivitySlotDefRenderer implements VertexRenderer GraphPoint centrePoint = activitySlotDef.getCentrePoint(); int vertexHeight = activitySlotDef.getHeight(); int vertexWidth = activitySlotDef.getWidth(); - + String[] linesOfText = new String[2+(hasError?0:1)]; FontMetrics metrics = g2d.getFontMetrics(); int lineWidth = 0; int lineHeight = metrics.getHeight(); - int linesHeight = lineHeight * linesOfText.length; + int linesHeight = lineHeight * linesOfText.length; int linesStartY = centrePoint.y - linesHeight / 2 + lineHeight * 2 / 3; int x = 0; int y = 0; @@ -41,7 +42,7 @@ public class ActivitySlotDefRenderer implements VertexRenderer linesOfText[0]="("+activitySlotDef.getActivityDef()+")"; linesOfText[1]=(String)activitySlotDef.getProperties().get("Name"); - + if (!hasError)linesOfText[2]=Language.translate(activitySlotDef.getErrors()); g2d.setPaint( !hasError ? mErrorPaint : isComposite ? mCompositePaint : mInactivePaint ); @@ -53,7 +54,7 @@ public class ActivitySlotDefRenderer implements VertexRenderer vertexHeight, true ); - + g2d.setPaint( mTextPaint ); // Draw the lines of text diff --git a/source/com/c2kernel/lifecycle/gui/view/CompActDefOutcomeHandler.java b/source/com/c2kernel/lifecycle/gui/view/CompActDefOutcomeHandler.java old mode 100755 new mode 100644 index cb0ef59..58964aa --- a/source/com/c2kernel/lifecycle/gui/view/CompActDefOutcomeHandler.java +++ b/source/com/c2kernel/lifecycle/gui/view/CompActDefOutcomeHandler.java @@ -15,7 +15,11 @@ import com.c2kernel.graph.layout.DefaultGraphLayoutGenerator; import com.c2kernel.graph.view.EditorPanel; import com.c2kernel.graph.view.VertexPropertyPanel; import com.c2kernel.gui.MainFrame; -import com.c2kernel.gui.tabs.outcome.*; +import com.c2kernel.gui.tabs.outcome.InvalidOutcomeException; +import com.c2kernel.gui.tabs.outcome.InvalidSchemaException; +import com.c2kernel.gui.tabs.outcome.OutcomeException; +import com.c2kernel.gui.tabs.outcome.OutcomeHandler; +import com.c2kernel.gui.tabs.outcome.OutcomeNotInitialisedException; import com.c2kernel.lifecycle.CompositeActivityDef; import com.c2kernel.lifecycle.gui.model.WfDefGraphPanel; import com.c2kernel.lifecycle.gui.model.WfEdgeDefFactory; @@ -44,26 +48,26 @@ public class CompActDefOutcomeHandler protected JButton mLoadButton = new JButton(Resource.getImageResource("graph/load.png")); protected JButton mLayoutButton = new JButton(Resource.getImageResource("graph/autolayout.png")); protected JButton[] mOtherToolBarButtons = { mLayoutButton, mLoadButton }; - + protected CompositeActivityDef mCompActDef = null; protected WfEdgeDefFactory mWfEdgeDefFactory = new WfEdgeDefFactory(); - protected WfVertexDefFactory mWfVertexDefFactory = new WfVertexDefFactory(); + protected WfVertexDefFactory mWfVertexDefFactory = new WfVertexDefFactory(); protected EditorPanel mEditorPanel; protected VertexPropertyPanel mPropertyPanel; protected JSplitPane mSplitPane; boolean unsaved; - + public CompActDefOutcomeHandler() { super(); - mPropertyPanel = loadPropertyPanel(); - mPropertyPanel.createLayout(new FindActDefPanel()); + mPropertyPanel = loadPropertyPanel(); + mPropertyPanel.createLayout(new FindActDefPanel()); mEditorPanel = new EditorPanel( mWfEdgeDefFactory, mWfVertexDefFactory, new WfVertexDefOutlineCreator(), - true, + true, mOtherToolBarButtons, new WfDefGraphPanel(new WfDirectedEdgeDefRenderer(), new WfVertexDefRenderer())); @@ -92,7 +96,8 @@ public class CompActDefOutcomeHandler protected void createListeners() { mLoadButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { + @Override + public void actionPerformed(ActionEvent ae) { File selectedFile = null; int returnValue = MainFrame.xmlChooser.showOpenDialog(null); @@ -110,32 +115,34 @@ public class CompActDefOutcomeHandler } case JFileChooser.CANCEL_OPTION : case JFileChooser.ERROR_OPTION : - + default : } } }); - + mLayoutButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent ae) { + @Override + public void actionPerformed(ActionEvent ae) { DefaultGraphLayoutGenerator.layoutGraph(mEditorPanel.mGraphModelManager.getModel()); } }); - } - + } + public void setUpGraphEditor() { mEditorPanel.mGraphModelManager.setModel(mCompActDef.getChildrenGraphModel()); // Give the editor panel the edge and vertex types mEditorPanel.updateVertexTypes(mCompActDef.getVertexTypeNameAndConstructionInfo()); mEditorPanel.updateEdgeTypes(mCompActDef.getEdgeTypeNameAndConstructionInfo()); mEditorPanel.enterSelectMode(); - mWfVertexDefFactory.setCreationContext(mCompActDef); + mWfVertexDefFactory.setCreationContext(mCompActDef); } - + /** * */ - public void setOutcome(String outcome) throws InvalidOutcomeException { + @Override + public void setOutcome(String outcome) throws InvalidOutcomeException { try { CompositeActivityDef newAct = (CompositeActivityDef)CastorXMLUtility.unmarshall(outcome); if (mCompActDef != null) @@ -149,14 +156,16 @@ public class CompActDefOutcomeHandler /** * */ - public void setDescription(String description) + @Override + public void setDescription(String description) throws InvalidSchemaException { - // ignore - always the same + // ignore - always the same } /** * */ - public void setReadOnly(boolean readOnly) { + @Override + public void setReadOnly(boolean readOnly) { mLayoutButton.setEnabled(!readOnly); mLoadButton.setEnabled(!readOnly); mEditorPanel.setEditable(!readOnly); @@ -165,13 +174,15 @@ public class CompActDefOutcomeHandler /** * */ - public JPanel getPanel() throws OutcomeNotInitialisedException { + @Override + public JPanel getPanel() throws OutcomeNotInitialisedException { return this; } /** * */ - public String getOutcome() throws OutcomeException { + @Override + public String getOutcome() throws OutcomeException { try { return CastorXMLUtility.marshall(mCompActDef); } catch (Exception ex) { @@ -181,20 +192,21 @@ public class CompActDefOutcomeHandler /** * */ - public void run() { - Thread.currentThread().setName("Composite Act Def Viewer"); + @Override + public void run() { + Thread.currentThread().setName("Composite Act Def Viewer"); createLayout(); createListeners(); - mPropertyPanel.setGraphModelManager(mEditorPanel.mGraphModelManager); - setUpGraphEditor(); + mPropertyPanel.setGraphModelManager(mEditorPanel.mGraphModelManager); + setUpGraphEditor(); } - + public VertexPropertyPanel loadPropertyPanel() { String wfPanelClass = Gateway.getProperty("WfPropertyPanel"); if (wfPanelClass != null) { try { - Class panelClass = Class.forName(wfPanelClass); + Class panelClass = Class.forName(wfPanelClass); return (VertexPropertyPanel)panelClass.newInstance(); } catch (Exception ex) { Logger.error("Could not load wf props panel:"+wfPanelClass); @@ -203,15 +215,18 @@ public class CompActDefOutcomeHandler } return new VertexPropertyPanel(); } - - public boolean isUnsaved() { + + @Override + public boolean isUnsaved() { return unsaved; } - - public void saved() { + + @Override + public void saved() { unsaved = false; } - + + @Override public void export(File targetFile) throws Exception { ElemActDefOutcomeHandler.exportAct(targetFile.getParentFile(), mCompActDef); } diff --git a/source/com/c2kernel/lifecycle/gui/view/ElemActDefOutcomeHandler.java b/source/com/c2kernel/lifecycle/gui/view/ElemActDefOutcomeHandler.java old mode 100755 new mode 100644 index a30491e..c37e5a7 --- a/source/com/c2kernel/lifecycle/gui/view/ElemActDefOutcomeHandler.java +++ b/source/com/c2kernel/lifecycle/gui/view/ElemActDefOutcomeHandler.java @@ -41,7 +41,8 @@ public class ElemActDefOutcomeHandler extends VertexPropertyPanel implements Out /** * */ - public void setOutcome(String outcome) throws InvalidOutcomeException { + @Override + public void setOutcome(String outcome) throws InvalidOutcomeException { try { act = (ActivityDef)CastorXMLUtility.unmarshall(outcome); setVertex(act); @@ -54,7 +55,8 @@ public class ElemActDefOutcomeHandler extends VertexPropertyPanel implements Out /** * */ - public void setDescription(String description) + @Override + public void setDescription(String description) throws InvalidSchemaException { // ignore } @@ -62,7 +64,8 @@ public class ElemActDefOutcomeHandler extends VertexPropertyPanel implements Out /** * */ - public void setReadOnly(boolean readOnly) { + @Override + public void setReadOnly(boolean readOnly) { setEditable(!readOnly); } @@ -70,48 +73,54 @@ public class ElemActDefOutcomeHandler extends VertexPropertyPanel implements Out /** * */ - public JPanel getPanel() throws OutcomeNotInitialisedException { + @Override + public JPanel getPanel() throws OutcomeNotInitialisedException { return this; } /** * */ - public String getOutcome() throws OutcomeException { + @Override + public String getOutcome() throws OutcomeException { try { return CastorXMLUtility.marshall(act); } catch (Exception ex) { Logger.error(ex); throw new OutcomeException(); - } + } } /** * */ - public void run() { + @Override + public void run() { validate(); } - - public boolean isUnsaved() { + + @Override + public boolean isUnsaved() { return unsaved; } - - public void saved() { + + @Override + public void saved() { unsaved = false; } - + + @Override public void export(File targetFile) throws Exception { exportAct(targetFile.getParentFile(), act); } - + public static void exportAct(File dir, ActivityDef actDef) throws Exception { FileStringUtility.string2File(new File(dir, actDef.getActName()+".xml"), CastorXMLUtility.marshall(actDef)); // Export associated schema exportSchema((String)actDef.getProperties().get("SchemaType"), (String)actDef.getProperties().get("SchemaVersion"), dir); // Export associated script exportScript((String)actDef.getProperties().get("ScriptName"), (String)actDef.getProperties().get("ScriptVersion"), dir); - + //Export child act if composite if (actDef instanceof CompositeActivityDef) { CompositeActivityDef compActDef = (CompositeActivityDef)actDef; @@ -121,32 +130,32 @@ public class ElemActDefOutcomeHandler extends VertexPropertyPanel implements Out exportScript((String)vert.getProperties().get("RoutingScriptName"), (String)vert.getProperties().get("RoutingScriptVersion"), dir); } GraphableVertex[] childDefs = compActDef.getLayoutableChildren(); - for (int i=0; i steps = new Vector(); Activity[] returnArray = null; @@ -307,7 +311,7 @@ public class CompositeActivity extends Activity } int j = 0; for (int i = 0; i < steps.size(); i++) - j += ((Activity[]) steps.elementAt(i)).length; + j += steps.elementAt(i).length; Activity[] tmp = super.query(agent, stateID, filter); if (tmp.length == 1) { @@ -318,9 +322,9 @@ public class CompositeActivity extends Activity j = 0; for (int i = 0; i < steps.size(); i++) { - Activity[] stepArray = (Activity[]) steps.elementAt(i); - for (int k = 0; k < stepArray.length; k++) - returnArray[j++] = stepArray[k]; + Activity[] stepArray = steps.elementAt(i); + for (Activity element : stepArray) + returnArray[j++] = element; } return returnArray; } @@ -328,7 +332,8 @@ public class CompositeActivity extends Activity /** * @see com.c2kernel.lifecycle.instance.Activity#calculateJobs() */ - public ArrayList calculateJobs(AgentPath agent, boolean recurse) + @Override + public ArrayList calculateJobs(AgentPath agent, boolean recurse) { ArrayList jobs = new ArrayList(); boolean childActive = false; @@ -345,7 +350,8 @@ public class CompositeActivity extends Activity return jobs; } - public ArrayList calculateAllJobs(AgentPath agent, boolean recurse) + @Override + public ArrayList calculateAllJobs(AgentPath agent, boolean recurse) { ArrayList jobs = new ArrayList(); if (recurse) @@ -361,7 +367,7 @@ public class CompositeActivity extends Activity /** * Method addNext. - * + * * @param origin * @param terminus * @return Next @@ -373,7 +379,7 @@ public class CompositeActivity extends Activity /** * Method addNext. - * + * * @param originID * @param terminusID * @return Next @@ -388,7 +394,7 @@ public class CompositeActivity extends Activity /** * Method hasGoodNumberOfActivity. - * + * * @return boolean */ public boolean hasGoodNumberOfActivity() @@ -408,7 +414,8 @@ public class CompositeActivity extends Activity /** * @see com.c2kernel.lifecycle.instance.Activity#getType() */ - public String getType() + @Override + public String getType() { if (getName().equals("domain")) return "domain"; @@ -416,16 +423,18 @@ public class CompositeActivity extends Activity } /** - * + * */ - public void reinit(int idLoop) + @Override + public void reinit(int idLoop) { super.reinit(idLoop); if (getChildrenGraphModel().getStartVertex() != null && getMachine().getCurrentState() != States.FINISHED) ((WfVertex) getChildrenGraphModel().getStartVertex()).reinit(idLoop); } - public void request(AgentPath agent, int transitionID, String requestData) throws AccessRightsException, InvalidTransitionException, InvalidDataException, ObjectAlreadyExistsException + @Override + public void request(AgentPath agent, int transitionID, String requestData) throws AccessRightsException, InvalidTransitionException, InvalidDataException, ObjectAlreadyExistsException { if (getChildrenGraphModel().getStartVertex() != null && getMachine().getCurrentState() != States.FINISHED && transitionID == Transitions.START) try @@ -440,10 +449,10 @@ public class CompositeActivity extends Activity public void refreshJobs() { GraphableVertex[] children = getChildren(); - for (int i = 0; i < children.length; i++) - if (children[i] instanceof CompositeActivity) - ((CompositeActivity) children[i]).refreshJobs(); - else if (children[i] instanceof Activity) - ((Activity) children[i]).pushJobsToAgents(); + for (GraphableVertex element : children) + if (element instanceof CompositeActivity) + ((CompositeActivity) element).refreshJobs(); + else if (element instanceof Activity) + ((Activity) element).pushJobsToAgents(); } } \ No newline at end of file diff --git a/source/com/c2kernel/lifecycle/instance/EventStorage.java b/source/com/c2kernel/lifecycle/instance/EventStorage.java old mode 100755 new mode 100644 index a78a2bf..40cffaf --- a/source/com/c2kernel/lifecycle/instance/EventStorage.java +++ b/source/com/c2kernel/lifecycle/instance/EventStorage.java @@ -8,7 +8,7 @@ import java.util.Hashtable; */ public class EventStorage implements Serializable { - private Hashtable mLists; + private Hashtable mLists; private EventList[] dummy = new EventList[0]; public Integer lastTransitionStored; @@ -16,9 +16,9 @@ public class EventStorage implements Serializable { return dummy; } - + public void setLists(EventList[] lists) { } - + } diff --git a/source/com/c2kernel/lifecycle/instance/JobPusher.java b/source/com/c2kernel/lifecycle/instance/JobPusher.java old mode 100755 new mode 100644 index e58170d..c6e5d26 --- a/source/com/c2kernel/lifecycle/instance/JobPusher.java +++ b/source/com/c2kernel/lifecycle/instance/JobPusher.java @@ -22,10 +22,11 @@ final class JobPusher extends Thread { this.myRole = role; } - public void run() + @Override + public void run() { Thread.currentThread().setName("Agent job pusher for "+activity.getName()+" to role "+myRole); - for (Enumeration e = myRole.getChildren(); e.hasMoreElements();) + for (Enumeration e = myRole.getChildren(); e.hasMoreElements();) { AgentPath nextAgent = (AgentPath)e.nextElement(); Logger.msg(7, "Activity.pushJobsToAgents() - Calculating jobs for " + nextAgent.getAgentName()); @@ -34,7 +35,7 @@ final class JobPusher extends Thread { // get joblist for user JobArrayList jobList = new JobArrayList(this.activity.calculateJobs(nextAgent, false)); // only transmit start, complete and resume jobs - for (Iterator element = jobList.list.iterator(); element.hasNext();) + for (Iterator element = jobList.list.iterator(); element.hasNext();) { Job thisJob = (Job) element.next(); if (thisJob.getPossibleTransition() != Transitions.START @@ -64,6 +65,6 @@ final class JobPusher extends Thread { Logger.error(ex); } } - + } } \ No newline at end of file diff --git a/source/com/c2kernel/lifecycle/instance/Join.java b/source/com/c2kernel/lifecycle/instance/Join.java index b61100e..3a4fd7d 100644 --- a/source/com/c2kernel/lifecycle/instance/Join.java +++ b/source/com/c2kernel/lifecycle/instance/Join.java @@ -26,6 +26,7 @@ public class Join extends WfVertex /** * @see com.c2kernel.lifecycle.instance.WfVertex#runNext() */ + @Override public void runNext(AgentPath agent) throws ScriptingEngineException { AdvancementCalculator adv = new AdvancementCalculator(); @@ -44,7 +45,7 @@ public class Join extends WfVertex } /** * Method addNext. - * + * * @param idNext */ public void addNext(String idNext) @@ -54,6 +55,7 @@ public class Join extends WfVertex /** * @see com.c2kernel.lifecycle.instance.WfVertex#reinit(int) */ + @Override public void reinit(int idLoop) { Vertex[] outVertices = getOutGraphables(); @@ -65,7 +67,7 @@ public class Join extends WfVertex } /** * Method getItemSystemKey. - * + * * @return String */ /* @@ -77,7 +79,7 @@ public class Join extends WfVertex } /** * Method setItemSystemKey. - * + * * @param itemSystemKey */ public void setItemSystemKey(String itemSystemKey) @@ -90,6 +92,7 @@ public class Join extends WfVertex // public void initItemSystemKey(String systemKey) { // this.setItemSystemKey(systemKey); // } + @Override public boolean verify() { mErrors.removeAllElements(); @@ -153,16 +156,18 @@ public class Join extends WfVertex /** * @see com.c2kernel.lifecycle.instance.WfVertex#getErrors() */ + @Override public String getErrors() { if (mErrors.size() == 0) return "No error"; else - return (String) mErrors.elementAt(0); + return mErrors.elementAt(0); } /** * @see com.c2kernel.lifecycle.instance.WfVertex#run() */ + @Override public void run(AgentPath agent) throws ScriptingEngineException { runNext(agent); @@ -170,6 +175,7 @@ public class Join extends WfVertex /** * @see com.c2kernel.lifecycle.instance.WfVertex#addNext(com.c2kernel.lifecycle.instance.WfVertex) */ + @Override public Next addNext(WfVertex vertex) { return new Next(this, vertex); @@ -177,6 +183,7 @@ public class Join extends WfVertex /** * @see com.c2kernel.lifecycle.instance.WfVertex#loop() */ + @Override public boolean loop() { boolean loop2 = false; @@ -191,15 +198,17 @@ public class Join extends WfVertex loopTested = false; return loop2; } + @Override public void runfirst(AgentPath agent) throws ScriptingEngineException { runNext(agent); } /* * (non-Javadoc) - * + * * @see com.c2kernel.graph.model.Vertex#isJoin() */ + @Override public boolean isJoin() { return true; diff --git a/source/com/c2kernel/lifecycle/instance/Loop.java b/source/com/c2kernel/lifecycle/instance/Loop.java old mode 100755 new mode 100644 index 556a9ca..8228ba9 --- a/source/com/c2kernel/lifecycle/instance/Loop.java +++ b/source/com/c2kernel/lifecycle/instance/Loop.java @@ -20,10 +20,12 @@ public class Loop extends XOrSplit /** * @see com.c2kernel.lifecycle.instance.WfVertex#loop() */ + @Override public boolean loop() { return true; } + @Override public void followNext(Next activeNext, AgentPath agent) throws ScriptingEngineException { WfVertex v = activeNext.getTerminusVertex(); @@ -38,6 +40,7 @@ public class Loop extends XOrSplit /** * @see com.c2kernel.lifecycle.instance.WfVertex#reinit(int) */ + @Override public void reinit(int idLoop) { Logger.msg(8, "Loop.reinit"); @@ -56,6 +59,7 @@ public class Loop extends XOrSplit /** * @see com.c2kernel.lifecycle.instance.WfVertex#verify() */ + @Override public boolean verify() { boolean err = super.verify(); @@ -64,13 +68,12 @@ public class Loop extends XOrSplit int k = 0; int l = 0; Vertex[] brothers = getParent().getChildren(); - for (int i = 0; i < brothers.length; i++) - if (brothers[i] instanceof Loop) + for (Vertex brother : brothers) + if (brother instanceof Loop) l++; - for (int i = 0; i < nexts.length; i++) - { - for (int j = 0; j < anteVertices.length; j++) - if (nexts[i].getID() == anteVertices[j].getID()) + for (Vertex next : nexts) { + for (Vertex anteVertice : anteVertices) + if (next.getID() == anteVertice.getID()) k++; } if (k != 1 && !(l > 1)) @@ -88,15 +91,15 @@ public class Loop extends XOrSplit { int id = vertex.getID(); Vertex[] anteVertices = GraphTraversal.getTraversal(getParent().getChildrenGraphModel(), this, GraphTraversal.kUp, false); - for (int i = 0; i < anteVertices.length; i++) - { - if (anteVertices[i].getID() == id) + for (Vertex anteVertice : anteVertices) { + if (anteVertice.getID() == id) { return true; } } return false; } + @Override public boolean isLoop() { return true; diff --git a/source/com/c2kernel/lifecycle/instance/Next.java b/source/com/c2kernel/lifecycle/instance/Next.java old mode 100755 new mode 100644 index 059dbf8..4df775c --- a/source/com/c2kernel/lifecycle/instance/Next.java +++ b/source/com/c2kernel/lifecycle/instance/Next.java @@ -28,7 +28,7 @@ public class Next extends GraphableEdge { super(pre, nex); getProperties().put("Alias",""); - getProperties().put("Type","Straight"); + getProperties().put("Type","Straight"); } /** @@ -43,6 +43,7 @@ public class Next extends GraphableEdge { return (WfVertex)((CompositeActivity)getParent()).getWf().search(getParent().getPath()+"/"+this.getTerminusVertexId()); } + @Override public boolean containsPoint(GraphPoint p) { GraphPoint originPoint = getOriginPoint(); diff --git a/source/com/c2kernel/lifecycle/instance/OrSplit.java b/source/com/c2kernel/lifecycle/instance/OrSplit.java old mode 100755 new mode 100644 index f0fcdd5..aea34b2 --- a/source/com/c2kernel/lifecycle/instance/OrSplit.java +++ b/source/com/c2kernel/lifecycle/instance/OrSplit.java @@ -18,6 +18,7 @@ public class OrSplit extends Split { super(); } + @Override public void runNext(AgentPath agent) throws ScriptingEngineException { String nexts = @@ -36,9 +37,8 @@ public class OrSplit extends Split { String thisNext = tok.nextToken(); Logger.msg(7, "Finding next " + thisNext); - for (int i = 0; i < outEdges.length; i++) - { - Next nextEdge = (Next) outEdges[i]; + for (DirectedEdge outEdge : outEdges) { + Next nextEdge = (Next) outEdge; if (thisNext != null && thisNext.equals(nextEdge.getProperties().get("Alias"))) { WfVertex term = nextEdge.getTerminusVertex(); @@ -57,6 +57,6 @@ public class OrSplit extends Split if (active == 0) throw new ScriptingEngineException("No nexts were activated!"); } - - + + } diff --git a/source/com/c2kernel/lifecycle/instance/ParserWF.java b/source/com/c2kernel/lifecycle/instance/ParserWF.java index 35fed90..02a0c6d 100644 --- a/source/com/c2kernel/lifecycle/instance/ParserWF.java +++ b/source/com/c2kernel/lifecycle/instance/ParserWF.java @@ -35,7 +35,6 @@ public class ParserWF nexts = new Vector(1, 1); i = 0; file = xmlfile; - int c; while (i < file.length() - 5) { if (file.substring(i, i + 5).equals(" requiredInput = script.getAllInputParams(); + for (KeyValuePair element : k) { + if (requiredInput.containsKey(element.getKey())) { - String value = k[i].getStringValue(); + String value = element.getStringValue(); Object inputParam = value; if (value.startsWith("viewpoint//")) @@ -126,11 +125,11 @@ public abstract class WfVertex extends GraphableVertex inputParam = null; } } - Logger.msg(5, "Split.evaluateScript() - Setting param " + k[i].getKey() + " to " + inputParam.toString()); - script.setInputParamValue(k[i].getKey(), inputParam); + Logger.msg(5, "Split.evaluateScript() - Setting param " + element.getKey() + " to " + inputParam.toString()); + script.setInputParamValue(element.getKey(), inputParam); } } - + if (requiredInput.containsKey("item")) { script.setInputParamValue("item", Gateway.getProxyManager().getProxy(entity)); } @@ -150,8 +149,8 @@ public abstract class WfVertex extends GraphableVertex throw new ScriptingEngineException(); } } - - private Script getScript(String name, String version) throws ScriptingEngineException + + private static Script getScript(String name, String version) throws ScriptingEngineException { Script script; try @@ -171,8 +170,8 @@ public abstract class WfVertex extends GraphableVertex return script; } - - + + public Workflow getWf() { return ((CompositeActivity)getParent()).getWf(); diff --git a/source/com/c2kernel/lifecycle/instance/Workflow.java b/source/com/c2kernel/lifecycle/instance/Workflow.java index 4c8aa94..1d12ee6 100644 --- a/source/com/c2kernel/lifecycle/instance/Workflow.java +++ b/source/com/c2kernel/lifecycle/instance/Workflow.java @@ -46,7 +46,7 @@ public class Workflow extends CompositeActivity implements C2KLocalObject { getProperties().put("ItemSystemKey", null); } - + public Workflow(CompositeActivity domain) { this(); domain.setName("domain"); @@ -54,10 +54,10 @@ public class Workflow extends CompositeActivity implements C2KLocalObject PredefinedStepContainer act = new PredefinedStepContainer(); addChild(act, new GraphPoint(300, 100)); } - + /** * Method getVertexTypeNameAndConstructionInfo. - * + * * @return TypeNameAndConstructionInfo[] */ /** getVertexTypeNameAndConstructionInfo() added by Steve */ @@ -67,7 +67,7 @@ public class Workflow extends CompositeActivity implements C2KLocalObject } /** * Method getEdgeTypeNameAndConstructionInfo. - * + * * @return TypeNameAndConstructionInfo[] */ /** getVertexTypeNameAndConstructionInfo() added by Steve */ @@ -77,7 +77,7 @@ public class Workflow extends CompositeActivity implements C2KLocalObject } /** * Method requestAction. - * + * * @param agentInfo * @param stepPath * @param transitionID @@ -101,6 +101,7 @@ public class Workflow extends CompositeActivity implements C2KLocalObject /** * @see com.c2kernel.graph.model.GraphableVertex#getPath() */ + @Override public String getPath() { return "workflow"; @@ -108,6 +109,7 @@ public class Workflow extends CompositeActivity implements C2KLocalObject /** * @see com.c2kernel.graph.model.Vertex#getName() */ + @Override public String getName() { return "workflow"; @@ -115,6 +117,7 @@ public class Workflow extends CompositeActivity implements C2KLocalObject /** * @see com.c2kernel.lifecycle.instance.Activity#getType() */ + @Override public String getType() { return "workflow"; @@ -122,12 +125,14 @@ public class Workflow extends CompositeActivity implements C2KLocalObject /** * @see com.c2kernel.graph.model.Vertex#setName(java.lang.String) */ + @Override public void setName(String name) { } /** * @see com.c2kernel.lifecycle.instance.WfVertex#verify() */ + @Override public boolean verify() { for (int i = 0; i < getChildren().length; i++) @@ -143,13 +148,14 @@ public class Workflow extends CompositeActivity implements C2KLocalObject /** * @see com.c2kernel.lifecycle.instance.Activity#getWf() */ + @Override public Workflow getWf() { return this; } /** * Method initialise. - * + * * @param systemKey */ public void initialise(int systemKey, AgentPath agent) @@ -166,7 +172,7 @@ public class Workflow extends CompositeActivity implements C2KLocalObject } /** * Method calculateJobs. - * + * * @param type * @return JobList */ @@ -185,6 +191,7 @@ public class Workflow extends CompositeActivity implements C2KLocalObject /** * @see com.c2kernel.lifecycle.instance.CompositeActivity#hasGoodNumberOfActivity() */ + @Override public boolean hasGoodNumberOfActivity() { return true; @@ -192,6 +199,7 @@ public class Workflow extends CompositeActivity implements C2KLocalObject /** * @see com.c2kernel.entity.C2KLocalObject#getClusterType() */ + @Override public String getClusterType() { return ClusterStorage.LIFECYCLE; diff --git a/source/com/c2kernel/lifecycle/instance/XOrSplit.java b/source/com/c2kernel/lifecycle/instance/XOrSplit.java index 108aa61..25baf0b 100644 --- a/source/com/c2kernel/lifecycle/instance/XOrSplit.java +++ b/source/com/c2kernel/lifecycle/instance/XOrSplit.java @@ -21,32 +21,32 @@ public class XOrSplit extends Split super(); } - public void runNext(AgentPath agent) throws ScriptingEngineException + @Override + public void runNext(AgentPath agent) throws ScriptingEngineException { ArrayList nextsToFollow = new ArrayList(); String nexts = this.evaluateScript( - (String) getProperties().get("RoutingScriptName"), + (String) getProperties().get("RoutingScriptName"), (String) getProperties().get("RoutingScriptVersion")).toString(); - + StringTokenizer tok = new StringTokenizer(nexts,","); String[] nextsTab = new String[tok.countTokens()]; for (int i=0;i hashMap) { String vertexTypeId = (String) hashMap.get("P1"); Point location = (Point) hashMap.get("P2"); @@ -69,7 +72,7 @@ public class WfVertexFactory implements VertexFactory, WorkflowDialogue Resource.getImageResource("graph/newvertex_large.png"), null, null); - if (newName == null || newName.equals("")) + if (newName.equals("")) return; } Activity act = null; @@ -80,7 +83,7 @@ public class WfVertexFactory implements VertexFactory, WorkflowDialogue } catch (Exception e) { - } + } if (act == null) mRootAct.newChild(unicName, vertexTypeId, location); else diff --git a/source/com/c2kernel/lifecycle/instance/gui/model/WfVertexOutlineCreator.java b/source/com/c2kernel/lifecycle/instance/gui/model/WfVertexOutlineCreator.java old mode 100755 new mode 100644 index dd4b8af..e8cb303 --- a/source/com/c2kernel/lifecycle/instance/gui/model/WfVertexOutlineCreator.java +++ b/source/com/c2kernel/lifecycle/instance/gui/model/WfVertexOutlineCreator.java @@ -14,7 +14,8 @@ public class WfVertexOutlineCreator implements VertexOutlineCreator,Serializable private final int mSplitJoinWidth = 60; private final int mSplitJoinHeight = 25; - public void setOutline(Vertex vertex) + @Override + public void setOutline(Vertex vertex) { GraphPoint centrePoint = vertex.getCentrePoint(); GraphPoint[] outlinePoints = new GraphPoint[ 4 ]; diff --git a/source/com/c2kernel/lifecycle/instance/gui/view/ActivityRenderer.java b/source/com/c2kernel/lifecycle/instance/gui/view/ActivityRenderer.java old mode 100755 new mode 100644 index a67b4fd..046ed7c --- a/source/com/c2kernel/lifecycle/instance/gui/view/ActivityRenderer.java +++ b/source/com/c2kernel/lifecycle/instance/gui/view/ActivityRenderer.java @@ -21,6 +21,7 @@ public class ActivityRenderer implements VertexRenderer private Paint mInactiveCompPaint = new Color(200, 200, 255); private Paint mErrorPaint = new Color(255, 50, 0); private Paint mTextPaint = Color.black; + @Override public void draw(Graphics2D g2d, Vertex vertex) { Activity activity = (Activity) vertex; @@ -28,7 +29,7 @@ public class ActivityRenderer implements VertexRenderer boolean hasError = !activity.verify(); boolean isComposite = activity.getIsComposite(); GraphPoint centrePoint = activity.getCentrePoint(); - String description = activity.getDescription(); + //String description = activity.getDescription(); String[] linesOfText = new String[3]; linesOfText[0] = "(" + activity.getType() + ")"; linesOfText[1] = activity.getName(); @@ -52,7 +53,7 @@ public class ActivityRenderer implements VertexRenderer else linesOfText[2] = Language.translate(States.getStateName(cs)); } - + FontMetrics metrics = g2d.getFontMetrics(); int lineWidth = 0; int lineHeight = metrics.getHeight(); @@ -86,7 +87,7 @@ public class ActivityRenderer implements VertexRenderer g2d.drawString(linesOfText[i], x, y); } } - private Polygon graphPointsToPolygon(GraphPoint[] points) + private static Polygon graphPointsToPolygon(GraphPoint[] points) { Polygon polygon = new Polygon(); int i = 0; @@ -96,7 +97,7 @@ public class ActivityRenderer implements VertexRenderer } return polygon; } - private String getWaitTime(GTimeStamp date) + private static String getWaitTime(GTimeStamp date) { GTimeStamp now = new GTimeStamp(); DateUtility.setToNow(now); diff --git a/source/com/c2kernel/lifecycle/instance/gui/view/FindActDefPanel.java b/source/com/c2kernel/lifecycle/instance/gui/view/FindActDefPanel.java old mode 100755 new mode 100644 index 5cb00bf..4c1a148 --- a/source/com/c2kernel/lifecycle/instance/gui/view/FindActDefPanel.java +++ b/source/com/c2kernel/lifecycle/instance/gui/view/FindActDefPanel.java @@ -33,7 +33,8 @@ public class FindActDefPanel extends SelectedVertexPanel { add(findButton); findButton.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) + @Override + public void actionPerformed(ActionEvent e) { try { DomainPath actPath = (DomainPath)new DomainPath("/desc/ActivityDesc/").find(currentAct.getActivityDef()); @@ -47,21 +48,23 @@ public class FindActDefPanel extends SelectedVertexPanel { * */ - public void select(Vertex vert) { + @Override + public void select(Vertex vert) { if (vert instanceof ActivitySlotDef) { findButton.setEnabled(true); currentAct = (ActivitySlotDef)vert; } - else + else clear(); - + } /** * */ - public void clear() { + @Override + public void clear() { findButton.setEnabled(false); currentAct = null; } diff --git a/source/com/c2kernel/lifecycle/instance/gui/view/SplitJoinRenderer.java b/source/com/c2kernel/lifecycle/instance/gui/view/SplitJoinRenderer.java old mode 100755 new mode 100644 index 4c3f8bf..036f79a --- a/source/com/c2kernel/lifecycle/instance/gui/view/SplitJoinRenderer.java +++ b/source/com/c2kernel/lifecycle/instance/gui/view/SplitJoinRenderer.java @@ -39,7 +39,8 @@ public class SplitJoinRenderer implements VertexRenderer private int mXXXTextXOffset = 0; - public void draw( Graphics2D g2d, Vertex vertex) + @Override + public void draw( Graphics2D g2d, Vertex vertex) { GraphPoint centrePoint = vertex.getCentrePoint(); String text = null; @@ -79,9 +80,9 @@ public class SplitJoinRenderer implements VertexRenderer textXOffset = mJoinTextXOffset; } else if ( vertex instanceof Join) - { + { String type= (String)((Join)vertex).getProperties().get("Type"); - if (type!=null && type.equals("Route")) + if (type!=null && type.equals("Route")) { text = mRouteText; textXOffset = mRouteTextXOffset; @@ -116,7 +117,7 @@ public class SplitJoinRenderer implements VertexRenderer vertexHeight ); g2d.drawString( text, centrePoint.x - textXOffset, centrePoint.y + mTextYOffset ); - + if (!hasErrors) { g2d.setPaint( mErrorPaint ); String errors = Language.translate(((WfVertex)vertex).getErrors()); diff --git a/source/com/c2kernel/lifecycle/instance/gui/view/TransitionPanel.java b/source/com/c2kernel/lifecycle/instance/gui/view/TransitionPanel.java index d33b717..32b234e 100644 --- a/source/com/c2kernel/lifecycle/instance/gui/view/TransitionPanel.java +++ b/source/com/c2kernel/lifecycle/instance/gui/view/TransitionPanel.java @@ -39,12 +39,12 @@ public class TransitionPanel extends SelectedVertexPanel implements ActionListen protected GridBagLayout gridbag; protected GridBagConstraints c; protected Box transBox; - protected JComboBox executors; + protected JComboBox executors; protected JComboBox states = new JComboBox(States.states); protected JCheckBox active = new JCheckBox(); protected JLabel status = new JLabel(); protected ItemProxy mItem; - + public TransitionPanel() { super(); gridbag = new GridBagLayout(); @@ -53,37 +53,37 @@ public class TransitionPanel extends SelectedVertexPanel implements ActionListen c.gridx=0; c.gridy=0; c.weightx=1; c.weighty=0; c.fill=GridBagConstraints.HORIZONTAL; - + JLabel title = new JLabel("Available Transitions"); title.setFont(EntityTabPane.titleFont); gridbag.setConstraints(title, c); add(title); - - c.gridy++; + + c.gridy++; gridbag.setConstraints(status, c); add(status); c.gridy++; - + transBox = Box.createHorizontalBox(); gridbag.setConstraints(transBox, c); add(transBox); - + c.weightx=0; c.gridx++; executors = MainFrame.getExecutionPlugins(); if (executors.getItemCount() > 1) { gridbag.setConstraints(executors, c); add(executors); } - - + + if (MainFrame.isAdmin) { c.gridx=0; c.gridy++; title = new JLabel("State Hacking"); title.setFont(EntityTabPane.titleFont); gridbag.setConstraints(title, c); add(title); - Box hackBox = Box.createHorizontalBox(); + Box hackBox = Box.createHorizontalBox(); hackBox.add(states); hackBox.add(Box.createHorizontalGlue()); hackBox.add(new JLabel("Active:")); @@ -94,14 +94,15 @@ public class TransitionPanel extends SelectedVertexPanel implements ActionListen states.addActionListener(this); active.addActionListener(this); } - + clear(); - + } /** * */ - public void select(Vertex vert) { + @Override + public void select(Vertex vert) { clear(); if (!(vert instanceof Activity)) return; mCurrentAct = (Activity)vert; @@ -129,8 +130,9 @@ public class TransitionPanel extends SelectedVertexPanel implements ActionListen } revalidate(); } - - public void actionPerformed(ActionEvent e) { + + @Override + public void actionPerformed(ActionEvent e) { if (e.getSource() == active && mCurrentAct != null) { mCurrentAct.active = active.isSelected(); return; @@ -142,14 +144,14 @@ public class TransitionPanel extends SelectedVertexPanel implements ActionListen if (!e.getActionCommand().startsWith("Trans:")) return; int transition = Integer.parseInt(e.getActionCommand().substring(6)); Logger.msg("Requesting transition "+transition); - Job thisJob = new Job(mItem.getSystemKey(), - mCurrentAct.getPath(), + Job thisJob = new Job(mItem.getSystemKey(), + mCurrentAct.getPath(), transition, new StateMachine(mCurrentAct).simulate(transition), mCurrentAct.getCurrentState(), mCurrentAct.getName(), mCurrentAct.getProperties(), - mCurrentAct.getType(), + mCurrentAct.getType(), MainFrame.userAgent.getName()); try { Executor selectedExecutor = (Executor)executors.getSelectedItem(); @@ -160,10 +162,11 @@ public class TransitionPanel extends SelectedVertexPanel implements ActionListen Logger.error(ex); JOptionPane.showMessageDialog(null, ex.getMessage(), className, JOptionPane.ERROR_MESSAGE); } - + } - public void clear() { + @Override + public void clear() { mCurrentAct = null; transBox.removeAll(); status.setText("No activity selected"); @@ -173,8 +176,8 @@ public class TransitionPanel extends SelectedVertexPanel implements ActionListen active.setEnabled(false); revalidate(); } - - + + /** * @param item The mItem to set. */ diff --git a/source/com/c2kernel/lifecycle/instance/gui/view/WfDirectedEdgeRenderer.java b/source/com/c2kernel/lifecycle/instance/gui/view/WfDirectedEdgeRenderer.java old mode 100755 new mode 100644 index 09dba77..f39d9a6 --- a/source/com/c2kernel/lifecycle/instance/gui/view/WfDirectedEdgeRenderer.java +++ b/source/com/c2kernel/lifecycle/instance/gui/view/WfDirectedEdgeRenderer.java @@ -4,6 +4,7 @@ import java.awt.Graphics2D; import java.awt.Shape; import java.awt.geom.AffineTransform; import java.awt.geom.GeneralPath; + import com.c2kernel.graph.model.DirectedEdge; import com.c2kernel.graph.model.GraphPoint; import com.c2kernel.graph.view.DirectedEdgeRenderer; @@ -17,6 +18,7 @@ public class WfDirectedEdgeRenderer implements DirectedEdgeRenderer mArrowTemplate.lineTo(0, 0); mArrowTemplate.lineTo(5, 5); } + @Override public void draw(Graphics2D g2d, DirectedEdge directedEdge) { GraphPoint originPoint = directedEdge.getOriginPoint(); @@ -87,7 +89,7 @@ public class WfDirectedEdgeRenderer implements DirectedEdgeRenderer if (text != null) g2d.drawString(text, midPoint.x + 10, midPoint.y); } - private double calcArrowAngle(int originX, int originY, int terminusX, int terminusY) + private static double calcArrowAngle(int originX, int originY, int terminusX, int terminusY) { double width = terminusX - originX; double height = terminusY - originY; diff --git a/source/com/c2kernel/lifecycle/instance/gui/view/WfVertexRenderer.java b/source/com/c2kernel/lifecycle/instance/gui/view/WfVertexRenderer.java old mode 100755 new mode 100644 index 1e731e0..92a1021 --- a/source/com/c2kernel/lifecycle/instance/gui/view/WfVertexRenderer.java +++ b/source/com/c2kernel/lifecycle/instance/gui/view/WfVertexRenderer.java @@ -13,7 +13,8 @@ public class WfVertexRenderer implements VertexRenderer protected ActivityRenderer mActivityRenderer = new ActivityRenderer(); protected SplitJoinRenderer mSplitJoinRenderer = new SplitJoinRenderer(); - public void draw( Graphics2D g2d, Vertex vertex) + @Override + public void draw( Graphics2D g2d, Vertex vertex) { if ( vertex instanceof Activity ) { mActivityRenderer.draw( g2d, vertex); } else if ( ( vertex instanceof Split ) || ( vertex instanceof Join ) ) { mSplitJoinRenderer.draw( g2d, vertex ); } diff --git a/source/com/c2kernel/lifecycle/instance/predefined/AddC2KObject.java b/source/com/c2kernel/lifecycle/instance/predefined/AddC2KObject.java old mode 100755 new mode 100644 index 27759be..b61187c --- a/source/com/c2kernel/lifecycle/instance/predefined/AddC2KObject.java +++ b/source/com/c2kernel/lifecycle/instance/predefined/AddC2KObject.java @@ -37,7 +37,8 @@ public class AddC2KObject extends PredefinedStep } //requestdata is xmlstring - public void request( AgentPath agent, int transitionID, String requestData) + @Override + public void request( AgentPath agent, int transitionID, String requestData) throws AccessRightsException, InvalidTransitionException, InvalidDataException @@ -54,7 +55,7 @@ public class AddC2KObject extends PredefinedStep { Logger.msg(5, "AddC2KObject::request() - data:" + getDataList(requestData)[0]); - + C2KLocalObject obj = (C2KLocalObject)CastorXMLUtility.unmarshall(getDataList(requestData)[0]); Gateway.getStorage().put(entityPath.getSysKey(), obj, null ); sendEventStoreOutcome(transitionID, requestData, agent); diff --git a/source/com/c2kernel/lifecycle/instance/predefined/AddDomainPath.java b/source/com/c2kernel/lifecycle/instance/predefined/AddDomainPath.java old mode 100755 new mode 100644 index 6756895..2cf619e --- a/source/com/c2kernel/lifecycle/instance/predefined/AddDomainPath.java +++ b/source/com/c2kernel/lifecycle/instance/predefined/AddDomainPath.java @@ -29,7 +29,8 @@ public class AddDomainPath extends PredefinedStep } //requestdata is xmlstring - public void request( AgentPath agent, int transitionID, String requestData) + @Override + public void request( AgentPath agent, int transitionID, String requestData) throws AccessRightsException, InvalidTransitionException, InvalidDataException diff --git a/source/com/c2kernel/lifecycle/instance/predefined/AddStepsFromDescription.java b/source/com/c2kernel/lifecycle/instance/predefined/AddStepsFromDescription.java old mode 100755 new mode 100644 index c4fab0c..f70c053 --- a/source/com/c2kernel/lifecycle/instance/predefined/AddStepsFromDescription.java +++ b/source/com/c2kernel/lifecycle/instance/predefined/AddStepsFromDescription.java @@ -21,6 +21,7 @@ public class AddStepsFromDescription extends PredefinedStep super(); } + @Override public void request( AgentPath agent, int transitionID, String requestData) throws AccessRightsException, InvalidTransitionException, InvalidDataException { diff --git a/source/com/c2kernel/lifecycle/instance/predefined/AssignItemToSlot.java b/source/com/c2kernel/lifecycle/instance/predefined/AssignItemToSlot.java old mode 100755 new mode 100644 index 88f89c3..40fe740 --- a/source/com/c2kernel/lifecycle/instance/predefined/AssignItemToSlot.java +++ b/source/com/c2kernel/lifecycle/instance/predefined/AssignItemToSlot.java @@ -11,7 +11,6 @@ package com.c2kernel.lifecycle.instance.predefined; -import java.util.Iterator; import com.c2kernel.collection.Collection; import com.c2kernel.collection.CollectionMember; @@ -41,14 +40,15 @@ public class AssignItemToSlot extends PredefinedStep super(); } - + /** * Params: * 0 - collection name * 1 - slot number * 2 - target entity key */ - public void request(AgentPath agent, int transitionID, String requestData) + @Override + public void request(AgentPath agent, int transitionID, String requestData) throws AccessRightsException, InvalidTransitionException, InvalidDataException @@ -57,35 +57,35 @@ public class AssignItemToSlot extends PredefinedStep String collName; int slotNo; int entityKey; - Collection coll; + Collection coll; Logger.msg(1, "AssignItemToSlot::request() - Starting."); checkAccessRights(agent); - + // extract parameters try { entityPath = getItemEntityPath(); String[] params = getDataList(requestData); collName = params[0]; slotNo = Integer.parseInt(params[1]); - entityKey = Integer.parseInt(params[2]); + entityKey = Integer.parseInt(params[2]); } catch (Exception e) { throw new InvalidDataException("Invalid parameters", ""); } - + // load collection try { - coll = (Collection)Gateway.getStorage().get(entityPath.getSysKey(), ClusterStorage.COLLECTION+"/"+collName, null); + coll = (Collection)Gateway.getStorage().get(entityPath.getSysKey(), ClusterStorage.COLLECTION+"/"+collName, null); } catch (Exception e) { Logger.error(e); throw new InvalidDataException("Error loading collection "+collName, ""); } - + // find member and assign entity boolean stored = false; - for (Iterator iter = coll.getMembers().list.iterator(); iter.hasNext();) { - CollectionMember member = (CollectionMember)iter.next(); + for (Object name : coll.getMembers().list) { + CollectionMember member = (CollectionMember)name; if (member.getID() == slotNo) { if (member.getEntityKey() > -1) throw new InvalidDataException("Member slot not empty", ""); @@ -101,8 +101,8 @@ public class AssignItemToSlot extends PredefinedStep if (!stored) { throw new InvalidDataException("Member slot "+slotNo+" not found.", ""); } - - + + try { Gateway.getStorage().put(entityPath.getSysKey(), coll, null); } catch (ClusterStorageException e) { diff --git a/source/com/c2kernel/lifecycle/instance/predefined/CreateItemFromDescription.java b/source/com/c2kernel/lifecycle/instance/predefined/CreateItemFromDescription.java index 7bedc81..ad92052 100644 --- a/source/com/c2kernel/lifecycle/instance/predefined/CreateItemFromDescription.java +++ b/source/com/c2kernel/lifecycle/instance/predefined/CreateItemFromDescription.java @@ -55,6 +55,7 @@ public class CreateItemFromDescription extends PredefinedStep } //requestdata is xmlstring + @Override public void request(AgentPath agent, int transitionID, String requestData) throws AccessRightsException, InvalidTransitionException, InvalidDataException,ObjectAlreadyExistsException { @@ -65,66 +66,66 @@ public class CreateItemFromDescription extends PredefinedStep String wfDefName = null; if (input.length > 2) // override wf wfDefName = input[2]; - + PropertyArrayList props = new PropertyArrayList(); Logger.msg(1, "AddNewItem::request() - Starting."); TransactionManager storage = Gateway.getStorage(); LDAPLookup lookup = Gateway.getLDAPLookup(); EntityPath myPath = getItemEntityPath(); checkAccessRights(agent); - + try { - // check if the path is already taken + // check if the path is already taken DomainPath context = new DomainPath(new DomainPath(domPath), newName); Logger.debug(8,"context "+context.getSysKey()+" "+context.getPath()+" "+context.getString()); - if (context.getSysKey()!=-1) - throw new ObjectAlreadyExistsException("The item name " +newName+ " exists already."); - + if (context.getSysKey()!=-1) + throw new ObjectAlreadyExistsException("The item name " +newName+ " exists already."); + // get init objects String[] collNames = storage.getClusterContents(myPath.getSysKey(), ClusterStorage.COLLECTION); ArrayList collections = new ArrayList(); - - + + // loop through collections to instantiate - for (int i = 0; i < collNames.length; i++) { - Collection thisCol = (Collection)storage.get(myPath.getSysKey(), ClusterStorage.COLLECTION+"/"+collNames[i], null); + for (String collName : collNames) { + Collection thisCol = (Collection)storage.get(myPath.getSysKey(), ClusterStorage.COLLECTION+"/"+collName, null); if (thisCol instanceof CollectionDescription) { - CollectionDescription thisDesc = (CollectionDescription)thisCol; - collections.add(CastorXMLUtility.marshall(thisDesc.newInstance())); + CollectionDescription thisDesc = (CollectionDescription)thisCol; + collections.add(CastorXMLUtility.marshall(thisDesc.newInstance())); } else if (thisCol.getName().equals("Workflow") && wfDefName == null) { - ArrayList members = thisCol.getMembers().list; + ArrayList members = thisCol.getMembers().list; // get the first member from the wf collection CollectionMember wfMember = (CollectionMember)members.get(0); wfDefName = wfMember.resolveEntity().getName(); } } - + // load workflow def if (wfDefName == null) throw new InvalidDataException("No workflow given or defined", ""); - + try { wfDef = (CompositeActivityDef)LocalObjectLoader.getActDef(wfDefName, "last"); } catch (ObjectNotFoundException ex) { - throw new InvalidDataException("Workflow def '"+wfDefName+"' item not found", ""); + throw new InvalidDataException("Workflow def '"+wfDefName+"' item not found", ""); } catch (ClassCastException ex) { throw new InvalidDataException("Activity def '"+wfDefName+"' was not Composite", ""); } - - + + // copy properties -- intend to create from propdesc PropertyDescriptionList pdList = PropertyUtility.getPropertyDescriptionOutcome(myPath.getSysKey()); for (int i = 0; i < pdList.list.size(); i++) { - PropertyDescription pd = (PropertyDescription) pdList.list.get(i); + PropertyDescription pd = pdList.list.get(i); String propName = pd.getName(); - String propVal = pd.getDefaultValue(); + String propVal = pd.getDefaultValue(); if (propName.equals("Name")) propVal = newName; - props.list.add( new Property(propName, propVal)); + props.list.add( new Property(propName, propVal)); } props.list.add( new Property("Creator", agent.getAgentName())); - + /* ITEM CREATION */ // generate new entity key @@ -132,8 +133,8 @@ public class CreateItemFromDescription extends PredefinedStep EntityPath entityPath = lookup.getNextKeyManager().generateNextEntityKey(); // resolve the item factory - Logger.msg(6, "CreateItemFromDescription - Resolving item factory"); - + Logger.msg(6, "CreateItemFromDescription - Resolving item factory"); + // create the Item object Logger.msg(3, "CreateItemFromDescription - Creating Item"); CorbaServer factory = Gateway.getCorbaServer(); @@ -141,26 +142,26 @@ public class CreateItemFromDescription extends PredefinedStep TraceableEntity newItem = (TraceableEntity)factory.createEntity(entityPath); Gateway.getLDAPLookup().add(entityPath); - + // initialise it with its properties and workflow - + Logger.msg(3, "CreateItemFromDescription - Initializing Item"); - + newItem.initialise( agent.getSysKey(), CastorXMLUtility.marshall(props), CastorXMLUtility.marshall(wfDef.instantiate())); - + // add collections if (collections.size() > 0) { Logger.msg(6, "CreateItemFromDescription - Adding Collections"); String[] colls = new String[1]; - for (Iterator iter = collections.iterator(); iter.hasNext();) { - colls[0] = (String)iter.next(); - newItem.requestAction(agent.getSysKey(), "workflow/predefined/AddC2KObject", Transitions.COMPLETE, PredefinedStep.bundleData(colls)); + for (Iterator iter = collections.iterator(); iter.hasNext();) { + colls[0] = iter.next(); + newItem.requestAction(agent.getSysKey(), "workflow/predefined/AddC2KObject", Transitions.COMPLETE, PredefinedStep.bundleData(colls)); } - } - + } + // add its domain path Logger.msg(3, "CreateItemFromDescription - Creating "+context); context.setEntity(entityPath); diff --git a/source/com/c2kernel/lifecycle/instance/predefined/Erase.java b/source/com/c2kernel/lifecycle/instance/predefined/Erase.java old mode 100755 new mode 100644 index 5c04f93..07d76b1 --- a/source/com/c2kernel/lifecycle/instance/predefined/Erase.java +++ b/source/com/c2kernel/lifecycle/instance/predefined/Erase.java @@ -40,7 +40,8 @@ public class Erase extends PredefinedStep } //requestdata is xmlstring - public void request(AgentPath agent, int transitionID, String requestData) + @Override + public void request(AgentPath agent, int transitionID, String requestData) throws AccessRightsException, InvalidTransitionException, InvalidDataException @@ -51,22 +52,22 @@ public class Erase extends PredefinedStep try { EntityPath entityPath = getItemEntityPath(); - + // find entity name Property name = (Property)Gateway.getStorage().get(entityPath.getSysKey(), ClusterStorage.PROPERTY+"/Name", null); - + // get all domain paths - Enumeration domPaths = Gateway.getLDAPLookup().search(new DomainPath(), name.getValue()); + Enumeration domPaths = Gateway.getLDAPLookup().search(new DomainPath(), name.getValue()); while (domPaths.hasMoreElements()) { DomainPath path = (DomainPath)domPaths.nextElement(); // delete them if (path.getSysKey() == entityPath.getSysKey()) Gateway.getLDAPLookup().delete(path); } - + //clear out all storages Gateway.getStorage().removeCluster(entityPath.getSysKey(), "", null); - + //remove domain path Gateway.getLDAPLookup().delete(entityPath); } diff --git a/source/com/c2kernel/lifecycle/instance/predefined/Import.java b/source/com/c2kernel/lifecycle/instance/predefined/Import.java old mode 100755 new mode 100644 index 36b7fc9..2f99937 --- a/source/com/c2kernel/lifecycle/instance/predefined/Import.java +++ b/source/com/c2kernel/lifecycle/instance/predefined/Import.java @@ -7,7 +7,9 @@ package com.c2kernel.lifecycle.instance.predefined; -import com.c2kernel.common.*; +import com.c2kernel.common.AccessRightsException; +import com.c2kernel.common.InvalidDataException; +import com.c2kernel.common.InvalidTransitionException; import com.c2kernel.lookup.AgentPath; import com.c2kernel.utils.Logger; @@ -15,7 +17,7 @@ import com.c2kernel.utils.Logger; * * $Revision: 1.21 $ * $Date: 2005/06/02 12:17:22 $ - * + * * Params: Schemaname_version:Viewpoint (optional), Outcome * * Copyright (C) 2003 CERN - European Organization for Nuclear Research @@ -29,7 +31,8 @@ public class Import extends PredefinedStep } //requestdata is xmlstring - public void request( AgentPath agent, int transitionID, String requestData) + @Override + public void request( AgentPath agent, int transitionID, String requestData) throws AccessRightsException, InvalidTransitionException, InvalidDataException @@ -41,11 +44,11 @@ public class Import extends PredefinedStep checkAccessRights(agent); String[] params = getDataList(requestData); - - + + int split1 = params[0].indexOf('_'); int split2 = params[0].indexOf(':'); - + String schemaName = params[0].substring(0, split1); String viewpoint = "last"; int schemaVersion; @@ -55,14 +58,14 @@ public class Import extends PredefinedStep } else schemaVersion = Integer.parseInt(params[0].substring(split1+1)); - + // set type & ver getProperties().put("SchemaType", schemaName); getProperties().put("SchemaVersion", String.valueOf(schemaVersion)); getProperties().put("Viewpoint", viewpoint); - + requestData = params[1]; - + sendEventStoreOutcome(transitionID, requestData, agent); } } diff --git a/source/com/c2kernel/lifecycle/instance/predefined/PredefinedStep.java b/source/com/c2kernel/lifecycle/instance/predefined/PredefinedStep.java old mode 100755 new mode 100644 index 8d95438..8aec993 --- a/source/com/c2kernel/lifecycle/instance/predefined/PredefinedStep.java +++ b/source/com/c2kernel/lifecycle/instance/predefined/PredefinedStep.java @@ -1,8 +1,10 @@ package com.c2kernel.lifecycle.instance.predefined; import java.io.StringReader; import java.io.StringWriter; + import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; + import org.apache.xml.serialize.Method; import org.apache.xml.serialize.OutputFormat; import org.apache.xml.serialize.XMLSerializer; @@ -13,6 +15,7 @@ import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import org.xml.sax.InputSource; + import com.c2kernel.lifecycle.instance.Activity; import com.c2kernel.utils.Logger; /*********************************************************************************************************************************************************************************************************************************************************************************************************** @@ -25,6 +28,7 @@ public class PredefinedStep extends Activity * predefined Steps are always Active, and have only one transition subclasses could override this method (if necessary) ******************************************************************************************************************************************************************************************************************************************************************************************************/ private boolean isPredefined = false; + @Override public boolean getActive() { if (isPredefined) @@ -32,6 +36,7 @@ public class PredefinedStep extends Activity else return super.getActive(); } + @Override public String getTransitions() { if (isPredefined) @@ -39,6 +44,7 @@ public class PredefinedStep extends Activity else return super.getTransitions(); } + @Override public String getErrors() { if (isPredefined) @@ -46,6 +52,7 @@ public class PredefinedStep extends Activity else return super.getErrors(); } + @Override public boolean verify() { if (isPredefined) @@ -55,7 +62,7 @@ public class PredefinedStep extends Activity } /** * Returns the isPredefined. - * + * * @return boolean */ public boolean getIsPredefined() @@ -64,7 +71,7 @@ public class PredefinedStep extends Activity } /** * Sets the isPredefined. - * + * * @param isPredefined * The isPredefined to set */ @@ -72,6 +79,7 @@ public class PredefinedStep extends Activity { this.isPredefined = isPredefined; } + @Override public String getType() { return getName(); @@ -86,10 +94,9 @@ public class PredefinedStep extends Activity Document dom = builder.newDocument(); Element root = dom.createElement("PredefinedStepOutcome"); dom.appendChild(root); - for (int i = 0; i < data.length; i++) - { + for (String element : data) { Element param = dom.createElement("param"); - Text t = dom.createTextNode(data[i]); + Text t = dom.createTextNode(element); param.appendChild(t); root.appendChild(param); } @@ -104,15 +111,15 @@ public class PredefinedStep extends Activity StringWriter stringOut = new StringWriter(); XMLSerializer serial = new XMLSerializer(stringOut, format); serial.asDOMSerializer(); - serial.serialize(dom); + serial.serialize(dom); return stringOut.toString(); } catch (Exception e) { Logger.error(e); StringBuffer xmlData = new StringBuffer().append(""); - for (int i = 0; i < data.length; i++) - xmlData.append(""); + for (String element : data) + xmlData.append(""); xmlData.append(""); return xmlData.toString(); } @@ -130,7 +137,7 @@ public class PredefinedStep extends Activity NodeList nodeList = scriptDoc.getElementsByTagName("param"); String[] result = new String[nodeList.getLength()]; for (int i = 0; i < nodeList.getLength(); i++) - { + { Node n = nodeList.item(i).getFirstChild(); if (n instanceof CDATASection) result[i] = ((CDATASection) n).getData(); diff --git a/source/com/c2kernel/lifecycle/instance/predefined/PredefinedStepContainer.java b/source/com/c2kernel/lifecycle/instance/predefined/PredefinedStepContainer.java old mode 100755 new mode 100644 index 10a9d12..d065afb --- a/source/com/c2kernel/lifecycle/instance/predefined/PredefinedStepContainer.java +++ b/source/com/c2kernel/lifecycle/instance/predefined/PredefinedStepContainer.java @@ -4,12 +4,12 @@ import com.c2kernel.lifecycle.instance.CompositeActivity; public class PredefinedStepContainer extends CompositeActivity { protected int num = 0; - + public PredefinedStepContainer() { super(); setName("predefined"); - getProperties().put("Description", "Contains all predefined Steps"); + getProperties().put("Description", "Contains all predefined Steps"); createChildren(); } public void createChildren() @@ -26,7 +26,7 @@ public class PredefinedStepContainer extends CompositeActivity predInit("Erase", "Deletes all objects and domain paths for this item.", new Erase()); predInit("Import", "Imports an outcome into the Item, with a given schema and viewpoint", new Import()); } - + public void predInit(String alias, String Description, PredefinedStep act) { act.setName(alias); @@ -38,18 +38,22 @@ public class PredefinedStepContainer extends CompositeActivity act.setIsPredefined(true); addChild(act, new GraphPoint(100, 75 * ++num)); } + @Override public boolean verify() { return true; } + @Override public String getErrors() { return "predefined"; } + @Override public boolean getActive() { return true; } + @Override public String getTransitions() { return ""; diff --git a/source/com/c2kernel/lifecycle/instance/predefined/RemoveC2KObject.java b/source/com/c2kernel/lifecycle/instance/predefined/RemoveC2KObject.java old mode 100755 new mode 100644 index 8004488..c9513a8 --- a/source/com/c2kernel/lifecycle/instance/predefined/RemoveC2KObject.java +++ b/source/com/c2kernel/lifecycle/instance/predefined/RemoveC2KObject.java @@ -35,7 +35,8 @@ public class RemoveC2KObject extends PredefinedStep } //requestdata is xmlstring - public void request(AgentPath agent, int transitionID, String requestData) + @Override + public void request(AgentPath agent, int transitionID, String requestData) throws AccessRightsException, InvalidTransitionException, InvalidDataException @@ -51,7 +52,7 @@ public class RemoveC2KObject extends PredefinedStep Logger.msg(5, "RemoveC2KObject::request() - path:"+path); - Gateway.getStorage().remove( entityPath.getSysKey(), path, null ); + Gateway.getStorage().remove( entityPath.getSysKey(), path, null ); sendEventStoreOutcome(transitionID, requestData, agent); } catch( Exception ex ) diff --git a/source/com/c2kernel/lifecycle/instance/predefined/RemoveDomainPath.java b/source/com/c2kernel/lifecycle/instance/predefined/RemoveDomainPath.java old mode 100755 new mode 100644 index af118e5..19ff7c6 --- a/source/com/c2kernel/lifecycle/instance/predefined/RemoveDomainPath.java +++ b/source/com/c2kernel/lifecycle/instance/predefined/RemoveDomainPath.java @@ -27,7 +27,8 @@ public class RemoveDomainPath extends PredefinedStep } //requestdata is xmlstring - public void request( AgentPath agent, int transitionID, String requestData) + @Override + public void request( AgentPath agent, int transitionID, String requestData) throws AccessRightsException, InvalidTransitionException, InvalidDataException diff --git a/source/com/c2kernel/lifecycle/instance/predefined/ReplaceDomainWorkflow.java b/source/com/c2kernel/lifecycle/instance/predefined/ReplaceDomainWorkflow.java old mode 100755 new mode 100644 index e8c6a6f..ba3e6c6 --- a/source/com/c2kernel/lifecycle/instance/predefined/ReplaceDomainWorkflow.java +++ b/source/com/c2kernel/lifecycle/instance/predefined/ReplaceDomainWorkflow.java @@ -20,6 +20,7 @@ public class ReplaceDomainWorkflow extends PredefinedStep super(); } + @Override public void request( AgentPath agent, int transitionID, String requestData) throws AccessRightsException, InvalidTransitionException, InvalidDataException { diff --git a/source/com/c2kernel/lifecycle/instance/predefined/ServerPredefinedStepContainer.java b/source/com/c2kernel/lifecycle/instance/predefined/ServerPredefinedStepContainer.java old mode 100755 new mode 100644 index 363d1fc..21eacda --- a/source/com/c2kernel/lifecycle/instance/predefined/ServerPredefinedStepContainer.java +++ b/source/com/c2kernel/lifecycle/instance/predefined/ServerPredefinedStepContainer.java @@ -17,13 +17,14 @@ import com.c2kernel.lifecycle.instance.predefined.entitycreation.CreateNewItem; public class ServerPredefinedStepContainer extends PredefinedStepContainer { - public void createChildren() + @Override + public void createChildren() { super.createChildren(); serverPredInit("CreateNewItem", "Creates a new Item in this Server without description.", new CreateNewItem(), "NewItem"); serverPredInit("CreateNewAgent", "Creates a new Item in this Server without description.", new CreateNewAgent(), "NewAgent"); } - + public void serverPredInit(String alias, String Description, PredefinedStep act, String schema) { act.setName(alias); diff --git a/source/com/c2kernel/lifecycle/instance/predefined/WriteProperty.java b/source/com/c2kernel/lifecycle/instance/predefined/WriteProperty.java old mode 100755 new mode 100644 index da526a2..77a0b43 --- a/source/com/c2kernel/lifecycle/instance/predefined/WriteProperty.java +++ b/source/com/c2kernel/lifecycle/instance/predefined/WriteProperty.java @@ -36,7 +36,8 @@ public class WriteProperty extends PredefinedStep } //requestdata is xmlstring - public void request( AgentPath agent, int transitionID, String requestData) + @Override + public void request( AgentPath agent, int transitionID, String requestData) throws AccessRightsException, InvalidTransitionException, InvalidDataException @@ -56,7 +57,7 @@ public class WriteProperty extends PredefinedStep { Logger.msg(5, "WriteProperty::request() - name:" + params[0] +" val:"+params[1]); - + Property newProp = new Property(params[0], params[1]); Gateway.getStorage().put(entityPath.getSysKey(), newProp, null ); sendEventStoreOutcome(transitionID, requestData, agent); diff --git a/source/com/c2kernel/lifecycle/instance/predefined/entitycreation/Aggregation.java b/source/com/c2kernel/lifecycle/instance/predefined/entitycreation/Aggregation.java index 3677220..073d662 100644 --- a/source/com/c2kernel/lifecycle/instance/predefined/entitycreation/Aggregation.java +++ b/source/com/c2kernel/lifecycle/instance/predefined/entitycreation/Aggregation.java @@ -5,20 +5,20 @@ import java.util.ArrayList; public class Aggregation implements java.io.Serializable { public boolean isDescription; - public ArrayList aggregationMemberList; + public ArrayList aggregationMemberList; public String name; public Aggregation() { super(); - aggregationMemberList = new ArrayList(); - } - + aggregationMemberList = new ArrayList(); + } + public Aggregation(String name, boolean isDescription) { this(); this.name = name; this.isDescription = isDescription; } - + public com.c2kernel.collection.Aggregation create() { return new com.c2kernel.collection.AggregationInstance(); } diff --git a/source/com/c2kernel/lifecycle/instance/predefined/entitycreation/AggregationMember.java b/source/com/c2kernel/lifecycle/instance/predefined/entitycreation/AggregationMember.java old mode 100755 new mode 100644 index 87baa1d..29d3cf9 --- a/source/com/c2kernel/lifecycle/instance/predefined/entitycreation/AggregationMember.java +++ b/source/com/c2kernel/lifecycle/instance/predefined/entitycreation/AggregationMember.java @@ -11,7 +11,7 @@ public class AggregationMember implements java.io.Serializable { public AggregationMember() { super(); } - + public AggregationMember(int slotNo, String itemDescPath, String itemPath, Geometry geometry) { this.slotNo = slotNo; this.itemDescriptionPath = itemDescPath; diff --git a/source/com/c2kernel/lifecycle/instance/predefined/entitycreation/CreateNewAgent.java b/source/com/c2kernel/lifecycle/instance/predefined/entitycreation/CreateNewAgent.java old mode 100755 new mode 100644 index b0eaaec..96371dd --- a/source/com/c2kernel/lifecycle/instance/predefined/entitycreation/CreateNewAgent.java +++ b/source/com/c2kernel/lifecycle/instance/predefined/entitycreation/CreateNewAgent.java @@ -26,7 +26,8 @@ public class CreateNewAgent extends PredefinedStep } //requestdata is xmlstring - public void request( AgentPath agent, int transitionID, String requestData) + @Override + public void request( AgentPath agent, int transitionID, String requestData) throws AccessRightsException, InvalidTransitionException, InvalidDataException diff --git a/source/com/c2kernel/lifecycle/instance/predefined/entitycreation/CreateNewItem.java b/source/com/c2kernel/lifecycle/instance/predefined/entitycreation/CreateNewItem.java old mode 100755 new mode 100644 index 49f8ada..a66b062 --- a/source/com/c2kernel/lifecycle/instance/predefined/entitycreation/CreateNewItem.java +++ b/source/com/c2kernel/lifecycle/instance/predefined/entitycreation/CreateNewItem.java @@ -26,7 +26,8 @@ public class CreateNewItem extends PredefinedStep } //requestdata is xmlstring - public void request( AgentPath agent, int transitionID, String requestData) + @Override + public void request( AgentPath agent, int transitionID, String requestData) throws AccessRightsException, InvalidTransitionException, InvalidDataException diff --git a/source/com/c2kernel/lifecycle/instance/predefined/entitycreation/Dependency.java b/source/com/c2kernel/lifecycle/instance/predefined/entitycreation/Dependency.java old mode 100755 new mode 100644 index 0896534..311c108 --- a/source/com/c2kernel/lifecycle/instance/predefined/entitycreation/Dependency.java +++ b/source/com/c2kernel/lifecycle/instance/predefined/entitycreation/Dependency.java @@ -1,7 +1,6 @@ package com.c2kernel.lifecycle.instance.predefined.entitycreation; import java.util.ArrayList; -import java.util.Iterator; import com.c2kernel.collection.MembershipException; import com.c2kernel.lookup.DomainPath; @@ -12,13 +11,13 @@ public class Dependency implements java.io.Serializable { public String name; public boolean isDescription; public String itemDescriptionPath; - public ArrayList dependencyMemberList; + public ArrayList dependencyMemberList; public Dependency() { super(); - dependencyMemberList = new ArrayList(); - } - + dependencyMemberList = new ArrayList(); + } + public Dependency(String itemDesc) { this(); this.itemDescriptionPath = itemDesc; @@ -33,8 +32,8 @@ public class Dependency implements java.io.Serializable { PropertyUtility.getPropertyDescriptionOutcome(new DomainPath(itemDescriptionPath).getSysKey()); //TODO: set props and class identifiers } - for (Iterator mems = dependencyMemberList.iterator(); mems.hasNext();) { - DependencyMember thisMem = (DependencyMember) mems.next(); + for (Object name2 : dependencyMemberList) { + DependencyMember thisMem = (DependencyMember) name2; int syskey = new DomainPath(thisMem.itemPath).getSysKey(); if (syskey == -1) throw new MembershipException("Cannot find "+thisMem.itemPath+" specified for collection."); diff --git a/source/com/c2kernel/lifecycle/instance/predefined/entitycreation/DependencyMember.java b/source/com/c2kernel/lifecycle/instance/predefined/entitycreation/DependencyMember.java old mode 100755 new mode 100644 index 00ac445..b70619f --- a/source/com/c2kernel/lifecycle/instance/predefined/entitycreation/DependencyMember.java +++ b/source/com/c2kernel/lifecycle/instance/predefined/entitycreation/DependencyMember.java @@ -9,10 +9,10 @@ public class DependencyMember implements java.io.Serializable { public DependencyMember() { super(); } - + public DependencyMember(String itemPath) { this.itemPath = itemPath; - + } } diff --git a/source/com/c2kernel/lifecycle/instance/predefined/entitycreation/Geometry.java b/source/com/c2kernel/lifecycle/instance/predefined/entitycreation/Geometry.java old mode 100755 new mode 100644 index 25a1455..f18b6d4 --- a/source/com/c2kernel/lifecycle/instance/predefined/entitycreation/Geometry.java +++ b/source/com/c2kernel/lifecycle/instance/predefined/entitycreation/Geometry.java @@ -25,5 +25,5 @@ public class Geometry implements java.io.Serializable { this.width = width; this.height = height; } - + } diff --git a/source/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewAgent.java b/source/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewAgent.java old mode 100755 new mode 100644 index fa575a3..30b80c4 --- a/source/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewAgent.java +++ b/source/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewAgent.java @@ -2,7 +2,6 @@ package com.c2kernel.lifecycle.instance.predefined.entitycreation; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; -import java.util.Iterator; import com.c2kernel.common.CannotManageException; import com.c2kernel.common.ObjectAlreadyExistsException; @@ -21,19 +20,19 @@ public class NewAgent implements java.io.Serializable { public String name; public String password; - - public ArrayList roles; + + public ArrayList roles; public NewAgent() { super(); - roles = new ArrayList(); - } - + roles = new ArrayList(); + } + public NewAgent(String name, String password) { this.name = name; this.password = password; } - + protected void create(int agentId) throws ObjectNotFoundException, ObjectCannotBeUpdated, NoSuchAlgorithmException, CannotManageException, ObjectAlreadyExistsException { AgentPath newAgent = Gateway.getLDAPLookup().getNextKeyManager().generateNextAgentKey(); newAgent.setAgentName(name); @@ -50,8 +49,8 @@ public class NewAgent implements java.io.Serializable { Logger.error(ex); throw new CannotManageException("Error initialising new agent"); } - for (Iterator iter = roles.iterator(); iter.hasNext();) { - String role = (String) iter.next(); + for (Object name2 : roles) { + String role = (String) name2; RolePath thisRole; try { thisRole = Gateway.getLDAPLookup().getRoleManager().getRolePath(role); @@ -60,6 +59,6 @@ public class NewAgent implements java.io.Serializable { } thisRole.addAgent(newAgent); } - + } } diff --git a/source/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewItem.java b/source/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewItem.java index 32ca623..339e294 100644 --- a/source/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewItem.java +++ b/source/com/c2kernel/lifecycle/instance/predefined/entitycreation/NewItem.java @@ -2,7 +2,6 @@ package com.c2kernel.lifecycle.instance.predefined.entitycreation; import java.util.ArrayList; -import java.util.Iterator; import com.c2kernel.collection.MembershipException; import com.c2kernel.common.CannotManageException; @@ -22,7 +21,7 @@ import com.c2kernel.utils.Logger; /** * Complete Structure for new item - * + * * @version $Revision: 1.8 $ $Date: 2006/03/03 13:52:21 $ */ public class NewItem { @@ -48,31 +47,30 @@ public class NewItem { /** * Field _aggregationList */ - public ArrayList aggregationList; + public ArrayList aggregationList; /** * Field _dependencyList */ - public ArrayList dependencyList; + public ArrayList dependencyList; public NewItem() { super(); propertyList = new ArrayList(); - aggregationList = new ArrayList(); - dependencyList = new ArrayList(); + aggregationList = new ArrayList(); + dependencyList = new ArrayList(); } - + public NewItem(String name, String initialPath, String wf) { this(); this.name = name; this.initialPath = initialPath; this.workflow = wf; } - + public void setProperty(String name, String value) { - for (Iterator iter = propertyList.iterator(); iter.hasNext();) { - Property prop = (Property) iter.next(); + for (Property prop : propertyList) { if (prop.name.equals(name)) { prop.value = value; return; @@ -80,30 +78,29 @@ public class NewItem { } propertyList.add(new Property(name, value)); } - + protected void create(int agentId) throws ObjectCannotBeUpdated, ObjectNotFoundException, CannotManageException, ObjectAlreadyExistsException { DomainPath domPath = new DomainPath(new DomainPath(initialPath), name); if (domPath.exists()) throw new ObjectAlreadyExistsException(domPath+" already exists!", ""); - + // create item EntityPath entPath = Gateway.getLDAPLookup().getNextKeyManager().generateNextEntityKey(); TraceableEntity newItem = (TraceableEntity)Gateway.getCorbaServer().createEntity(entPath); Gateway.getLDAPLookup().add(entPath); - + // assemble properties PropertyArrayList propList = new PropertyArrayList(); propList.list.add(new com.c2kernel.property.Property("Name", name)); - for (Iterator iter = propertyList.iterator(); iter.hasNext();) { - Property element = (Property) iter.next(); + for (Property element : propertyList) { propList.list.add(new com.c2kernel.property.Property(element.name, element.value)); } // init the new item try { - + // find workflow def CompositeActivityDef compact = (CompositeActivityDef)LocalObjectLoader.getActDef(workflow, "last"); - + newItem.initialise( agentId, CastorXMLUtility.marshall(propList), @@ -113,11 +110,11 @@ public class NewItem { Logger.error(ex); throw new CannotManageException("Problem initialising new item. See server log.", ""); } - + // create collections - - for (Iterator iter = dependencyList.iterator(); iter.hasNext();) { - Dependency element = (Dependency) iter.next(); + + for (Object name2 : dependencyList) { + Dependency element = (Dependency) name2; try { Gateway.getStorage().put(entPath.getSysKey(), element.create(), null); } catch (ClusterStorageException ex) { @@ -128,9 +125,9 @@ public class NewItem { throw new CannotManageException("A specified member is not of the correct type in "+element.name, ""); } } - - for (Iterator iter = aggregationList.iterator(); iter.hasNext();) { - Aggregation element = (Aggregation) iter.next(); + + for (Object name2 : aggregationList) { + Aggregation element = (Aggregation) name2; try { Gateway.getStorage().put(entPath.getSysKey(), element.create(), null); } catch (ClusterStorageException ex) { @@ -140,6 +137,6 @@ public class NewItem { } // register domain path domPath.setEntity(entPath); - Gateway.getLDAPLookup().add(domPath); + Gateway.getLDAPLookup().add(domPath); } } diff --git a/source/com/c2kernel/lifecycle/instance/predefined/entitycreation/Property.java b/source/com/c2kernel/lifecycle/instance/predefined/entitycreation/Property.java old mode 100755 new mode 100644 index d99a3e3..e2d214c --- a/source/com/c2kernel/lifecycle/instance/predefined/entitycreation/Property.java +++ b/source/com/c2kernel/lifecycle/instance/predefined/entitycreation/Property.java @@ -1,7 +1,7 @@ package com.c2kernel.lifecycle.instance.predefined.entitycreation; /** * New Properties for the item - * + * * @version $Revision: 1.1 $ $Date: 2005/04/28 13:48:26 $ */ public class Property implements java.io.Serializable { diff --git a/source/com/c2kernel/lifecycle/instance/stateMachine/StateMachine.java b/source/com/c2kernel/lifecycle/instance/stateMachine/StateMachine.java old mode 100755 new mode 100644 index da7419c..8159106 --- a/source/com/c2kernel/lifecycle/instance/stateMachine/StateMachine.java +++ b/source/com/c2kernel/lifecycle/instance/stateMachine/StateMachine.java @@ -15,12 +15,12 @@ public class StateMachine implements Serializable { public int state = 0; private Activity activity; - + public static final String SKIPPABLE = "Skippable"; public static final String REPEATABLE = "Repeatable"; public static final String IGNORABLE = "Ignorable"; public static final String AUTOSTART = "Autostart"; - + /** * Method StateMachine. @@ -28,11 +28,11 @@ public class StateMachine implements Serializable */ public StateMachine(Activity act) { - activity = act; + activity = act; } - + /** row : States from (WAITING,RESERVED,STARTED,SUSPENDED,FINISHED,RWAITING,RRESERVED,RSTARTED,RSUSPENDED) - * collumn : transition (RESERVE,START,SKIP,DONE,COMPLETE,SUSPEND,REASIGN,RESUME,REPEAT,IGNORE,PROCEED) + * collumn : transition (RESERVE,START,SKIP,DONE,COMPLETE,SUSPEND,REASIGN,RESUME,REPEAT,IGNORE,PROCEED) * cell : State that is reached (-1 if transition not allowed) */ private int[][] getCurrentMachine() @@ -49,14 +49,14 @@ public class StateMachine implements Serializable /*7 RSTARTED*/ { -1, -1, -1, -1, 4, 8, -1, -1, -1,getIgnorable()?5:-1, -1},/*7 RSTARTED*/ /*8 RSUSPENDED*/ { -1, -1, -1, -1, -1, -1, 8, 7, -1, -1, -1} /*8 RSUSPENDED*/ }; - return returnArray; + return returnArray; } /** * @see java.lang.Object#Object() */ public StateMachine() - { + { } /** @@ -77,10 +77,10 @@ public class StateMachine implements Serializable int[] trans = new int[9]; int cmpt = 0; for (int i=0; i< getCurrentMachine()[state].length;i++) - if (getCurrentMachine()[state][i]!=-1) trans[cmpt++]=i; - + if (getCurrentMachine()[state][i]!=-1) trans[cmpt++]=i; + int [] result = new int[cmpt]; - for (int i=0;i -1) { - state=newState; + state=newState; return true; } Logger.msg("StateMachine.traverse() - Illegal transition "+Transitions.getTransitionName(transition)+" from "+States.getStateName(state)); @@ -138,5 +138,5 @@ public class StateMachine implements Serializable { return activity.getActive(); } - + } diff --git a/source/com/c2kernel/lifecycle/instance/stateMachine/States.java b/source/com/c2kernel/lifecycle/instance/stateMachine/States.java old mode 100755 new mode 100644 index 638a7b0..b142e35 --- a/source/com/c2kernel/lifecycle/instance/stateMachine/States.java +++ b/source/com/c2kernel/lifecycle/instance/stateMachine/States.java @@ -20,7 +20,7 @@ public class States public final static int RRESERVED = 6; public final static int RSTARTED = 7; public final static int RSUSPENDED = 8; - + //everything less that this constant is NOT a repeating state public final static int REPEATSTATESTART = 5; diff --git a/source/com/c2kernel/lifecycle/instance/stateMachine/Transitions.java b/source/com/c2kernel/lifecycle/instance/stateMachine/Transitions.java old mode 100755 new mode 100644 index 6597686..4239baa --- a/source/com/c2kernel/lifecycle/instance/stateMachine/Transitions.java +++ b/source/com/c2kernel/lifecycle/instance/stateMachine/Transitions.java @@ -26,11 +26,11 @@ public class Transitions public final static int ACTIVATION = 11; private static String[] transitions = { "reserve", "start", "skip", "done", "complete", "suspend", "reassign", "resume", "repeat","ignore","proceed","activation" }; - + public static String getTransitionName(int trans) { try - { + { return Language.translate(transitions[trans]); } catch (ArrayIndexOutOfBoundsException ex) diff --git a/source/com/c2kernel/lifecycle/routingHelpers/ViewpointDataHelper.java b/source/com/c2kernel/lifecycle/routingHelpers/ViewpointDataHelper.java old mode 100755 new mode 100644 index 754bd8f..0258347 --- a/source/com/c2kernel/lifecycle/routingHelpers/ViewpointDataHelper.java +++ b/source/com/c2kernel/lifecycle/routingHelpers/ViewpointDataHelper.java @@ -34,7 +34,7 @@ public class ViewpointDataHelper String viewpoint; String xpath; Object[] retArr; - + // find syskey, viewname, xpath int firstSlash = value.indexOf("/"); if (firstSlash > 0) { @@ -49,16 +49,16 @@ public class ViewpointDataHelper } } else return errArr; - + // find entity EntityPath sourcePath; - try + try { sourcePath = new EntityPath(Integer.parseInt(entityPath)); } catch (Exception e) { sourcePath = new EntityPath(entityPath); } - + try { // load viewpoint ItemProxy dataSource = (ItemProxy)Gateway.getProxyManager().getProxy(sourcePath); @@ -71,7 +71,7 @@ public class ViewpointDataHelper else retArr = XmlElementParser.parse(outcome.getData(), xpath); return retArr; - + } catch (ObjectNotFoundException e) { return errArr; } diff --git a/source/com/c2kernel/lookup/AgentPath.java b/source/com/c2kernel/lookup/AgentPath.java old mode 100755 new mode 100644 index 01c764f..5ff6988 --- a/source/com/c2kernel/lookup/AgentPath.java +++ b/source/com/c2kernel/lookup/AgentPath.java @@ -31,26 +31,26 @@ import com.novell.ldap.LDAPEntry; **/ public class AgentPath extends EntityPath { - + private String mAgentName=null; private String mPassword=null; - - public AgentPath(int syskey, String agentName) - throws InvalidAgentPathException,InvalidEntityPathException + + public AgentPath(int syskey, String agentName) + throws InvalidAgentPathException,InvalidEntityPathException { super(syskey); if (agentName!=null && agentName.length()>0) setAgentName(agentName); - else + else throw new InvalidAgentPathException(); } - + public AgentPath(int syskey) - throws InvalidEntityPathException + throws InvalidEntityPathException { super(syskey); } - + public AgentPath(EntityPath entity) { super(); try { @@ -59,7 +59,7 @@ public class AgentPath extends EntityPath //won't happen as the entity path was valid } } - + public void setAgentName(String agentID) { mAgentName = agentID; @@ -75,19 +75,19 @@ public class AgentPath extends EntityPath } catch (ObjectNotFoundException e) { mAgentName = ""; } - } + } return mAgentName; } public RolePath[] getRoles() { - return Gateway.getLDAPLookup().getRoleManager().getRoles(this); + return Gateway.getLDAPLookup().getRoleManager().getRoles(this); } - + public boolean hasRole(RolePath role) { return Gateway.getLDAPLookup().getRoleManager().hasRole(this, role); } - + public boolean hasRole(String role) { try { return hasRole(Gateway.getLDAPLookup().getRoleManager().getRolePath(role)); @@ -106,12 +106,13 @@ public class AgentPath extends EntityPath return mPassword; } - public String dump() { + @Override + public String dump() { return super.dump()+ "\n agentID="+ mAgentName; - } - + } + static String generateUserPassword(String pass, String algo) throws NoSuchAlgorithmException { MessageDigest sha = MessageDigest.getInstance(algo); sha.reset(); @@ -121,21 +122,22 @@ public class AgentPath extends EntityPath digest.append(Base64.encode(hash)); return digest.toString(); } - - public LDAPAttributeSet createAttributeSet() throws ObjectCannotBeUpdated + + @Override + public LDAPAttributeSet createAttributeSet() throws ObjectCannotBeUpdated { LDAPAttributeSet attrs = new LDAPAttributeSet(); attrs.add(new LDAPAttribute("objectclass","cristalagent")); - attrs.add(new LDAPAttribute("intsyskey",Integer.toString(mSysKey))); + attrs.add(new LDAPAttribute("intsyskey",Integer.toString(mSysKey))); attrs.add(new LDAPAttribute("cn", getPath()[getPath().length-1])); if (mIOR != null) attrs.add(new LDAPAttribute("ior", Gateway.getORB().object_to_string(mIOR))); - + if (mAgentName!=null && mAgentName.length()>0) attrs.add(new LDAPAttribute("uid",mAgentName)); else throw new ObjectCannotBeUpdated("Cannot create agent. No userId specified", ""); - + if (mPassword!=null && mPassword.length()>0) try { attrs.add(new LDAPAttribute("userPassword",generateUserPassword(mPassword, "SHA"))); @@ -144,9 +146,9 @@ public class AgentPath extends EntityPath } else throw new ObjectCannotBeUpdated("Cannot create agent. No password given", ""); - + return attrs; } - + } diff --git a/source/com/c2kernel/lookup/DomainPath.java b/source/com/c2kernel/lookup/DomainPath.java old mode 100755 new mode 100644 index ad314ee..ce849ce --- a/source/com/c2kernel/lookup/DomainPath.java +++ b/source/com/c2kernel/lookup/DomainPath.java @@ -30,15 +30,15 @@ public class DomainPath extends Path public DomainPath() { - super(Path.UNKNOWN); + super(Path.UNKNOWN); } public DomainPath(short type) { - super(); + super(); mType = type; } - + public DomainPath(String[] path) { super(path, Path.UNKNOWN); @@ -54,7 +54,7 @@ public class DomainPath extends Path super(path, Path.UNKNOWN); setEntity(entity); } - + public DomainPath(DomainPath parent, String child) { super(parent, child); } @@ -62,47 +62,50 @@ public class DomainPath extends Path /* the root of domain paths is /domain * clearly */ - public String getRoot() { + @Override + public String getRoot() { return "domain"; } - + public DomainPath getParent() { if (mPath.length == 0) return null; - + String[] parentPath = new String[mPath.length-1]; System.arraycopy(mPath, 0, parentPath, 0, parentPath.length); return new DomainPath(parentPath); } - + public void setEntity(EntityPath newTarget) { if (newTarget == null) { // clear target = null; mType = Path.CONTEXT; return; } - + target = newTarget; mType = Path.ENTITY; } - - public EntityPath getEntity() throws ObjectNotFoundException { + + @Override + public EntityPath getEntity() throws ObjectNotFoundException { if (mType == UNKNOWN) { // must decide checkType(); } - + if (target == null) throw new ObjectNotFoundException("Path is a context", ""); return target; } - - public short getType() { + + @Override + public short getType() { if (mType == UNKNOWN) { // must decide checkType(); } return mType; } - + public void checkType() { try { setEntity(Gateway.getLDAPLookup().resolvePath(this)); @@ -114,7 +117,7 @@ public class DomainPath extends Path } } - + /** * Retrieves the domkey of the path * @return the last path component; @@ -123,18 +126,20 @@ public class DomainPath extends Path return mPath[mPath.length-1]; } - public int getSysKey() { + @Override + public int getSysKey() { if (mType == UNKNOWN) { // must decide checkType(); } - + if (mType == ENTITY) { return target.getSysKey(); } else return INVALID; } - public LDAPAttributeSet createAttributeSet() { + @Override + public LDAPAttributeSet createAttributeSet() { LDAPAttributeSet attrs = new LDAPAttributeSet(); attrs.add(new LDAPAttribute("cn",getName())); if (getType() == ENTITY) { diff --git a/source/com/c2kernel/lookup/EntityPath.java b/source/com/c2kernel/lookup/EntityPath.java index 3a24228..4f9b771 100644 --- a/source/com/c2kernel/lookup/EntityPath.java +++ b/source/com/c2kernel/lookup/EntityPath.java @@ -39,12 +39,12 @@ public class EntityPath extends Path * Note no EntityPath constructors allow setting of CONTEXT or ENTITY: * The object decides that for itself from the number of components */ - + public EntityPath(int syskey) throws InvalidEntityPathException { super(); setSysKey(syskey); } - + /* */ public EntityPath() @@ -55,15 +55,15 @@ public class EntityPath extends Path /* */ - public EntityPath(String[] path) throws InvalidEntityPathException + public EntityPath(String[] path) throws InvalidEntityPathException { - super(path, Path.CONTEXT); // dummy - it will get replaced in checkSysPath() + super(path, Path.CONTEXT); // dummy - it will get replaced in checkSysPath() checkSysPath(); } /* */ - public EntityPath(String path) throws InvalidEntityPathException + public EntityPath(String path) throws InvalidEntityPathException { super(path, Path.CONTEXT); checkSysPath(); @@ -75,33 +75,35 @@ public class EntityPath extends Path super(parent, child); checkSysPath(); } - + // EntityPaths root in /entity - public String getRoot() { + @Override + public String getRoot() { return "entity"; } - - public EntityPath getEntity() throws ObjectNotFoundException { + + @Override + public EntityPath getEntity() throws ObjectNotFoundException { return this; } - + public byte[] getOID() { if (mSysKey == Path.INVALID) return null; return String.valueOf(mSysKey).getBytes(); } /*************************************************************************/ - + /** Returns int form of syskey (if possible) */ - public int getSysKey() { - if (mSysKey == Path.INVALID && mType == Path.ENTITY) + @Override + public int getSysKey() { + if (mSysKey == Path.INVALID && mType == Path.ENTITY) try { if (mPath.length != elementNo) throw new InvalidEntityPathException("Incorrect number of components for a system key"); mSysKey = 0; - for (int i=0; i maxSysKey) + if (sysKey < 0 || sysKey > maxSysKey) throw new InvalidEntityPathException("System key "+sysKey+" out of range"); String stringPath = Integer.toString(sysKey); ArrayList newKey = new ArrayList(); @@ -142,31 +144,32 @@ public class EntityPath extends Path newKey.add(0, nextComponent.toString()); } - mPath = (String[])(newKey.toArray(mPath)); + mPath = (newKey.toArray(mPath)); mSysKey = sysKey; mStringPath = null; - mDN = null; + mDN = null; mType = Path.ENTITY; checkSysPath(); - } + } public void checkSysPath() throws InvalidEntityPathException { if (mPath.length > elementNo) throw new InvalidEntityPathException("EntityPath cannot have more than "+elementNo+" components: "+toString()); - if (mPath.length == elementNo) + if (mPath.length == elementNo) mType = Path.ENTITY; else mType = Path.CONTEXT; } - public LDAPAttributeSet createAttributeSet() throws ObjectCannotBeUpdated { - LDAPAttributeSet attrs = new LDAPAttributeSet(); + @Override + public LDAPAttributeSet createAttributeSet() throws ObjectCannotBeUpdated { + LDAPAttributeSet attrs = new LDAPAttributeSet(); attrs.add(new LDAPAttribute("objectclass","cristalentity")); attrs.add(new LDAPAttribute("intsyskey",Integer.toString(mSysKey))); attrs.add(new LDAPAttribute("cn", getPath()[getPath().length-1])); if (mIOR != null) attrs.add(new LDAPAttribute("ior", Gateway.getORB().object_to_string(mIOR))); return attrs; - } + } } diff --git a/source/com/c2kernel/lookup/LDAPLookup.java b/source/com/c2kernel/lookup/LDAPLookup.java old mode 100755 new mode 100644 index 04d99f0..9bae873 --- a/source/com/c2kernel/lookup/LDAPLookup.java +++ b/source/com/c2kernel/lookup/LDAPLookup.java @@ -5,7 +5,6 @@ package com.c2kernel.lookup; -import java.util.Enumeration; import java.util.StringTokenizer; import com.c2kernel.common.ObjectAlreadyExistsException; @@ -18,10 +17,16 @@ import com.c2kernel.entity.proxy.ProxyMessage; import com.c2kernel.process.Gateway; import com.c2kernel.utils.Logger; import com.c2kernel.utils.Resource; -import com.novell.ldap.*; +import com.novell.ldap.LDAPAttributeSet; +import com.novell.ldap.LDAPConnection; +import com.novell.ldap.LDAPDN; +import com.novell.ldap.LDAPEntry; +import com.novell.ldap.LDAPException; +import com.novell.ldap.LDAPSearchConstraints; +import com.novell.ldap.LDAPSearchResults; /** - * The LDAPLookup object, statically accessible through the Gateway, manages + * The LDAPLookup object, statically accessible through the Gateway, manages * the LDAP connection for the cristal process. It provides: *
      *
    • Authentication - returning an AgentProxy object if a user has logged in @@ -32,7 +37,7 @@ import com.novell.ldap.*; * @author $Author: abranson $ */ -public class LDAPLookup +public class LDAPLookup { private LDAPConnection mLDAPConn; @@ -40,30 +45,30 @@ public class LDAPLookup private NextKeyManager mNextKeyManager; private LDAPPropertyManager mPropManager; private LDAPRoleManager mRoleManager; - - + + /** - * Creates a new LDAPLookup manager with the properties supplied. + * Creates a new LDAPLookup manager with the properties supplied. * This should be only done by the Gateway during initialisation. - * + * * @param props The LDAP properties object that extracts LDAP connection properties from the global c2kprops */ public LDAPLookup(LDAPProperties props) throws LDAPException { Logger.msg(8,"LDAPLookup - initialising."); - + mLDAPProps = props; - + mLDAPConn = createConnection(mLDAPProps); - + Path.mGlobalPath=props.mGlobalPath; Path.mRootPath=props.mRootPath; Path.mLocalPath=props.mLocalPath; - + EntityPath.mTypeRoot = "cn=entity,"+props.mLocalPath; DomainPath.mTypeRoot = "cn=domain,"+props.mLocalPath; - + mNextKeyManager = new NextKeyManager(this, "cn=last,"+EntityPath.mTypeRoot); Logger.debug("LDAP.useOldProps="+Gateway.getProperty("LDAP.useOldProps", "false")); if (Gateway.getProperty("LDAP.useOldProps", "false").equals("true")) { @@ -77,9 +82,9 @@ public class LDAPLookup mRoleManager = new LDAPRoleManager(this, "cn=agent,"+DomainPath.mTypeRoot, EntityPath.mTypeRoot); } - + /** - * Utility method to connect to an LDAP server + * Utility method to connect to an LDAP server * @param lp LDAP properties to connect with * @return a novell LDAPConnection object * @throws LDAPException when the connection was unsuccessful @@ -92,13 +97,13 @@ public class LDAPLookup Logger.msg(3, "LDAPLookup - authenticating user:" + lp.mUser); ld.bind( LDAPConnection.LDAP_V3, lp.mUser, - String.valueOf(lp.mPassword).getBytes()); + String.valueOf(lp.mPassword).getBytes()); Logger.msg(3, "LDAPLookup - authentication successful"); LDAPSearchConstraints searchCons = new LDAPSearchConstraints(); searchCons.setMaxResults(0); ld.setConstraints(searchCons); - + return ld; } @@ -110,7 +115,7 @@ public class LDAPLookup { return mNextKeyManager; } - + /** * Gets the property manager, that is used to read and write cristal properties to the LDAP store. * @return Returns the global LDAPPropertyManager. @@ -124,23 +129,23 @@ public class LDAPLookup */ public LDAPRoleManager getRoleManager() { return mRoleManager; - } + } /** * Returns the current LDAP connection, and attempts to reconnect if it has been closed. * @return */ - protected LDAPConnection getConnection() - { + protected LDAPConnection getConnection() + { if (!mLDAPConn.isConnected()) { Logger.warning("LDAPLookup - lost connection to LDAP server. Attempting to reconnect."); try { mLDAPConn = createConnection(mLDAPProps); } catch (LDAPException ex) { } } - return mLDAPConn; + return mLDAPConn; } - + /** * Disconnects the connection with the LDAP server during shutdown */ @@ -156,7 +161,7 @@ public class LDAPLookup } } - /** + /** * Attempts to resolve the CORBA object for a Path, either directly or through an alias. * @param path the path to resolve * @return the CORBA object @@ -197,13 +202,13 @@ public class LDAPLookup } /** - * + * * @param domPath * @return * @throws InvalidEntityPathException * @throws ObjectNotFoundException */ - protected EntityPath resolvePath(DomainPath domPath) + protected EntityPath resolvePath(DomainPath domPath) throws InvalidEntityPathException, ObjectNotFoundException { EntityPath referencedPath = null; LDAPEntry domEntry = LDAPLookupUtils.getEntry(getConnection(), domPath @@ -221,12 +226,11 @@ public class LDAPLookup return referencedPath; } - + public LDAPEntry add(Path path) throws ObjectCannotBeUpdated, ObjectAlreadyExistsException { - String root = path.getRoot(); try { checkLDAPContext(path); LDAPAttributeSet attrSet = path.createAttributeSet(); @@ -256,10 +260,9 @@ public class LDAPLookup EntityProxyManager.sendProxyEvent(new ProxyMessage(ProxyMessage.NA, path.toString(), ProxyMessage.DELETED)); } } - + //change specs, add boolean alias leaf context protected void checkLDAPContext(Path path) - throws LDAPException { String dn = path.getFullDN(); if (!LDAPLookupUtils.exists(getConnection(),dn)) @@ -290,7 +293,7 @@ public class LDAPLookup public void createBootTree() { Logger.msg(8,"Initializing LDAP Boot tree"); - + //create org LDAPLookupUtils.createOrganizationContext(getConnection(), Path.mGlobalPath); //create root @@ -298,13 +301,13 @@ public class LDAPLookup //create local LDAPLookupUtils.createCristalContext(getConnection(), Path.mLocalPath); } - - public void install() throws LDAPException + + public void install() { createBootTree(); initTree( Resource.getTextResource("boot/LDAPboot.txt")); } - + public void initTree(String bootFile) { Logger.msg(8,"Verifying Cristal LDAP roots"); @@ -315,21 +318,21 @@ public class LDAPLookup Logger.msg(8,"Checking " + line+Path.mLocalPath); LDAPLookupUtils.createCristalContext(getConnection(), line+Path.mLocalPath); } - - } - + + } + //typically search for cn=barcode - public Enumeration search(Path start, String filter) + public LDAPPathSet search(Path start, String filter) { Logger.msg(8,"LDAPLookup::search() From " + start.getDN() + " for cn=" + filter ); return search(start.getFullDN(),"cn="+LDAPLookupUtils.escapeSearchFilter(filter)); } - - protected Enumeration search(String startDN, int scope, String filter, LDAPSearchConstraints searchCons) - { + + protected LDAPPathSet search(String startDN, int scope, String filter, LDAPSearchConstraints searchCons) + { Logger.msg(8,"Searching for "+filter+" in "+startDN); searchCons.setMaxResults(0); - String[] attr = { LDAPConnection.ALL_USER_ATTRS }; + String[] attr = { LDAPConnection.ALL_USER_ATTRS }; try { LDAPSearchResults res = getConnection().search(LDAPLookupUtils.escapeDN(startDN),scope, @@ -341,9 +344,9 @@ public class LDAPLookup Logger.error("LDAPException::LDAPLookup::search() " + ex.toString()); return new LDAPPathSet(); } - } + } //typically search for (any filter combination) - public Enumeration search(String startDN,String filter) + public LDAPPathSet search(String startDN,String filter) { LDAPSearchConstraints searchCons = new LDAPSearchConstraints(); searchCons.setBatchSize(0); @@ -351,14 +354,14 @@ public class LDAPLookup return search(startDN,LDAPConnection.SCOPE_SUB,filter,searchCons); } - public Enumeration searchEntities(Path start) { + public LDAPPathSet searchEntities(Path start) { LDAPSearchConstraints searchCons = new LDAPSearchConstraints(); searchCons.setBatchSize(0); searchCons.setDereference(LDAPSearchConstraints.DEREF_SEARCHING); return search(start.getFullDN(), LDAPConnection.SCOPE_SUB, "objectClass=cristalentity", searchCons); } - - public Enumeration searchAliases(DomainPath start) { + + public LDAPPathSet searchAliases(DomainPath start) { LDAPSearchConstraints searchCons = new LDAPSearchConstraints(); searchCons.setBatchSize(0); searchCons.setDereference(LDAPSearchConstraints.DEREF_NEVER); @@ -368,8 +371,8 @@ public class LDAPLookup public boolean exists(Path path) { return LDAPLookupUtils.exists(getConnection(), path.getFullDN()); } - - public Class getEntityClass(Path path) throws ObjectNotFoundException { + + public Class getEntityClass(Path path) throws ObjectNotFoundException { String[] attr = { LDAPConnection.ALL_USER_ATTRS }; try { LDAPEntry anEntry=getConnection().read(path.getDN()+Path.mLocalPath,attr); @@ -380,7 +383,7 @@ public class LDAPLookup return ActiveEntity.class; else throw new ObjectNotFoundException("Not an entity", ""); - + } catch (LDAPException ex) { if (ex.getResultCode() == LDAPException.NO_SUCH_OBJECT) throw new ObjectNotFoundException("Entity does not exist", ""); @@ -388,7 +391,7 @@ public class LDAPLookup throw new ObjectNotFoundException("Error getting entity class", ""); } } - + /** converts an LDAPentry to a Path object * Note that the search producing the entry should have retrieved the attrs * 'ior' and 'uniquemember' @@ -398,14 +401,14 @@ public class LDAPLookup protected Path nodeToPath(LDAPEntry entry) throws InvalidEntityPathException, ObjectNotFoundException { String dn = entry.getDN(); - + // extract syskey int entityKey = -1; try { String entityKeyStr = LDAPLookupUtils.getFirstAttributeValue(entry,"intsyskey"); entityKey = Integer.parseInt(entityKeyStr); } catch (Exception e) { } - + // extract IOR org.omg.CORBA.Object ior = null; try { @@ -420,10 +423,10 @@ public class LDAPLookup String agentID = LDAPLookupUtils.getFirstAttributeValue(entry,"uid"); thisPath = new AgentPath(entityKey, agentID); } - + else if (LDAPLookupUtils.existsAttributeValue(entry,"objectclass","cristalrole")) { //cristalrole - thisPath = new RolePath(LDAPDN.explodeDN(dn,true)[0], + thisPath = new RolePath(LDAPDN.explodeDN(dn,true)[0], LDAPLookupUtils.getFirstAttributeValue(entry, "jobList").equals("TRUE")); } else if (LDAPLookupUtils.existsAttributeValue(entry,"objectclass","aliasObject") || @@ -431,7 +434,7 @@ public class LDAPLookup { DomainPath domainPath = new DomainPath(); domainPath.setDN(dn); - thisPath = domainPath; + thisPath = domainPath; } else if (LDAPLookupUtils.existsAttributeValue(entry,"objectclass","cristalentity") || (LDAPLookupUtils.existsAttributeValue(entry,"objectclass","cristalcontext") && dn.endsWith(EntityPath.mTypeRoot))) @@ -452,8 +455,8 @@ public class LDAPLookup else { throw new ObjectNotFoundException("Unrecognised LDAP entry. Not a cristal entry"); - } - + } + //set IOR if we have one if (ior!=null) thisPath.setIOR(ior); return thisPath; diff --git a/source/com/c2kernel/lookup/LDAPLookupUtils.java b/source/com/c2kernel/lookup/LDAPLookupUtils.java old mode 100755 new mode 100644 index 6516374..8df365b --- a/source/com/c2kernel/lookup/LDAPLookupUtils.java +++ b/source/com/c2kernel/lookup/LDAPLookupUtils.java @@ -49,7 +49,7 @@ final public class LDAPLookupUtils { return getEntry(ld, dn, LDAPSearchConstraints.DEREF_NEVER); } - + static public String getFirstAttributeValue(LDAPEntry anEntry, String attribute) throws ObjectNotFoundException { LDAPAttribute attr = anEntry.getAttribute(attribute); @@ -61,11 +61,11 @@ final public class LDAPLookupUtils static public String[] getAllAttributeValues(LDAPEntry anEntry, String attribute) throws ObjectNotFoundException { LDAPAttribute attr = anEntry.getAttribute(attribute); - if (attr!=null) + if (attr!=null) return attr.getStringValueArray(); - + throw new ObjectNotFoundException("No attributes named '"+attribute+"'", ""); - + } static public boolean existsAttributeValue(LDAPEntry anEntry, String attribute, String value) @@ -94,7 +94,7 @@ final public class LDAPLookupUtils //this is for a single-valued attribute static public void setAttributeValue(LDAPConnection ld, LDAPEntry anEntry, String attribute, String newValue) throws ObjectNotFoundException, ObjectCannotBeUpdated - { + { try { if (!hasOneAttributeValue(anEntry, attribute)) throw new ObjectCannotBeUpdated("Attribute "+attribute + " of entry " + anEntry.getDN()+" has more than one value", ""); @@ -102,26 +102,26 @@ final public class LDAPLookupUtils addAttributeValue(ld, anEntry, attribute, newValue); } try - { + { ld.modify(anEntry.getDN(),new LDAPModification(LDAPModification.REPLACE,new LDAPAttribute(attribute,newValue))); - } - catch (LDAPException ex) + } + catch (LDAPException ex) { Logger.error(ex); throw new ObjectCannotBeUpdated("Attribute " + attribute + " of entry " + anEntry.getDN() + " could not be modified", ""); } } - + //this is for a multi-valued attribute eg uniqueMember static public void addAttributeValue(LDAPConnection ld, LDAPEntry anEntry, String attribute, String value) throws ObjectCannotBeUpdated { - try + try { - ld.modify(anEntry.getDN(),new LDAPModification(LDAPModification.ADD, new LDAPAttribute(attribute,value))); - } - catch (LDAPException ex) + ld.modify(anEntry.getDN(),new LDAPModification(LDAPModification.ADD, new LDAPAttribute(attribute,value))); + } + catch (LDAPException ex) { Logger.error(ex); throw new ObjectCannotBeUpdated("Attribute " + attribute + " of entry " + anEntry.getDN() + " could not be added.", ""); @@ -131,18 +131,18 @@ final public class LDAPLookupUtils //this is for a multi-valued attribute eg uniqueMember static public void removeAttributeValue(LDAPConnection ld, LDAPEntry anEntry, String attribute, String value) throws ObjectCannotBeUpdated - { + { try { ld.modify(anEntry.getDN(),new LDAPModification(LDAPModification.DELETE,new LDAPAttribute(attribute,value))); - } - catch (LDAPException ex) + } + catch (LDAPException ex) { Logger.error(ex); throw new ObjectCannotBeUpdated("Attribute " + attribute + " of entry " + anEntry.getDN() + " could not be deleted", ""); } } - + static public boolean exists(LDAPConnection ld, String name) { try { @@ -178,7 +178,7 @@ final public class LDAPLookupUtils LDAPSearchConstraints searchCons = new LDAPSearchConstraints(); searchCons.setBatchSize(0); searchCons.setDereference(LDAPSearchConstraints.DEREF_NEVER); - + try { LDAPSearchResults res = ld.search(dn,LDAPConnection.SCOPE_ONE,filter,attr,false,searchCons); @@ -200,7 +200,7 @@ final public class LDAPLookupUtils LDAPSearchConstraints searchCons = new LDAPSearchConstraints(); searchCons.setBatchSize(0); searchCons.setDereference(LDAPSearchConstraints.DEREF_NEVER); - + try { LDAPSearchResults res = ld.search(dn,LDAPConnection.SCOPE_ONE,filter,attr,false,searchCons); @@ -209,7 +209,7 @@ final public class LDAPLookupUtils while (res.hasMore()) { LDAPEntry findEntry=res.next(); - if (findEntry!=null) + if (findEntry!=null) { result[i++] = new String(findEntry.getDN()); } @@ -254,9 +254,9 @@ final public class LDAPLookupUtils objectclass_values[0] = "cristalcontext"; if (name.equals("last")) attrs.add(new LDAPAttribute("intsyskey", "0")); - - attrs.add(new LDAPAttribute("objectclass",objectclass_values)); - + + attrs.add(new LDAPAttribute("objectclass",objectclass_values)); + LDAPLookupUtils.addEntry(ld,new LDAPEntry(dn,attrs)); } catch (Exception ex) @@ -269,7 +269,7 @@ final public class LDAPLookupUtils { if (LDAPLookupUtils.exists(ld,dn)) return; - + try { String name = LDAPDN.explodeDN(dn,true)[0]; @@ -283,7 +283,7 @@ final public class LDAPLookupUtils { Logger.msg(ex.toString()); } - } + } public static String escapeDN (String name) { //From RFC 2253 and the / character for JNDI final char[] META_CHARS = {'+', '"', '<', '>', ';', '/'}; @@ -296,8 +296,8 @@ final public class LDAPLookupUtils escapedStr = escapedStr.replaceAll("^#","\\\\#"); escapedStr = escapedStr.replaceAll("^ | $","\\\\ "); - for (int i=0;i < META_CHARS.length;i++) { - escapedStr = escapedStr.replaceAll("\\"+META_CHARS[i],"\\\\" + META_CHARS[i]); + for (char element : META_CHARS) { + escapedStr = escapedStr.replaceAll("\\"+element,"\\\\" + element); } Logger.msg(6, "LDAP DN "+name+" escaped to "+escapedStr); return escapedStr; @@ -313,5 +313,5 @@ final public class LDAPLookupUtils escapedStr = escapedStr.replaceAll("\\)","\\\\29"); Logger.msg(6, "LDAP Search Filter "+filter+" escaped to "+escapedStr); return escapedStr; - } + } } diff --git a/source/com/c2kernel/lookup/LDAPPathSet.java b/source/com/c2kernel/lookup/LDAPPathSet.java old mode 100755 new mode 100644 index 9c68c5c..d3cf7d9 --- a/source/com/c2kernel/lookup/LDAPPathSet.java +++ b/source/com/c2kernel/lookup/LDAPPathSet.java @@ -19,35 +19,37 @@ import com.novell.ldap.LDAPSearchResults; -public class LDAPPathSet implements Enumeration { +public class LDAPPathSet implements Enumeration { LDAPSearchResults results; LDAPEntry nextEntry; - + public LDAPPathSet() { // empty results = null; } - + public LDAPPathSet(LDAPSearchResults results) { this.results = results; } - - public boolean hasMoreElements() { + + @Override + public boolean hasMoreElements() { if (results == null) return false; if (nextEntry != null) return true; if (results.hasMore()) try { nextEntry = results.next(); return true; - } catch (LDAPException ex) { + } catch (LDAPException ex) { if (ex.getResultCode()!=32) {// no results Logger.error(ex); Logger.error("Error loading LDAP result set: "+ex.getMessage()); } - } + } return false; } - - public Object nextElement() { + + @Override + public Path nextElement() { if (results == null) return null; try { if (nextEntry == null) diff --git a/source/com/c2kernel/lookup/LDAPPropertyManager.java b/source/com/c2kernel/lookup/LDAPPropertyManager.java index a1fd6af..57ed17d 100644 --- a/source/com/c2kernel/lookup/LDAPPropertyManager.java +++ b/source/com/c2kernel/lookup/LDAPPropertyManager.java @@ -49,13 +49,13 @@ public class LDAPPropertyManager { LDAPEntry entityEntry = LDAPLookupUtils.getEntry(ldap.getConnection(), thisEntity.getFullDN()); ArrayList propbag = new ArrayList(); LDAPAttribute props = entityEntry.getAttribute("cristalprop"); - for (Enumeration e = props.getStringValues(); e.hasMoreElements();) { + for (Enumeration e = props.getStringValues(); e.hasMoreElements();) { String thisProp = (String)e.nextElement(); propbag.add(thisProp.substring(0, thisProp.indexOf(':'))); } - + String[] retArr = new String[props.size()]; - return (String[])propbag.toArray(retArr); + return propbag.toArray(retArr); } /** @@ -101,13 +101,13 @@ public class LDAPPropertyManager { LDAPLookupUtils.addAttributeValue(ldap.getConnection(), entityEntry, "cristalprop", prop.getName()+":"+prop.getValue()); } - private String getPropertyAttr(LDAPEntry myEntry, String propName) throws ObjectNotFoundException { + private static String getPropertyAttr(LDAPEntry myEntry, String propName) throws ObjectNotFoundException { // delete existing props LDAPAttribute props = myEntry.getAttribute("cristalprop"); if (props == null) throw new ObjectNotFoundException("Property "+propName+" does not exist", ""); String propPrefix = propName+":"; - for (Enumeration e = props.getStringValues(); e.hasMoreElements();) { + for (Enumeration e = props.getStringValues(); e.hasMoreElements();) { String val = (String)e.nextElement(); if (val.toLowerCase().startsWith(propPrefix.toLowerCase())) return val.substring(propPrefix.length()); diff --git a/source/com/c2kernel/lookup/LDAPRoleManager.java b/source/com/c2kernel/lookup/LDAPRoleManager.java index a45da13..1df2f29 100644 --- a/source/com/c2kernel/lookup/LDAPRoleManager.java +++ b/source/com/c2kernel/lookup/LDAPRoleManager.java @@ -7,7 +7,10 @@ import com.c2kernel.common.ObjectAlreadyExistsException; import com.c2kernel.common.ObjectCannotBeUpdated; import com.c2kernel.common.ObjectNotFoundException; import com.c2kernel.utils.Logger; -import com.novell.ldap.*; +import com.novell.ldap.LDAPConnection; +import com.novell.ldap.LDAPEntry; +import com.novell.ldap.LDAPException; +import com.novell.ldap.LDAPSearchConstraints; /************************************************************************** * @@ -27,7 +30,7 @@ public class LDAPRoleManager { LDAPLookup mLdap; private String mRolePath; private String mEntityPath; - + public LDAPRoleManager(LDAPLookup ldap, String rolePath, String entityPath) { super(); this.mLdap = ldap; @@ -44,14 +47,14 @@ public class LDAPRoleManager { // create the role RolePath rolePath = new RolePath(roleName, jobList); - String roleDN = rolePath.getFullDN(); + String roleDN = rolePath.getFullDN(); LDAPEntry roleNode; try - { + { roleNode = LDAPLookupUtils.getEntry(mLdap.getConnection(), rolePath.getFullDN()); throw new ObjectAlreadyExistsException(); } catch (ObjectNotFoundException ex) { } - + //create CristalRole if it does not exist roleNode = new LDAPEntry(roleDN, rolePath.createAttributeSet()); try { @@ -60,7 +63,7 @@ public class LDAPRoleManager { throw new ObjectCannotBeUpdated(e.getLDAPErrorMessage(), ""); } return rolePath; - + } public void deleteRole(RolePath role) throws ObjectNotFoundException, ObjectCannotBeUpdated { @@ -72,7 +75,7 @@ public class LDAPRoleManager { } protected void addRole(AgentPath agent, RolePath role) - throws ObjectCannotBeUpdated, ObjectNotFoundException + throws ObjectCannotBeUpdated, ObjectNotFoundException { LDAPEntry roleEntry = LDAPLookupUtils.getEntry(mLdap.getConnection(), role.getFullDN()); //add memberDN to uniqueMember if it is not yet a member @@ -82,7 +85,7 @@ public class LDAPRoleManager { throw new ObjectCannotBeUpdated("Agent " + agent.getAgentName() + " already has role " + role.getName()); } - protected void removeRole(AgentPath agent, RolePath role) + protected void removeRole(AgentPath agent, RolePath role) throws ObjectCannotBeUpdated, ObjectNotFoundException { LDAPEntry roleEntry = LDAPLookupUtils.getEntry(mLdap.getConnection(), role.getFullDN()); @@ -91,44 +94,42 @@ public class LDAPRoleManager { else throw new ObjectCannotBeUpdated("Agent did not have that role"); } - + protected boolean hasRole(AgentPath agent, RolePath role) { - String filter = "(&(objectclass=cristalrole)(uniqueMember="+agent.getFullDN()+")(cn="+role.getName()+"))"; + String filter = "(&(objectclass=cristalrole)(uniqueMember="+agent.getFullDN()+")(cn="+role.getName()+"))"; LDAPSearchConstraints searchCons = new LDAPSearchConstraints(); searchCons.setBatchSize(0); searchCons.setDereference(LDAPSearchConstraints.DEREF_NEVER ); - Enumeration roles = mLdap.search(mRolePath,LDAPConnection.SCOPE_SUB,filter,searchCons); + Enumeration roles = mLdap.search(mRolePath,LDAPConnection.SCOPE_SUB,filter,searchCons); return roles.hasMoreElements(); } protected AgentPath[] getAgents(RolePath role) throws ObjectNotFoundException { - //get the roleDN entry, and its uniqueMember entry pointing to + //get the roleDN entry, and its uniqueMember entry pointing to LDAPEntry roleEntry; try { roleEntry = LDAPLookupUtils.getEntry(mLdap.getConnection(), role.getFullDN()); } catch (ObjectNotFoundException e) { throw new ObjectNotFoundException("Role does not exist", ""); } - + String[] res = LDAPLookupUtils.getAllAttributeValues(roleEntry,"uniqueMember"); ArrayList agents = new ArrayList(); - for (int i=0; i roles = mLdap.search(mRolePath,LDAPConnection.SCOPE_SUB,filter,searchCons); ArrayList roleList = new ArrayList(); - + while(roles.hasMoreElements()) { RolePath path = (RolePath) roles.nextElement(); - roleList.add(path); - } + roleList.add(path); + } RolePath[] roleArr = new RolePath[roleList.size()]; - roleArr = (RolePath[])roleList.toArray(roleArr); + roleArr = roleList.toArray(roleArr); return roleArr; } /** * Utility for looking up a login name - * + * * @param ld * @param agentName * @param baseDN @@ -164,15 +165,15 @@ public class LDAPRoleManager { * @throws ObjectNotFoundException */ public AgentPath getAgentPath(String agentName) throws ObjectNotFoundException - { + { //search to get the userDN equivalent of the userID LDAPSearchConstraints searchCons = new LDAPSearchConstraints(); searchCons.setBatchSize(0); searchCons.setDereference(LDAPSearchConstraints.DEREF_NEVER ); - String filter = "(&(objectclass=cristalagent)(uid="+agentName+"))"; - Enumeration res = mLdap.search(mEntityPath,LDAPConnection.SCOPE_SUB,filter,searchCons); + String filter = "(&(objectclass=cristalagent)(uid="+agentName+"))"; + Enumeration res = mLdap.search(mEntityPath,LDAPConnection.SCOPE_SUB,filter,searchCons); if (!res.hasMoreElements()) - throw new ObjectNotFoundException("Agent not found"); + throw new ObjectNotFoundException("Agent not found"); Path result = (Path)res.nextElement(); if (result instanceof AgentPath) return (AgentPath)result; @@ -185,15 +186,15 @@ public class LDAPRoleManager { LDAPSearchConstraints searchCons = new LDAPSearchConstraints(); searchCons.setBatchSize(0); searchCons.setDereference(LDAPSearchConstraints.DEREF_NEVER ); - String filter = "(&(objectclass=cristalrole)(cn="+roleName+"))"; - Enumeration res = mLdap.search(mRolePath,LDAPConnection.SCOPE_SUB,filter,searchCons); + String filter = "(&(objectclass=cristalrole)(cn="+roleName+"))"; + Enumeration res = mLdap.search(mRolePath,LDAPConnection.SCOPE_SUB,filter,searchCons); if (!res.hasMoreElements()) - throw new ObjectNotFoundException("Role not found"); + throw new ObjectNotFoundException("Role not found"); Path result = (Path)res.nextElement(); if (result instanceof RolePath) return (RolePath)result; else - throw new ObjectNotFoundException("Entry was not a Role"); + throw new ObjectNotFoundException("Entry was not a Role"); } } diff --git a/source/com/c2kernel/lookup/LegacyLDAPPropertyManager.java b/source/com/c2kernel/lookup/LegacyLDAPPropertyManager.java old mode 100755 new mode 100644 index 62653fb..638c694 --- a/source/com/c2kernel/lookup/LegacyLDAPPropertyManager.java +++ b/source/com/c2kernel/lookup/LegacyLDAPPropertyManager.java @@ -15,7 +15,8 @@ public class LegacyLDAPPropertyManager extends LDAPPropertyManager { public LegacyLDAPPropertyManager(LDAPLookup ldap) { super(ldap); } - + + @Override public void deleteProperty(EntityPath thisEntity, String name) throws ObjectNotFoundException, ObjectCannotBeUpdated { try { LDAPLookupUtils.delete(ldap.getConnection(), "cn="+name+","+thisEntity.getFullDN()); @@ -25,6 +26,7 @@ public class LegacyLDAPPropertyManager extends LDAPPropertyManager { } } + @Override public String[] getPropertyNames(EntityPath thisEntity) throws ObjectNotFoundException { String props[]= LDAPLookupUtils.getChildrenDNs(ldap.getConnection(), thisEntity.getFullDN(), "objectclass=cristalproperty"); String names[] = new String[props.length]; @@ -33,6 +35,7 @@ public class LegacyLDAPPropertyManager extends LDAPPropertyManager { return names; } + @Override public String getPropertyValue(EntityPath thisEntity, String name) throws ObjectNotFoundException { LDAPEntry anEntry = LDAPLookupUtils.getEntry(ldap.getConnection(),"cn="+name+","+thisEntity.getFullDN()); if (anEntry==null) @@ -40,10 +43,12 @@ public class LegacyLDAPPropertyManager extends LDAPPropertyManager { return LDAPLookupUtils.getFirstAttributeValue(anEntry,"propval"); } + @Override public boolean hasProperties(EntityPath thisEntity) throws ObjectNotFoundException { return LDAPLookupUtils.hasChildren(ldap.getConnection(), thisEntity.getFullDN(), "objectclass=cristalproperty" ); } + @Override public void setProperty(EntityPath thisEntity, Property prop) throws ObjectNotFoundException, ObjectCannotBeUpdated { try { LDAPEntry anEntry = LDAPLookupUtils.getEntry(ldap.getConnection(),"cn="+prop.getName()+","+thisEntity.getFullDN()); @@ -64,7 +69,7 @@ public class LegacyLDAPPropertyManager extends LDAPPropertyManager { } catch (Exception e) { Logger.error(e); throw new ObjectCannotBeUpdated(e.getMessage(), ""); - } + } } } } diff --git a/source/com/c2kernel/lookup/NextKeyManager.java b/source/com/c2kernel/lookup/NextKeyManager.java old mode 100755 new mode 100644 index 04581c0..fd873fd --- a/source/com/c2kernel/lookup/NextKeyManager.java +++ b/source/com/c2kernel/lookup/NextKeyManager.java @@ -18,7 +18,7 @@ public class NextKeyManager { LDAPLookup ldap; String lastKeyPath; - + public NextKeyManager(LDAPLookup ldap, String lastKeyPath) { super(); this.ldap = ldap; @@ -28,9 +28,8 @@ public class NextKeyManager { public synchronized EntityPath generateNextEntityKey() throws ObjectCannotBeUpdated, ObjectNotFoundException { - LDAPEntry lastKeyEntry = LDAPLookupUtils.getEntry(ldap.getConnection(),lastKeyPath); EntityPath lastKey = getLastEntityPath(); - + try { lastKey.setSysKey(lastKey.getSysKey()+1); } catch (InvalidEntityPathException ex) { @@ -38,21 +37,21 @@ public class NextKeyManager { } //set the last key writeLastEntityKey(lastKey.getSysKey()); - + return lastKey; } - + public synchronized AgentPath generateNextAgentKey() throws ObjectCannotBeUpdated, ObjectNotFoundException { EntityPath newEntity = generateNextEntityKey(); return new AgentPath(newEntity); } - + public void writeLastEntityKey(int sysKey) throws ObjectCannotBeUpdated, ObjectNotFoundException { LDAPEntry lastKeyEntry = LDAPLookupUtils.getEntry(ldap.getConnection(),lastKeyPath); LDAPLookupUtils.setAttributeValue(ldap.getConnection(), lastKeyEntry,"intsyskey",Integer.toString(sysKey)); } - + public EntityPath getLastEntityPath() throws ObjectNotFoundException { LDAPEntry lastKeyEntry = LDAPLookupUtils.getEntry(ldap.getConnection(),lastKeyPath); @@ -66,7 +65,7 @@ public class NextKeyManager { } catch (NumberFormatException ex) { throw new ObjectNotFoundException("Invalid syskey in lastkey."); } - + } - + } diff --git a/source/com/c2kernel/lookup/Path.java b/source/com/c2kernel/lookup/Path.java index b713493..4966d1e 100644 --- a/source/com/c2kernel/lookup/Path.java +++ b/source/com/c2kernel/lookup/Path.java @@ -32,10 +32,10 @@ public abstract class Path implements Serializable public static final String delim = "/"; // types - public static final short UNKNOWN = 0; + public static final short UNKNOWN = 0; public static final short CONTEXT = 1; public static final short ENTITY = 2; - + // invalid int key public static final int INVALID = -1; @@ -54,11 +54,11 @@ public abstract class Path implements Serializable protected org.omg.CORBA.Object mIOR = null; // // needed for unusual subclass constructors - + protected static String mGlobalPath; //cern.ch protected static String mRootPath; //cristal2 protected static String mLocalPath; //lab27 - + public Path() { } @@ -115,7 +115,7 @@ public abstract class Path implements Serializable { mStringPath = null; mDN = null; - mPath = (String[])path.clone(); + mPath = path.clone(); mSysKey = INVALID; } @@ -134,7 +134,7 @@ public abstract class Path implements Serializable newPath.add(tok.nextToken()); } - mPath = (String[])(newPath.toArray(mPath)); + mPath = (newPath.toArray(mPath)); mStringPath = null; mDN = null; mSysKey = INVALID; @@ -153,7 +153,7 @@ public abstract class Path implements Serializable { mStringPath = null; mDN = null; - mPath = (String[])(path.getPath().clone()); + mPath = (path.getPath().clone()); mSysKey = INVALID; } @@ -167,7 +167,7 @@ public abstract class Path implements Serializable String root = "cn="+getRoot()+","; if (dn.endsWith(mLocalPath)) dn = dn.substring(0, dn.lastIndexOf(mLocalPath)); - + if (dn.endsWith(root)) dn = dn.substring(0, dn.lastIndexOf(root)); @@ -180,7 +180,7 @@ public abstract class Path implements Serializable else break; } - mPath = (String[])(newPath.toArray(mPath)); + mPath = (newPath.toArray(mPath)); mSysKey = INVALID; mStringPath = null; mDN = dn+root; @@ -204,8 +204,8 @@ public abstract class Path implements Serializable { if (mStringPath == null) { StringBuffer stringPathBuffer = new StringBuffer("/").append(getRoot()); - for (int i=0; i getChildren() { String filter = "objectclass=*"; LDAPSearchConstraints searchCons = new LDAPSearchConstraints(); searchCons.setBatchSize(10); searchCons.setDereference(LDAPSearchConstraints.DEREF_FINDING ); return Gateway.getLDAPLookup().search(getFullDN(), LDAPConnection.SCOPE_ONE,filter,searchCons); } - + public Path find(String name) throws ObjectNotFoundException { - Enumeration e = Gateway.getLDAPLookup().search(this, name); + Enumeration e = Gateway.getLDAPLookup().search(this, name); if (e.hasMoreElements()) { Path thisPath =(Path)e.nextElement(); if (e.hasMoreElements()) @@ -277,24 +277,26 @@ public abstract class Path implements Serializable } throw new ObjectNotFoundException("No match for "+name, ""); } - + public abstract EntityPath getEntity() throws ObjectNotFoundException; public abstract LDAPAttributeSet createAttributeSet() throws ObjectCannotBeUpdated; - - public boolean equals( Object path ) - { + + @Override + public boolean equals( Object path ) + { return toString().equals(path.toString()); } - - public int hashCode() { + + @Override + public int hashCode() { return toString().hashCode(); } public String dump() { StringBuffer comp = new StringBuffer("Components: { "); - for (int i=0; i getChildren() { AgentPath[] agents = getAgentsWithRole(); Vector children = new Vector(agents.length); for (int i = 0; i < agents.length; i++) children.add(i, agents[i]); return children.elements(); } - + public AgentPath[] getAgentsWithRole() { try { return Gateway.getLDAPLookup().getRoleManager().getAgents(this); @@ -77,20 +79,21 @@ public class RolePath extends DomainPath return new AgentPath[0]; } } - + public void addAgent(AgentPath agent) throws ObjectCannotBeUpdated, ObjectNotFoundException { Gateway.getLDAPLookup().getRoleManager().addRole(agent, this); } - + public void removeAgent(AgentPath agent) throws ObjectCannotBeUpdated, ObjectNotFoundException { Gateway.getLDAPLookup().getRoleManager().removeRole(agent, this); } - - public String dump() { + + @Override + public String dump() { StringBuffer comp = new StringBuffer("Components: { "); - for (int i=0; i iter = allStores.values().iterator(); iter.hasNext();) { - ClusterStorage thisStorage = (ClusterStorage)iter.next(); + for (ClusterStorage thisStorage : allStores.values()) { try { thisStorage.close(); } catch (ClusterStorageException ex) { @@ -94,28 +97,28 @@ public class ClusterStorageManager { * Collection, Property) Must specify if the request is a read or a write. */ private ArrayList findStorages(String clusterType, boolean forWrite) { - + if (!ready) { Logger.error("ClusterStorageManager.findStorages() - called before init!"); return null; } - + // choose the right cache for readers or writers HashMap> cache; if (forWrite) cache = clusterWriters; else cache = clusterReaders; - + // check to see if we've been asked to do this before if (cache.containsKey(clusterType)) - return (ArrayList)cache.get(clusterType); - + return cache.get(clusterType); + // not done yet, we'll have to query them all Logger.msg(7, "ClusterStorageManager.findStorages() - finding storage for "+clusterType+" forWrite:"+forWrite); ArrayList useableStorages = new ArrayList(); - for (int i = 0; i < clusterPriority.length; i++) { - ClusterStorage thisStorage = (ClusterStorage)allStores.get(clusterPriority[i]); + for (String element : clusterPriority) { + ClusterStorage thisStorage = allStores.get(element); short requiredSupport = forWrite ? ClusterStorage.WRITE : ClusterStorage.READ; if ((thisStorage.queryClusterSupport(clusterType) & requiredSupport) == requiredSupport) { Logger.msg(7, "ClusterStorageManager.findStorages() - Got "+thisStorage.getName()); @@ -126,20 +129,18 @@ public class ClusterStorageManager { return useableStorages; } - /** - * Retrieves the ids of the next level of a cluster + /** + * Retrieves the ids of the next level of a cluster * Does not look in any currently open transactions. */ public String[] getClusterContents(Integer sysKey, String path) throws ClusterStorageException { //String[] retArr = new String[0]; ArrayList contents = new ArrayList(); // get all readers - String type = ClusterStorage.getClusterType(path); Logger.msg(8, "ClusterStorageManager.getClusterContents() - Finding contents of "+path); ArrayList readers = findStorages(ClusterStorage.getClusterType(path), false); // try each in turn until we get a result - for (Iterator i = readers.iterator(); i.hasNext();) { - ClusterStorage thisReader = (ClusterStorage)i.next(); + for (ClusterStorage thisReader : readers) { try { String[] thisArr = thisReader.getClusterContents(sysKey, path); if (thisArr != null) { @@ -154,10 +155,10 @@ public class ClusterStorageManager { " could not retrieve contents of " + sysKey + "/" + path + ": " + e.getMessage()); } } - + String[] retArr = new String[0]; - retArr = (String[])contents.toArray(retArr); - return retArr; + retArr = contents.toArray(retArr); + return retArr; } /** Internal get method. Retrieves clusters from ClusterStorages & maintains the memory cache */ @@ -166,16 +167,16 @@ public class ClusterStorageManager { // check cache first SoftCache sysKeyMemCache = null; if (memoryCache.containsKey(sysKeyIntObj)) { - sysKeyMemCache = (SoftCache)memoryCache.get(sysKeyIntObj); + sysKeyMemCache = memoryCache.get(sysKeyIntObj); synchronized(sysKeyMemCache) { - C2KLocalObject obj = (C2KLocalObject)sysKeyMemCache.get(path); + C2KLocalObject obj = sysKeyMemCache.get(path); if (obj != null) { Logger.msg(7, "ClusterStorageManager.get() - found "+sysKeyIntObj+"/"+path+" in memcache"); return obj; } } } - + // special case - loading viewpoint contents if (path.startsWith(ClusterStorage.VIEWPOINT) && path.endsWith("/data")) { @@ -188,11 +189,10 @@ public class ClusterStorageManager { return data; } } - + // else try each reader in turn until we find it ArrayList readers = findStorages(ClusterStorage.getClusterType(path), false); - for (Iterator i = readers.iterator(); i.hasNext(); ) { - ClusterStorage thisReader = (ClusterStorage)i.next(); + for (ClusterStorage thisReader : readers) { try { result = thisReader.get(sysKeyIntObj, path); Logger.msg(7, "ClusterStorageManager.get() - reading "+path+" from "+thisReader.getName() + " for intkey=" + sysKeyIntObj); @@ -222,8 +222,7 @@ public class ClusterStorageManager { public void put(Integer sysKeyIntObj, C2KLocalObject obj) throws ClusterStorageException { String path = ClusterStorage.getPath(obj); ArrayList writers = findStorages(ClusterStorage.getClusterType(path), true); - for (Iterator i = writers.iterator(); i.hasNext(); ) { - ClusterStorage thisWriter = (ClusterStorage)i.next(); + for (ClusterStorage thisWriter : writers) { try { Logger.msg(7, "ClusterStorageManager.put() - writing "+path+" to "+thisWriter.getName()); thisWriter.put(sysKeyIntObj, obj); @@ -236,18 +235,18 @@ public class ClusterStorageManager { // put in mem cache if that worked SoftCache sysKeyMemCache; if (memoryCache.containsKey(sysKeyIntObj)) - sysKeyMemCache = (SoftCache)memoryCache.get(sysKeyIntObj); + sysKeyMemCache = memoryCache.get(sysKeyIntObj); else { sysKeyMemCache = new SoftCache(); - synchronized (memoryCache) { + synchronized (memoryCache) { memoryCache.put(sysKeyIntObj, sysKeyMemCache); } } - + synchronized(sysKeyMemCache) { sysKeyMemCache.put(path, obj); } - + if (Logger.doLog(9)) dumpCacheContents(9); // transmit proxy event @@ -257,8 +256,7 @@ public class ClusterStorageManager { /** Deletes a cluster from all writers */ public void remove(Integer sysKeyIntObj, String path) throws ClusterStorageException { ArrayList writers = findStorages(ClusterStorage.getClusterType(path), true); - for (Iterator i = writers.iterator(); i.hasNext(); ) { - ClusterStorage thisWriter = (ClusterStorage)i.next(); + for (ClusterStorage thisWriter : writers) { try { Logger.msg(7, "ClusterStorageManager.delete() - removing "+path+" from "+thisWriter.getName()); thisWriter.delete(sysKeyIntObj, path); @@ -268,24 +266,24 @@ public class ClusterStorageManager { throw e; } } - + if (memoryCache.containsKey(sysKeyIntObj)) { - SoftCache sysKeyMemCache = (SoftCache)memoryCache.get(sysKeyIntObj); + SoftCache sysKeyMemCache = memoryCache.get(sysKeyIntObj); synchronized (sysKeyMemCache) { sysKeyMemCache.remove(path); } } - + // transmit proxy event EntityProxyManager.sendProxyEvent( new ProxyMessage(sysKeyIntObj.intValue(), path, ProxyMessage.DELETED)); } - + public void clearCache(Integer sysKeyIntObj, String path) { Logger.msg(7, "CSM.clearCache() - removing "+sysKeyIntObj+"/"+path); - + if (memoryCache.containsKey(sysKeyIntObj)) { - SoftCache sysKeyMemCache = (SoftCache)memoryCache.get(sysKeyIntObj); + SoftCache sysKeyMemCache = memoryCache.get(sysKeyIntObj); synchronized(sysKeyMemCache) { for (Iterator iter = sysKeyMemCache.keySet().iterator(); iter.hasNext();) { String thisPath = (String)iter.next(); @@ -297,15 +295,15 @@ public class ClusterStorageManager { } } } - + public void clearCache(Integer sysKeyIntObj) { Logger.msg(5, "CSM.clearCache() - removing entire cache of "+sysKeyIntObj); - + if (memoryCache.containsKey(sysKeyIntObj)) { synchronized (memoryCache) { if (Logger.doLog(6)) { - SoftCache sysKeyMemCache = (SoftCache)memoryCache.get(sysKeyIntObj); + SoftCache sysKeyMemCache = memoryCache.get(sysKeyIntObj); int size = sysKeyMemCache.size(); Logger.msg(6, "CSM.clearCache() - "+size+" objects to remove."); } @@ -315,25 +313,24 @@ public class ClusterStorageManager { else Logger.msg(6, "CSM.clearCache() - No objects cached"); } - + public void clearCache() { synchronized (memoryCache) { memoryCache.clear(); } Logger.msg(5, "CSM.clearCache() - cleared entire cache, "+memoryCache.size()+" entities."); } - + public void dumpCacheContents(int logLevel) { if (!Logger.doLog(logLevel)) return; synchronized(memoryCache) { - for (Iterator iter = memoryCache.keySet().iterator(); iter.hasNext();) { - Integer sysKey = (Integer) iter.next(); + for (Integer sysKey : memoryCache.keySet()) { Logger.msg(logLevel, "Cached Objects of Entity "+sysKey); - SoftCache sysKeyMemCache = (SoftCache)memoryCache.get(sysKey); + SoftCache sysKeyMemCache = memoryCache.get(sysKey); try { synchronized(sysKeyMemCache) { - for (Iterator iterator = sysKeyMemCache.keySet().iterator();iterator.hasNext();) { - String path = (String) iterator.next(); + for (Object name : sysKeyMemCache.keySet()) { + String path = (String) name; try { Logger.msg(logLevel, " Path "+path+": "+sysKeyMemCache.get(path).getClass().getName()); } catch (NullPointerException e) { @@ -345,20 +342,20 @@ public class ClusterStorageManager { Logger.msg(logLevel, "Cache modified - aborting"); } } - Logger.msg(logLevel, "Total number of cached entities: "+memoryCache.size()); + Logger.msg(logLevel, "Total number of cached entities: "+memoryCache.size()); } - } - + } + public Object query(String id, Object query) throws ClusterStorageException { - ClusterStorage requiredStorage = (ClusterStorage)allStores.get(id); - if (requiredStorage == null) + ClusterStorage requiredStorage = allStores.get(id); + if (requiredStorage == null) throw new ClusterStorageException("Storage "+id+" not found."); return requiredStorage.query(query); } - + public String queryToXML(String id, String query, boolean genericFormat) throws ClusterStorageException { - ClusterStorage requiredStorage = (ClusterStorage)allStores.get(id); - if (requiredStorage == null) + ClusterStorage requiredStorage = allStores.get(id); + if (requiredStorage == null) throw new ClusterStorageException("Storage "+id+" not found."); return requiredStorage.queryToXML(query, genericFormat); } diff --git a/source/com/c2kernel/persistency/LDAPClientReader.java b/source/com/c2kernel/persistency/LDAPClientReader.java old mode 100755 new mode 100644 index c40658e..ac9215c --- a/source/com/c2kernel/persistency/LDAPClientReader.java +++ b/source/com/c2kernel/persistency/LDAPClientReader.java @@ -8,14 +8,16 @@ import com.c2kernel.entity.C2KLocalObject; public class LDAPClientReader extends LDAPClusterStorage { // return all readwrite support as readonly - public short queryClusterSupport(String clusterType) { + @Override + public short queryClusterSupport(String clusterType) { return (short)(super.queryClusterSupport(clusterType) & READ); } - - + + /** * @see com.c2kernel.persistency.ClusterStorage#delete(Integer, String) */ + @Override public void delete(Integer sysKey, String path) throws ClusterStorageException { throw new ClusterStorageException("Writing not supported in ClientReader"); @@ -24,6 +26,7 @@ public class LDAPClientReader extends LDAPClusterStorage { /** * @see com.c2kernel.persistency.ClusterStorage#getName() */ + @Override public String getName() { return "LDAP Client Cluster Reader"; } @@ -31,6 +34,7 @@ public class LDAPClientReader extends LDAPClusterStorage { /** * @see com.c2kernel.persistency.ClusterStorage#put(Integer, String, C2KLocalObject) */ + public void put(Integer sysKey, String path, C2KLocalObject obj) throws ClusterStorageException { throw new ClusterStorageException("Writing not supported in ClientReader"); diff --git a/source/com/c2kernel/persistency/LDAPClusterStorage.java b/source/com/c2kernel/persistency/LDAPClusterStorage.java index fb36d9f..16ac7a0 100644 --- a/source/com/c2kernel/persistency/LDAPClusterStorage.java +++ b/source/com/c2kernel/persistency/LDAPClusterStorage.java @@ -14,32 +14,38 @@ import com.c2kernel.utils.Logger; public class LDAPClusterStorage extends ClusterStorage { LDAPPropertyManager ldapStore; - public void open() throws ClusterStorageException { + @Override + public void open() throws ClusterStorageException { ldapStore = Gateway.getLDAPLookup().getPropManager(); } - public void close() throws ClusterStorageException { + @Override + public void close() throws ClusterStorageException { } // introspection - public short queryClusterSupport(String clusterType) { + @Override + public short queryClusterSupport(String clusterType) { if (clusterType.equals(PROPERTY)) return READWRITE; else return NONE; } - public String getName() { + @Override + public String getName() { return "LDAP Cluster Storage"; } - - public String getId() { + + @Override + public String getId() { return "LDAP"; } // retrieve object by path - public C2KLocalObject get(Integer sysKey, String path) throws ClusterStorageException { + @Override + public C2KLocalObject get(Integer sysKey, String path) throws ClusterStorageException { Logger.msg(6, "LDAPClusterStorage.get() - "+sysKey+"/"+path); StringTokenizer tok = new StringTokenizer(path, "/"); int pathLength = tok.countTokens(); @@ -75,7 +81,8 @@ public class LDAPClusterStorage extends ClusterStorage { return newObj; } // store object by path - public void put(Integer sysKey, C2KLocalObject obj) throws ClusterStorageException { + @Override + public void put(Integer sysKey, C2KLocalObject obj) throws ClusterStorageException { Logger.msg(6, "LDAPClusterStorage.put() - "+sysKey+"/"+ClusterStorage.getPath(obj)); String type = obj.getClusterType(); @@ -100,7 +107,8 @@ public class LDAPClusterStorage extends ClusterStorage { } // delete cluster - public void delete(Integer sysKey, String path) throws ClusterStorageException { + @Override + public void delete(Integer sysKey, String path) throws ClusterStorageException { StringTokenizer tok = new StringTokenizer(path, "/"); int pathLength = tok.countTokens(); if (pathLength != 2) @@ -120,7 +128,7 @@ public class LDAPClusterStorage extends ClusterStorage { } catch (Exception e1) { Logger.error(e1); throw new ClusterStorageException("LDAPClusterStorage - could not delete property"); - } + } } else throw new ClusterStorageException("Cluster type "+type+" not supported."); @@ -130,26 +138,27 @@ public class LDAPClusterStorage extends ClusterStorage { /* navigation */ // directory listing - public String[] getClusterContents(Integer sysKey, String path) throws ClusterStorageException { + @Override + public String[] getClusterContents(Integer sysKey, String path) throws ClusterStorageException { Logger.msg(6, "LDAPClusterStorage.getClusterContents() - "+sysKey+"/"+path); StringTokenizer tok = new StringTokenizer(path, "/"); int pathLength = tok.countTokens(); if (pathLength > 1) return new String[0]; - + String type = getClusterType(path); - try + try { EntityPath thisEntity = new EntityPath(sysKey.intValue()); if (type.equals(PROPERTY)) return ldapStore.getPropertyNames(thisEntity); - else + else if (type.equals("")) { // root query String[] allClusters = new String[0]; ArrayList clusterList = new ArrayList(); if (ldapStore.hasProperties(thisEntity)) clusterList.add(PROPERTY); - allClusters = (String[])clusterList.toArray(allClusters); + allClusters = clusterList.toArray(allClusters); return allClusters; } else diff --git a/source/com/c2kernel/persistency/ProxyLoader.java b/source/com/c2kernel/persistency/ProxyLoader.java index 687141f..e614b0d 100644 --- a/source/com/c2kernel/persistency/ProxyLoader.java +++ b/source/com/c2kernel/persistency/ProxyLoader.java @@ -21,38 +21,44 @@ public class ProxyLoader extends ClusterStorage { HashMap entities = new HashMap(); LDAPLookup lookup; - public void open() throws ClusterStorageException { + @Override + public void open() throws ClusterStorageException { lookup = Gateway.getLDAPLookup(); } - public void close() throws ClusterStorageException { + @Override + public void close() throws ClusterStorageException { } // introspection - public short queryClusterSupport(String clusterType) { + @Override + public short queryClusterSupport(String clusterType) { return READ; } - public String getName() { + @Override + public String getName() { return "Proxy Cluster Loader"; } - - public String getId() { + + @Override + public String getId() { return "CORBA"; } // retrieve object by path - public C2KLocalObject get(Integer sysKey, String path) throws ClusterStorageException { + @Override + public C2KLocalObject get(Integer sysKey, String path) throws ClusterStorageException { try { ManageableEntity thisEntity = getIOR(sysKey); String type = getClusterType(path); // fetch the xml from the item String queryData = thisEntity.queryData(path); - + if (queryData != null) { - if (type.equals(OUTCOME)) + if (type.equals(OUTCOME)) return new Outcome(path, queryData); - else + else return (C2KLocalObject)CastorXMLUtility.unmarshall(queryData); } } catch (Exception e) { @@ -61,14 +67,16 @@ public class ProxyLoader extends ClusterStorage { } return null; } - + // store object by path - public void put(Integer sysKey, C2KLocalObject obj) throws ClusterStorageException { + @Override + public void put(Integer sysKey, C2KLocalObject obj) throws ClusterStorageException { // not supported throw new ClusterStorageException("Cannot write to items through the ProxyLoader"); } // delete cluster - public void delete(Integer sysKey, String path) throws ClusterStorageException { + @Override + public void delete(Integer sysKey, String path) throws ClusterStorageException { // not supported throw new ClusterStorageException("Cannot write to items through the ProxyLoader"); } @@ -76,33 +84,34 @@ public class ProxyLoader extends ClusterStorage { /* navigation */ // directory listing - public String[] getClusterContents(Integer sysKey, String path) throws ClusterStorageException { + @Override + public String[] getClusterContents(Integer sysKey, String path) throws ClusterStorageException { try { ManageableEntity thisEntity = getIOR(sysKey); String contents = thisEntity.queryData(path+"/all"); StringTokenizer tok = new StringTokenizer(contents, ","); String[] result = new String[tok.countTokens()]; - for (int i=0; i extends TreeMap implements C2KLocalObject { private int mID=-1; private String mName; protected int mSysKey; private String mPath = ""; - protected String[] keys = null; - Object keyLock = new Object(); - protected C2KLocalObject[] values = null; + Object keyLock = null; TransactionManager storage; - EntityProxyObserver listener; + EntityProxyObserver listener; + Comparator comp; EntityProxy source; - Object mLocker; // if this remote map will participate in a transaction - + Object mLocker; // if this remote map will participate in a transaction + public RemoteMap(int sysKey, String path, Object locker) { + + super(new Comparator() { + @Override + public int compare(String o1, String o2) { + Integer i1 = null, i2 = null; + try { + i1 = Integer.valueOf(o1); + i2 = Integer.valueOf(o2); + return i1.compareTo(i2); + } catch (NumberFormatException ex) { } + return o1.compareTo(o2); + } + }); + mSysKey = sysKey; mLocker = locker; @@ -56,138 +67,99 @@ public class RemoteMap implements C2KLocalObject, Map { mID = Integer.parseInt(mName); } catch (NumberFormatException e) {} storage = Gateway.getStorage(); - - listener = new EntityProxyObserver() { - public void add(C2KLocalObject obj) { - synchronized (keyLock) { - if (keys == null) return; - boolean found = false; - for (int i=0; i() { + @Override + public void add(V obj) { + synchronized (this) { + putLocal(obj.getName(), obj); + } } - public void remove(String id) { - synchronized (keyLock) { - if (keys == null) return; - boolean found = false; - for (int i=0; i(listener, path, false)); } catch (Exception ex) { Logger.error("Error subscribing to remote map. Changes will not be received"); Logger.error(ex); } } - - protected void loadKeys() throws ClusterStorageException { - synchronized(keyLock) { - keys = storage.getClusterContents(mSysKey, mPath+mName); - values = new C2KLocalObject[keys.length]; + + protected void loadKeys() { + if (keyLock != null) return; + clear(); + keyLock = new Object(); + synchronized(this) { + String[] keys; + try { + keys = storage.getClusterContents(mSysKey, mPath+mName); + for (String key : keys) super.put(key, null); + } catch (ClusterStorageException e) { + Logger.error(e); + } + } } - - protected String[] getKeys() { - try { - if (keys == null) loadKeys(); - } catch (ClusterStorageException e) { - Logger.error(e); - keys = new String[0]; - } - return keys; - } - + public synchronized int getLastId() { - - synchronized (this) { - int lastID = -1; - - String[] allIds = getKeys(); - - for (int i = 0; i < allIds.length; i++) { - try { - int thisID = Integer.parseInt(allIds[i]); - if (thisID > lastID) lastID = thisID; - } catch (NumberFormatException e) { - Logger.warning("RemoteMap.getLastID() - Cluster contained invalid id: "+allIds[i]); - } - } - Logger.msg(7, "RemoteMap.getLastID() - last id in "+mPath+mName+" of "+mSysKey+" is "+lastID); - return lastID; - } - } - + loadKeys(); + try { + return Integer.parseInt(lastKey()); + } catch (NumberFormatException ex) { + return -1; + } + } + // c2kLocalObject methods public void setID(int id) { mID = id; } public int getID() { return mID; } + @Override public void setName(String name) { mName = name; } + @Override public String getName() { return mName; } /** * Cannot be stored */ + @Override public String getClusterType() { return null; } /** * @see java.util.Map#clear() */ + @Override public synchronized void clear() { - keys = null; + synchronized (this) { + super.clear(); + } + keyLock = null; } - + /** * @see java.util.Map#containsKey(Object) */ + @Override public synchronized boolean containsKey(Object key) { - getKeys(); - for (int i = 0; i < keys.length; i++) { - if (key.equals(keys[i])) - return true; - } - return false; + if (keyLock == null) loadKeys(); + return super.containsKey(key); } /** @@ -195,46 +167,40 @@ public class RemoteMap implements C2KLocalObject, Map { * Very expensive, but if you must, you must. * @see java.util.Map#containsValue(Object) */ + @Override public synchronized boolean containsValue(Object value) { - getKeys(); - synchronized(keyLock) { - if (values == null) values = new C2KLocalObject[keys.length]; - for (int i = 0; i < keys.length; i++) { - try { - if (values[i] == null) values[i] = storage.get(mSysKey, mPath+mName+"/"+keys[i], mLocker); - if (value.equals(values[i])) return true; - } catch (ClusterStorageException ex) { - Logger.error(ex); - } catch (ObjectNotFoundException e) { - Logger.error(e); - } + loadKeys(); + synchronized(this) { + for (String key: keySet()) { + if (get(key).equals(value)) return true; } } return false; } - /** - * @see java.util.Map#entrySet() - */ - public synchronized Set entrySet() { - return new RemoteMap.RemoteSet(this, KEYS); - } /** * @see java.util.Map#get(Object) */ - public synchronized Object get(Object key) { - getKeys(); - synchronized(keyLock) { - if (values == null) values = new C2KLocalObject[keys.length]; + @Override + public synchronized V get(Object objKey) { + loadKeys(); + String key; + if (objKey instanceof Integer) + key = ((Integer)objKey).toString(); + else if (objKey instanceof String) + key = (String)objKey; + else + return null; + + synchronized(this) { try { - for (int i = 0; i < keys.length; i++) { - if (key.equals(keys[i])) { - if (values[i] == null) - values[i] = storage.get(mSysKey, mPath+mName+"/"+keys[i], mLocker); - return values[i]; - } + V value = super.get(key); + if (value == null) { + value = (V)storage.get(mSysKey, mPath+mName+"/"+key, mLocker); + super.put(key, value); } + return value; } catch (ClusterStorageException e) { Logger.error(e); } catch (ObjectNotFoundException e) { @@ -247,15 +213,19 @@ public class RemoteMap implements C2KLocalObject, Map { /** * @see java.util.Map#isEmpty() */ + @Override public synchronized boolean isEmpty() { - return getKeys().length==0; + loadKeys(); + return super.isEmpty(); } /** * @see java.util.Map#keySet() */ - public synchronized Set keySet() { - return new RemoteMap.RemoteSet(this, KEYS); + @Override + public synchronized Set keySet() { + loadKeys(); + return super.keySet(); } /** @@ -263,60 +233,59 @@ public class RemoteMap implements C2KLocalObject, Map { * the key is ignored - it can be fetched from the value. * @see java.util.Map#put(Object, Object) */ - public synchronized Object put(Object key, Object value) { + @Override + public synchronized V put(String key, V value) { try { - C2KLocalObject newValue = (C2KLocalObject)value; - synchronized(keyLock) { - storage.put(mSysKey, newValue, mLocker); - keys = null; values = null; + synchronized(this) { + storage.put(mSysKey, value, mLocker); + return putLocal(key, value); } } catch (ClusterStorageException e) { Logger.error(e); return null; - } catch (ClassCastException e) { - Logger.error("RemoteMap.put() - value was not a localobject, it was a "+value.getClass().getName()); - return null; } - return value; } - - /** - * @see java.util.Map#putAll(Map) - */ - public synchronized void putAll(Map t) { - for (Iterator iter = t.keySet().iterator(); iter.hasNext();) { - Object key = iter.next(); - put(key, t.get(key)); - } + + protected synchronized V putLocal(String key, V value) { + return super.put(key, value); } /** * @see java.util.Map#remove(Object) */ - public synchronized Object remove(Object key) { - try { + @Override + public synchronized V remove(Object key) { + loadKeys(); + if (containsKey(key)) try { synchronized(keyLock) { storage.remove(mSysKey, mPath+mName+"/"+key, mLocker); - keys = null; values = null; - } + return super.remove(key); + } } catch (ClusterStorageException e) { Logger.error(e); } return null; } + + protected synchronized V removeLocal(Object key) { + return super.remove(key); + } /** * @see java.util.Map#size() */ + @Override public synchronized int size() { - return getKeys().length; + loadKeys(); + return super.size(); } /** * @see java.util.Map#values() */ - public synchronized Collection values() { - return new RemoteMap.RemoteSet(this, VALUES); + @Override + public synchronized Collection values() { + return new RemoteSet(this); } /** @@ -324,39 +293,45 @@ public class RemoteMap implements C2KLocalObject, Map { * Disallows all writes. */ - private class RemoteSet extends AbstractSet { - RemoteMap mParent; - boolean mMode; - - public RemoteSet(RemoteMap parent, boolean mode) { + private class RemoteSet extends AbstractSet { + RemoteMap mParent; + + public RemoteSet(RemoteMap parent) { mParent = parent; - mMode = mode; } - // no modifications allowed - public boolean add(Object o) { + // no modifications allowed + @Override + public boolean add(E o) { throw new UnsupportedOperationException(); } - public boolean addAll(Collection c) { + @Override + public boolean addAll(Collection c) { throw new UnsupportedOperationException(); } - public void clear() { + @Override + public void clear() { throw new UnsupportedOperationException(); } - public boolean remove(Object o) { + @Override + public boolean remove(Object o) { throw new UnsupportedOperationException(); } - public boolean removeAll(Collection c) { + @Override + public boolean removeAll(Collection c) { throw new UnsupportedOperationException(); } - public boolean retainAll(Collection c) { + @Override + public boolean retainAll(Collection c) { throw new UnsupportedOperationException(); } - public Iterator iterator() { - return new RemoteIterator(mParent, mMode); + @Override + public Iterator iterator() { + return new RemoteIterator(mParent); } + @Override public int size() { return mParent.size(); } @@ -366,32 +341,26 @@ public class RemoteMap implements C2KLocalObject, Map { * Iterator view on RemoteMap data. Doesn't preload anything. * REVISIT: Will go strange if the RemoteMap is modified. Detect this and throw ConcurrentMod ex */ - private class RemoteIterator implements Iterator { - RemoteMap mParent; - boolean mMode; - String[] keyArr; - int pos; - - public RemoteIterator(RemoteMap parent, boolean mode) { + private class RemoteIterator implements Iterator { + RemoteMap mParent; + Iterator iter; + + public RemoteIterator(RemoteMap parent) { mParent = parent; - mMode = mode; - keyArr = mParent.getKeys(); + iter = mParent.keySet().iterator(); } + @Override public boolean hasNext() { - return (pos(); pendingTransactions = new HashMap>(); } - + public boolean hasPendingTransactions() { return pendingTransactions.size() > 0; } - + public ClusterStorageManager getDb() { return storage; } @@ -40,40 +38,36 @@ public class TransactionManager { Logger.msg("Transaction Manager: Closing storages"); storage.close(); } - + public String[] getClusterContents(int sysKey, String path) throws ClusterStorageException { if (path.startsWith("/") && path.length() > 1) path = path.substring(1); return storage.getClusterContents(new Integer(sysKey), path); } - + /** * Public get method. Required a 'locker' object for a transaction key. * Checks the transaction table first to see if the caller has uncommitted changes */ - public C2KLocalObject get(int sysKey, String path, Object locker) - throws ClusterStorageException, + public C2KLocalObject get(int sysKey, String path, Object locker) + throws ClusterStorageException, ObjectNotFoundException { if (path.startsWith("/") && path.length() > 1) path = path.substring(1); - + // deal out top level remote maps - if (path.indexOf('/') == -1) { - try { - if (path.equals(ClusterStorage.HISTORY)) - return new History(sysKey, locker); - if (path.equals(ClusterStorage.JOB)) - return new JobList(sysKey, locker); - } catch (InvalidEntityPathException ex) { - throw new ObjectNotFoundException("Invalid key"); - } + if (path.indexOf('/') == -1) { + if (path.equals(ClusterStorage.HISTORY)) + return new History(sysKey, locker); + if (path.equals(ClusterStorage.JOB)) + return new JobList(sysKey, locker); } - + Integer sysKeyIntObj = new Integer(sysKey); // check to see if the locker has been modifying this cluster synchronized(locks) { if (locks.containsKey(sysKeyIntObj) && locks.get(sysKeyIntObj).equals(locker)) { - ArrayList lockerTransaction = (ArrayList)pendingTransactions.get(locker); - for (Iterator i = lockerTransaction.iterator(); i.hasNext(); ) { - TransactionEntry thisEntry = (TransactionEntry)i.next(); + ArrayList lockerTransaction = pendingTransactions.get(locker); + for (Object name : lockerTransaction) { + TransactionEntry thisEntry = (TransactionEntry)name; if (sysKey == thisEntry.sysKey.intValue() && path.equals(thisEntry.getPath())) { if (thisEntry.obj == null) throw new ClusterStorageException("ClusterStorageManager.get() - Cluster " + path + " has been deleted in " + sysKey + @@ -94,7 +88,7 @@ public class TransactionManager { Integer sysKeyIntObj = new Integer(sysKey); ArrayList lockerTransaction; String path = ClusterStorage.getPath(obj); - + synchronized(locks) { // look to see if this object is already locked if (locks.containsKey(sysKeyIntObj)) { @@ -157,7 +151,7 @@ public class TransactionManager { pendingTransactions.put(locker, lockerTransaction); } } - + // create the new entry in the transaction table TransactionEntry newEntry = new TransactionEntry(sysKeyIntObj, path, null); /* equals() in TransactionEntry only compares sysKey and path, so we can use @@ -167,38 +161,38 @@ public class TransactionManager { if (lockerTransaction.contains(newEntry)) lockerTransaction.remove(newEntry); lockerTransaction.add(newEntry); - } + } } - + /** * Removes all child objects from the given path - * + * * @param sysKey - entity to delete from * @param path - root path to delete * @param locker - locking object - * + * * @throws ClusterStorageException - when deleting fails */ public void removeCluster(int sysKey, String path, Object locker) throws ClusterStorageException { - + String[] children = getClusterContents(sysKey, path); - for (int i = 0; i < children.length; i++) - removeCluster(sysKey, path+(path.length()>0?"/":"")+children[i], locker); + for (String element : children) + removeCluster(sysKey, path+(path.length()>0?"/":"")+element, locker); if (children.length==0 && path.indexOf("/") > -1) remove(sysKey, path, locker); - } + } /** * Writes all pending changes to the backends. */ public void commit(Object locker) { synchronized(locks) { - ArrayList lockerTransactions = (ArrayList)pendingTransactions.get(locker); + ArrayList lockerTransactions = pendingTransactions.get(locker); HashMap exceptions = new HashMap(); // quit if no transactions are present; if (lockerTransactions == null) return; - for (Iterator i = lockerTransactions.iterator();i.hasNext();) { - TransactionEntry thisEntry = (TransactionEntry)i.next(); + for (Object name : lockerTransactions) { + TransactionEntry thisEntry = (TransactionEntry)name; try { if (thisEntry.obj == null) storage.remove(thisEntry.sysKey, thisEntry.path); @@ -207,14 +201,13 @@ public class TransactionManager { locks.remove(thisEntry.sysKey); } catch (Exception e) { exceptions.put(thisEntry, e); - } + } } pendingTransactions.remove(locker); if (exceptions.size() > 0) { // oh dear Logger.error("TransactionManager.commit() - Problems during transaction commit of locker "+locker.toString()+". Database may be in an inconsistent state."); - for (Iterator iter = exceptions.keySet().iterator(); iter.hasNext();) { - TransactionEntry entry = (TransactionEntry) iter.next(); - Exception ex = (Exception)exceptions.get(entry); + for (TransactionEntry entry : exceptions.keySet()) { + Exception ex = exceptions.get(entry); Logger.msg(entry.toString()); Logger.error(ex); } @@ -231,8 +224,7 @@ public class TransactionManager { public void abort(Object locker) { synchronized(locks) { if (locks.containsValue(locker)) { - for (Iterator i=locks.keySet().iterator(); i.hasNext();) { - Integer thisKey = (Integer)i.next(); + for (Integer thisKey : locks.keySet()) { if (locks.get(thisKey).equals(locker)) locks.remove(thisKey); } @@ -240,7 +232,7 @@ public class TransactionManager { pendingTransactions.remove(locker); } } - + public void clearCache(int sysKey, String path) { if (sysKey == -1) storage.clearCache(); @@ -248,9 +240,9 @@ public class TransactionManager { storage.clearCache(new Integer(sysKey)); else storage.clearCache(new Integer(sysKey), path); - + } - + public void dumpPendingTransactions(int logLevel) { Logger.msg(logLevel, "================"); Logger.msg(logLevel, "Transaction dump"); @@ -258,22 +250,20 @@ public class TransactionManager { if (locks.size() == 0) Logger.msg(logLevel, " None"); else - for (Iterator iter = locks.keySet().iterator(); iter.hasNext();) { - Integer thisKey = (Integer)iter.next(); + for (Integer thisKey : locks.keySet()) { Object locker = locks.get(thisKey); Logger.msg(logLevel, " "+thisKey+" locked by "+locker); } - + Logger.msg(logLevel, "Open transactions:"); if (pendingTransactions.size() == 0) Logger.msg(logLevel, " None"); else - for (Iterator iter = pendingTransactions.keySet().iterator(); iter.hasNext();) { - Object thisLocker = iter.next(); + for (Object thisLocker : pendingTransactions.keySet()) { Logger.msg(logLevel, " Transaction owner:"+thisLocker); - ArrayList entries = (ArrayList)pendingTransactions.get(thisLocker); - for (Iterator iterator = entries.iterator(); iterator.hasNext();) { - TransactionEntry thisEntry = (TransactionEntry) iterator.next(); + ArrayList entries = pendingTransactions.get(thisLocker); + for (Object name : entries) { + TransactionEntry thisEntry = (TransactionEntry) name; Logger.msg(logLevel, " "+thisEntry.toString()); } } @@ -290,12 +280,13 @@ public class TransactionManager { this.path = path; this.obj = obj; } - + public String getPath() { return ClusterStorage.getPath(obj); } - public String toString() { + @Override + public String toString() { StringBuffer report = new StringBuffer(); if (obj == null) report.append("Delete"); @@ -303,11 +294,12 @@ public class TransactionManager { report.append("Put "+obj.getClass().getName()); report.append(" at ").append(path).append(" in ").append(sysKey); return report.toString(); - + } /** * @see java.lang.Object#hashCode() */ + @Override public int hashCode() { return sysKey.hashCode()*getPath().hashCode(); } @@ -315,20 +307,21 @@ public class TransactionManager { /** * @see java.lang.Object#equals(java.lang.Object) */ + @Override public boolean equals(Object other) { if (other instanceof TransactionEntry) - return hashCode() == ((TransactionEntry)other).hashCode(); + return hashCode() == ((TransactionEntry)other).hashCode(); return false; } } - + public Object query(String id, Object query) throws ClusterStorageException { return storage.query(id, query); } - + public String queryToXML(String id, String query, boolean genericFormat) throws ClusterStorageException { return storage.queryToXML(id, query, genericFormat); } - + } diff --git a/source/com/c2kernel/persistency/XMLClusterStorage.java b/source/com/c2kernel/persistency/XMLClusterStorage.java index 24697af..277551d 100644 --- a/source/com/c2kernel/persistency/XMLClusterStorage.java +++ b/source/com/c2kernel/persistency/XMLClusterStorage.java @@ -17,7 +17,8 @@ public class XMLClusterStorage extends ClusterStorage { public XMLClusterStorage() { } - public void open() throws ClusterStorageException { + @Override + public void open() throws ClusterStorageException { String rootProp = Gateway.getProperty("XMLStorage.root"); if (rootProp == null) throw new ClusterStorageException("XMLClusterStorage.open() - Root path not given in config file."); @@ -31,33 +32,38 @@ public class XMLClusterStorage extends ClusterStorage { } } - public void close() { + @Override + public void close() { rootDir = null; } // introspection - public short queryClusterSupport(String clusterType) { + @Override + public short queryClusterSupport(String clusterType) { return ClusterStorage.READWRITE; } - public String getName() { + @Override + public String getName() { return "XML File Cluster Storage"; } - - public String getId() { + + @Override + public String getId() { return "XML"; } /* object manipulation */ // retrieve object by path - public C2KLocalObject get(Integer sysKey, String path) throws ClusterStorageException { + @Override + public C2KLocalObject get(Integer sysKey, String path) throws ClusterStorageException { try { String type = ClusterStorage.getClusterType(path); String filePath = getFilePath(sysKey, path)+".xml"; String objString = FileStringUtility.file2String(filePath); if (objString.length() == 0) return null; - + if (type.equals("Outcome")) return new Outcome(path, objString); else @@ -70,7 +76,8 @@ public class XMLClusterStorage extends ClusterStorage { } // store object by path - public void put(Integer sysKey, C2KLocalObject obj) throws ClusterStorageException { + @Override + public void put(Integer sysKey, C2KLocalObject obj) throws ClusterStorageException { try { String filePath = getFilePath(sysKey, getPath(obj)+".xml"); Logger.msg(7, "Writing "+filePath); @@ -89,7 +96,8 @@ public class XMLClusterStorage extends ClusterStorage { } // delete cluster - public void delete(Integer sysKey, String path) throws ClusterStorageException { + @Override + public void delete(Integer sysKey, String path) throws ClusterStorageException { try { String filePath = getFilePath(sysKey, path+".xml"); boolean success = FileStringUtility.deleteDir(filePath, true, true); @@ -104,11 +112,12 @@ public class XMLClusterStorage extends ClusterStorage { /* navigation */ // directory listing - public String[] getClusterContents(Integer sysKey, String path) throws ClusterStorageException { + @Override + public String[] getClusterContents(Integer sysKey, String path) throws ClusterStorageException { String[] result = new String[0]; try { String filePath = getFilePath(sysKey, path); - ArrayList paths = FileStringUtility.listDir( filePath, true, false ); + ArrayList paths = FileStringUtility.listDir( filePath, true, false ); if (paths == null) return result; // dir doesn't exist yet ArrayList contents = new ArrayList(); String previous = null; @@ -126,8 +135,8 @@ public class XMLClusterStorage extends ClusterStorage { if (next.indexOf('/') > -1) next = next.substring(next.lastIndexOf('/')+1); contents.add(next); } - - result = (String[])contents.toArray(result); + + result = contents.toArray(result); return result; } catch (Exception e) { Logger.error(e); diff --git a/source/com/c2kernel/persistency/outcome/Outcome.java b/source/com/c2kernel/persistency/outcome/Outcome.java old mode 100755 new mode 100644 index f919230..a5ecb29 --- a/source/com/c2kernel/persistency/outcome/Outcome.java +++ b/source/com/c2kernel/persistency/outcome/Outcome.java @@ -24,18 +24,18 @@ public class Outcome implements C2KLocalObject { String mSchemaType; int mSchemaVersion; static DocumentBuilder parser; - + static { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); - dbf.setNamespaceAware(false); + dbf.setNamespaceAware(false); try { parser = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { Logger.error(e); - } + } } - + //id is the eventID public Outcome(int id, String data, String schemaType, int schemaVersion) { mID = id; @@ -43,23 +43,23 @@ public class Outcome implements C2KLocalObject { mSchemaType = schemaType; mSchemaVersion = schemaVersion; } - + public Outcome(String path, String data) throws PersistencyException { // derive all the meta data from the path StringTokenizer tok = new StringTokenizer(path,"/"); - if (tok.countTokens() != 3 && !(tok.nextToken().equals("Outcome"))) + if (tok.countTokens() != 3 && !(tok.nextToken().equals("Outcome"))) throw new PersistencyException("Outcome() - Outcome path must have three components: "+path, null); mSchemaType = tok.nextToken(); String verstring = tok.nextToken(); String objId = tok.nextToken(); try { mSchemaVersion = Integer.parseInt(verstring); - } catch (NumberFormatException ex) { + } catch (NumberFormatException ex) { throw new PersistencyException("Outcome() - Outcome version was an invalid number: "+verstring, null); } try { mID = Integer.parseInt(objId); - } catch (NumberFormatException ex) { + } catch (NumberFormatException ex) { mID = -1; } mData = data; @@ -73,7 +73,8 @@ public class Outcome implements C2KLocalObject { return mID; } - public void setName(String name) { + @Override + public void setName(String name) { try { mID = Integer.parseInt(name); } catch (NumberFormatException e) { @@ -81,14 +82,15 @@ public class Outcome implements C2KLocalObject { } } - public String getName() { + @Override + public String getName() { return String.valueOf(mID); } public void setData(String data) { mData = data; } - + public void setData(Document data) { mData = serialize(data, false); } @@ -96,11 +98,11 @@ public class Outcome implements C2KLocalObject { public String getData() { return mData; } - + public void setSchemaType(String schemaType) { mSchemaType = schemaType; } - + public String getSchemaType() { return mSchemaType; } @@ -108,24 +110,25 @@ public class Outcome implements C2KLocalObject { public void setSchemaURL(int schemaVersion) { mSchemaVersion = schemaVersion; } - + public int getSchemaVersion() { return mSchemaVersion; - } - + } + public void setSchemaVersion(int schVer) { mSchemaVersion = schVer; - } - + } + + @Override public String getClusterType() { return ClusterStorage.OUTCOME; } - + // special script API methods /** * Parses the outcome into a DOM tree - * @return a DOM Document + * @return a DOM Document */ public Document getDOM() { try { @@ -137,7 +140,7 @@ public class Outcome implements C2KLocalObject { return null; } } - + static public String serialize(Document doc, boolean prettyPrint) { String serializedDoc = null; diff --git a/source/com/c2kernel/persistency/outcome/OutcomeValidator.java b/source/com/c2kernel/persistency/outcome/OutcomeValidator.java old mode 100755 new mode 100644 index 1a76322..73f5706 --- a/source/com/c2kernel/persistency/outcome/OutcomeValidator.java +++ b/source/com/c2kernel/persistency/outcome/OutcomeValidator.java @@ -10,7 +10,6 @@ import org.apache.xerces.parsers.XMLGrammarPreparser; import org.apache.xerces.util.SymbolTable; import org.apache.xerces.util.XMLGrammarPoolImpl; import org.apache.xerces.xni.XNIException; -import org.apache.xerces.xni.grammars.Grammar; import org.apache.xerces.xni.grammars.XMLGrammarDescription; import org.apache.xerces.xni.parser.XMLErrorHandler; import org.apache.xerces.xni.parser.XMLInputSource; @@ -43,33 +42,33 @@ public class OutcomeValidator implements ErrorHandler, XMLErrorHandler { /** Schema full checking feature id (http://apache.org/xml/features/validation/schema-full-checking). */ protected static final String SCHEMA_FULL_CHECKING_FEATURE_ID = "http://apache.org/xml/features/validation/schema-full-checking"; public static final String GRAMMAR_POOL = "http://apache.org/xml/properties/internal/grammar-pool"; - + static SchemaValidator schemaValid = new SchemaValidator(); - + Schema schema; protected StringBuffer errors = null; - XMLGrammarPoolImpl schemaGrammarPool = new XMLGrammarPoolImpl(1); - SymbolTable sym = new SymbolTable(); - + XMLGrammarPoolImpl schemaGrammarPool = new XMLGrammarPoolImpl(1); + SymbolTable sym = new SymbolTable(); + public static OutcomeValidator getValidator(Schema schema) throws InvalidDataException { String schemaId = schema.docType+"_"+schema.docVersion; - + if (schemaId.equals("Schema_0")) return schemaValid; - + return new OutcomeValidator(schema); } - + protected OutcomeValidator() { errors = new StringBuffer(); } - + public OutcomeValidator(Schema schema) throws InvalidDataException { this.schema = schema; - + if (schema.docType.equals("Schema")) throw new InvalidDataException("Use SchemaValidator to validate schema", ""); - + errors = new StringBuffer(); Logger.msg(5, "Parsing "+schema.docType+" version "+schema.docVersion+". "+schema.schema.length()+" chars"); @@ -83,7 +82,7 @@ public class OutcomeValidator implements ErrorHandler, XMLErrorHandler { preparser.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, true); preparser.setErrorHandler(this); try { - Grammar g = preparser.preparseGrammar(XMLGrammarDescription.XML_SCHEMA, new XMLInputSource(null, null, null, new StringReader(schema.schema), null)); + preparser.preparseGrammar(XMLGrammarDescription.XML_SCHEMA, new XMLInputSource(null, null, null, new StringReader(schema.schema), null)); } catch (IOException ex) { throw new InvalidDataException("Error parsing schema: "+ex.getMessage(), ""); } @@ -91,13 +90,13 @@ public class OutcomeValidator implements ErrorHandler, XMLErrorHandler { if (errors.length() > 0) { throw new InvalidDataException("Schema error: \n"+errors.toString(), ""); } - + } - + public synchronized String validate(Outcome outcome) { if (outcome == null) return "Outcome object was null"; Logger.msg(5, "Validating outcome no "+outcome.getID()+" as "+schema.docType+" v"+schema.docVersion); - if (outcome.getSchemaType().equals(schema.docType) + if (outcome.getSchemaType().equals(schema.docType) && outcome.getSchemaVersion() == schema.docVersion) { return validate(outcome.getData()); } @@ -112,20 +111,20 @@ public class OutcomeValidator implements ErrorHandler, XMLErrorHandler { XMLParserConfiguration parserConfiguration = new IntegratedParserConfiguration(sym, schemaGrammarPool); parserConfiguration.setFeature(NAMESPACES_FEATURE_ID, true); parserConfiguration.setFeature(VALIDATION_FEATURE_ID, true); - // now we can still do schema features just in case, + // now we can still do schema features just in case, // so long as it's our configuraiton...... parserConfiguration.setFeature(SCHEMA_VALIDATION_FEATURE_ID, true); parserConfiguration.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, true); DOMParser parser = new DOMParser(parserConfiguration); parser.setErrorHandler(this); - + parser.parse(new XMLInputSource(null, null, null, new StringReader(outcome), null)); } catch (Exception e) { return e.getMessage(); } - return errors.toString(); - } - + return errors.toString(); + } + private void appendError(String level, Exception ex) { errors.append(level); String message = ex.getMessage(); @@ -134,32 +133,36 @@ public class OutcomeValidator implements ErrorHandler, XMLErrorHandler { errors.append(message); errors.append("\n"); } - + /** * ErrorHandler for instances */ - public void error(SAXParseException ex) throws SAXException { + @Override + public void error(SAXParseException ex) throws SAXException { appendError("ERROR: ", ex); } /** * */ - public void fatalError(SAXParseException ex) throws SAXException { + @Override + public void fatalError(SAXParseException ex) throws SAXException { appendError("FATAL: ", ex); } /** * */ - public void warning(SAXParseException ex) throws SAXException { + @Override + public void warning(SAXParseException ex) throws SAXException { appendError("WARNING: ", ex); } /** * XMLErrorHandler for schema */ - public void error(String domain, String key, XMLParseException ex) + @Override + public void error(String domain, String key, XMLParseException ex) throws XNIException { appendError("ERROR: ", ex); } @@ -167,7 +170,8 @@ public class OutcomeValidator implements ErrorHandler, XMLErrorHandler { /** * */ - public void fatalError(String domain, String key, XMLParseException ex) + @Override + public void fatalError(String domain, String key, XMLParseException ex) throws XNIException { appendError("FATAL: ", ex); } @@ -175,9 +179,10 @@ public class OutcomeValidator implements ErrorHandler, XMLErrorHandler { /** * */ - public void warning(String domain, String key, XMLParseException ex) + @Override + public void warning(String domain, String key, XMLParseException ex) throws XNIException { - appendError("WARNING: ", ex); + appendError("WARNING: ", ex); } } diff --git a/source/com/c2kernel/persistency/outcome/Schema.java b/source/com/c2kernel/persistency/outcome/Schema.java old mode 100755 new mode 100644 index 9514ebe..73969f2 --- a/source/com/c2kernel/persistency/outcome/Schema.java +++ b/source/com/c2kernel/persistency/outcome/Schema.java @@ -7,7 +7,7 @@ package com.c2kernel.persistency.outcome; * $Date: 2006/09/14 14:13:26 $ * * Copyright (C) 2003 CERN - European Organization for Nuclear Research - * All rights reserved. + * All rights reserved. */ public class Schema { diff --git a/source/com/c2kernel/persistency/outcome/SchemaValidator.java b/source/com/c2kernel/persistency/outcome/SchemaValidator.java old mode 100755 new mode 100644 index f2dfa0b..be8564b --- a/source/com/c2kernel/persistency/outcome/SchemaValidator.java +++ b/source/com/c2kernel/persistency/outcome/SchemaValidator.java @@ -26,18 +26,19 @@ public class SchemaValidator extends OutcomeValidator { */ public SchemaValidator() { - + } public org.exolab.castor.xml.schema.Schema getSOM() { - return castorSchema; + return castorSchema; } /** * */ - public synchronized String validate(String outcome) { + @Override + public synchronized String validate(String outcome) { errors = new StringBuffer(); try { InputSource schemaSource = new InputSource(new StringReader(outcome)); diff --git a/source/com/c2kernel/persistency/outcome/Viewpoint.java b/source/com/c2kernel/persistency/outcome/Viewpoint.java old mode 100755 new mode 100644 index 7fc2aa5..a3fe283 --- a/source/com/c2kernel/persistency/outcome/Viewpoint.java +++ b/source/com/c2kernel/persistency/outcome/Viewpoint.java @@ -16,13 +16,13 @@ import com.c2kernel.process.Gateway; * $Date: 2005/10/05 07:39:36 $ * * Copyright (C) 2003 CERN - European Organization for Nuclear Research - * All rights reserved. + * All rights reserved. */ // public static final String codeRevision = // "$Revision: 1.10 $ $Date: 2005/10/05 07:39:36 $ $Author: abranson $"; public class Viewpoint implements C2KLocalObject { - + int ID = -1; // not really used in this // db fields @@ -30,9 +30,9 @@ public class Viewpoint implements C2KLocalObject { String schemaName; String name; int schemaVersion; - int eventId; + int eventId; public static final int NONE = -1; - + public Viewpoint() { eventId = NONE; sysKey = Path.INVALID; @@ -40,7 +40,7 @@ public class Viewpoint implements C2KLocalObject { schemaName = null; name = null; } - + public Viewpoint(int sysKey, String schemaName, String name, int schemaVersion, int eventId) { this.sysKey = sysKey; this.schemaName = schemaName; @@ -55,6 +55,7 @@ public class Viewpoint implements C2KLocalObject { return retVal; } + @Override public String getClusterType() { return ClusterStorage.VIEWPOINT; } @@ -80,6 +81,7 @@ public class Viewpoint implements C2KLocalObject { * Returns the name. * @return String */ + @Override public String getName() { return name; } @@ -128,6 +130,7 @@ public class Viewpoint implements C2KLocalObject { * Sets the name. * @param name The name to set */ + @Override public void setName(String name) { this.name = name; } @@ -168,8 +171,9 @@ public class Viewpoint implements C2KLocalObject { return (Event)Gateway.getStorage().get(sysKey, ClusterStorage.HISTORY+"/"+eventId, null); } - - public String toString() { + + @Override + public String toString() { return name; } diff --git a/source/com/c2kernel/process/AbstractMain.java b/source/com/c2kernel/process/AbstractMain.java old mode 100755 new mode 100644 index 97af4f8..9282d45 --- a/source/com/c2kernel/process/AbstractMain.java +++ b/source/com/c2kernel/process/AbstractMain.java @@ -53,10 +53,10 @@ abstract public class AbstractMain String configPath = null; String connectPath = null; java.util.Properties c2kProps = null; - int logLevel = 0; + int logLevel = 0; PrintStream logStream = System.out; String centreId = null; - + try { if( args != null ) @@ -125,12 +125,12 @@ abstract public class AbstractMain // Set up log stream Logger.addLogStream(logStream, logLevel); - + if (configPath == null) { System.out.println("No config file specified"); usage(); } - + // Load config & connect files into c2kprops c2kProps = FileStringUtility.loadConfigFile( configPath ); @@ -167,7 +167,7 @@ abstract public class AbstractMain ex.printStackTrace(); usage(); } - + Logger.msg(7, "AbstractMain::standardSetUp() - readC2KArgs() DONE."); return c2kProps; @@ -201,5 +201,5 @@ abstract public class AbstractMain Gateway.close(); Logger.msg(5, "AbstractMain::standardTearDown() - DONE."); } - + } diff --git a/source/com/c2kernel/process/Bootstrap.java b/source/com/c2kernel/process/Bootstrap.java index 777568c..6ffdd01 100644 --- a/source/com/c2kernel/process/Bootstrap.java +++ b/source/com/c2kernel/process/Bootstrap.java @@ -3,12 +3,10 @@ package com.c2kernel.process; import java.net.InetAddress; import java.util.Enumeration; import java.util.HashMap; -import java.util.Iterator; import java.util.StringTokenizer; import com.c2kernel.common.ObjectNotFoundException; import com.c2kernel.entity.TraceableEntity; -import com.c2kernel.entity.agent.ActiveEntity; import com.c2kernel.entity.proxy.ItemProxy; import com.c2kernel.events.Event; import com.c2kernel.events.History; @@ -56,18 +54,19 @@ public class Bootstrap checkAdminAgents(); // create the server's mother item - createServerItem(); + createServerItem(); new Thread(new Runnable() { + @Override public void run() { try { Thread.currentThread().setName("Bootstrapper"); - + // make sure all of the boot items are up-to-date verifyBootDataItems(); - + // verify the server item's wf initServerItemWf(); - + // create the factories etc. createBootstrapFactoryItems(); Logger.msg("Bootstrap.run() - Bootstrapping complete"); @@ -78,7 +77,7 @@ public class Bootstrap } }).start(); } - + /************************************************************************** * Checks all kernel descriptions, stored in resources **************************************************************************/ @@ -87,7 +86,7 @@ public class Bootstrap Logger.msg(1, "Verifying kernel boot items"); bootItems = FileStringUtility.url2String(Resource.getKernelResourceURL("boot/allbootitems.txt")); verifyBootDataItems(bootItems, true); - if (Resource.getDomainBaseURL() == null) + if (Resource.getDomainBaseURL() == null) Logger.msg(1, "No Domain base URL. Skipping domain boot check."); else { try { @@ -100,7 +99,7 @@ public class Bootstrap return; } Logger.msg(1, "Verifying domain agents"); - + try { bootItems = FileStringUtility.url2String(Resource.getDomainResourceURL("boot/domainagents.txt")); verifyDomainAgents(bootItems); @@ -110,11 +109,11 @@ public class Bootstrap return; } } - + Logger.msg(1, "Boot data items complete"); - + } - + private static void verifyDomainAgents(String agentFile) throws Exception { StringTokenizer str = new StringTokenizer(agentFile, "\n\r"); while (str.hasMoreTokens()) { @@ -123,7 +122,7 @@ public class Bootstrap checkAgent(agent.nextToken(), agent.nextToken(), agent.nextToken(), agent.nextToken().equalsIgnoreCase("true")); } } - + private static void verifyBootDataItems(String bootList, boolean isKernel) { StringTokenizer str = new StringTokenizer(bootList, "\n\r"); while (str.hasMoreTokens()) { @@ -139,9 +138,9 @@ public class Bootstrap bootstrapFactoryItems.put(itemName, data); continue; } - + Logger.msg(1, "Bootstrap.verifyBootItems() - Verifying data of "+getDataType(itemType)+" "+itemName); - Enumeration en = Gateway.getLDAPLookup().search(getTypeRoot(itemType), itemName); + Enumeration en = Gateway.getLDAPLookup().search(getTypeRoot(itemType), itemName); ItemProxy thisProxy; if (!en.hasMoreElements()) { @@ -156,7 +155,7 @@ public class Bootstrap String oldData = currentData.getOutcome().getData(); if (data.equals(oldData)) { Logger.msg(5, "Bootstrap.verifyBootItems() - Data identical, no update required"); - + continue; } } catch (ObjectNotFoundException ex) { @@ -191,12 +190,12 @@ public class Bootstrap PropertyDescriptionList pdList = (PropertyDescriptionList)CastorXMLUtility.unmarshall(Resource.getTextResource("boot/property/"+itemType+"Prop.xml")); PropertyArrayList props = new PropertyArrayList(); for (int i = 0; i < pdList.list.size(); i++) { - PropertyDescription pd = (PropertyDescription) pdList.list.get(i); + PropertyDescription pd = pdList.list.get(i); String propName = pd.getName(); String propVal = propName.equals("Name")?itemName:pd.getDefaultValue(); - props.list.add(new Property(propName, propVal)); + props.list.add(new Property(propName, propVal)); } - + EntityPath entityPath = Gateway.getLDAPLookup().getNextKeyManager().generateNextEntityKey(); TraceableEntity newItem = (TraceableEntity)Gateway.getCorbaServer().createEntity(entityPath); Gateway.getLDAPLookup().add(entityPath); @@ -219,7 +218,7 @@ public class Bootstrap return new DomainPath("/desc/OutcomeDesc/"); throw new Exception("Unknown bootstrap item type: "+type); } - + private static String getDataType(String type) throws Exception { if (type.equals("CA")) return "CompositeActivityDef"; @@ -230,36 +229,36 @@ public class Bootstrap if (type.equals("SC")) return "Script"; throw new Exception("Unknown bootstrap item type: "+type); - + } - + /************************************************************************** * Checks for the existence of the admin users so you can use Cristal **************************************************************************/ - private static void checkAgent(String name, String pass, String role, boolean joblist) throws Exception { + private static void checkAgent(String name, String pass, String role, boolean joblist) throws Exception { Logger.msg(1, "Bootstrap.checkAgent() - Checking for existence of '"+name+"' user."); LDAPLookup lookup = Gateway.getLDAPLookup(); try { - AgentPath agentPath = lookup.getRoleManager().getAgentPath(name); + lookup.getRoleManager().getAgentPath(name); Logger.msg(3, "Bootstrap.checkAgent() - User '"+name+"' found."); return; } catch (ObjectNotFoundException ex) { } Logger.msg("Bootstrap.checkAgent() - User '"+name+"' not found. Creating."); - + RolePath rolePath; try { rolePath = lookup.getRoleManager().getRolePath(role); } catch (ObjectNotFoundException ex) { rolePath = lookup.getRoleManager().createRole(role, joblist); } - + try { EntityPath entityPath = lookup.getNextKeyManager().generateNextEntityKey(); AgentPath agentPath = new AgentPath(entityPath.getSysKey(), name); agentPath.setPassword(pass); - ActiveEntity adminAgent = (ActiveEntity)Gateway.getCorbaServer().createEntity(agentPath); + Gateway.getCorbaServer().createEntity(agentPath); Gateway.getLDAPLookup().add(agentPath); - + // assign admin role Logger.msg("Bootstrap.checkAgent() - Assigning role '"+role+"'"); rolePath.addAgent(agentPath); @@ -273,21 +272,21 @@ public class Bootstrap } /** - * + * */ public static void checkAdminAgents() throws Exception { // check for administrative user String adminPassword = Gateway.getProperty("AdminPassword", "admin12345"); - + checkAgent("admin", adminPassword, "Admin", false); - + // check for import user checkAgent("system", adminPassword, "Admin", false); - + // check for local usercode user checkAgent(InetAddress.getLocalHost().getHostName(), "uc", "UserCode", true); - } - + } + public static void createServerItem() throws Exception { String serverName = Gateway.getProperty("ItemServer.name"); thisServerPath = new DomainPath("/servers/"+serverName); @@ -297,7 +296,7 @@ public class Bootstrap } catch (ObjectNotFoundException ex) { Logger.msg("Creating server item "+thisServerPath); serverEntity = Gateway.getLDAPLookup().getNextKeyManager().generateNextEntityKey(); - TraceableEntity newItem = (TraceableEntity)Gateway.getCorbaServer().createEntity(serverEntity); + Gateway.getCorbaServer().createEntity(serverEntity); Gateway.getLDAPLookup().add(serverEntity); thisServerPath.setEntity(serverEntity); Gateway.getLDAPLookup().add(thisServerPath); @@ -306,15 +305,15 @@ public class Bootstrap Gateway.getStorage().put(serverEntity.getSysKey(), new Property("Type", "Server"), null); Gateway.getStorage().put(serverEntity.getSysKey(), new Property("KernelVersion", Resource.getKernelVersion()), null); if (Gateway.getProperty("ItemServer.Proxy.port") != null) - Gateway.getStorage().put(serverEntity.getSysKey(), + Gateway.getStorage().put(serverEntity.getSysKey(), new Property("ProxyPort", Gateway.getProperty("ItemServer.Proxy.port")), null); if (Gateway.getProperty("ItemServer.Console.port") != null) - Gateway.getStorage().put(serverEntity.getSysKey(), + Gateway.getStorage().put(serverEntity.getSysKey(), new Property("ConsolePort", Gateway.getProperty("ItemServer.Console.port")), null); Gateway.getProxyManager().connectToProxyServer(Gateway.getProperty("ItemServer.name"), Integer.parseInt(Gateway.getProperty("ItemServer.Proxy.port"))); } - + public static void initServerItemWf() throws Exception { CompositeActivityDef serverWfCa = (CompositeActivityDef)LocalObjectLoader.getActDef("ServerItemWorkflow", "last"); Workflow wf = new Workflow((CompositeActivity)serverWfCa.instantiate()); @@ -325,21 +324,20 @@ public class Bootstrap Gateway.getStorage().put(thisServerPath.getSysKey(), wf, null); // add this proxy server in case it was just registered, or the port has changed } - + public static void createBootstrapFactoryItems() throws Exception { Logger.msg(1, "Verifying local object factories"); - for (Iterator iter = bootstrapFactoryItems.keySet().iterator(); iter.hasNext();) { - String itemName = (String) iter.next(); - String itemXML = (String)bootstrapFactoryItems.get(itemName); + for (String itemName : bootstrapFactoryItems.keySet()) { + String itemXML = bootstrapFactoryItems.get(itemName); Logger.msg(2, "Verifying "+itemName); NewItem item = (NewItem)CastorXMLUtility.unmarshall(itemXML); DomainPath factPath = new DomainPath(new DomainPath(item.initialPath), item.name); if (factPath.exists()) continue; ItemProxy serverEntity = (ItemProxy)Gateway.getProxyManager().getProxy(thisServerPath); serverEntity.requestAction( - Gateway.getLDAPLookup().getRoleManager().getAgentPath("system").getSysKey(), + Gateway.getLDAPLookup().getRoleManager().getAgentPath("system").getSysKey(), "workflow/predefined/CreateNewItem", - Transitions.DONE, + Transitions.DONE, itemXML); Logger.msg("Bootstrap.createBootstrapFactoryItems() - Created factory item: "+itemName); ItemProxy factProxy = (ItemProxy)Gateway.getProxyManager().getProxy(factPath); diff --git a/source/com/c2kernel/process/Gateway.java b/source/com/c2kernel/process/Gateway.java index 276b7b4..3a03088 100644 --- a/source/com/c2kernel/process/Gateway.java +++ b/source/com/c2kernel/process/Gateway.java @@ -20,26 +20,30 @@ import com.c2kernel.lookup.LDAPLookup; import com.c2kernel.lookup.LDAPProperties; import com.c2kernel.persistency.ClusterStorageException; import com.c2kernel.persistency.TransactionManager; -import com.c2kernel.utils.*; +import com.c2kernel.utils.CastorXMLUtility; +import com.c2kernel.utils.FileStringUtility; +import com.c2kernel.utils.Language; +import com.c2kernel.utils.Logger; +import com.c2kernel.utils.Resource; import com.c2kernel.utils.server.SimpleTCPIPServer; /************************************************************************** * The Gateway is the central object of a CRISTAL process. It initializes, * maintains and shuts down every other subsystem in both the client and the - * server. - * + * server. + * * Child objects: *
        - *
      • LDAPLookup - Provides access to the CRISTAL directory. Find or + *
      • LDAPLookup - Provides access to the CRISTAL directory. Find or * search for Items or Agents. - *
      • EntityProxyManager - Gives a local proxy object for Entities found + *
      • EntityProxyManager - Gives a local proxy object for Entities found * in LDAP. Execute activities in Items, query or subscribe to Entity data. *
      • TransactionManager - Access to the configured CRISTAL databases *
      • CorbaServer - Manages the memory pool of active Entities *
      • mORB - the Orbacus CORBA ORB *
      - * + * * @author $Author: abranson $ $Date: 2005/10/12 12:51:54 $ * @version $Revision: 1.17 $ **************************************************************************/ @@ -58,26 +62,26 @@ public class Gateway private Gateway() { } /** - * Initialises the Gateway and all of the client objects it holds, with + * Initialises the Gateway and all of the client objects it holds, with * the exception of the LDAPLookup, which is initialised during connect() - * - * @param props - java.util.Properties containing all application properties. + * + * @param props - java.util.Properties containing all application properties. * If null, the java system properties are used * @throws InvalidDataException - invalid properties caused a failure in initialisation */ static public void init(Properties props) throws InvalidDataException { // if supplied props are null, use system props - if (props == null) props = System.getProperties(); + if (props == null) props = System.getProperties(); // set resource URLs from config String resURL = props.getProperty("KernelResourceURL"); if (resURL != null && resURL.length()>0) Resource.setKernelBaseURL(resURL); - + resURL = props.getProperty("DomainResourceURL"); if (resURL != null && resURL.length()>0) Resource.setDomainBaseURL(resURL); - + // Start with default props from kernel jar try { mC2KProps = FileStringUtility.loadConfigFile( Resource.getKernelResourceURL("textFiles/defaultConf.properties").toString()); @@ -86,7 +90,7 @@ public class Gateway } // Overwrite with supplied props - for (Enumeration e = props.propertyNames(); e.hasMoreElements();) { + for (Enumeration e = props.propertyNames(); e.hasMoreElements();) { String propName = (String)e.nextElement(); mC2KProps.put(propName, props.get(propName)); } @@ -109,7 +113,7 @@ public class Gateway //Initialise language file String languageFile = getProperty("language.file"); - if (languageFile != null && languageFile.length() > 0) { + if (languageFile != null && languageFile.length() > 0) { Language.isTranlated=true; Language.mTableOfTranslation = FileStringUtility.loadLanguageFile(languageFile); } @@ -118,24 +122,24 @@ public class Gateway Resource.setImportURL(new URL("file:"+getProperty("Import.dir"))); } catch (MalformedURLException e) { Logger.error("Import directory not set. "+getProperty("Import.dir")); - } + } } - + /** - * Makes this process capable of creating and managing server entities. Runs the - * bootstrap to create the root LDAP contexts, initialises the CORBA server and + * Makes this process capable of creating and managing server entities. Runs the + * bootstrap to create the root LDAP contexts, initialises the CORBA server and * time-out manager. - * + * * @throws InvalidDataException - error initialising */ static public void startServer() throws InvalidDataException { try { // check top level LDAP contexts mLDAPLookup.install(); - + // start entity proxy server EntityProxyManager.initServer(); - + // Init ORB - set various config to sys properties java.util.Properties sysProps = System.getProperties(); String serverName = getProperty("ItemServer.name"); @@ -151,18 +155,18 @@ public class Gateway mORB = org.omg.CORBA.ORB.init(new String[0], sysProps); Logger.msg("Gateway.init() - ORB initialised. ORB is " + mORB.getClass().getName() ); - + // start corba server components mCorbaServer = new CorbaServer(); // start checking bootstrap items Bootstrap.run(); - + } catch (Exception ex) { Logger.error(ex); Logger.die("Exception starting server components. Shutting down."); } - + // start the http server try { int httpPort = Integer.parseInt(Gateway.getProperty("ItemServer.HTTP.port")); @@ -172,14 +176,14 @@ public class Gateway } catch (NumberFormatException ex) { Logger.msg(3, "Invalid or no HTTP port defined. HTTP server not available."); } - + System.out.println("Server '"+Gateway.getCentreId()+"' initialised."); } - + /** * Connects to the LDAP server in an administrative context - using the admin username and * password given in the LDAP.user and LDAP.password props of the kernel properties. - * + * * @throws InvalidDataException - bad params * @throws ClusterStorageException - error starting storages */ @@ -210,11 +214,11 @@ public class Gateway setup(); } - + /** - * Authenticates a user and returns and AgentProxy on them without overriding the system LDAP context. + * Authenticates a user and returns and AgentProxy on them without overriding the system LDAP context. * Useful for handling multiple users in one context e.g. on a web server - * + * * @param agentName - username * @param agentPassword - password * @return AgentProxy on that user @@ -233,7 +237,7 @@ public class Gateway String agentDN = agentPath.getFullDN(); ldapProps.mUser = agentDN; ldapProps.mPassword = agentPassword; - + try { LDAPLookup.createConnection(ldapProps); return (AgentProxy)getProxyManager().getProxy(mLDAPLookup.getRoleManager().getAgentPath(agentName)); @@ -242,11 +246,11 @@ public class Gateway throw new InvalidDataException("Could not log in", ""); } } - + /** * Logs into the LDAP server with the given username and password, and initialises the lookup. - * + * * @param agentName - username * @param agentPassword - password * @return an AgentProxy on the requested user @@ -254,25 +258,25 @@ public class Gateway */ static public AgentProxy connect(String agentName, String agentPassword) throws InvalidDataException - { - + { + LDAPProperties ldapProps = new LDAPProperties(); if (ldapProps.mHost!=null && ldapProps.mPort!= null && ldapProps.mLocalPath!=null ) - { + { try { ldapProps.mUser = ""; ldapProps.mPassword = ""; mLDAPLookup = new LDAPLookup(ldapProps); String agentDN = mLDAPLookup.getRoleManager().getAgentPath(agentName).getFullDN(); - + //found agentDN, try to log in with it ldapProps.mUser = agentDN; ldapProps.mPassword = agentPassword; mLDAPLookup = new LDAPLookup(ldapProps); - + // find agent proxy AgentPath agentPath = mLDAPLookup.getRoleManager().getAgentPath(agentName); - + if (agentPath!=null) { setup(); @@ -281,7 +285,7 @@ public class Gateway else { throw new InvalidDataException("The agentDN " +agentDN+ " is invalid.", ""); - } + } } catch (ClusterStorageException e) { Logger.error(e); throw new InvalidDataException(Language.translate("Error initialising storage")+Language.translate(". See log."), ""); @@ -293,35 +297,35 @@ public class Gateway throw new InvalidDataException(Language.translate("Could not log in")+": "+Language.translate(e.getMessage()), ""); } - } + } else { throw new InvalidDataException("Cannot log in. Some connection properties are not set.", ""); - } - + } + } - + /** * Initializes the storage and proxy manager, called during connect. - * + * * @throws InvalidDataException * @throws ClusterStorageException */ - static private void setup() + static private void setup() throws InvalidDataException, - ClusterStorageException + ClusterStorageException { - + // Init storages mStorage = new TransactionManager(); mProxyManager = new EntityProxyManager(); } - + /** * Shuts down all kernel api objects */ - public static void close() + public static void close() { // shut down servers if running if (mCorbaServer != null) @@ -330,17 +334,17 @@ public class Gateway if (mHTTPServer != null) mHTTPServer.stopListening(); mHTTPServer = null; - + // disconnect from storages if (mStorage != null) mStorage.close(); mStorage = null; - + // disconnect from ldap if (mLDAPLookup != null) mLDAPLookup.disconnect(); mLDAPLookup = null; - + // shut down proxy manager if (mProxyManager != null) mProxyManager.shutdown(); @@ -370,21 +374,21 @@ public class Gateway { return mCorbaServer; } - + static public TransactionManager getStorage() { return mStorage; } - + static public EntityProxyManager getProxyManager() { return mProxyManager; } - + static public String getCentreId() { return getProperty("LocalCentre"); - } - + } + static public String getProperty(String propName) { return getProperty(propName, null); } @@ -393,20 +397,20 @@ public class Gateway if (mC2KProps == null) return defaultValue; return mC2KProps.getProperty(propName, defaultValue); } - + static public void setProperty(String propName, String propValue) { if (mC2KProps == null) return; mC2KProps.put(propName, propValue); - } - - static public Enumeration propertyNames() { + } + + static public Enumeration propertyNames() { return mC2KProps.propertyNames(); } - + static public void dumpC2KProps(int logLevel) { if (!Logger.doLog(logLevel)) return; Logger.msg(logLevel, "C2K Properties:"); - for (Enumeration e = propertyNames(); e.hasMoreElements();) { + for (Enumeration e = propertyNames(); e.hasMoreElements();) { String name = (String) e.nextElement(); Logger.msg(" "+name+": "+getProperty(name)); } diff --git a/source/com/c2kernel/process/ItemHTTPBridge.java b/source/com/c2kernel/process/ItemHTTPBridge.java old mode 100755 new mode 100644 index 8ef2e58..40f48f7 --- a/source/com/c2kernel/process/ItemHTTPBridge.java +++ b/source/com/c2kernel/process/ItemHTTPBridge.java @@ -3,8 +3,6 @@ package com.c2kernel.process; import java.util.StringTokenizer; import com.c2kernel.entity.C2KLocalObject; -import com.c2kernel.lookup.DomainPath; -import com.c2kernel.lookup.EntityPath; import com.c2kernel.utils.CastorXMLUtility; import com.c2kernel.utils.server.HTTPRequestHandler; @@ -19,22 +17,24 @@ public class ItemHTTPBridge extends HTTPRequestHandler { public ItemHTTPBridge() { } - public String getName() { + @Override + public String getName() { return "Item HTTP Server"; } - public String processRequest() { - System.out.println("ItemHTTPBridge::ProcessRequest()"); + @Override + public String processRequest() { + System.out.println("ItemHTTPBridge::ProcessRequest()"); StringTokenizer tok = new StringTokenizer(resource, "?"); - String itemPath = tok.nextToken(); + //String itemPath = tok.nextToken(); String query = tok.nextToken(); int sysKey = -1; //Path path = Gateway.getLDAPLookup().; if (method.equals("GET")) { try { - DomainPath domPath = new DomainPath(itemPath); - EntityPath entityPath = domPath.getEntity(); - + //DomainPath domPath = new DomainPath(itemPath); + //EntityPath entityPath = domPath.getEntity(); + if (sysKey > -1) { C2KLocalObject response = Gateway.getStorage().get(sysKey, query, null); return CastorXMLUtility.marshall(response); diff --git a/source/com/c2kernel/process/StandardClient.java b/source/com/c2kernel/process/StandardClient.java index 2b04613..f6f48ed 100644 --- a/source/com/c2kernel/process/StandardClient.java +++ b/source/com/c2kernel/process/StandardClient.java @@ -12,7 +12,7 @@ package com.c2kernel.process; abstract public class StandardClient extends AbstractMain { - + //TODO: Auto-update from server } diff --git a/source/com/c2kernel/process/StandardServer.java b/source/com/c2kernel/process/StandardServer.java old mode 100755 new mode 100644 index 2c9bcaf..72b761e --- a/source/com/c2kernel/process/StandardServer.java +++ b/source/com/c2kernel/process/StandardServer.java @@ -16,21 +16,21 @@ import org.tanukisoftware.wrapper.WrapperManager; import com.c2kernel.utils.Logger; /************************************************************************** - * Base class for all servers i.e. c2k processes that serve Entities + * Base class for all servers i.e. c2k processes that serve Entities * * @author $Author: abranson $ $Date: 2005/04/28 13:49:43 $ * @version $Revision: 1.47 $ **************************************************************************/ public class StandardServer extends AbstractMain implements WrapperListener { - protected static StandardServer server; + protected static StandardServer server; /************************************************************************** * C2KRootPOA suitable for Factory objects **************************************************************************/ - + @@ -44,26 +44,27 @@ public class StandardServer extends AbstractMain implements WrapperListener { // read args and init Gateway standardSetUp(args); - + // connect to LDAP as root Gateway.connect(); - + //start console Logger.initConsole("ItemServer"); - + //initialize the server objects Gateway.startServer(); - + Logger.msg(5, "StandardServer::standardInitialisation - complete."); } - + /************************************************************************** * Sets up and runs and item server **************************************************************************/ - public Integer start(String[] args) - { + @Override + public Integer start(String[] args) + { try { //initialise everything @@ -76,17 +77,18 @@ public class StandardServer extends AbstractMain implements WrapperListener } return null; } - + public static void main(String[] args) { server = new StandardServer(); AbstractMain.runningAsWrapper = true; WrapperManager.start( server, args ); } - + /** * */ - public void controlEvent(int event) { + @Override + public void controlEvent(int event) { if (WrapperManager.isControlledByNativeWrapper()) { // The Wrapper will take care of this event } else { @@ -105,11 +107,12 @@ public class StandardServer extends AbstractMain implements WrapperListener * Closes all listeners, quits the VM. * This method should be called to kill the server process * e.g. from the NT service wrapper - **************************************************************************/ - public int stop(int arg0) { + **************************************************************************/ + @Override + public int stop(int arg0) { try - { - // close gateway + { + // close gateway standardTearDown(); } catch( Exception ex ) @@ -117,7 +120,7 @@ public class StandardServer extends AbstractMain implements WrapperListener Logger.error(ex); return 1; } - + Logger.msg("StandardServer::shutdown - complete. "); return 0; } diff --git a/source/com/c2kernel/process/UserCodeProcess.java b/source/com/c2kernel/process/UserCodeProcess.java index 18fed06..9c2deab 100644 --- a/source/com/c2kernel/process/UserCodeProcess.java +++ b/source/com/c2kernel/process/UserCodeProcess.java @@ -4,7 +4,6 @@ import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.HashMap; -import java.util.Iterator; import com.c2kernel.common.InvalidDataException; import com.c2kernel.common.InvalidTransitionException; @@ -12,7 +11,7 @@ import com.c2kernel.entity.C2KLocalObject; import com.c2kernel.entity.agent.Job; import com.c2kernel.entity.proxy.AgentProxy; import com.c2kernel.entity.proxy.EntityProxyObserver; -import com.c2kernel.entity.proxy.MemberControl; +import com.c2kernel.entity.proxy.MemberSubscription; import com.c2kernel.lifecycle.instance.stateMachine.Transitions; import com.c2kernel.persistency.ClusterStorage; import com.c2kernel.utils.Logger; @@ -25,12 +24,12 @@ import com.c2kernel.utils.Logger; * Copyright (C) 2003 CERN - European Organization for Nuclear Research * All rights reserved. **************************************************************************/ -public class UserCodeProcess extends StandardClient implements EntityProxyObserver, Runnable { +public class UserCodeProcess extends StandardClient implements EntityProxyObserver, Runnable { protected AgentProxy agent; static boolean active = true; ArrayList ignoredPaths = new ArrayList(); HashMap jobs; - + public UserCodeProcess(String agentName, String agentPass) { // login - try for a while in case server hasn't imported our user yet for (int i=1;i<6;i++) { @@ -48,12 +47,13 @@ public class UserCodeProcess extends StandardClient implements EntityProxyObserv } System.out.println(getDesc()+" initialised for " + agentName); } - - public void run() { + + @Override + public void run() { Thread.currentThread().setName("Usercode Process"); jobs = new HashMap(); // subscribe to job list - agent.subscribe(this, ClusterStorage.JOB, true); + agent.subscribe(new MemberSubscription(this, ClusterStorage.JOB, true)); while (active) { Job thisJob = null; synchronized (jobs) { @@ -62,10 +62,10 @@ public class UserCodeProcess extends StandardClient implements EntityProxyObserv if (thisJob == null) thisJob = getJob(jobs, Transitions.START); if (thisJob == null) - thisJob = getJob(jobs, Transitions.SUSPEND); + thisJob = getJob(jobs, Transitions.SUSPEND); if (thisJob == null) thisJob = getJob(jobs, Transitions.RESUME); - + if (thisJob == null) { Logger.error("No supported jobs, but joblist is not empty! Discarding remaining jobs"); jobs.clear(); @@ -74,7 +74,7 @@ public class UserCodeProcess extends StandardClient implements EntityProxyObserv jobs.remove(ClusterStorage.getPath(thisJob)); } } - + if (thisJob != null) { String jobKey = thisJob.getItemSysKey()+":"+thisJob.getStepPath(); try { @@ -82,8 +82,8 @@ public class UserCodeProcess extends StandardClient implements EntityProxyObserv Logger.msg(5, "Testing start conditions"); boolean start = assessStartConditions(thisJob); if (start) { - Logger.msg(5, "Attempting to start"); - agent.execute(thisJob); + Logger.msg(5, "Attempting to start"); + agent.execute(thisJob); } else { Logger.msg(5, "Start conditions failed "+thisJob.getStepName()+" in "+thisJob.getItemSysKey()); @@ -103,7 +103,7 @@ public class UserCodeProcess extends StandardClient implements EntityProxyObserv if (!ignoredPaths.contains(jobKey)) agent.execute(thisJob); } - } catch (InvalidTransitionException ex) { + } catch (InvalidTransitionException ex) { // must have already been done by someone else - ignore } catch (Throwable ex) { Logger.error("Error executing "+Transitions.getTransitionName(thisJob.getPossibleTransition())+" job:"); @@ -121,7 +121,7 @@ public class UserCodeProcess extends StandardClient implements EntityProxyObserv } } catch (InterruptedException ex) { } } - + // shut down try { @@ -132,10 +132,10 @@ public class UserCodeProcess extends StandardClient implements EntityProxyObserv Logger.error(ex); } } - - private Job getJob(HashMap jobs, int transition) { - for (Iterator list = jobs.values().iterator();list.hasNext();) { - Job thisJob = (Job)list.next(); + + private static Job getJob(HashMap jobs, int transition) { + for (C2KLocalObject c2kLocalObject : jobs.values()) { + Job thisJob = (Job)c2kLocalObject; if (thisJob.getPossibleTransition() == transition) { Logger.msg(1,"================================================================="); Logger.msg(1, "Got "+Transitions.getTransitionName(transition)+" job for "+thisJob.getStepName()+" in "+thisJob.getItemSysKey()); @@ -144,27 +144,23 @@ public class UserCodeProcess extends StandardClient implements EntityProxyObserv } return null; } - + public boolean assessStartConditions(Job job) { - // default implementation - has no start conditions. + // default implementation - has no start conditions. return true; } - + public void runUCLogic(Job job) throws Exception { // default implementation - the agent will execute any scripts defined when we execute agent.execute(job); } - - + + /** * Receives job from the AgentProxy. Reactivates thread if sleeping. */ - public void add(C2KLocalObject contents) { - if (contents instanceof MemberControl) { - MemberControl ctrl = (MemberControl)contents; - Logger.msg(5,ctrl.toString()); - } - else + @Override + public void add(Job contents) { synchronized(jobs) { Logger.msg(7, "Adding "+ClusterStorage.getPath(contents)); jobs.put(ClusterStorage.getPath(contents), contents); @@ -172,11 +168,18 @@ public class UserCodeProcess extends StandardClient implements EntityProxyObserv } } + + @Override + public void control(String control, String msg) { + if (control == MemberSubscription.ERROR) + Logger.error("Error in job subscription: "+msg); + } /** * Removes job removal notification from the AgentProxy. */ - public void remove(String id) { + @Override + public void remove(String id) { synchronized(jobs) { Logger.msg(7, "Deleting "+id); jobs.remove(id); @@ -186,7 +189,7 @@ public class UserCodeProcess extends StandardClient implements EntityProxyObserv public static UserCodeProcess getInstance() throws UnknownHostException { return new UserCodeProcess(InetAddress.getLocalHost().getHostName(), "uc"); } - + static public void main(String[] args) { int status = 0; @@ -197,7 +200,8 @@ public class UserCodeProcess extends StandardClient implements EntityProxyObserv UserCodeProcess proc = getInstance(); new Thread(proc).start(); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { - public void run() { + @Override + public void run() { shutdown(); } })); @@ -218,7 +222,7 @@ public class UserCodeProcess extends StandardClient implements EntityProxyObserv System.exit(status); } } - + public String getDesc() { return("Usercode Process"); } @@ -226,4 +230,5 @@ public class UserCodeProcess extends StandardClient implements EntityProxyObserv public static void shutdown() { active = false; } + } diff --git a/source/com/c2kernel/property/Property.java b/source/com/c2kernel/property/Property.java old mode 100755 new mode 100644 index 2374c1b..3022cc5 --- a/source/com/c2kernel/property/Property.java +++ b/source/com/c2kernel/property/Property.java @@ -41,7 +41,8 @@ public class Property implements C2KLocalObject /************************************************************************** * **************************************************************************/ - public void setName(String name) + @Override + public void setName(String name) { mName = name; } @@ -50,7 +51,8 @@ public class Property implements C2KLocalObject /************************************************************************** * **************************************************************************/ - public String getName() + @Override + public String getName() { return mName; } @@ -75,6 +77,7 @@ public class Property implements C2KLocalObject /** * @see com.c2kernel.entity.C2KLocalObject#getClusterType() */ + @Override public String getClusterType() { return ClusterStorage.PROPERTY; } diff --git a/source/com/c2kernel/property/PropertyArrayList.java b/source/com/c2kernel/property/PropertyArrayList.java index dffbaf6..f59b2d5 100644 --- a/source/com/c2kernel/property/PropertyArrayList.java +++ b/source/com/c2kernel/property/PropertyArrayList.java @@ -13,17 +13,17 @@ import java.util.ArrayList; import com.c2kernel.utils.CastorArrayList; -public class PropertyArrayList extends CastorArrayList +public class PropertyArrayList extends CastorArrayList { public PropertyArrayList() - { + { super(); } - + public PropertyArrayList(ArrayList aList) - { + { super(aList); } - + } diff --git a/source/com/c2kernel/property/PropertyDescription.java b/source/com/c2kernel/property/PropertyDescription.java old mode 100755 new mode 100644 index dbbd6b9..cd3b93c --- a/source/com/c2kernel/property/PropertyDescription.java +++ b/source/com/c2kernel/property/PropertyDescription.java @@ -9,10 +9,10 @@ package com.c2kernel.property; -public class PropertyDescription +public class PropertyDescription { private String mName=null; - private String mDefaultValue=null; + private String mDefaultValue=null; private boolean mIsClassIdentifier=false; private boolean mIsMutable=false; @@ -20,13 +20,13 @@ public class PropertyDescription public PropertyDescription() { } - + public PropertyDescription(String name, String defaultValue, boolean isClassIdentifier, boolean isMutable ) { setName(name); setDefaultValue(defaultValue); setIsClassIdentifier(isClassIdentifier); - setIsMutable(isMutable); + setIsMutable(isMutable); } public void setName(String name) @@ -44,7 +44,7 @@ public class PropertyDescription mDefaultValue = defaultValue; } - public void setIsMutable(boolean mutable) + public void setIsMutable(boolean mutable) { mIsMutable = mutable; } @@ -68,7 +68,7 @@ public class PropertyDescription { return mIsMutable; } - + public Property getProperty() { return new Property(mName,mDefaultValue); diff --git a/source/com/c2kernel/property/PropertyDescriptionList.java b/source/com/c2kernel/property/PropertyDescriptionList.java index 64754a7..4728569 100644 --- a/source/com/c2kernel/property/PropertyDescriptionList.java +++ b/source/com/c2kernel/property/PropertyDescriptionList.java @@ -10,26 +10,25 @@ package com.c2kernel.property; import java.util.ArrayList; -import java.util.Iterator; import com.c2kernel.utils.CastorArrayList; -public class PropertyDescriptionList extends CastorArrayList +public class PropertyDescriptionList extends CastorArrayList { public PropertyDescriptionList() - { + { super(); } - + public PropertyDescriptionList(ArrayList aList) - { + { super(aList); } - + public String getClassProps() { StringBuffer props = new StringBuffer(); - for (Iterator iter = list.iterator(); iter.hasNext();) { - PropertyDescription element = (PropertyDescription)iter.next(); + for (Object name : list) { + PropertyDescription element = (PropertyDescription)name; if (element.getIsClassIdentifier()) { if (props.length()>0) props.append(","); @@ -38,10 +37,10 @@ public class PropertyDescriptionList extends CastorArrayList pdlist, String name) { Object[] values = pdlist.toArray(); - for (int i=0;i pdlist) { Object[] values = pdlist.toArray(); StringBuffer names = new StringBuffer(); - for (int i=0;i pdlist) { Object[] values = pdlist.toArray(); StringBuffer names = new StringBuffer(); for (int i=0;i msg; boolean fatal = false; - + public ErrorInfo() { super(); msg = new ArrayList(); } - + public void addError(String error) { msg.add(error); } - + public String getErrors() { StringBuffer err = new StringBuffer(); - for (Iterator iter = msg.iterator(); iter.hasNext();) { - String element = (String)iter.next(); + for (String element : msg) { err.append(element+"\n"); } return err.toString(); } - + public void setFatal() { fatal=true; } - + public boolean getFatal() { return fatal; } diff --git a/source/com/c2kernel/scripting/Parameter.java b/source/com/c2kernel/scripting/Parameter.java old mode 100755 new mode 100644 index c51c9d4..a518c02 --- a/source/com/c2kernel/scripting/Parameter.java +++ b/source/com/c2kernel/scripting/Parameter.java @@ -5,43 +5,43 @@ package com.c2kernel.scripting; * Place holder for the Parameter details to be passed to the script. **************************************************************************/ public class Parameter { - + private String name; - private Class type; + private Class type; private boolean initialised=false; - + public Parameter(String name) { this.name = name; } - + public void setName(String n) { name=n; } - + public String getName() { return name; } - - public void setType(Class t) + + public void setType(Class t) { type=t; } - - public Class getType() + + public Class getType() { return type; } - + public void setInitialised(boolean state) { initialised=state; } - + public boolean getInitialised() { return initialised; } - + } diff --git a/source/com/c2kernel/scripting/Script.java b/source/com/c2kernel/scripting/Script.java index 4abb5cf..0820c26 100644 --- a/source/com/c2kernel/scripting/Script.java +++ b/source/com/c2kernel/scripting/Script.java @@ -3,7 +3,6 @@ package com.c2kernel.scripting; import java.io.StringReader; import java.util.ArrayList; import java.util.HashMap; -import java.util.Iterator; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; @@ -33,7 +32,7 @@ import com.ibm.bsf.BSFManager; **************************************************************************/ public class Script { - Class mOutputClass; + Class mOutputClass; String mOutputName; String mScript = ""; String mName; @@ -48,26 +47,26 @@ public class Script * Loads script xml and parses it for script source, parameters and output specifications. * First tries to load the script from resource path /scriptFiles/scriptName_scriptVersion.xml * If not found tries to find item at /desc/ScriptDesc/scriptName and load Viewpoint scriptVersion from it. - * + * * For the specification of script xml, see the Script schema from resources. - * + * * @param scriptName - name of the script * @param scriptVersion - named version of the script (must be numbered viewpoint) - * @throws ScriptParsingException - when script not found (ScriptLoadingException) or xml is invalid (ScriptParsingException) + * @throws ScriptParsingException - when script not found (ScriptLoadingException) or xml is invalid (ScriptParsingException) */ - public Script(String scriptName, int scriptVersion) throws ScriptingEngineException + public Script(String scriptName, int scriptVersion) throws ScriptingEngineException { this(scriptName, scriptVersion, new BSFManager()); } - + public Script(String scriptName, int scriptVersion, BSFManager scriptManager) throws ScriptingEngineException { - mName = scriptName; + mName = scriptName; mVersion = String.valueOf(scriptVersion); if (scriptName.equals("")) return; setScriptEnv(scriptManager); setScript(mName, mVersion); - } + } /** * Creates a script executor for the supplied expression, bypassing the xml parsing bit @@ -82,12 +81,12 @@ public class Script mOutputClass = Object.class; mScript = expr; } - + public Script(String lang, String expr) throws ScriptingEngineException { this(lang, expr, new BSFManager()); } - + public Script(ItemProxy object, AgentProxy subject, Job job) throws ScriptingEngineException { this(job.getActPropString("ScriptName"), job.getActPropString("ScriptVersion") == null ? -1 : Integer.parseInt(job.getActPropString("ScriptVersion"))); @@ -103,7 +102,7 @@ public class Script setOutput("errors", "com.c2kernel.scripting.ErrorInfo"); } - + public void setScript(String scriptName, String scriptVersion) throws ScriptingEngineException { try @@ -121,10 +120,10 @@ public class Script public void setScriptEnv(BSFManager manager) { this.scriptManager = manager; } - + /** * Extracts script data from script xml. - * + * * @param scriptXML * @throws ScriptParsingException - when script is invalid */ @@ -189,10 +188,9 @@ public class Script String includeName = currentParam.getAttribute("name"); String includeVersion = currentParam.getAttribute("version"); try { - Script includedScript = new Script(includeName, Integer.parseInt(includeVersion), scriptManager); + Script includedScript = new Script(includeName, Integer.parseInt(includeVersion), scriptManager); mIncludes.add(includedScript); - for (Iterator iter = includedScript.getInputParams().values().iterator(); iter.hasNext();) { - Parameter includeParam = (Parameter) iter.next(); + for (Parameter includeParam : includedScript.getInputParams().values()) { addIncludedInputParam(includeParam.getName(), includeParam.getType()); } } catch (NumberFormatException e) { @@ -200,8 +198,8 @@ public class Script } catch (ScriptingEngineException e) { throw new ScriptParsingException("Error parsing imported script "+includeName+"_"+includeVersion+": "+e.getMessage()); } - - + + } //load Script else if (paramName.equals("script")) @@ -243,12 +241,12 @@ public class Script mAllInputParams.put(inputParam.getName(), inputParam); } - - protected void addIncludedInputParam(String name, Class type) throws ParameterException + + protected void addIncludedInputParam(String name, Class type) throws ParameterException { // check if we already have it if (mAllInputParams.containsKey(name)) { - Parameter existingParam = (Parameter)mAllInputParams.get(name); + Parameter existingParam = mAllInputParams.get(name); // check the types match if (existingParam.getType() == type) return; // matches @@ -256,7 +254,7 @@ public class Script throw new ParameterException("Parameter conflict. Parameter'"+name+"' is declared as " +existingParam.getType().getName()+" is declared in another script as "+type.getName()); } - + Parameter inputParam = new Parameter(name); inputParam.setType(type); @@ -264,7 +262,7 @@ public class Script mAllInputParams.put(inputParam.getName(), inputParam); } - + protected void setOutput(String name, String type) throws ScriptParsingException { @@ -306,7 +304,7 @@ public class Script * @return HashMap of String (name), com.c2kernel.scripting.Parameter (param) * @see com.c2kernel.scripting.Parameter */ - public HashMap getInputParams() + public HashMap getInputParams() { return mInputParams; } @@ -316,21 +314,21 @@ public class Script * @return HashMap of String (name), com.c2kernel.scripting.Parameter (param) * @see com.c2kernel.scripting.Parameter */ - public HashMap getAllInputParams() + public HashMap getAllInputParams() { return mAllInputParams; } /** * Submits an input parameter to the script. Must be declared by name and type in the script XML. - * + * * @param name - input parameter name from the script xml * @param value - object to use for this parameter * @throws ParameterException - name not found or wrong type */ public void setInputParamValue(String name, Object value) throws ParameterException { - Parameter param = (Parameter) mInputParams.get(name); + Parameter param = mInputParams.get(name); if (!mAllInputParams.containsKey(name)) throw new ParameterException("Parameter " + name + " not found in parameter list"); @@ -347,22 +345,21 @@ public class Script throw new ParameterException("Error initialising parameter '"+name+"' - "+ex.getMessage()); } } - + // pass param down to child scripts - for (Iterator iter = mIncludes.iterator(); iter.hasNext();) { - Script importScript = (Script) iter.next(); + for (Script importScript : mIncludes) { importScript.setInputParamValue(name, value); } } /** * Executes the script with the submitted parameters. All declared input parametes should have been set first. - * - * @return The return value depends on the way the output type was declared in the script xml. + * + * @return The return value depends on the way the output type was declared in the script xml. *
      • If there was no output class declared then null is returned *
      • If a class was declared, but not named, then the object returned by the script is checked * to be of that type, then returned. - *
      • If the output value was named and typed, then an object of that class is created and + *
      • If the output value was named and typed, then an object of that class is created and * passed to the script as an input parameter. The script should set this before it returns. *
      * @throws ScriptingEngineException - input parameters weren't set, there was an error executing the script, or the output was invalid @@ -374,9 +371,7 @@ public class Script // check input params StringBuffer missingParams = new StringBuffer(); - for (Iterator iter = mInputParams.values().iterator(); iter.hasNext();) - { - Parameter thisParam = (Parameter) iter.next(); + for (Parameter thisParam : mInputParams.values()) { if (!thisParam.getInitialised()) missingParams.append(thisParam.getName()).append("\n"); } @@ -385,11 +380,10 @@ public class Script throw new ScriptingEngineException("Execution aborted, the following declared parameters were not set: \n" + missingParams.toString()); // execute the child scripts - for (Iterator iter = mIncludes.iterator(); iter.hasNext();) { - Script importScript = (Script) iter.next(); + for (Script importScript : mIncludes) { importScript.execute(); } - + // run the script try @@ -400,13 +394,13 @@ public class Script Logger.msg(8, "Script.execute() - script returned \"" + returnValue + "\""); if (mOutputName != null) { - // retrieve the value from the registered output bean + // retrieve the value from the registered output bean outputValue = scriptManager.lookupBean(mOutputName); Logger.msg(8, "Script.execute() - output bean value: \"" + outputValue + "\""); } } catch (Exception ex) - { + { throw new ScriptingEngineException("Error executing script: " + ex.getMessage()); } @@ -431,8 +425,8 @@ public class Script */ public void reset() { - for (Iterator iter = mInputParams.values().iterator(); iter.hasNext();) - ((Parameter) iter.next()).setInitialised(false); + for (Parameter parameter : mInputParams.values()) + parameter.setInitialised(false); scriptManager = new BSFManager(); } } diff --git a/source/com/c2kernel/scripting/ScriptConsole.java b/source/com/c2kernel/scripting/ScriptConsole.java index d79cd5c..33d4b7f 100644 --- a/source/com/c2kernel/scripting/ScriptConsole.java +++ b/source/com/c2kernel/scripting/ScriptConsole.java @@ -4,7 +4,6 @@ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.InterruptedIOException; -import java.io.OutputStreamWriter; import java.io.PrintStream; import java.net.InetAddress; import java.net.Socket; @@ -47,7 +46,7 @@ public class ScriptConsole implements SocketHandler { static ArrayList securityHosts = new ArrayList(); public static final short NONE = 0; public static final short ALLOW = 1; - public static final short DENY = 2; + public static final short DENY = 2; static short securityMode; static { @@ -75,18 +74,20 @@ public class ScriptConsole implements SocketHandler { public ScriptConsole() { } - public String getName() { + @Override + public String getName() { return "Script Console"; } - public boolean isBusy() { + @Override + public boolean isBusy() { return (socket != null); } - public void setSocket(Socket newSocket) { + @Override + public void setSocket(Socket newSocket) { try { input = new BufferedReader(new InputStreamReader(newSocket.getInputStream())); - OutputStreamWriter ansi = new OutputStreamWriter(newSocket.getOutputStream(), "US-ASCII"); output = new PrintStream(newSocket.getOutputStream()); newSocket.setSoTimeout(0); socket = newSocket; @@ -100,7 +101,8 @@ public class ScriptConsole implements SocketHandler { } } - public void shutdown() { + @Override + public void shutdown() { Socket closingSocket = socket; socket = null; if (closingSocket == null) @@ -118,7 +120,8 @@ public class ScriptConsole implements SocketHandler { } - public void run() { + @Override + public void run() { // check permission boolean allowed = true; if (securityMode!=NONE) { @@ -127,7 +130,7 @@ public class ScriptConsole implements SocketHandler { allowed = false; } else if (securityMode==ALLOW) - allowed = false; + allowed = false; } if (!allowed) { @@ -150,7 +153,7 @@ public class ScriptConsole implements SocketHandler { try { manager.declareBean("system", Gateway.getProxyManager().getProxy( Gateway.getLDAPLookup().getRoleManager().getAgentPath("system")), AgentProxy.class); - } catch (Exception ex) { + } catch (Exception ex) { output.println("System agent unavailable"); } context = manager.loadScriptingEngine("javascript"); @@ -200,7 +203,7 @@ public class ScriptConsole implements SocketHandler { continue; } try { - if (command.endsWith("\\")) { + if (command.endsWith("\\")) { commandBuffer.append(command.substring(0,command.length()-1)); continue; } @@ -208,11 +211,11 @@ public class ScriptConsole implements SocketHandler { command = commandBuffer.toString(); commandBuffer = new StringBuffer(); Logger.msg("Console command from "+socket.getInetAddress()+": "+command); - + // process control if (command.equals("shutdown")) { WrapperManager.stop(0); - } + } else { Object response = context.eval("Command", 0, 0, command); if (response instanceof org.mozilla.javascript.Undefined) diff --git a/source/com/c2kernel/scripting/ScriptingEngineException.java b/source/com/c2kernel/scripting/ScriptingEngineException.java old mode 100755 new mode 100644 index 2c8128c..ab8383c --- a/source/com/c2kernel/scripting/ScriptingEngineException.java +++ b/source/com/c2kernel/scripting/ScriptingEngineException.java @@ -1,7 +1,7 @@ package com.c2kernel.scripting; public class ScriptingEngineException extends java.lang.Exception { - + /** * Creates new sciptingEngineException without detail message. */ diff --git a/source/com/c2kernel/utils/ActDefCache.java b/source/com/c2kernel/utils/ActDefCache.java index 148d934..2982aa3 100644 --- a/source/com/c2kernel/utils/ActDefCache.java +++ b/source/com/c2kernel/utils/ActDefCache.java @@ -1,26 +1,26 @@ /** - * + * */ package com.c2kernel.utils; import com.c2kernel.common.InvalidDataException; import com.c2kernel.common.ObjectNotFoundException; -import com.c2kernel.entity.C2KLocalObject; import com.c2kernel.entity.proxy.EntityProxyObserver; import com.c2kernel.entity.proxy.ItemProxy; +import com.c2kernel.entity.proxy.MemberSubscription; import com.c2kernel.lifecycle.ActivityDef; import com.c2kernel.persistency.ClusterStorage; import com.c2kernel.persistency.ClusterStorageException; import com.c2kernel.persistency.outcome.Viewpoint; public class ActDefCache { - + SoftCache actCache = new SoftCache(); - + public ActivityDef get(String actName, String actVersion) throws ObjectNotFoundException, InvalidDataException { ActivityDef thisActDef; synchronized(actCache) { - ActCacheEntry thisActDefEntry = ((ActCacheEntry)actCache.get(actName+"_"+actVersion)); + ActCacheEntry thisActDefEntry = actCache.get(actName+"_"+actVersion); if (thisActDefEntry == null) { Logger.msg(6, actName+" v"+actVersion+" not found in cache. Retrieving."); ItemProxy actDefItem = LocalObjectLoader.loadLocalObjectDef("/desc/ActivityDesc/", actName); @@ -50,7 +50,7 @@ public class ActDefCache { } return thisActDef; } - + public void removeAct(String id) { synchronized(actCache) { if (actCache.keySet().contains(id)) { @@ -60,7 +60,7 @@ public class ActDefCache { } } - public class ActCacheEntry implements EntityProxyObserver { + public class ActCacheEntry implements EntityProxyObserver { public String id; public ItemProxy actProxy; public ActivityDef actDef; @@ -70,22 +70,31 @@ public class ActDefCache { this.actDef = actDef; this.parent = parent; this.actProxy = actProxy; - actProxy.subscribe(this, ClusterStorage.VIEWPOINT, false); + actProxy.subscribe(new MemberSubscription(this, ClusterStorage.VIEWPOINT, false)); } + @Override public void finalize() { parent.removeAct(id); actProxy.unsubscribe(this); } - public void add(C2KLocalObject contents) { + @Override + public void add(Viewpoint contents) { parent.removeAct(id); } - + + @Override public void remove(String id) { parent.removeAct(id); } - + + @Override public String toString() { - return "ActDef cache entry: "+id; + return "ActDef cache entry: "+id; + } + @Override + public void control(String control, String msg) { + // TODO Auto-generated method stub + } } } \ No newline at end of file diff --git a/source/com/c2kernel/utils/CastorArrayList.java b/source/com/c2kernel/utils/CastorArrayList.java index 7596dd9..ed15c0f 100644 --- a/source/com/c2kernel/utils/CastorArrayList.java +++ b/source/com/c2kernel/utils/CastorArrayList.java @@ -5,7 +5,7 @@ import java.util.ArrayList; /************************************************************************** * Wrapper for a root element to an ArrayList. Castor Marshalls arraylists - * as multiple elements, so this class is needed to provide a root element + * as multiple elements, so this class is needed to provide a root element * to stop it crashing. * * $Revision: 1.4 $ @@ -17,12 +17,12 @@ import java.util.ArrayList; // abstract public class CastorArrayList implements Serializable{ public ArrayList list; - + public CastorArrayList() { super(); - list = new ArrayList(); + list = new ArrayList(); } - + public CastorArrayList(ArrayList list) { this(); this.list = list; diff --git a/source/com/c2kernel/utils/CastorXMLUtility.java b/source/com/c2kernel/utils/CastorXMLUtility.java index 1f68e77..4dca391 100644 --- a/source/com/c2kernel/utils/CastorXMLUtility.java +++ b/source/com/c2kernel/utils/CastorXMLUtility.java @@ -21,7 +21,7 @@ import com.c2kernel.persistency.outcome.Outcome; /************************************************************************** * Loads all mapfiles, and wraps marshalling/unmarshalling - * + * * @author $Author: abranson $ $Date: 2004/10/20 14:10:21 $ * @version $Revision: 1.12 $ **************************************************************************/ @@ -33,7 +33,7 @@ public class CastorXMLUtility /** * Looks for a file called 'index.xml' at the given URL, and loads every file * listed in there by relative path - * + * * @param mapURL - map root */ static public void loadMapsFrom(URL mapURL) throws InvalidDataException { @@ -46,7 +46,7 @@ public class CastorXMLUtility Logger.warning("Could not load map index from "+mapURL.toString()); return; } - + StringTokenizer sTokenizer = new StringTokenizer(index); while( sTokenizer.hasMoreTokens() ) { String thisMap = sTokenizer.nextToken(); @@ -55,11 +55,11 @@ public class CastorXMLUtility } catch (Exception e) { Logger.error(e); throw new InvalidDataException("Error loading map '"+thisMap+"'", ""); - } + } } Logger.msg("Loaded all maps from "+mapURL.toString()); } - + /************************************************************************** * Updates a mapping referenced by the mapID. * The same mapping cannot be loaded many times as it generates an exception. diff --git a/source/com/c2kernel/utils/DateUtility.java b/source/com/c2kernel/utils/DateUtility.java old mode 100755 new mode 100644 index 6e3b569..bc9fb05 --- a/source/com/c2kernel/utils/DateUtility.java +++ b/source/com/c2kernel/utils/DateUtility.java @@ -39,7 +39,7 @@ public class DateUtility time.append(timeStamp.mSecond); return time.toString(); } - + public static int getNbDayInYear(GTimeStamp date) { int centuary = date.mYear / 100; @@ -78,7 +78,7 @@ public class DateUtility return 31; } } - + public static long diff(GTimeStamp date1, GTimeStamp date2) { GTimeStamp tmp = new GTimeStamp(date1.mYear, date1.mMonth, date1.mDay, date1.mHour, date1.mMinute, date1.mSecond, date1.mTimeOffset); @@ -114,5 +114,5 @@ public class DateUtility tmp.mDay = tmp.mDay + getNbDayInMonth(tmp); } return (((tmp.mDay - date2.mDay) * 24 + tmp.mHour - date2.mHour) * 60 + tmp.mMinute - date2.mMinute) * 60 + tmp.mSecond - date2.mSecond; - } + } } diff --git a/source/com/c2kernel/utils/Dom4JElementParser.java b/source/com/c2kernel/utils/Dom4JElementParser.java old mode 100755 new mode 100644 index a4d5bbe..e3601e5 --- a/source/com/c2kernel/utils/Dom4JElementParser.java +++ b/source/com/c2kernel/utils/Dom4JElementParser.java @@ -16,14 +16,14 @@ public class Dom4JElementParser try { SAXReader reader = new SAXReader(); - + Document d = reader.read(new StringReader(data)); - List list = d.selectNodes( xpath ); + List list = d.selectNodes( xpath ); String[] returnArray = new String[list.size()]; int i=0; - for ( Iterator iter = list.iterator(); iter.hasNext();i++ ) - { - Object object = iter.next(); + for ( Iterator iter = list.iterator(); iter.hasNext();i++ ) + { + Object object = iter.next(); if (object instanceof Element) returnArray[i]=((Element)object).getText(); else if (object instanceof Attribute) returnArray[i]=((Attribute)object).getText(); } diff --git a/source/com/c2kernel/utils/FileStringUtility.java b/source/com/c2kernel/utils/FileStringUtility.java index 84f46ca..843a44e 100644 --- a/source/com/c2kernel/utils/FileStringUtility.java +++ b/source/com/c2kernel/utils/FileStringUtility.java @@ -1,7 +1,16 @@ package com.c2kernel.utils; //Java -import java.io.*; +import java.io.BufferedInputStream; +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; import java.lang.reflect.Array; import java.net.MalformedURLException; import java.net.URL; @@ -73,7 +82,7 @@ public class FileStringUtility lines.addElement(thisLine); String[] lineArray = new String[lines.size()]; for (int i = 0; i < lines.size(); i++) - lineArray[i] = (String) lines.get(i); + lineArray[i] = lines.get(i); return lineArray; } @@ -106,7 +115,7 @@ public class FileStringUtility **************************************************************************/ static public void string2File(String fileName, String data) throws FileNotFoundException, IOException { - string2File(new File(fileName), data); + string2File(new File(fileName), data); } /************************************************************************** @@ -226,8 +235,8 @@ public class FileStringUtility { files = dir.listFiles(); - for (int i = 0; i < files.length; i++) - deleteDir(files[i].getAbsolutePath(), true, true); + for (File file : files) + deleteDir(file.getAbsolutePath(), true, true); } return deleteDir(dirPath); @@ -255,11 +264,10 @@ public class FileStringUtility files = dir.listFiles(); - for (int i = 0; i < files.length; i++) - { - fileName = files[i].getName(); + for (File file : files) { + fileName = file.getName(); - if (files[i].isFile()) + if (file.isFile()) { fileNames.add(dirPath + "/" + fileName); } @@ -334,7 +342,7 @@ public class FileStringUtility /************************************************************************** * Load the contents of the language file * *************************************************************************/ - static public Hashtable loadLanguageFile(String configFile) + static public Hashtable loadLanguageFile(String configFile) { try { @@ -353,7 +361,7 @@ public class FileStringUtility { Logger.error("FileStringUtility.loadLanguageFile() - could not load language file '" + configFile+"'"); Logger.error(e); - return new Hashtable(); + return new Hashtable(); } } @@ -402,7 +410,7 @@ public class FileStringUtility StringBuffer tmp=new StringBuffer(src); int length = from.length(); int index = tmp.toString().indexOf(from); - while (index>0) + while (index>0) { tmp.replace(index,index+length,to); index = tmp.toString().indexOf(from); diff --git a/source/com/c2kernel/utils/GTimeStampComparator.java b/source/com/c2kernel/utils/GTimeStampComparator.java old mode 100755 new mode 100644 index f57f20d..3680a50 --- a/source/com/c2kernel/utils/GTimeStampComparator.java +++ b/source/com/c2kernel/utils/GTimeStampComparator.java @@ -4,23 +4,24 @@ import java.util.Comparator; import com.c2kernel.common.GTimeStamp; -public class GTimeStampComparator implements Comparator { +public class GTimeStampComparator implements Comparator { + @Override public int compare(Object arg0, Object arg1) { GTimeStamp t0 = (GTimeStamp)arg0; GTimeStamp t1 = (GTimeStamp)arg1; - + int retVal = compareInt(t0.mYear, t1.mYear); if (retVal == 0) retVal = compareInt(t0.mMonth, t1.mMonth); if (retVal == 0) retVal = compareInt(t0.mDay, t1.mDay); if (retVal == 0) retVal = compareInt(t0.mHour-(t0.mTimeOffset/3600), t1.mHour-(t1.mTimeOffset/3600)); if (retVal == 0) retVal = compareInt(t0.mMinute, t1.mMinute); if (retVal == 0) retVal = compareInt(t0.mSecond, t1.mSecond); - + return retVal; } - private int compareInt(int i, int j) { + private static int compareInt(int i, int j) { return i-j; } } diff --git a/source/com/c2kernel/utils/KeyValuePair.java b/source/com/c2kernel/utils/KeyValuePair.java old mode 100755 new mode 100644 index 149797e..5523eb6 --- a/source/com/c2kernel/utils/KeyValuePair.java +++ b/source/com/c2kernel/utils/KeyValuePair.java @@ -13,11 +13,11 @@ public class KeyValuePair mKey = key; mValue = value; } - + public String getKey() { return mKey; } - + public void setKey(String key) { mKey = key; } @@ -25,22 +25,22 @@ public class KeyValuePair public Object getValue() { return mValue; } - + public void setValue(Object value) { mValue = value; } - + public String getStringValue() { if (mValue instanceof String) return (String)mValue; else return null; } - + public void setStringValue(String value) { mValue = value; } - + public Integer getIntegerValue() { if (mValue instanceof Integer) return (Integer)mValue; @@ -58,20 +58,20 @@ public class KeyValuePair else return null; } - + public void setBooleanValue(Boolean value) { mValue = value; - } - + } + public Float getFloatValue() { if (mValue instanceof Float) return (Float)mValue; else return null; } - + public void setFloatValue(Float value) { mValue = value; - } - + } + } diff --git a/source/com/c2kernel/utils/Language.java b/source/com/c2kernel/utils/Language.java index ee74f96..0b71d16 100644 --- a/source/com/c2kernel/utils/Language.java +++ b/source/com/c2kernel/utils/Language.java @@ -11,11 +11,11 @@ import java.util.Hashtable; public class Language { - public static Hashtable mTableOfTranslation = new Hashtable(); + public static Hashtable mTableOfTranslation = new Hashtable(); public static Hashtable mTableOfUntranslated = new Hashtable(); public static boolean isTranlated=false; - private Hashtable tableOfTranslation = new Hashtable(); - + private Hashtable tableOfTranslation = new Hashtable(); + public static String translate(String english) { if (!isTranlated) return english; @@ -23,13 +23,13 @@ public class Language if (rep != null && !rep.equals("")) { String translated = (String) mTableOfTranslation.get(english); if (translated != null) return translated; - else + else { mTableOfUntranslated.put(english,""); try { String s = ""; - Enumeration e = mTableOfUntranslated.keys(); + Enumeration e = mTableOfUntranslated.keys(); while (e.hasMoreElements()) s =s+"\n"+e.nextElement(); FileStringUtility.string2File("untranslated.txt",s); } @@ -42,11 +42,11 @@ public class Language } return rep; } - + public Language(String filePath) - { + { String languageFile = filePath; - if (languageFile == null || languageFile.length() == 0) + if (languageFile == null || languageFile.length() == 0) // no language file defined for this process return; tableOfTranslation = FileStringUtility.loadLanguageFile(languageFile); @@ -56,7 +56,7 @@ public class Language String rep = english; if (rep != null && !rep.equals("")) { String translated = (String) tableOfTranslation.get(english); - if (translated != null) + if (translated != null) rep = translated; } return rep; diff --git a/source/com/c2kernel/utils/LocalObjectLoader.java b/source/com/c2kernel/utils/LocalObjectLoader.java old mode 100755 new mode 100644 index 620b030..8a73e3c --- a/source/com/c2kernel/utils/LocalObjectLoader.java +++ b/source/com/c2kernel/utils/LocalObjectLoader.java @@ -14,8 +14,8 @@ import com.c2kernel.process.Gateway; public class LocalObjectLoader { private static ActDefCache actCache = new ActDefCache(); - static public ItemProxy loadLocalObjectDef(String root, String name) - throws ObjectNotFoundException + static public ItemProxy loadLocalObjectDef(String root, String name) + throws ObjectNotFoundException { DomainPath defRoot = new DomainPath(root); DomainPath defPath = (DomainPath)defRoot.find(name); @@ -32,7 +32,7 @@ public class LocalObjectLoader { Logger.error(ex); throw new ObjectNotFoundException("Error loading script " + scriptName + " version " + scriptVersion, ""); } - + } static public Schema getSchema(String schemaName, int schemaVersion) throws ObjectNotFoundException { @@ -40,14 +40,14 @@ public class LocalObjectLoader { Schema thisSchema = new Schema(); thisSchema.docType = schemaName; thisSchema.docVersion = schemaVersion; - + // don't bother if this is the Schema schema - for bootstrap esp. if (schemaName.equals("Schema") && schemaVersion == 0) { thisSchema.breakApart = false; thisSchema.schema=""; return thisSchema; } - + ItemProxy schema = loadLocalObjectDef("/desc/OutcomeDesc/", schemaName); Viewpoint schemaView = (Viewpoint)schema.getObject(ClusterStorage.VIEWPOINT + "/Schema/" + schemaVersion); try { @@ -58,18 +58,18 @@ public class LocalObjectLoader { } String breakApart = schema.getProperty("BreakApart"); thisSchema.breakApart = breakApart.equals("1"); - + return thisSchema; } /** * Retrieves a named version of activity def from the database - * + * * @param actName - activity name * @param version - named version (String) * @return ActivityDef * @throws ObjectNotFoundException - When activity or version does not exist - */ + */ static public ActivityDef getActDef(String actName, String actVersion) throws ObjectNotFoundException, InvalidDataException { Logger.msg(5, "Loading activity def "+actName+" v"+actVersion); return actCache.get(actName, actVersion); diff --git a/source/com/c2kernel/utils/Logger.java b/source/com/c2kernel/utils/Logger.java index 2d4d975..45edbee 100644 --- a/source/com/c2kernel/utils/Logger.java +++ b/source/com/c2kernel/utils/Logger.java @@ -32,9 +32,9 @@ public class Logger static private void printMessage(String message, int msgLogLevel) { synchronized(logStreams) { - for (Iterator iter = logStreams.keySet().iterator(); iter.hasNext();) { - PrintStream element = (PrintStream)iter.next(); - int logLevel = ((Integer)logStreams.get(element)).intValue(); + for (Iterator iter = logStreams.keySet().iterator(); iter.hasNext();) { + PrintStream element = iter.next(); + int logLevel = logStreams.get(element).intValue(); if (logLevel < msgLogLevel || (logLevel > 9 && logLevel - 10 < msgLogLevel)) continue; if (logLevel > 9) @@ -51,7 +51,7 @@ public class Logger } } } - + static private void printMessage(Throwable ex) { StringWriter msgString = new StringWriter(); PrintWriter msg = new PrintWriter(msgString); @@ -59,7 +59,7 @@ public class Logger ex.printStackTrace(msg); printMessage(msgString.toString(), 0); } - + static public boolean doLog(int logLevel) { return mHighestLogLevel >= logLevel; @@ -67,7 +67,7 @@ public class Logger /** * Use this only for temporary messages while developing/debugging When the code is stable, change calls to debug to * message/warning/error with an appropriate log level This makes it easier to manage debug calls in the source. - * + * * @param msg - * the string to write to the console, or log file if specified in cmd line */ @@ -81,7 +81,7 @@ public class Logger } /** * Use Logger.message to report information that will be useful for debugging a release - * + * * @param level - * log level of this message. If the current log level has been on the cmd line to be less that this number, the log message * will not be displayed @@ -143,23 +143,22 @@ public class Logger if (logLevel > 9) logLevel-=10; if (logLevel > mHighestLogLevel) mHighestLogLevel = logLevel; } - + } /** * @param console */ public static void removeLogStream(PrintStream console) { synchronized(logStreams) { - Integer logIntObj = (Integer)logStreams.get(console); - if (logIntObj == null) return; // not registered + Integer logIntObj = logStreams.get(console); + if (logIntObj == null) return; // not registered int logLevel = (logIntObj).intValue(); logStreams.remove(console); - + // recalculate lowest log level if (logLevel == mHighestLogLevel || (logLevel > 9 && logLevel-10 == mHighestLogLevel)) { mHighestLogLevel = -1; - for (Iterator iter = logStreams.values().iterator(); iter.hasNext();) { - Integer element = (Integer)iter.next(); + for (Integer element : logStreams.values()) { int thisLogLevel = element.intValue()>9?element.intValue()-10:element.intValue(); if (thisLogLevel > mHighestLogLevel || mHighestLogLevel == -1) mHighestLogLevel = thisLogLevel; @@ -167,7 +166,7 @@ public class Logger } } } - + static public void initConsole(String id) { String portString = Gateway.getProperty(id+".Console.port"); @@ -177,19 +176,19 @@ public class Logger } catch (NumberFormatException ex) { Logger.msg("No port defined for "+id+" console. Using any port."); } - + mConsole = new SimpleTCPIPServer(port, ScriptConsole.class, 5); mConsole.startListening(); Gateway.setProperty(id+".Console.port", String.valueOf(mConsole.getPort())); } - + static public int getConsolePort() { return mConsole.getPort(); } - + static public void closeConsole() { if (mConsole != null) - mConsole.stopListening(); + mConsole.stopListening(); } } diff --git a/source/com/c2kernel/utils/Resource.java b/source/com/c2kernel/utils/Resource.java index 33100d8..361549d 100644 --- a/source/com/c2kernel/utils/Resource.java +++ b/source/com/c2kernel/utils/Resource.java @@ -62,7 +62,7 @@ public class Resource { static public URL getDomainResourceURL(String resName) throws MalformedURLException { return new URL(domainBaseURL, resName); } - + private static URL getURLorResURL(String newURL) { URL result; try { @@ -83,16 +83,16 @@ public class Resource { Logger.msg(8, "Resource::getTextResource() - Getting resource: " + resName); if (txtCache.containsKey(resName)) { - return (String)txtCache.get(resName); + return txtCache.get(resName); } try { - + String newRes = null; try { newRes = FileStringUtility.url2String(getDomainResourceURL(resName)); } catch (Exception ex) { } // no domain base - + if (newRes == null || newRes.length() == 0) { // not found in domain newRes = FileStringUtility.url2String(getKernelResourceURL(resName)); } @@ -104,7 +104,7 @@ public class Resource { } /** * Gets an image from the resource directories - * + * * @param resName - filename after resources/images * @return */ @@ -116,13 +116,13 @@ public class Resource { return nullImg; } } - + static public ImageIcon getImage(String resName) throws ObjectNotFoundException { if (resName == null) return nullImg; if (imgCache.containsKey(resName)) { - return (ImageIcon)imgCache.get(resName); + return imgCache.get(resName); } URL imgLocation = null; @@ -134,7 +134,7 @@ public class Resource { newImg = new ImageIcon(imgLocation); } catch (MalformedURLException e) { } } - + // try kernel resources next if (newImg == null || newImg.getIconHeight() == -1) { try { @@ -142,12 +142,12 @@ public class Resource { newImg = new ImageIcon(imgLocation); } catch (MalformedURLException e) { } } - + // else return null image if (newImg == null || newImg.getIconHeight() == -1) { throw new ObjectNotFoundException(); } - + else imgCache.put(resName, newImg); Logger.msg(7, "Loaded "+resName+" "+newImg.getIconWidth()+"x"+newImg.getIconHeight()); return newImg; @@ -175,13 +175,13 @@ public class Resource { return "Domain application version not found"; } } - + static public String getKernelVersion() { try { return FileStringUtility.url2String(getKernelResourceURL("textFiles/version.txt")); } catch (Exception ex) { return "No version info found"; } - + } } diff --git a/source/com/c2kernel/utils/SoftCache.java b/source/com/c2kernel/utils/SoftCache.java index 6680f30..9c95f2e 100644 --- a/source/com/c2kernel/utils/SoftCache.java +++ b/source/com/c2kernel/utils/SoftCache.java @@ -2,12 +2,16 @@ package com.c2kernel.utils; import java.lang.ref.ReferenceQueue; import java.lang.ref.SoftReference; -import java.util.*; +import java.util.AbstractMap; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.Map; +import java.util.Set; /******************************************************************************* * SoftReferences are reaped if no strong references are left and the vm is * running out of memory. Most caches in the kernel use this. - * + * * $Revision: 1.5 $ $Date: 2004/10/29 13:29:09 $ ******************************************************************************/ public class SoftCache extends AbstractMap { @@ -43,7 +47,8 @@ public class SoftCache extends AbstractMap { return result; } - public V put(K key, V value) { + @Override + public V put(K key, V value) { processQueue(); if (minSize > 0) { hardCache.addFirst(value); @@ -54,33 +59,38 @@ public class SoftCache extends AbstractMap { return value; } - public V remove(Object key) { + @Override + public V remove(Object key) { processQueue(); return hash.remove(key).get(); } - public void clear() { + @Override + public void clear() { hardCache.clear(); while(queue.poll()!=null); hash.clear(); } - public int size() { + @Override + public int size() { processQueue(); return hash.size(); } - - public Set keySet() { + + @Override + public Set keySet() { processQueue(); return hash.keySet(); } - public Set> entrySet() { + @Override + public Set> entrySet() { // Would have to create another Map to do this - too expensive // Throwing runtime expensive is dangerous, but better than nulls throw new UnsupportedOperationException(); - } - + } + private static class SoftValue extends SoftReference { private final Object key; private SoftValue(Object key, V value, ReferenceQueue q) { @@ -88,15 +98,15 @@ public class SoftCache extends AbstractMap { this.key = key; } } - + /** * Look for values that have been reaped, and remove their keys from the cache */ private void processQueue() { - SoftValue sv; - while ((sv = (SoftValue) queue.poll()) != null) { + SoftValue sv; + while ((sv = (SoftValue) queue.poll()) != null) { hash.remove(sv.key); } } - + } diff --git a/source/com/c2kernel/utils/TransientCache.java b/source/com/c2kernel/utils/TransientCache.java index 8991b87..d58617e 100644 --- a/source/com/c2kernel/utils/TransientCache.java +++ b/source/com/c2kernel/utils/TransientCache.java @@ -1,9 +1,14 @@ package com.c2kernel.utils; -import java.lang.ref.*; -import java.util.*; +import java.lang.ref.Reference; +import java.util.AbstractMap; +import java.util.AbstractSet; +import java.util.Hashtable; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; /************************************************************************** - * TransientCache - Uses transient references to allow unused entries to be + * TransientCache - Uses transient references to allow unused entries to be * reaped by the java garbage collector. * * $Revision: 1.1 $ @@ -13,10 +18,11 @@ import java.util.*; * All rights reserved. **************************************************************************/ public abstract class TransientCache extends AbstractMap { - + private Map> map = new Hashtable>(); - - public synchronized Set> entrySet() { + + @Override + public synchronized Set> entrySet() { Map newMap = new Hashtable(); Iterator>> iter = map.entrySet().iterator(); while (iter.hasNext()) { @@ -24,28 +30,30 @@ public abstract class TransientCache extends AbstractMap { Reference ref = me.getValue(); V o = ref.get(); if (o == null) { - // Delete cleared reference + // Delete cleared reference iter.remove(); } else { - // Copy out interior object + // Copy out interior object newMap.put(me.getKey(), o); } } - // Return set of interior objects + // Return set of interior objects return newMap.entrySet(); } - - public synchronized V put(K key, V value) { + + @Override + public synchronized V put(K key, V value) { Reference ref = makeReference(value); - ref = (Reference)map.put(key, ref); + ref = map.put(key, ref); if (ref != null) return (ref.get()); return null; } - + public abstract Reference makeReference(Object value); - - public V remove(Object key) { + + @Override + public V remove(Object key) { Iterator>> i = map.entrySet().iterator(); Entry> correctEntry = null; if (key == null) { @@ -72,38 +80,46 @@ public abstract class TransientCache extends AbstractMap { /** * */ - public void clear() { + @Override + public void clear() { map.entrySet().clear(); } - + private transient Set keySet = null; - - public Set keySet() { + + @Override + public Set keySet() { if (keySet == null) { keySet = new AbstractSet() { - public Iterator iterator() { + @Override + public Iterator iterator() { return new Iterator() { private Iterator>> i = map.entrySet().iterator(); - public boolean hasNext() { + @Override + public boolean hasNext() { return i.hasNext(); } - public K next() { + @Override + public K next() { return i.next().getKey(); } - public void remove() { + @Override + public void remove() { i.remove(); } }; } - public int size() { + @Override + public int size() { return TransientCache.this.size(); } - public boolean contains(Object k) { + @Override + public boolean contains(Object k) { return TransientCache.this.containsKey(k); } }; diff --git a/source/com/c2kernel/utils/XmlElementParser.java b/source/com/c2kernel/utils/XmlElementParser.java index 0f138d3..69cee31 100644 --- a/source/com/c2kernel/utils/XmlElementParser.java +++ b/source/com/c2kernel/utils/XmlElementParser.java @@ -24,7 +24,7 @@ public class XmlElementParser return parseOld(data, xpath); } } - + public static String[] parseOld(String data, String path) { Vector returnData = new Vector(); @@ -41,13 +41,13 @@ public class XmlElementParser int i=taille; while (pathTokens.hasMoreElements()) pathElements[--i] = pathTokens.nextToken(); - + if (Logger.doLog(6)) { Logger.msg(6, "Path elements:"); - for (int x=0;x= 0) + if (split >= 0) headers.put( headerLine.substring(0, split), headerLine.substring(split+2) @@ -81,10 +86,10 @@ public class HTTPRequestHandler implements SocketHandler { String response = null; try { - + if (headers.containsKey("Content-length")) { // read POST data StringBuffer postBuffer = new StringBuffer(); - int received = 0; int length = Integer.parseInt((String)headers.get("Content-length")); + int received = 0; int length = Integer.parseInt(headers.get("Content-length")); try { while (received < length) { String postLine = request.readLine(); @@ -98,7 +103,7 @@ public class HTTPRequestHandler implements SocketHandler { } } // Got the params, generate response - + returnMIME = "text/xml"; statusCode = "200 OK"; @@ -109,47 +114,47 @@ public class HTTPRequestHandler implements SocketHandler { System.out.println(new Date().toString()+" "+currentSocket.getInetAddress()+" "+method+" "+resource+" "+statusCode); OutputStream output = currentSocket.getOutputStream(); - + statusCode = "HTTP/1.0 "+statusCode+CRLF; output.write(statusCode.getBytes()); - + returnMIME = "Content-type: "+returnMIME+CRLF; output.write(returnMIME.getBytes()); - + String contentLength = "Content-Length: "+response.length()+CRLF; output.write(contentLength.getBytes()); - + // Possible: last mod? // end of headers output.write(CRLF.getBytes()); - + // write the content output.write(response.getBytes()); request.close(); output.close(); currentSocket.close(); - } catch (IOException ex2) { + } catch (IOException ex2) { Logger.error(ex2); } // aborted connection probably currentSocket = null; } - + /* This is a dummy method that doesn't support anything. * Override it. */ - + public String processRequest() { return error("501 Not Implemented", "The method "+method+" you have requested is not supported by this server."); } - + public String error(String code, String desc) { statusCode = code; returnMIME = "text/html"; - return ("" + + return ("" + ""+code+"" + "

      "+code+"

      " + "

      "+desc+ "


      Cristal Item HTTP server"); } } - + diff --git a/source/com/c2kernel/utils/server/SimpleTCPIPServer.java b/source/com/c2kernel/utils/server/SimpleTCPIPServer.java index 8db9257..930fcee 100644 --- a/source/com/c2kernel/utils/server/SimpleTCPIPServer.java +++ b/source/com/c2kernel/utils/server/SimpleTCPIPServer.java @@ -1,11 +1,9 @@ package com.c2kernel.utils.server; -import java.io.InputStream; import java.io.InterruptedIOException; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; -import java.util.Iterator; import java.util.ListIterator; import java.util.NoSuchElementException; @@ -17,13 +15,13 @@ public class SimpleTCPIPServer implements Runnable int port = 0; int maxConn = 10; Thread listener = null; - Class handlerClass = null; + Class handlerClass = null; ServerSocket serverSocket = null; boolean keepListening = true; ArrayList currentHandlers = new ArrayList(); static short noServers = 0; - public SimpleTCPIPServer(int port, Class handlerClass, int maxConnections) + public SimpleTCPIPServer(int port, Class handlerClass, int maxConnections) { this.port = port; this.handlerClass = handlerClass; @@ -35,26 +33,25 @@ public class SimpleTCPIPServer implements Runnable { if(listener != null) return; keepListening = true; - + listener = new Thread(this); listener.start(); } - + public void stopListening() { Logger.msg("SimpleTCPIPServer: Closing server for " + handlerClass.getName() +" on port "+ port); keepListening = false; - for (Iterator iter = currentHandlers.iterator(); iter.hasNext();) { - SocketHandler thisHandler = (SocketHandler)iter.next(); + for (SocketHandler thisHandler : currentHandlers) { thisHandler.shutdown(); } } - public void run() + @Override + public void run() { Thread.currentThread().setName("TCP/IP Server for "+handlerClass.getName()); Socket connectionSocket = null; - InputStream inputStream = null; try { serverSocket = new ServerSocket(port); @@ -64,11 +61,11 @@ public class SimpleTCPIPServer implements Runnable serverSocket.setSoTimeout(500); SocketHandler freeHandler = null; while(keepListening) { - if (freeHandler == null || freeHandler.isBusy()) { - ListIterator i = currentHandlers.listIterator(); + if (freeHandler == null || freeHandler.isBusy()) { + ListIterator i = currentHandlers.listIterator(); try { do { - freeHandler = (SocketHandler)i.next(); + freeHandler = i.next(); } while (freeHandler.isBusy()); } catch (NoSuchElementException e) { // create new one @@ -105,7 +102,7 @@ public class SimpleTCPIPServer implements Runnable listener = null; Logger.msg("SimpleTCPIPServer - Servers still running: "+--noServers); } - + public int getPort() { return port; } diff --git a/source/com/c2kernel/utils/server/SocketHandler.java b/source/com/c2kernel/utils/server/SocketHandler.java old mode 100755 new mode 100644 index 455a9bd..8d37714 --- a/source/com/c2kernel/utils/server/SocketHandler.java +++ b/source/com/c2kernel/utils/server/SocketHandler.java @@ -3,13 +3,13 @@ package com.c2kernel.utils.server; import java.net.Socket; public interface SocketHandler extends Runnable { - + public String getName(); - + public boolean isBusy(); - + public void setSocket(Socket newSocket); - + public void shutdown(); } - + diff --git a/source/com/c2kernel/utils/server/UDPListener.java b/source/com/c2kernel/utils/server/UDPListener.java old mode 100755 new mode 100644 index 1f02361..3b1fc9d --- a/source/com/c2kernel/utils/server/UDPListener.java +++ b/source/com/c2kernel/utils/server/UDPListener.java @@ -18,15 +18,16 @@ import com.c2kernel.utils.Logger; **************************************************************************/ public abstract class UDPListener extends Thread { - + private boolean active = true; protected DatagramSocket socket; - + public UDPListener() { super(); } - - public void run() { + + @Override + public void run() { Thread.currentThread().setName("UDP Server"); byte[] buffer = new byte[255]; DatagramPacket newPacket = new DatagramPacket(buffer, buffer.length); @@ -44,10 +45,10 @@ public abstract class UDPListener extends Thread { } socket.close(); } - + protected abstract void processPacket(DatagramPacket packet) throws InvalidDataException; - + public void shutdown() { - active = false; + active = false; } } -- cgit v1.2.3