perfsonar-dev - [pS-dev] [GEANT/SA2/ps-java-services] r6294 - in trunk: parent perfsonar-java-base2 perfsonar-java-bas e2/src perfsonar-java-base2/src/checkstyle perfsonar-java- base2/src/main/java/org/perfsonar/base2/client perfsonar-j ava-base2/src/main/java/org/perfsonar/base2/client/authn p erfsonar-java-base2/src/main/java/org/perfsonar/base2/clie nt/authn/edugain perfsonar-java-base2/src/main/java/org/pe rfsonar/base2/service/authn perfsonar-java-base2/src/main/ java/org/perfsonar/base2/service/authn/component perfsonar -java-base2/src/main/java/org/perfsonar/base2/service/auth n/component/wssec perfsonar-java-base2/src/main/java/org/p erfsonar/base2/service/authn/tokens perfsonar-java-base2/s rc/main/java/org/perfsonar/base2/service/axis2interface pe rfsonar-java-base2/src/main/java/org/perfsonar/base2/servi ce/configuration perfsonar-java-base2/src/main/java/org/pe rfsonar/base2/service/configuration/migration perfsonar-ja va-base2/src/main/java/org/perfsonar/base2/service/configu ration/migration/g rammar perfsonar-java-base2/src/main/ja va/org/perfsonar/base2/service/configuration/migration/gra mmar/function perfsonar-java-base2/src/main/java/org/perfs onar/base2/service/exceptions perfsonar-java-base2/src/mai n/java/org/perfsonar/base2/service/messages perfsonar-java -base2/src/main/java/org/perfsonar/base2/service/registrat ion perfsonar-java-base2/src/main/java/org/perfsonar/base2 /service/requesthandler perfsonar-java-base2/src/main/java /org/perfsonar/base2/service/requesthandler/axis2 perfsona r-java-base2/src/main/java/org/perfsonar/base2/service/req uesthandler/file perfsonar-java-base2/src/main/java/org/pe rfsonar/base2/service/scheduler perfsonar-java-base2/src/m ain/java/org/perfsonar/base2/service/scheduler/singleThrea d perfsonar-java-base2/src/main/java/org/perfsonar/base2/s ervice/storage/xml perfsonar-java-base2/src/main/java/org/ perfsonar/base2/service/storage/xml/exist perfsonar-java-b ase2/src/main/java/org/perfsonar/base2/service/util perfso nar-java-base2/src/mai n/java/org/perfsonar/base2/service/ validation perfsonar-java-base2/src/main/java/org/perfsona r/base2/servlets perfsonar-java-base2/src/main/java/org/pe rfsonar/base2/xml perfsonar-java-base2/src/main/java/org/p erfsonar/base2/xml/nmwg perfsonar-java-base2/src/main/java /org/perfsonar/contrib perfsonar-java-base2/src/main/java/ org/perfsonar/service/simpleservice perfsonar-java-base2/s rc/main/java/org/perfsonar/test perfsonar-java-base2/src/m ain/resources/perfsonar/conf perfsonar-java-base2/src/test /java/org/perfsonar/base2/service perfsonar-java-base2/src /test/java/org/perfsonar/base2/service/configuration/migra tion perfsonar-java-base2/src/test/java/org/perfsonar/base 2/service/configuration/migration/grammar perfsonar-java-b ase2/src/test/java/org/perfsonar/base2/service/configurati on/migration/grammar/function perfsonar-java-base2/src/tes t/java/org/perfsonar/base2/service/validation
Subject: perfsonar development work
List archive
[pS-dev] [GEANT/SA2/ps-java-services] r6294 - in trunk: parent perfsonar-java-base2 perfsonar-java-bas e2/src perfsonar-java-base2/src/checkstyle perfsonar-java- base2/src/main/java/org/perfsonar/base2/client perfsonar-j ava-base2/src/main/java/org/perfsonar/base2/client/authn p erfsonar-java-base2/src/main/java/org/perfsonar/base2/clie nt/authn/edugain perfsonar-java-base2/src/main/java/org/pe rfsonar/base2/service/authn perfsonar-java-base2/src/main/ java/org/perfsonar/base2/service/authn/component perfsonar -java-base2/src/main/java/org/perfsonar/base2/service/auth n/component/wssec perfsonar-java-base2/src/main/java/org/p erfsonar/base2/service/authn/tokens perfsonar-java-base2/s rc/main/java/org/perfsonar/base2/service/axis2interface pe rfsonar-java-base2/src/main/java/org/perfsonar/base2/servi ce/configuration perfsonar-java-base2/src/main/java/org/pe rfsonar/base2/service/configuration/migration perfsonar-ja va-base2/src/main/java/org/perfsonar/base2/service/configu ration/migration/g rammar perfsonar-java-base2/src/main/ja va/org/perfsonar/base2/service/configuration/migration/gra mmar/function perfsonar-java-base2/src/main/java/org/perfs onar/base2/service/exceptions perfsonar-java-base2/src/mai n/java/org/perfsonar/base2/service/messages perfsonar-java -base2/src/main/java/org/perfsonar/base2/service/registrat ion perfsonar-java-base2/src/main/java/org/perfsonar/base2 /service/requesthandler perfsonar-java-base2/src/main/java /org/perfsonar/base2/service/requesthandler/axis2 perfsona r-java-base2/src/main/java/org/perfsonar/base2/service/req uesthandler/file perfsonar-java-base2/src/main/java/org/pe rfsonar/base2/service/scheduler perfsonar-java-base2/src/m ain/java/org/perfsonar/base2/service/scheduler/singleThrea d perfsonar-java-base2/src/main/java/org/perfsonar/base2/s ervice/storage/xml perfsonar-java-base2/src/main/java/org/ perfsonar/base2/service/storage/xml/exist perfsonar-java-b ase2/src/main/java/org/perfsonar/base2/service/util perfso nar-java-base2/src/mai n/java/org/perfsonar/base2/service/ validation perfsonar-java-base2/src/main/java/org/perfsona r/base2/servlets perfsonar-java-base2/src/main/java/org/pe rfsonar/base2/xml perfsonar-java-base2/src/main/java/org/p erfsonar/base2/xml/nmwg perfsonar-java-base2/src/main/java /org/perfsonar/contrib perfsonar-java-base2/src/main/java/ org/perfsonar/service/simpleservice perfsonar-java-base2/s rc/main/java/org/perfsonar/test perfsonar-java-base2/src/m ain/resources/perfsonar/conf perfsonar-java-base2/src/test /java/org/perfsonar/base2/service perfsonar-java-base2/src /test/java/org/perfsonar/base2/service/configuration/migra tion perfsonar-java-base2/src/test/java/org/perfsonar/base 2/service/configuration/migration/grammar perfsonar-java-b ase2/src/test/java/org/perfsonar/base2/service/configurati on/migration/grammar/function perfsonar-java-base2/src/tes t/java/org/perfsonar/base2/service/validation
Chronological Thread
- From:
- To:
- Subject: [pS-dev] [GEANT/SA2/ps-java-services] r6294 - in trunk: parent perfsonar-java-base2 perfsonar-java-bas e2/src perfsonar-java-base2/src/checkstyle perfsonar-java- base2/src/main/java/org/perfsonar/base2/client perfsonar-j ava-base2/src/main/java/org/perfsonar/base2/client/authn p erfsonar-java-base2/src/main/java/org/perfsonar/base2/clie nt/authn/edugain perfsonar-java-base2/src/main/java/org/pe rfsonar/base2/service/authn perfsonar-java-base2/src/main/ java/org/perfsonar/base2/service/authn/component perfsonar -java-base2/src/main/java/org/perfsonar/base2/service/auth n/component/wssec perfsonar-java-base2/src/main/java/org/p erfsonar/base2/service/authn/tokens perfsonar-java-base2/s rc/main/java/org/perfsonar/base2/service/axis2interface pe rfsonar-java-base2/src/main/java/org/perfsonar/base2/servi ce/configuration perfsonar-java-base2/src/main/java/org/pe rfsonar/base2/service/configuration/migration perfsonar-ja va-base2/src/main/java/org/perfsonar/base2/service/configu ration/migration/g rammar perfsonar-java-base2/src/main/ja va/org/perfsonar/base2/service/configuration/migration/gra mmar/function perfsonar-java-base2/src/main/java/org/perfs onar/base2/service/exceptions perfsonar-java-base2/src/mai n/java/org/perfsonar/base2/service/messages perfsonar-java -base2/src/main/java/org/perfsonar/base2/service/registrat ion perfsonar-java-base2/src/main/java/org/perfsonar/base2 /service/requesthandler perfsonar-java-base2/src/main/java /org/perfsonar/base2/service/requesthandler/axis2 perfsona r-java-base2/src/main/java/org/perfsonar/base2/service/req uesthandler/file perfsonar-java-base2/src/main/java/org/pe rfsonar/base2/service/scheduler perfsonar-java-base2/src/m ain/java/org/perfsonar/base2/service/scheduler/singleThrea d perfsonar-java-base2/src/main/java/org/perfsonar/base2/s ervice/storage/xml perfsonar-java-base2/src/main/java/org/ perfsonar/base2/service/storage/xml/exist perfsonar-java-b ase2/src/main/java/org/perfsonar/base2/service/util perfso nar-java-base2/src/mai n/java/org/perfsonar/base2/service/ validation perfsonar-java-base2/src/main/java/org/perfsona r/base2/servlets perfsonar-java-base2/src/main/java/org/pe rfsonar/base2/xml perfsonar-java-base2/src/main/java/org/p erfsonar/base2/xml/nmwg perfsonar-java-base2/src/main/java /org/perfsonar/contrib perfsonar-java-base2/src/main/java/ org/perfsonar/service/simpleservice perfsonar-java-base2/s rc/main/java/org/perfsonar/test perfsonar-java-base2/src/m ain/resources/perfsonar/conf perfsonar-java-base2/src/test /java/org/perfsonar/base2/service perfsonar-java-base2/src /test/java/org/perfsonar/base2/service/configuration/migra tion perfsonar-java-base2/src/test/java/org/perfsonar/base 2/service/configuration/migration/grammar perfsonar-java-b ase2/src/test/java/org/perfsonar/base2/service/configurati on/migration/grammar/function perfsonar-java-base2/src/tes t/java/org/perfsonar/base2/service/validation
- Date: Tue, 30 Apr 2013 14:14:32 +0100 (BST)
- Authentication-results: sfpop-ironport04.merit.edu; dkim=neutral (message not signed) header.i=none
Author: dante.delvaux
Date: 2013-04-30 14:14:31 +0100 (Tue, 30 Apr 2013)
New Revision: 6294
Added:
trunk/perfsonar-java-base2/src/checkstyle/
trunk/perfsonar-java-base2/src/checkstyle/checkstyle.xml
Modified:
trunk/parent/pom.xml
trunk/perfsonar-java-base2/pom.xml
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/Axis2Client.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/Client.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/UbCMDSTest.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/X509TestClient.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/authn/AttrEERequestGenerator.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/authn/AuthNDataFactory.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/authn/AuthNEERequestGenerator.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/authn/AuthNSAMLData.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/authn/AuthNX509Data.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/authn/AuthREERequestGenerator.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/authn/WSSAuthNSAMLData.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/authn/WSSAuthNX509Data.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/authn/edugain/EduGAINFilterHelper.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/authn/edugain/EduGAINMetadataService.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/AADispatchManager.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/AADispatchProtocol.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/AADispatchProtocolFactory.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/AADispatchSOAPProtocol.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/AttrRequest.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/AttrResponse.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/AuthNRequest.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/AuthNResponse.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/AuthRRequest.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/AuthRResponse.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/component/AuthNComponent.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/component/DynamicCrypto.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/component/wssec/WSSecAuthNComponent.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/tokens/SecTokenManager.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/tokens/SecTokenManagerFactory.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/tokens/SecTokenSOAPManager.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/tokens/SecurityToken.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/axis2interface/PerfsonarService.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/Action.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/Actions.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/AuxiliaryComponents.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/Configuration.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/ConfigurationManager.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/ElementConf.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/Entry.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/Extension.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/LookupInformation.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/Message.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/MessageHandler.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/Option.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/OptionEntry.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/ProtocolMappings.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/SchedulingComponent.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/Service.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/ConfigFilesCollection.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/MigratorComponent.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/SimpleTemplateEngine.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/TemplateEngine.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/grammar/BaseExpression.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/grammar/Expression.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/grammar/Interpreter.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/grammar/Loop.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/grammar/LoopExpression.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/grammar/PropertyExpression.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/grammar/function/Function.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/grammar/function/FunctionExpression.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/grammar/function/IndexerFunction.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/grammar/function/ReplaceFunction.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/exceptions/PerfSONARException.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/messages/GenericMessageHandler.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/messages/MessageHandler.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/registration/AbstractRegistrationAction.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/registration/GenericLSRegistrator.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/registration/LSRegistrationAction.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/registration/LSRegistrator.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/registration/MetadataExistDBRegisterDataSource.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/registration/RegisterDataSource.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/requesthandler/EchoServiceEngine.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/requesthandler/RequestHandler.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/requesthandler/ServiceEngine.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/requesthandler/ServiceMessage.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/requesthandler/axis2/Axis2RequestHandler.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/requesthandler/file/FileRequestHandler.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/scheduler/Scheduler.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/scheduler/SchedulerAction.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/scheduler/SchedulerTask.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/scheduler/SchedulingComponent.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/scheduler/SimpleAction.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/scheduler/SimpleScheduler.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/scheduler/singleThread/SchedulerTaskComparator.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/scheduler/singleThread/SingleThreadScheduler.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/DataCredential.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/XMLDBComponent.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/XMLDBConstants.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/XMLDBResult.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/XMLDataStorage.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/exist/ExistDbErrorException.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/exist/ExistDbHTTPAccess.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/exist/ExistHTTPDataStorage.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/exist/ExtendedExistHTTPDataStorage.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/exist/HTTPAccess.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/exist/HTTPResult.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/util/ResultCodesUtil.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/validation/JREVersion.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/servlets/AuthServlet.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/servlets/ExistDBInitServlet.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/AXIOMCreator.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/ConfigurationStaxParser.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/Element.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/ElementSerializer.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/ParserSource.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/StaxParser.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/StringBufferOutputStream.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/TextElement.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/nmwg/Data.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/nmwg/Key.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/nmwg/Metadata.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/nmwg/NMWGNamespaceFactory.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/nmwg/Parameter.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/nmwg/Parameters.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/nmwg/ParametersContainer.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/contrib/HTTPServer.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/service/simpleservice/SimpleServiceServiceEngine.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/test/ElementToJavaGenerator.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/test/StaxParserSimple.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/test/TestParser.java
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/test/ThreadTask.java
trunk/perfsonar-java-base2/src/main/resources/perfsonar/conf/configuration-rules.xml
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/AllTests.java
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/AllMigrationTests.java
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/ConfigFilesCollectionTest.java
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/FileNamePatternTest.java
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/MigratorComponentTest.java
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/SimpleTemplateEngineTest.java
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/configuration.xml.template
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/expected.xml
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/grammar/AllGrammarTests.java
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/grammar/LoopExpressionTest.java
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/grammar/LoopTest.java
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/grammar/PropertyExpressionTest.java
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/grammar/function/AllFunctionTests.java
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/grammar/function/FunctionExpressionTest.java
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/grammar/function/FunctionTestCase.java
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/grammar/function/IndexerFunctionTest.java
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/grammar/function/ReplaceFunctionTest.java
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/wizard.properties
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/validation/JREVersionTest.java
Log:
pSbase2: adding checkstyle configuration and correcting the major deviations
from standard.
Modified: trunk/parent/pom.xml
===================================================================
--- trunk/parent/pom.xml 2013-04-30 09:50:21 UTC (rev 6293)
+++ trunk/parent/pom.xml 2013-04-30 13:14:31 UTC (rev 6294)
@@ -286,7 +286,7 @@
<artifactId>maven-surefire-plugin</artifactId>
<version>2.14.1</version>
<configuration>
- <forkMode>always</forkMode>
+ <forkCount>1</forkCount>
</configuration>
</plugin>
Modified: trunk/perfsonar-java-base2/pom.xml
===================================================================
--- trunk/perfsonar-java-base2/pom.xml 2013-04-30 09:50:21 UTC (rev 6293)
+++ trunk/perfsonar-java-base2/pom.xml 2013-04-30 13:14:31 UTC (rev 6294)
@@ -17,6 +17,10 @@
<name>perfSONAR base 2</name>
<description>The perfSONAR base provides a number of common, shared
classes which can be used by MA, MP and Clients.</description>
<inceptionYear>2009</inceptionYear>
+
+ <properties>
+ <slf4j.version>1.7.5</slf4j.version> <!-- Needs to be aligned with
the parent/pom.xml -->
+ </properties>
<issueManagement>
<system>JIRA</system>
@@ -51,19 +55,13 @@
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
- <version>1.6.6</version>
+ <version>${slf4j.version}</version>
</dependency>
<dependency>
- <groupId>org.opensaml</groupId>
- <artifactId>xmltooling</artifactId>
- <version>1.1.0</version>
- </dependency>
-
- <dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
- <version>1.6.6</version>
+ <version>${slf4j.version}</version>
</dependency>
</dependencies>
@@ -74,7 +72,6 @@
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
- <version>4.11</version>
<scope>test</scope>
</dependency>
@@ -260,6 +257,12 @@
</dependency>
<dependency>
+ <groupId>exist</groupId>
+ <artifactId>exist</artifactId>
+ <version>1.2.6</version>
+ </dependency>
+
+ <dependency>
<artifactId>xmlrpc-client</artifactId>
<groupId>org.apache.xmlrpc</groupId>
<version>3.0</version>
@@ -274,14 +277,15 @@
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
- <version>1.6.6</version>
</dependency>
-
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
- <version>1.6.6</version>
</dependency>
+ <dependency>
+ <groupId>log4j</groupId>
+ <artifactId>log4j</artifactId>
+ </dependency>
<dependency>
<groupId>org.opensaml</groupId>
@@ -290,12 +294,6 @@
</dependency>
<dependency>
- <groupId>exist</groupId>
- <artifactId>exist</artifactId>
- <version>1.2.6</version>
- </dependency>
-
- <dependency>
<groupId>org.apache.santuario</groupId>
<artifactId>xmlsec</artifactId>
<version>1.4.6</version>
@@ -319,11 +317,6 @@
<version>4.0.1</version>
</dependency>
- <dependency>
- <groupId>log4j</groupId>
- <artifactId>log4j</artifactId>
- <version>1.2.17</version>
- </dependency>
</dependencies>
</project>
Added: trunk/perfsonar-java-base2/src/checkstyle/checkstyle.xml
===================================================================
--- trunk/perfsonar-java-base2/src/checkstyle/checkstyle.xml
(rev 0)
+++ trunk/perfsonar-java-base2/src/checkstyle/checkstyle.xml 2013-04-30
13:14:31 UTC (rev 6294)
@@ -0,0 +1,215 @@
+<?xml version="1.0"?>
+<!DOCTYPE module PUBLIC
+ "-//Puppy Crawl//DTD Check Configuration 1.3//EN"
+ "http://www.puppycrawl.com/dtds/configuration_1_3.dtd">
+
+<!--
+ Based on the default checkstyle configuration, but with minor
+ modifications based on established conventions in existing
+ perfsonar code.
+-->
+
+<!--
+
+ Checkstyle configuration that checks the sun coding conventions from:
+
+ - the Java Language Specification at
+ http://java.sun.com/docs/books/jls/second_edition/html/index.html
+
+ - the Sun Code Conventions at http://java.sun.com/docs/codeconv/
+
+ - the Javadoc guidelines at
+ http://java.sun.com/j2se/javadoc/writingdoccomments/index.html
+
+ - the JDK Api documentation http://java.sun.com/j2se/docs/api/index.html
+
+ - some best practices
+
+ Checkstyle is very configurable. Be sure to read the documentation at
+ http://checkstyle.sf.net (or in your downloaded distribution).
+
+ Most Checks are configurable, be sure to consult the documentation.
+
+ To completely disable a check, just comment it out or delete it from the
file.
+
+ Finally, it is worth reading the documentation.
+
+-->
+
+<module name="Checker">
+ <!--
+ If you set the basedir property below, then all reported file
+ names will be relative to the specified directory. See
+ http://checkstyle.sourceforge.net/5.x/config.html#Checker
+
+ <property name="basedir" value="${basedir}"/>
+ -->
+
+ <!-- Checks that a package-info.java file exists for each package.
-->
+ <!-- See http://checkstyle.sf.net/config_javadoc.html#JavadocPackage -->
+ <!--module name="JavadocPackage"/-->
+
+ <!-- Checks whether files end with a new line. -->
+ <!-- See http://checkstyle.sf.net/config_misc.html#NewlineAtEndOfFile -->
+ <module name="NewlineAtEndOfFile"/>
+
+ <!-- Checks that property files contain the same keys. -->
+ <!-- See http://checkstyle.sf.net/config_misc.html#Translation -->
+ <module name="Translation"/>
+
+ <!-- Checks for Size Violations. -->
+ <!-- See http://checkstyle.sf.net/config_sizes.html -->
+ <module name="FileLength"/>
+
+ <!-- Checks for whitespace -->
+ <!-- See http://checkstyle.sf.net/config_whitespace.html -->
+ <module name="FileTabCharacter">
+ <property name="severity" value="warning"/>
+ </module>
+
+ <!-- Miscellaneous other checks. -->
+ <!-- See http://checkstyle.sf.net/config_misc.html -->
+ <module name="RegexpSingleline">
+ <!-- I only want lines with *code* reported with trailing spaces, not
for empty ones or empty comment lines -->
+ <property name="format" value="[^[:space:]\*]+\s+$"/>
+ <property name="minimum" value="0"/>
+ <property name="maximum" value="0"/>
+ <property name="message" value="Line has trailing spaces."/>
+ </module>
+
+ <!-- Checks for Headers -->
+ <!-- See http://checkstyle.sf.net/config_header.html -->
+ <!-- <module name="Header"> -->
+ <!-- <property name="headerFile" value="${checkstyle.header.file}"/>
-->
+ <!-- <property name="fileExtensions" value="java"/> -->
+ <!-- </module> -->
+
+ <module name="TreeWalker">
+
+ <!-- Checks for Javadoc comments. -->
+ <!-- See http://checkstyle.sf.net/config_javadoc.html -->
+ <!--module name="JavadocMethod"/>
+ <module name="JavadocType"/>
+ <module name="JavadocVariable"/-->
+ <module name="JavadocStyle">
+ <property name="checkFirstSentence" value="false"/>
+ </module>
+
+ <!-- Checks for Naming Conventions. -->
+ <!-- See http://checkstyle.sf.net/config_naming.html -->
+ <module name="ConstantName"/>
+ <module name="LocalFinalVariableName"/>
+ <module name="LocalVariableName"/>
+ <module name="MemberName"/>
+ <module name="MethodName"/>
+ <module name="PackageName"/>
+ <module name="ParameterName"/>
+ <module name="StaticVariableName"/>
+ <module name="TypeName"/>
+
+
+ <!-- Checks for imports -->
+ <!-- See http://checkstyle.sf.net/config_import.html -->
+ <module name="AvoidStarImport"/>
+ <module name="IllegalImport"/> <!-- defaults to sun.* packages -->
+ <module name="RedundantImport"/>
+ <module name="UnusedImports">
+ <property name="severity" value="warning"/>
+ </module>
+
+
+ <!-- Checks for Size Violations. -->
+ <!-- See http://checkstyle.sf.net/config_sizes.html -->
+ <module name="LineLength">
+ <property name="max" value="150"/>
+ </module>
+ <module name="MethodLength">
+ <property name="severity" value="warning"/>
+ <property name="max" value="190"/>
+ </module>
+ <module name="ParameterNumber">
+ <property name="severity" value="warning"/>
+ </module>
+
+
+ <!-- Checks for whitespace -->
+ <!-- See http://checkstyle.sf.net/config_whitespace.html -->
+ <module name="EmptyForIteratorPad"/>
+ <module name="GenericWhitespace"/>
+ <module name="MethodParamPad"/>
+ <module name="NoWhitespaceAfter"/>
+ <module name="NoWhitespaceBefore"/>
+ <module name="OperatorWrap"/>
+ <module name="ParenPad"/>
+ <module name="TypecastParenPad"/>
+ <module name="WhitespaceAfter"/>
+ <module name="WhitespaceAround"/>
+
+
+ <!-- Modifier Checks -->
+ <!-- See http://checkstyle.sf.net/config_modifiers.html -->
+ <module name="ModifierOrder"/>
+ <module name="RedundantModifier"/>
+
+
+ <!-- Checks for blocks. You know, those {}'s -->
+ <!-- See http://checkstyle.sf.net/config_blocks.html -->
+ <module name="AvoidNestedBlocks"/>
+ <module name="EmptyBlock">
+ <property name="tokens"
+
value="LITERAL_DO,LITERAL_FINALLY,LITERAL_ELSE,LITERAL_FOR,LITERAL_TRY,LITERAL_WHILE,INSTANCE_INIT,STATIC_INIT"/>
+ </module>
+ <module name="NeedBraces"/>
+ <module name="RightCurly"/>
+
+
+ <!-- Checks for common coding problems -->
+ <!-- See http://checkstyle.sf.net/config_coding.html -->
+ <!--module name="AvoidInlineConditionals"/-->
+ <module name="EmptyStatement"/>
+ <module name="EqualsHashCode"/>
+ <module name="HiddenField">
+ <property name="tokens" value="VARIABLE_DEF"/>
+ </module>
+ <module name="IllegalInstantiation"/>
+ <module name="InnerAssignment"/>
+ <!--module name="MagicNumber"/-->
+ <module name="MissingSwitchDefault"/>
+ <module name="RedundantThrows">
+ <property name="suppressLoadErrors" value="true"/>
+ </module>
+ <module name="SimplifyBooleanExpression"/>
+ <module name="SimplifyBooleanReturn"/>
+
+ <!-- Checks for class design -->
+ <!-- See http://checkstyle.sf.net/config_design.html -->
+ <!--module name="DesignForExtension"/-->
+ <module name="FinalClass"/>
+ <module name="HideUtilityClassConstructor">
+ <property name="severity" value="warning"/>
+ </module>
+ <module name="InterfaceIsType">
+ <property name="severity" value="warning"/>
+ </module>
+ <module name="VisibilityModifier">
+ <property name="protectedAllowed" value="true"/>
+ </module>
+
+
+ <!-- Miscellaneous other checks. -->
+ <!-- See http://checkstyle.sf.net/config_misc.html -->
+ <module name="ArrayTypeStyle"/>
+ <!--module name="FinalParameters"/-->
+ <!-- I don't want the TODO comments being reported by CheckStyle -->
+ <!--<module name="TodoComment"/>-->
+ <module name="UpperEll"/>
+
+ <module name="FileContentsHolder"/>
+ </module>
+
+ <module name="SuppressionCommentFilter">
+ <property name="offCommentFormat" value="CHECKSTYLE_OFF: ALL"/>
+ <property name="onCommentFormat" value="CHECKSTYLE_ON: ALL"/>
+ </module>
+
+</module>
Property changes on: trunk/perfsonar-java-base2/src/checkstyle/checkstyle.xml
___________________________________________________________________
Added: svn:mime-type
+ text/plain
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/Axis2Client.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/Axis2Client.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/Axis2Client.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -29,17 +29,20 @@
this.parseFromConfiguration = parseFromConfiguration;
}
- public Element send(String url, Element e) throws PerfSONARException{
+ public Element send(String url, Element e) throws PerfSONARException {
AXIOMCreator ac = new AXIOMCreator();
try {
OMElement response = send(url, ac.getElement(e));
StaxParser sp;
- if (isParseFromConfiguration()) sp = new
ConfigurationStaxParser();
- else sp = new StaxParser();
+ if (isParseFromConfiguration()) {
+ sp = new ConfigurationStaxParser();
+ } else {
+ sp = new StaxParser();
+ }
return sp.parse(response.getXMLStreamReader());
} catch (Exception excp) {
- throw new PerfSONARException("client","Cannot send message to
["+url+"]: "+excp.getMessage());
+ throw new PerfSONARException("client", "Cannot send message to
[" + url + "]: " + excp.getMessage());
}
}
@@ -51,7 +54,7 @@
try {
send(url, ac.getElement(e));
} catch (Exception excp) {
- throw new PerfSONARException("client","Cannot send message to
["+url+"]: "+excp.getMessage());
+ throw new PerfSONARException("client", "Cannot send message to
[" + url + "]: " + excp.getMessage());
}
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/Client.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/Client.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/Client.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -6,8 +6,8 @@
public interface Client {
- public Element send(String url, Element e) throws PerfSONARException;
+ Element send(String url, Element e) throws PerfSONARException;
- public void sendNoResponse(String url, Element e) throws
PerfSONARException;
+ void sendNoResponse(String url, Element e) throws PerfSONARException;
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/UbCMDSTest.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/UbCMDSTest.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/UbCMDSTest.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -10,13 +10,13 @@
public class UbCMDSTest {
- public void testMDS(String[] args) {
- try {
- String defaultMDS="http://mds.rediris.es:8080";
- if (args.length==1) {
- defaultMDS=args[0];
- }
- List<BEMetaData>
bes=EduGAINMetadataService.getOrganizationList(defaultMDS);
+ public void testMDS(String[] args) {
+ try {
+ String defaultMDS = "http://mds.rediris.es:8080";
+ if (args.length == 1) {
+ defaultMDS = args[0];
+ }
+ List<BEMetaData> bes =
EduGAINMetadataService.getOrganizationList(defaultMDS);
for (BEMetaData be : bes) {
System.out.println("Bridging Element " +
be.getComponentID());
CAInterface caonline = be.getCAInterface();
@@ -24,16 +24,16 @@
System.out.println("*** CA online: " +
caonline.getContactURL());
}
}
- } catch (PerfSONARException e) {
- }
- }
+ } catch (PerfSONARException e) {
+ }
+ }
- /**
- * @param args
- */
- public static void main(String[] args) {
- UbCMDSTest mdsTest=new UbCMDSTest();
- mdsTest.testMDS(args);
- }
+ /**
+ * @param args
+ */
+ public static void main(String[] args) {
+ UbCMDSTest mdsTest = new UbCMDSTest();
+ mdsTest.testMDS(args);
+ }
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/X509TestClient.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/X509TestClient.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/X509TestClient.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -23,7 +23,6 @@
public class X509TestClient {
-
public static void main(String[] args) {
try {
@@ -35,12 +34,12 @@
if (args.length == 5) {
endPoint = args[0];
- inFile = args[1];
- outFile = args[2];
+ inFile = args[1];
+ outFile = args[2];
keyFile = args[3];
certFile = args[4];
} else {
- System.out.println("Error: Wrong number of parameters
("+args.length+") !!!");
+ System.out.println("Error: Wrong number of parameters (" +
args.length + ") !!!");
return;
}
System.out.println("End point: " + endPoint);
@@ -48,10 +47,10 @@
System.out.println("Response: " + outFile);
System.out.println("Private key file: " + keyFile);
System.out.println("Certificate file: " + certFile);
- DateFormat zulu = new
SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
- zulu.setTimeZone(TimeZone.getTimeZone("UTC"));
- Calendar cal=Calendar.getInstance();
- System.out.println("Date host: "+zulu.format(cal.getTime()));
+ DateFormat zulu = new
SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
+ zulu.setTimeZone(TimeZone.getTimeZone("UTC"));
+ Calendar cal = Calendar.getInstance();
+ System.out.println("Date host: " + zulu.format(cal.getTime()));
File file = new File(inFile);
FileInputStream fis = new FileInputStream(file);
@@ -65,14 +64,14 @@
SOAPBody soapBody = soapFactory.createSOAPBody(se);
soapBody.addChild(requestOMElement);
- Document doc =
Axis2Util.getDocumentFromSOAPEnvelope(se, true);
+ Document doc = Axis2Util.getDocumentFromSOAPEnvelope(se, true);
- AuthNX509Data
authnData=AuthNDataFactory.getDefaultAuthNX509Data();
- Object reqRaw=authnData.addX509STInMessage(doc, keyFile,
certFile);
- SOAPEnvelope envelope = (SOAPEnvelope)reqRaw;
+ AuthNX509Data authnData =
AuthNDataFactory.getDefaultAuthNX509Data();
+ Object reqRaw = authnData.addX509STInMessage(doc, keyFile,
certFile);
+ SOAPEnvelope envelope = (SOAPEnvelope) reqRaw;
- OMElement result = new Axis2Client().send(endPoint,
- envelope.getHeader().getFirstElement(),
requestOMElement);
+ OMElement result = new Axis2Client().send(endPoint,
envelope.getHeader().getFirstElement(),
+ requestOMElement);
FileOutputStream fos = new FileOutputStream(new File(outFile));
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/authn/AttrEERequestGenerator.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/authn/AttrEERequestGenerator.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/authn/AttrEERequestGenerator.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -19,28 +19,28 @@
import org.perfsonar.base2.xml.nmwg.Subject;
public class AttrEERequestGenerator {
- private static String metaId = "attrmetadata";
- private static String paramsId = "keys";
- private static String paramKey = "SecurityToken";
- private static String dataId = "attr1";
- private static String
WSS_X509="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3";
- private static String messageType = "AttrEERequest";
+ private static String metaId = "attrmetadata";
+ private static String paramsId = "keys";
+ private static String paramKey = "SecurityToken";
+ private static String dataId = "attr1";
+ private static String wssX509 =
"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3";
+ private static String messageType = "AttrEERequest";
- public Message generateRequestMessage() throws PerfSONARException {
- Metadata meta = new Metadata();
- meta.setId(metaId);
+ public Message generateRequestMessage() throws PerfSONARException {
+ Metadata meta = new Metadata();
+ meta.setId(metaId);
Parameters params = new Parameters();
params.setId(paramsId);
Parameter param = new Parameter();
param.setParameter("name", paramKey);
- param.setText(WSS_X509);
+ param.setText(wssX509);
params.addParameter(param);
meta.setParameters(params);
- Data data = new Data();
- data.setId(dataId);
- data.setMetadataIdRef(metaId);
+ Data data = new Data();
+ data.setId(dataId);
+ data.setMetadataIdRef(metaId);
Message message = new Message();
message.setType(messageType);
@@ -48,11 +48,11 @@
message.setData(data);
return message;
- }
+ }
- public Message generateRequestMessage(String secToken, AttrRequest
attrReq) throws PerfSONARException {
- Metadata meta = new Metadata();
- meta.setId(metaId);
+ public Message generateRequestMessage(String secToken, AttrRequest
attrReq) throws PerfSONARException {
+ Metadata meta = new Metadata();
+ meta.setId(metaId);
Parameters params = new Parameters();
params.setId(paramsId);
@@ -62,37 +62,37 @@
params.addParameter(param);
meta.setParameters(params);
- Data data = new Data();
- data.setId(dataId);
- data.setMetadataIdRef(metaId);
+ Data data = new Data();
+ data.setId(dataId);
+ data.setMetadataIdRef(metaId);
Message message = new Message();
message.setType(messageType);
message.setMetadata(meta);
message.setData(data);
- Subject attrSub=new Subject();
- attrSub.setText(getSAMLMessage(attrReq));
+ Subject attrSub = new Subject();
+ attrSub.setText(getSAMLMessage(attrReq));
message.getMetadata(metaId).setSubject(attrSub);
return message;
- }
+ }
- public Message generateRequestMessage(AttrRequest attrReq) throws
PerfSONARException {
- Metadata meta = new Metadata();
- meta.setId(metaId);
+ public Message generateRequestMessage(AttrRequest attrReq) throws
PerfSONARException {
+ Metadata meta = new Metadata();
+ meta.setId(metaId);
Parameters params = new Parameters();
params.setId(paramsId);
Parameter param = new Parameter();
param.setParameter("name", paramKey);
- param.setText(WSS_X509);
+ param.setText(wssX509);
params.addParameter(param);
meta.setParameters(params);
- Data data = new Data();
- data.setId(dataId);
- data.setMetadataIdRef(metaId);
+ Data data = new Data();
+ data.setId(dataId);
+ data.setMetadataIdRef(metaId);
Message message = new Message();
message.setType(messageType);
@@ -100,31 +100,43 @@
message.setData(data);
String reqString = getSAMLMessage(attrReq);
- reqString = reqString.replaceAll("\n", "");
- reqString = reqString.replaceAll("\r", "");
- reqString = reqString.replaceAll("\t", "");
- reqString = reqString.replaceAll(" ", "");
- Element authrElement = new Element("subject", "aa",
"http://ggf.org/ns/nmwg/tools/org/perfsonar/service/as/attr/1.0/");
+ reqString = reqString.replaceAll("\n", "");
+ reqString = reqString.replaceAll("\r", "");
+ reqString = reqString.replaceAll("\t", "");
+ reqString = reqString.replaceAll(" ", "");
+ Element authrElement = new Element("subject", "aa",
+
"http://ggf.org/ns/nmwg/tools/org/perfsonar/service/as/attr/1.0/");
authrElement.setText(reqString);
message.getMetadata(metaId).addChild(authrElement);
return message;
- }
+ }
- private String getSAMLMessage(AttrRequest attrReq) {
- Date date=new Date();
- Format formatter = new SimpleDateFormat("yyyy-MM-dd");
- Format formatter2 = new SimpleDateFormat("HH:mm:ss");
- String samlMessage = "<samlp:AttributeQuery
xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
xmlns:saml=\"urn:oasis:names:tc:SAML:2.0:assertion\"
xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\"
ID=\""+UUID.randomUUID().toString()+"\" Version=\"2.0\"
IssueInstant=\""+formatter.format(date)+"T"+formatter2.format(date)+"Z\">" +
- "<saml:Issuer>"+attrReq.getIssuer()+"</saml:Issuer>" +
- "<saml:Subject><saml:NameID
Format=\"urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified\">"+attrReq.getSubject()+"</saml:NameID></saml:Subject>";
+ private String getSAMLMessage(AttrRequest attrReq) {
+ Date date = new Date();
+ Format formatter = new SimpleDateFormat("yyyy-MM-dd");
+ Format formatter2 = new SimpleDateFormat("HH:mm:ss");
+ String samlMessage = "<samlp:AttributeQuery
xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ + " xmlns:saml=\"urn:oasis:names:tc:SAML:2.0:assertion\"
xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\" ID=\""
+ + UUID.randomUUID().toString()
+ + "\" Version=\"2.0\" IssueInstant=\""
+ + formatter.format(date)
+ + "T"
+ + formatter2.format(date)
+ + "Z\">"
+ + "<saml:Issuer>"
+ + attrReq.getIssuer()
+ + "</saml:Issuer>"
+ + "<saml:Subject><saml:NameID
Format=\"urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified\">"
+ + attrReq.getSubject() + "</saml:NameID></saml:Subject>";
Map<String, Map<String, List<String>>> attrs =
attrReq.getAttributes();
for (String urn : attrs.keySet()) {
Map<String, List<String>> data = attrs.get(urn);
Iterator<String> attrNames = data.keySet().iterator();
String friendlyName = attrNames.next();
- samlMessage += "<saml:Attribute
NameFormat=\"urn:oasis:names:tc:SAML:2.0:attrname-format:uri\" Name=\"" + urn
+ "\" FriendlyName=\"" + friendlyName + "\">";
+ samlMessage += "<saml:Attribute
NameFormat=\"urn:oasis:names:tc:SAML:2.0:attrname-format:uri\" Name=\""
+ + urn + "\" FriendlyName=\"" + friendlyName + "\">";
List<String> attrsValues = data.get(friendlyName);
for (String attrsValue : attrsValues) {
@@ -133,8 +145,8 @@
samlMessage += "</saml:Attribute>";
}
- samlMessage += "</samlp:AttributeQuery>";
+ samlMessage += "</samlp:AttributeQuery>";
return samlMessage;
- }
+ }
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/authn/AuthNDataFactory.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/authn/AuthNDataFactory.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/authn/AuthNDataFactory.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -1,13 +1,13 @@
package org.perfsonar.base2.client.authn;
public class AuthNDataFactory {
- public static AuthNX509Data getDefaultAuthNX509Data() {
- AuthNX509Data data=new WSSAuthNX509Data();
- return data;
- }
+ public static AuthNX509Data getDefaultAuthNX509Data() {
+ AuthNX509Data data = new WSSAuthNX509Data();
+ return data;
+ }
- public static AuthNSAMLData getDefaultAuthNSAMLData() {
- AuthNSAMLData data=new WSSAuthNSAMLData();
- return data;
- }
+ public static AuthNSAMLData getDefaultAuthNSAMLData() {
+ AuthNSAMLData data = new WSSAuthNSAMLData();
+ return data;
+ }
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/authn/AuthNEERequestGenerator.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/authn/AuthNEERequestGenerator.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/authn/AuthNEERequestGenerator.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -8,28 +8,28 @@
import org.perfsonar.base2.xml.nmwg.Parameters;
public class AuthNEERequestGenerator {
- private static String metaId = "authNmetadata";
- private static String paramsId = "keys";
- private static String paramKey = "SecurityToken";
- private static String dataId = "authN1";
- private static String
WSS_X509="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3";
- private static String messageType = "AuthNEERequest";
+ private static String metaId = "authNmetadata";
+ private static String paramsId = "keys";
+ private static String paramKey = "SecurityToken";
+ private static String dataId = "authN1";
+ private static String wssX509 =
"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3";
+ private static String messageType = "AuthNEERequest";
- public Message generateRequestMessage() throws PerfSONARException {
- Metadata meta = new Metadata();
- meta.setId(metaId);
+ public Message generateRequestMessage() throws PerfSONARException {
+ Metadata meta = new Metadata();
+ meta.setId(metaId);
Parameters params = new Parameters();
params.setId(paramsId);
Parameter param = new Parameter();
param.setParameter("name", paramKey);
- param.setText(WSS_X509);
+ param.setText(wssX509);
params.addParameter(param);
meta.setParameters(params);
- Data data = new Data();
- data.setId(dataId);
- data.setMetadataIdRef(metaId);
+ Data data = new Data();
+ data.setId(dataId);
+ data.setMetadataIdRef(metaId);
Message message = new Message();
message.setType(messageType);
@@ -37,11 +37,11 @@
message.setData(data);
return message;
- }
+ }
- public Message generateRequestMessage(String secToken) throws
PerfSONARException {
- Metadata meta = new Metadata();
- meta.setId(metaId);
+ public Message generateRequestMessage(String secToken) throws
PerfSONARException {
+ Metadata meta = new Metadata();
+ meta.setId(metaId);
Parameters params = new Parameters();
params.setId(paramsId);
@@ -51,9 +51,9 @@
params.addParameter(param);
meta.setParameters(params);
- Data data = new Data();
- data.setId(dataId);
- data.setMetadataIdRef(metaId);
+ Data data = new Data();
+ data.setId(dataId);
+ data.setMetadataIdRef(metaId);
Message message = new Message();
message.setType(messageType);
@@ -61,6 +61,6 @@
message.setData(data);
return message;
- }
+ }
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/authn/AuthNSAMLData.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/authn/AuthNSAMLData.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/authn/AuthNSAMLData.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -8,6 +8,11 @@
import org.perfsonar.base2.service.exceptions.PerfSONARException;
public interface AuthNSAMLData {
- public Object addSAMLSTInMessage(Object message,SAMLAssertion
authAssertion,PrivateKey key,Collection<Certificate> certchain,String
cidPerfsonarResource,String cidPerfsonarClient) throws PerfSONARException;
- public Object addSAMLSTInMessage(Object message,SAMLAssertion
authAssertion,PrivateKey key,Collection<Certificate> certchain,String
cidPerfsonarResource,String cidPerfsonarClient,int ttl) throws
PerfSONARException;
+ Object addSAMLSTInMessage(Object message, SAMLAssertion authAssertion,
PrivateKey key,
+ Collection<Certificate> certchain, String cidPerfsonarResource,
String cidPerfsonarClient)
+ throws PerfSONARException;
+
+ Object addSAMLSTInMessage(Object message, SAMLAssertion authAssertion,
PrivateKey key,
+ Collection<Certificate> certchain, String cidPerfsonarResource,
String cidPerfsonarClient, int ttl)
+ throws PerfSONARException;
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/authn/AuthNX509Data.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/authn/AuthNX509Data.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/authn/AuthNX509Data.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -6,8 +6,14 @@
import org.perfsonar.base2.service.exceptions.PerfSONARException;
public interface AuthNX509Data {
- public Object addX509STInMessage(Object message,String
privKeyFile,String certFile) throws PerfSONARException;
- public Object addX509STInMessage(Object message,PrivateKey
privateKey,X509Certificate cert) throws PerfSONARException;
- public Object addX509STInMessage(Object message,String
privKeyFile,String certFile,int ttl) throws PerfSONARException;
- public Object addX509STInMessage(Object message,PrivateKey
privateKey,X509Certificate cert,int ttl) throws PerfSONARException;
+ Object addX509STInMessage(Object message, String privKeyFile, String
certFile) throws PerfSONARException;
+
+ Object addX509STInMessage(Object message, PrivateKey privateKey,
X509Certificate cert)
+ throws PerfSONARException;
+
+ Object addX509STInMessage(Object message, String privKeyFile, String
certFile, int ttl)
+ throws PerfSONARException;
+
+ Object addX509STInMessage(Object message, PrivateKey privateKey,
X509Certificate cert, int ttl)
+ throws PerfSONARException;
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/authn/AuthREERequestGenerator.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/authn/AuthREERequestGenerator.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/authn/AuthREERequestGenerator.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -8,28 +8,28 @@
import org.perfsonar.base2.xml.nmwg.Parameters;
public class AuthREERequestGenerator {
- private static String metaId = "authRmetadata";
- private static String paramsId = "keys";
- private static String paramKey = "SecurityToken";
- private static String dataId = "authR1";
- private static String
WSS_X509="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3";
- private static String messageType = "AuthREERequest";
+ private static String metaId = "authRmetadata";
+ private static String paramsId = "keys";
+ private static String paramKey = "SecurityToken";
+ private static String dataId = "authR1";
+ private static String wssX509 =
"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3";
+ private static String messageType = "AuthREERequest";
- public Message generateRequestMessage() throws PerfSONARException {
- Metadata meta = new Metadata();
- meta.setId(metaId);
+ public Message generateRequestMessage() throws PerfSONARException {
+ Metadata meta = new Metadata();
+ meta.setId(metaId);
Parameters params = new Parameters();
params.setId(paramsId);
Parameter param = new Parameter();
param.setParameter("name", paramKey);
- param.setText(WSS_X509);
+ param.setText(wssX509);
params.addParameter(param);
meta.setParameters(params);
- Data data = new Data();
- data.setId(dataId);
- data.setMetadataIdRef(metaId);
+ Data data = new Data();
+ data.setId(dataId);
+ data.setMetadataIdRef(metaId);
Message message = new Message();
message.setType(messageType);
@@ -37,11 +37,11 @@
message.setData(data);
return message;
- }
+ }
- public Message generateRequestMessage(String secToken) throws
PerfSONARException {
- Metadata meta = new Metadata();
- meta.setId(metaId);
+ public Message generateRequestMessage(String secToken) throws
PerfSONARException {
+ Metadata meta = new Metadata();
+ meta.setId(metaId);
Parameters params = new Parameters();
params.setId(paramsId);
@@ -51,9 +51,9 @@
params.addParameter(param);
meta.setParameters(params);
- Data data = new Data();
- data.setId(dataId);
- data.setMetadataIdRef(metaId);
+ Data data = new Data();
+ data.setId(dataId);
+ data.setMetadataIdRef(metaId);
Message message = new Message();
message.setType(messageType);
@@ -61,5 +61,5 @@
message.setData(data);
return message;
- }
+ }
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/authn/WSSAuthNSAMLData.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/authn/WSSAuthNSAMLData.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/authn/WSSAuthNSAMLData.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -51,50 +51,51 @@
import org.w3c.dom.Text;
public class WSSAuthNSAMLData implements AuthNSAMLData {
- private static int defaultTtl=900;
+ private static int defaultTtl = 900;
- private String sigalg = XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1;
+ private String sigalg = XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1;
private String digalg = MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1;
- public Object addSAMLSTInMessage(Object message,
- SAMLAssertion authAssertion, PrivateKey key,
Collection<Certificate> certchain,
- String cidPerfsonarResource, String
cidPerfsonarClient)
- throws PerfSONARException {
- return addSAMLSTInMessage(message, authAssertion, key,
certchain, cidPerfsonarResource, cidPerfsonarClient, defaultTtl);
- }
+ public Object addSAMLSTInMessage(Object message, SAMLAssertion
authAssertion, PrivateKey key,
+ Collection<Certificate> certchain, String cidPerfsonarResource,
String cidPerfsonarClient)
+ throws PerfSONARException {
+ return addSAMLSTInMessage(message, authAssertion, key, certchain,
cidPerfsonarResource, cidPerfsonarClient,
+ defaultTtl);
+ }
- public Object addSAMLSTInMessage(Object message,
- SAMLAssertion authAssertion, PrivateKey key,
Collection<Certificate> certchain,
- String cidPerfsonarResource, String
cidPerfsonarClient, int ttl)
- throws PerfSONARException {
- SOAPEnvelope envelope = null;
- if (!(message instanceof Document)) {
- throw new
PerfSONARException("error.as.body","WSSAuthNSAMLData: the method
addSAMLSTInMessage requires a Document object");
- }
+ public Object addSAMLSTInMessage(Object message, SAMLAssertion
authAssertion, PrivateKey key,
+ Collection<Certificate> certchain, String cidPerfsonarResource,
String cidPerfsonarClient, int ttl)
+ throws PerfSONARException {
+ SOAPEnvelope envelope = null;
+ if (!(message instanceof Document)) {
+ throw new PerfSONARException("error.as.body",
+ "WSSAuthNSAMLData: the method addSAMLSTInMessage
requires a Document object");
+ }
// add the security provider
- BouncyCastleProvider bcp = new BouncyCastleProvider();
+ BouncyCastleProvider bcp = new BouncyCastleProvider();
java.security.Security.addProvider(bcp);
// add the private and public keys
Crypto crypto = null;
try {
- crypto = new DynamicCrypto();
+ crypto = new DynamicCrypto();
} catch (CredentialException e) {
- throw new
PerfSONARException("error.as.crypto","WSSAuthNSAMLData: "+e.getMessage());
+ throw new PerfSONARException("error.as.crypto",
"WSSAuthNSAMLData: " + e.getMessage());
}
- KeyStore ks=crypto.getKeyStore();
+ KeyStore ks = crypto.getKeyStore();
try {
- Certificate[] certs = new Certificate[certchain.size()];
- certs = certchain.toArray(certs);
- ks.setKeyEntry("xmlsec", key, "security".toCharArray(),
certs);
+ Certificate[] certs = new Certificate[certchain.size()];
+ certs = certchain.toArray(certs);
+ ks.setKeyEntry("xmlsec", key, "security".toCharArray(), certs);
} catch (KeyStoreException e) {
- throw new PerfSONARException("error.as.crypto","WSSAuthNData:
"+e.getMessage());
+ throw new PerfSONARException("error.as.crypto", "WSSAuthNData: "
+ e.getMessage());
}
try {
- SAMLAssertion sa=getAssertionAsSecurityToken(authAssertion,
key, certchain, cidPerfsonarResource, cidPerfsonarClient);
+ SAMLAssertion sa = getAssertionAsSecurityToken(authAssertion,
key, certchain, cidPerfsonarResource,
+ cidPerfsonarClient);
- Document doc = (Document)message;
+ Document doc = (Document) message;
WSSecHeader secHeader = new WSSecHeader();
secHeader.setActor("we");
@@ -103,34 +104,28 @@
WSSecSignature sec509 = new WSSecSignature();
sec509.setUserInfo("xmlsec", "security");
SOAPConstants soapConstants = SOAPConstants.SOAP11_CONSTANTS;
- Vector<WSEncryptionPart> parts = new
Vector<WSEncryptionPart>(1,1);
+ Vector<WSEncryptionPart> parts = new Vector<WSEncryptionPart>(1,
1);
// Set up to use STRTransorm to sign the signature token
- WSEncryptionPart encP =
- new WSEncryptionPart(
- "STRTransform",
- soapConstants.getEnvelopeURI(),
- "Content");
+ WSEncryptionPart encP = new WSEncryptionPart("STRTransform",
soapConstants.getEnvelopeURI(), "Content");
parts.add(encP);
// Adding timestamp information
WSSecTimestamp timestamp = new WSSecTimestamp();
- timestamp.prepare(doc);
- adjustTime(timestamp,ttl/2);
- WSSecurityUtil.prependChildElement(doc, secHeader
- .getSecurityHeader(), timestamp.getElement(), false);
- parts.add(new WSEncryptionPart(timestamp.getId()));
+ timestamp.prepare(doc);
+ adjustTime(timestamp, ttl / 2);
+ WSSecurityUtil.prependChildElement(doc,
secHeader.getSecurityHeader(), timestamp.getElement(), false);
+ parts.add(new WSEncryptionPart(timestamp.getId()));
- // Adding the SAML assertion as a binary token
- BinarySecurity bs=new BinarySecurity(doc);
- bs.setID("SAML");
- bs.getElement().setAttributeNS(null, "ValueType",
"#SAMLBase64Binary");
-
((Text)bs.getElement().getFirstChild()).setData(Base64.encode(sa.toString().getBytes()));
- WSSecurityUtil.prependChildElement(doc, secHeader
- .getSecurityHeader(), bs.getElement(), false);
- parts.add(new WSEncryptionPart(bs.getID()));
+ // Adding the SAML assertion as a binary token
+ BinarySecurity bs = new BinarySecurity(doc);
+ bs.setID("SAML");
+ bs.getElement().setAttributeNS(null, "ValueType",
"#SAMLBase64Binary");
+ ((Text)
bs.getElement().getFirstChild()).setData(Base64.encode(sa.toString().getBytes()));
+ WSSecurityUtil.prependChildElement(doc,
secHeader.getSecurityHeader(), bs.getElement(), false);
+ parts.add(new WSEncryptionPart(bs.getID()));
- // Setting parts
+ // Setting parts
sec509.setParts(parts);
sec509.setKeyIdentifierType(WSConstants.BST_DIRECT_REFERENCE);
@@ -140,85 +135,84 @@
envelope = Axis2Util.getSOAPEnvelopeFromDOMDocument(signedDoc,
true);
} catch (Exception e) {
- e.printStackTrace();
- throw new
PerfSONARException("error.as.signing","WSSAuthNSAMLData: "+e.getMessage());
+ e.printStackTrace();
+ throw new PerfSONARException("error.as.signing",
"WSSAuthNSAMLData: " + e.getMessage());
}
return envelope;
- }
+ }
- private SAMLAssertion getAssertionAsSecurityToken(SAMLAssertion
authAssertion,PrivateKey key,Collection<Certificate> certchain,String
cidPerfsonarResource,String cidPerfsonarClient) throws SAMLException {
- SAMLAssertion authStatementAssertion=new SAMLAssertion();
+ private SAMLAssertion getAssertionAsSecurityToken(SAMLAssertion
authAssertion, PrivateKey key,
+ Collection<Certificate> certchain, String cidPerfsonarResource,
String cidPerfsonarClient)
+ throws SAMLException {
+ SAMLAssertion authStatementAssertion = new SAMLAssertion();
- // Adding the client information
- SAMLAudienceRestrictionCondition cond=new
SAMLAudienceRestrictionCondition();
- cond.addAudience(cidPerfsonarResource);
- authStatementAssertion.addCondition(cond);
- authStatementAssertion.setIssuer(cidPerfsonarClient);
+ // Adding the client information
+ SAMLAudienceRestrictionCondition cond = new
SAMLAudienceRestrictionCondition();
+ cond.addAudience(cidPerfsonarResource);
+ authStatementAssertion.addCondition(cond);
+ authStatementAssertion.setIssuer(cidPerfsonarClient);
- SAMLSubject subject=new SAMLSubject();
- subject.addConfirmationMethod("relayed-trust");
- Iterator<?> it=authAssertion.getStatements();
- while (it.hasNext()) {
- SAMLStatement st=(SAMLStatement)it.next();
- if (st instanceof SAMLAuthenticationStatement) {
- SAMLAuthenticationStatement
as=(SAMLAuthenticationStatement)st;
- SAMLNameIdentifier
old=as.getSubject().getNameIdentifier();
- subject.setNameIdentifier(new
SAMLNameIdentifier(old.getName(),old.getNameQualifier(),old.getFormat()));
- }
- }
- try {
- Document request =
authAssertion.toDOM().getOwnerDocument();
+ SAMLSubject subject = new SAMLSubject();
+ subject.addConfirmationMethod("relayed-trust");
+ Iterator<?> it = authAssertion.getStatements();
+ while (it.hasNext()) {
+ SAMLStatement st = (SAMLStatement) it.next();
+ if (st instanceof SAMLAuthenticationStatement) {
+ SAMLAuthenticationStatement as =
(SAMLAuthenticationStatement) st;
+ SAMLNameIdentifier old = as.getSubject().getNameIdentifier();
+ subject.setNameIdentifier(new
SAMLNameIdentifier(old.getName(), old.getNameQualifier(), old.getFormat()));
+ }
+ }
+ try {
+ Document request = authAssertion.toDOM().getOwnerDocument();
- Element c=request.createElementNS(XML.SAML_NS,
"SubjectConfirmationData");
- c.appendChild(authAssertion.toDOM());
+ Element c = request.createElementNS(XML.SAML_NS,
"SubjectConfirmationData");
+ c.appendChild(authAssertion.toDOM());
- subject.setConfirmationData(c);
- } catch (Exception pce) {
- pce.printStackTrace();
- }
+ subject.setConfirmationData(c);
+ } catch (Exception pce) {
+ pce.printStackTrace();
+ }
- SAMLAuthenticationStatement authStatement=new
SAMLAuthenticationStatement();
-
authStatement.setAuthMethod(SAMLAuthenticationStatement.AuthenticationMethod_Unspecified);
- authStatement.setAuthInstant(new Date());
- authStatement.setSubject(subject);
- authStatementAssertion.addStatement(authStatement);
+ SAMLAuthenticationStatement authStatement = new
SAMLAuthenticationStatement();
+
authStatement.setAuthMethod(SAMLAuthenticationStatement.AuthenticationMethod_Unspecified);
+ authStatement.setAuthInstant(new Date());
+ authStatement.setSubject(subject);
+ authStatementAssertion.addStatement(authStatement);
- authStatementAssertion.sign(sigalg, digalg, key, certchain);
+ authStatementAssertion.sign(sigalg, digalg, key, certchain);
- return authStatementAssertion;
- }
+ return authStatementAssertion;
+ }
-
- private void adjustTime(WSSecTimestamp timestamp, int range) throws
WSSecurityException {
+ private void adjustTime(WSSecTimestamp timestamp, int range) throws
WSSecurityException {
DateFormat zulu = null;
if (WSSConfig.getDefaultWSConfig().isPrecisionInMilliSeconds()) {
- zulu = new XmlSchemaDateFormat();
+ zulu = new XmlSchemaDateFormat();
+ } else {
+ zulu = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
+ zulu.setTimeZone(TimeZone.getTimeZone("UTC"));
}
- else {
- zulu = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
- zulu.setTimeZone(TimeZone.getTimeZone("UTC"));
- }
- Element e=timestamp.getElement();
- Timestamp ts=new Timestamp(e);
- Element e2=ts.getElement();
- for (int i=0; i<e2.getChildNodes().getLength(); i++) {
- Element e3=(Element)e2.getChildNodes().item(i);
+ Element e = timestamp.getElement();
+ Timestamp ts = new Timestamp(e);
+ Element e2 = ts.getElement();
+ for (int i = 0; i < e2.getChildNodes().getLength(); i++) {
+ Element e3 = (Element) e2.getChildNodes().item(i);
- NodeList list = e3.getChildNodes();
- if (list.getLength()>0) {
- Node n1 = list.item(0);
- TextImpl ti = (TextImpl) n1;
- if (e3.getNodeName().equals("wsu:Created")) {
- ts.getCreated().add(Calendar.SECOND, -range);
-
ti.setData(zulu.format(ts.getCreated().getTime()));
- }
- else if
(e3.getNodeName().equals("wsu:Expires")) {
- ts.getExpires().add(Calendar.SECOND, -range);
-
ti.setData(zulu.format(ts.getExpires().getTime()));
- }
- }
- }
- }
+ NodeList list = e3.getChildNodes();
+ if (list.getLength() > 0) {
+ Node n1 = list.item(0);
+ TextImpl ti = (TextImpl) n1;
+ if (e3.getNodeName().equals("wsu:Created")) {
+ ts.getCreated().add(Calendar.SECOND, -range);
+ ti.setData(zulu.format(ts.getCreated().getTime()));
+ } else if (e3.getNodeName().equals("wsu:Expires")) {
+ ts.getExpires().add(Calendar.SECOND, -range);
+ ti.setData(zulu.format(ts.getExpires().getTime()));
+ }
+ }
+ }
+ }
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/authn/WSSAuthNX509Data.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/authn/WSSAuthNX509Data.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/authn/WSSAuthNX509Data.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -43,61 +43,65 @@
import org.w3c.dom.NodeList;
public class WSSAuthNX509Data implements AuthNX509Data {
- private static int defaultTtl=900;
+ private static int defaultTtl = 900;
- public Object addX509STInMessage(Object message,String
privKeyFile,String certFile) throws PerfSONARException {
- return
addX509STInMessage(message,privKeyFile,certFile,defaultTtl);
- }
+ public Object addX509STInMessage(Object message, String privKeyFile,
String certFile) throws PerfSONARException {
+ return addX509STInMessage(message, privKeyFile, certFile,
defaultTtl);
+ }
- public Object addX509STInMessage(Object message,String
privKeyFile,String certFile,int ttl) throws PerfSONARException {
- if (!(message instanceof Document)) {
- throw new
PerfSONARException("error.as.body","WSSAuthNX509Data: the method
addX509STInMessage requires a Document object");
- }
+ public Object addX509STInMessage(Object message, String privKeyFile,
String certFile, int ttl)
+ throws PerfSONARException {
+ if (!(message instanceof Document)) {
+ throw new PerfSONARException("error.as.body",
+ "WSSAuthNX509Data: the method addX509STInMessage
requires a Document object");
+ }
// add the security provider
- BouncyCastleProvider bcp = new BouncyCastleProvider();
+ BouncyCastleProvider bcp = new BouncyCastleProvider();
java.security.Security.addProvider(bcp);
// add the private and public keys
Crypto crypto = null;
try {
- crypto = new DynamicCrypto();
+ crypto = new DynamicCrypto();
} catch (CredentialException e) {
- throw new
PerfSONARException("error.as.crypto","WSSAuthNX509Data: "+e.getMessage());
+ throw new PerfSONARException("error.as.crypto",
"WSSAuthNX509Data: " + e.getMessage());
}
- X509Certificate cert=addCertificate(crypto,certFile);
- PrivateKey privateKey=addPrivateKey(privKeyFile);
+ X509Certificate cert = addCertificate(crypto, certFile);
+ PrivateKey privateKey = addPrivateKey(privKeyFile);
return addX509STInMessage(message, privateKey, cert, ttl);
- }
+ }
- public Object addX509STInMessage(Object message,PrivateKey
privateKey,X509Certificate cert, int ttl) throws PerfSONARException {
- SOAPEnvelope envelope = null;
- if (!(message instanceof Document)) {
- throw new
PerfSONARException("error.as.body","WSSAuthNX509Data: the method
addX509STInMessage requires a Document object");
- }
+ public Object addX509STInMessage(Object message, PrivateKey privateKey,
X509Certificate cert, int ttl)
+ throws PerfSONARException {
+ SOAPEnvelope envelope = null;
+ if (!(message instanceof Document)) {
+ throw new PerfSONARException("error.as.body",
+ "WSSAuthNX509Data: the method addX509STInMessage
requires a Document object");
+ }
// add the security provider
- BouncyCastleProvider bcp = new BouncyCastleProvider();
+ BouncyCastleProvider bcp = new BouncyCastleProvider();
java.security.Security.addProvider(bcp);
Crypto crypto = null;
try {
- crypto = new DynamicCrypto();
+ crypto = new DynamicCrypto();
} catch (CredentialException e) {
- throw new
PerfSONARException("error.as.crypto","WSSAuthNX509Data: "+e.getMessage());
+ throw new PerfSONARException("error.as.crypto",
"WSSAuthNX509Data: " + e.getMessage());
}
- KeyStore ks=crypto.getKeyStore();
+ KeyStore ks = crypto.getKeyStore();
try {
- ks.setKeyEntry("xmlsec", privateKey,
"security".toCharArray(), new Certificate[]{cert});
+ ks.setKeyEntry("xmlsec", privateKey, "security".toCharArray(),
new Certificate[] {cert });
} catch (KeyStoreException e) {
- throw new
PerfSONARException("error.as.crypto","WSSAuthNX509Data: "+e.getMessage());
+ throw new PerfSONARException("error.as.crypto",
"WSSAuthNX509Data: " + e.getMessage());
}
try {
- Document doc = (Document)message;
+ Document doc = (Document) message;
WSSecHeader secHeader = new WSSecHeader();
secHeader.setActor("ac");
@@ -107,24 +111,19 @@
WSSecSignature sec509 = new WSSecSignature();
sec509.setUserInfo("xmlsec", "security");
SOAPConstants soapConstants = SOAPConstants.SOAP11_CONSTANTS;
- Vector<WSEncryptionPart> parts = new
Vector<WSEncryptionPart>(1,1);
+ Vector<WSEncryptionPart> parts = new Vector<WSEncryptionPart>(1,
1);
// Set up to use STRTransorm to sign the signature token
- WSEncryptionPart encP =
- new WSEncryptionPart(
- "STRTransform",
- soapConstants.getEnvelopeURI(),
- "Content");
+ WSEncryptionPart encP = new WSEncryptionPart("STRTransform",
soapConstants.getEnvelopeURI(), "Content");
parts.add(encP);
// Adding timestamp information
WSSecTimestamp timestamp = new WSSecTimestamp();
timestamp.setTimeToLive(ttl);
- timestamp.prepare(doc);
- adjustTime(timestamp,ttl/2);
- WSSecurityUtil.prependChildElement(doc, secHeader
- .getSecurityHeader(), timestamp.getElement(), false);
- parts.add(new WSEncryptionPart(timestamp.getId()));
+ timestamp.prepare(doc);
+ adjustTime(timestamp, ttl / 2);
+ WSSecurityUtil.prependChildElement(doc,
secHeader.getSecurityHeader(), timestamp.getElement(), false);
+ parts.add(new WSEncryptionPart(timestamp.getId()));
sec509.setParts(parts);
sec509.setKeyIdentifierType(WSConstants.BST_DIRECT_REFERENCE);
@@ -134,81 +133,80 @@
envelope = Axis2Util.getSOAPEnvelopeFromDOMDocument(signedDoc,
true);
} catch (Exception e) {
- e.printStackTrace();
- throw new
PerfSONARException("error.as.signing","WSSAuthNX509Data: "+e.getMessage());
+ e.printStackTrace();
+ throw new PerfSONARException("error.as.signing",
"WSSAuthNX509Data: " + e.getMessage());
}
return envelope;
}
- public Object addX509STInMessage(Object message,PrivateKey
privateKey,X509Certificate cert) throws PerfSONARException {
- return addX509STInMessage(message,privateKey,cert,defaultTtl);
- }
+ public Object addX509STInMessage(Object message, PrivateKey privateKey,
X509Certificate cert)
+ throws PerfSONARException {
+ return addX509STInMessage(message, privateKey, cert, defaultTtl);
+ }
- private PrivateKey addPrivateKey(String privKeyFile) throws
PerfSONARException {
- try {
- BufferedReader in = new BufferedReader(new
FileReader(privKeyFile));
- String str;
- String previousStr="";
- String data="";
- in.readLine();
- while ((str = in.readLine()) != null) {
- data+=previousStr;
- previousStr=str+"\n";
- }
- in.close();
+ private PrivateKey addPrivateKey(String privKeyFile) throws
PerfSONARException {
+ try {
+ BufferedReader in = new BufferedReader(new
FileReader(privKeyFile));
+ String str;
+ String previousStr = "";
+ String data = "";
+ in.readLine();
+ while ((str = in.readLine()) != null) {
+ data += previousStr;
+ previousStr = str + "\n";
+ }
+ in.close();
- byte[] bytes=Base64.decode(data);
- PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes);
- KeyFactory keyFactory = KeyFactory.getInstance("RSA");
- PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
- return privateKey;
- } catch (Exception e) {
- throw new
PerfSONARException("error.as.getting_privkey","WSSAuthNX509Data:
"+e.getMessage());
- }
- }
+ byte[] bytes = Base64.decode(data);
+ PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes);
+ KeyFactory keyFactory = KeyFactory.getInstance("RSA");
+ PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
+ return privateKey;
+ } catch (Exception e) {
+ throw new PerfSONARException("error.as.getting_privkey",
"WSSAuthNX509Data: " + e.getMessage());
+ }
+ }
- private X509Certificate addCertificate(Crypto crypto,String certFile)
throws PerfSONARException {
- try {
- InputStream isCert=new FileInputStream(certFile);
+ private X509Certificate addCertificate(Crypto crypto, String certFile)
throws PerfSONARException {
+ try {
+ InputStream isCert = new FileInputStream(certFile);
- X509Certificate cert=crypto.loadCertificate(isCert);
+ X509Certificate cert = crypto.loadCertificate(isCert);
- return cert;
- } catch (Exception e) {
- throw new
PerfSONARException("error.as.getting_cert","WSSAuthNX509Data:
"+e.getMessage());
- }
- }
+ return cert;
+ } catch (Exception e) {
+ throw new PerfSONARException("error.as.getting_cert",
"WSSAuthNX509Data: " + e.getMessage());
+ }
+ }
- private void adjustTime(WSSecTimestamp timestamp, int range) throws
WSSecurityException {
+ private void adjustTime(WSSecTimestamp timestamp, int range) throws
WSSecurityException {
DateFormat zulu = null;
if (WSSConfig.getDefaultWSConfig().isPrecisionInMilliSeconds()) {
- zulu = new XmlSchemaDateFormat();
+ zulu = new XmlSchemaDateFormat();
+ } else {
+ zulu = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
+ zulu.setTimeZone(TimeZone.getTimeZone("UTC"));
}
- else {
- zulu = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
- zulu.setTimeZone(TimeZone.getTimeZone("UTC"));
- }
- Element e=timestamp.getElement();
- Timestamp ts=new Timestamp(e);
- Element e2=ts.getElement();
- for (int i=0; i<e2.getChildNodes().getLength(); i++) {
- Element e3=(Element)e2.getChildNodes().item(i);
+ Element e = timestamp.getElement();
+ Timestamp ts = new Timestamp(e);
+ Element e2 = ts.getElement();
+ for (int i = 0; i < e2.getChildNodes().getLength(); i++) {
+ Element e3 = (Element) e2.getChildNodes().item(i);
- NodeList list = e3.getChildNodes();
- if (list.getLength()>0) {
- Node n1 = list.item(0);
- TextImpl ti = (TextImpl) n1;
- if (e3.getNodeName().equals("wsu:Created")) {
- ts.getCreated().add(Calendar.SECOND, -range);
-
ti.setData(zulu.format(ts.getCreated().getTime()));
- }
- else if
(e3.getNodeName().equals("wsu:Expires")) {
- ts.getExpires().add(Calendar.SECOND, -range);
-
ti.setData(zulu.format(ts.getExpires().getTime()));
- }
- }
- }
- }
+ NodeList list = e3.getChildNodes();
+ if (list.getLength() > 0) {
+ Node n1 = list.item(0);
+ TextImpl ti = (TextImpl) n1;
+ if (e3.getNodeName().equals("wsu:Created")) {
+ ts.getCreated().add(Calendar.SECOND, -range);
+ ti.setData(zulu.format(ts.getCreated().getTime()));
+ } else if (e3.getNodeName().equals("wsu:Expires")) {
+ ts.getExpires().add(Calendar.SECOND, -range);
+ ti.setData(zulu.format(ts.getExpires().getTime()));
+ }
+ }
+ }
+ }
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/authn/edugain/EduGAINFilterHelper.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/authn/edugain/EduGAINFilterHelper.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/authn/edugain/EduGAINFilterHelper.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -11,30 +11,31 @@
import org.opensaml.SAMLStatement;
public class EduGAINFilterHelper {
-
- @SuppressWarnings("unchecked") // should be save
- public static SAMLAssertion getAuthenticationAssertion(HttpSession
session) {
- SAMLAssertion authStatementAssertion=null;
-
- Enumeration<String> attrs = session.getAttributeNames();
- while (attrs.hasMoreElements()&&authStatementAssertion==null)
{
- String attrName = attrs.nextElement();
- Object attrValRaw = session.getAttribute(attrName);
- if (attrValRaw instanceof SAMLResponse) {
- SAMLResponse
samlResponse=(SAMLResponse)attrValRaw;
- Iterator<SAMLAssertion>
it=samlResponse.getAssertions();
- while
(it.hasNext()&&authStatementAssertion==null) {
- SAMLAssertion assertion=it.next();
- Iterator<SAMLStatement>
it2=assertion.getStatements();
- while
(it2.hasNext()&&authStatementAssertion==null) {
- SAMLStatement
statement=it2.next();
- if (statement instanceof
SAMLAuthenticationStatement) {
-
authStatementAssertion=assertion;
- }
- }
- }
- }
- }
- return authStatementAssertion;
- }
+
+ @SuppressWarnings("unchecked")
+ // should be save
+ public static SAMLAssertion getAuthenticationAssertion(HttpSession
session) {
+ SAMLAssertion authStatementAssertion = null;
+
+ Enumeration<String> attrs = session.getAttributeNames();
+ while (attrs.hasMoreElements() && authStatementAssertion == null) {
+ String attrName = attrs.nextElement();
+ Object attrValRaw = session.getAttribute(attrName);
+ if (attrValRaw instanceof SAMLResponse) {
+ SAMLResponse samlResponse = (SAMLResponse) attrValRaw;
+ Iterator<SAMLAssertion> it = samlResponse.getAssertions();
+ while (it.hasNext() && authStatementAssertion == null) {
+ SAMLAssertion assertion = it.next();
+ Iterator<SAMLStatement> it2 = assertion.getStatements();
+ while (it2.hasNext() && authStatementAssertion == null) {
+ SAMLStatement statement = it2.next();
+ if (statement instanceof
SAMLAuthenticationStatement) {
+ authStatementAssertion = assertion;
+ }
+ }
+ }
+ }
+ }
+ return authStatementAssertion;
+ }
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/authn/edugain/EduGAINMetadataService.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/authn/edugain/EduGAINMetadataService.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/client/authn/edugain/EduGAINMetadataService.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -13,24 +13,25 @@
import net.geant.edugain.meta.query.MetaDataRequester;
public class EduGAINMetadataService {
- private static final String defaultUriMDS="http://mds.ladok.umu.se/";
+ private static final String DEFAULT_URI_MDS = "http://mds.ladok.umu.se/";
- public static List<BEMetaData> getOrganizationList(String uriMds)
throws PerfSONARException {
- List<BEMetaData> list=new LinkedList<BEMetaData>();
- try {
- MetaDataRequester requester=new MetaDataRequester();
- XMLObject xo=requester.getXMLMetaData(new
URL(uriMds), "md:EntitiesDescriptor");
- FederationMetaData fmd=requester.getFedMetaData(xo);
- ArrayList<BEMetaData> listBEs=fmd.getBeMetaDataList();
- list.addAll(listBEs);
+ public static List<BEMetaData> getOrganizationList(String uriMds) throws
PerfSONARException {
+ List<BEMetaData> list = new LinkedList<BEMetaData>();
+ try {
+ MetaDataRequester requester = new MetaDataRequester();
+ XMLObject xo = requester.getXMLMetaData(new URL(uriMds),
"md:EntitiesDescriptor");
+ FederationMetaData fmd = requester.getFedMetaData(xo);
+ ArrayList<BEMetaData> listBEs = fmd.getBeMetaDataList();
+ list.addAll(listBEs);
- return list;
- } catch (Exception e) {
- throw new
PerfSONARException("error.as.mds_query","EduGAINMetadataService: a problem
querying the MDS: "+e.getMessage());
- }
- }
+ return list;
+ } catch (Exception e) {
+ throw new PerfSONARException("error.as.mds_query",
"EduGAINMetadataService: a problem querying the MDS: "
+ + e.getMessage());
+ }
+ }
- public static List<BEMetaData> getOrganizationList() throws
PerfSONARException {
- return getOrganizationList(defaultUriMDS);
- }
+ public static List<BEMetaData> getOrganizationList() throws
PerfSONARException {
+ return getOrganizationList(DEFAULT_URI_MDS);
+ }
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/AADispatchManager.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/AADispatchManager.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/AADispatchManager.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -3,17 +3,17 @@
import org.perfsonar.base2.service.exceptions.PerfSONARException;
public class AADispatchManager {
- AADispatchProtocol protocol;
+ private AADispatchProtocol protocol;
- public AADispatchManager(AADispatchProtocol prot) {
- this.protocol=prot;
- }
+ public AADispatchManager(AADispatchProtocol prot) {
+ this.protocol = prot;
+ }
- public AuthNResponse getAuthentication(AuthNRequest req) throws
PerfSONARException {
- return protocol.getAuthentication(req);
- }
+ public AuthNResponse getAuthentication(AuthNRequest req) throws
PerfSONARException {
+ return protocol.getAuthentication(req);
+ }
- public AuthRResponse getAuthorization(AuthRRequest req) throws
PerfSONARException {
- return protocol.getAuthorization(req);
- }
+ public AuthRResponse getAuthorization(AuthRRequest req) throws
PerfSONARException {
+ return protocol.getAuthorization(req);
+ }
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/AADispatchProtocol.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/AADispatchProtocol.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/AADispatchProtocol.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -3,8 +3,11 @@
import org.perfsonar.base2.service.exceptions.PerfSONARException;
public interface AADispatchProtocol {
- public void setAuthService(String uriAuthServer);
- public AuthNResponse getAuthentication(AuthNRequest req) throws
PerfSONARException;
- public AuthRResponse getAuthorization(AuthRRequest req) throws
PerfSONARException;
- public AttrResponse getAttributes(AttrRequest req) throws
PerfSONARException;
+ void setAuthService(String uriAuthServer);
+
+ AuthNResponse getAuthentication(AuthNRequest req) throws
PerfSONARException;
+
+ AuthRResponse getAuthorization(AuthRRequest req) throws
PerfSONARException;
+
+ AttrResponse getAttributes(AttrRequest req) throws PerfSONARException;
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/AADispatchProtocolFactory.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/AADispatchProtocolFactory.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/AADispatchProtocolFactory.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -3,7 +3,7 @@
import org.perfsonar.base2.service.exceptions.PerfSONARException;
public class AADispatchProtocolFactory {
- public static AADispatchProtocol getDefaultAADispatchProtocol()
throws PerfSONARException {
- return new AADispatchSOAPProtocol();
- }
+ public static AADispatchProtocol getDefaultAADispatchProtocol() throws
PerfSONARException {
+ return new AADispatchSOAPProtocol();
+ }
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/AADispatchSOAPProtocol.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/AADispatchSOAPProtocol.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/AADispatchSOAPProtocol.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -38,50 +38,51 @@
import org.perfsonar.base2.xml.nmwg.Parameters;
public class AADispatchSOAPProtocol implements AADispatchProtocol {
- public static final String
WSS_X509="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3";
- public static final String
WSS_SAML="http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1";
+ public static final String WSS_X509 =
"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3";
+ public static final String WSS_SAML =
"http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1";
- private String asPoint;
+ private String asPoint;
- protected static final Logger logger =
LoggerFactory.getLogger(AADispatchSOAPProtocol.class);
+ protected static final Logger LOGGER =
LoggerFactory.getLogger(AADispatchSOAPProtocol.class);
- public AADispatchSOAPProtocol() throws PerfSONARException {
- this.asPoint = "";
- }
+ public AADispatchSOAPProtocol() throws PerfSONARException {
+ this.asPoint = "";
+ }
- public AADispatchSOAPProtocol(String asPoint) throws
PerfSONARException {
- this.asPoint=asPoint;
- }
+ public AADispatchSOAPProtocol(String asPoint) throws PerfSONARException {
+ this.asPoint = asPoint;
+ }
- public void setAuthService(String uriAuthServer) {
- this.setAsPoint(uriAuthServer);
- }
+ public void setAuthService(String uriAuthServer) {
+ this.setAsPoint(uriAuthServer);
+ }
- public String getAsPoint() {
- return asPoint;
- }
+ public String getAsPoint() {
+ return asPoint;
+ }
- public void setAsPoint(String asPoint) {
- this.asPoint = asPoint;
- }
+ public void setAsPoint(String asPoint) {
+ this.asPoint = asPoint;
+ }
- private String getClient(SecurityToken token) throws Exception {
- Object stValue=token.getSecTokenValue();
- if (SecTokenSOAPManager.isDelegated(token)) {
- SAMLAssertion assertion=(SAMLAssertion)stValue;
- String clientIssuer=assertion.getIssuer();
+ private String getClient(SecurityToken token) throws Exception {
+ Object stValue = token.getSecTokenValue();
+ if (SecTokenSOAPManager.isDelegated(token)) {
+ SAMLAssertion assertion = (SAMLAssertion) stValue;
+ String clientIssuer = assertion.getIssuer();
- return clientIssuer;
- }
+ return clientIssuer;
+ }
- return "";
- }
+ return "";
+ }
- public SOAPHeaderBlock updateSecurityTokenParameter(Message
requestMessage, SecurityToken token) throws PerfSONARException {
- Parameter parameter = null;
+ public SOAPHeaderBlock updateSecurityTokenParameter(Message
requestMessage, SecurityToken token)
+ throws PerfSONARException {
+ Parameter parameter = null;
- // get the parameter which specifies the format of the
security token
- Collection<Metadata>
metadatas=requestMessage.getMetadataCollection();
+ // get the parameter which specifies the format of the security token
+ Collection<Metadata> metadatas =
requestMessage.getMetadataCollection();
for (Metadata meta : metadatas) {
Parameters pars = meta.getParameters();
if (pars.getParameterValues("SecurityToken") != null) {
@@ -89,11 +90,11 @@
}
}
- SOAPHeader header=(SOAPHeader)token.getSecToken();
+ SOAPHeader header = (SOAPHeader) token.getSecToken();
ArrayList<?> headerBlocks =
header.getHeaderBlocksWithNSURI(WSConstants.WSSE_NS);
- SOAPHeaderBlock secHeader = null;
- //Issue is axiom - a returned collection must not be null
- if(headerBlocks != null) {
+ SOAPHeaderBlock secHeader = null;
+ // Issue is axiom - a returned collection must not be null
+ if (headerBlocks != null) {
for (Object headerBlock : headerBlocks) {
SOAPHeaderBlock elem = (SOAPHeaderBlock) headerBlock;
if (elem.getLocalName().equals(WSConstants.WSSE_LN)) {
@@ -101,25 +102,25 @@
break;
}
}
- }
+ }
- if(secHeader == null) {
- throw new PerfSONARException("AADispatchSOAPProtocol:
Can't obtain required security header");
- }
+ if (secHeader == null) {
+ throw new PerfSONARException("AADispatchSOAPProtocol: Can't
obtain required security header");
+ }
- Iterator<?> it =
secHeader.getChildrenWithLocalName("BinarySecurityToken");
- while (it.hasNext()) {
- OMElement e = (OMElement)it.next();
- if (e.getAttributeValue(new
QName("ValueType"))!=null&&
- e.getAttributeValue(new
QName("ValueType")).equals("#SAMLBase64Binary")) {
-
parameter.setParameter("value",AADispatchSOAPProtocol.WSS_SAML);
- }
- }
+ Iterator<?> it =
secHeader.getChildrenWithLocalName("BinarySecurityToken");
+ while (it.hasNext()) {
+ OMElement e = (OMElement) it.next();
+ if (e.getAttributeValue(new QName("ValueType")) != null
+ && e.getAttributeValue(new
QName("ValueType")).equals("#SAMLBase64Binary")) {
+ parameter.setParameter("value",
AADispatchSOAPProtocol.WSS_SAML);
+ }
+ }
- return secHeader;
- }
+ return secHeader;
+ }
- private ServiceMessage sendMessage(String point,Message
requestMessage, SecurityToken token) throws Exception {
+ private ServiceMessage sendMessage(String point, Message requestMessage,
SecurityToken token) throws Exception {
EndpointReference targetEPR = new EndpointReference(point);
Options options = new Options();
@@ -127,7 +128,7 @@
options.setTransportInProtocol(Constants.TRANSPORT_HTTP);
ServiceClient sender = new ServiceClient();
- SOAPHeaderBlock shb =
updateSecurityTokenParameter(requestMessage, token);
+ SOAPHeaderBlock shb = updateSecurityTokenParameter(requestMessage,
token);
sender.addHeader(shb);
sender.setOptions(options);
@@ -144,114 +145,112 @@
Element respElem = sp.parse(response.getXMLStreamReader());
ServiceMessage sm = new ServiceMessage(respElem);
return sm;
- }
+ }
- public AuthNResponse getAuthentication(AuthNRequest req) throws
PerfSONARException {
- AuthNResponse resp=new AuthNResponse();
- // prepare to call - set service elements
- try {
+ public AuthNResponse getAuthentication(AuthNRequest req) throws
PerfSONARException {
+ AuthNResponse resp = new AuthNResponse();
+ // prepare to call - set service elements
+ try {
- Message authnRequest = new
AuthNEERequestGenerator().generateRequestMessage();
- ServiceMessage responseMsg = sendMessage(asPoint,
authnRequest, req.getSecurityToken());
- Element response = responseMsg.getElement();
+ Message authnRequest = new
AuthNEERequestGenerator().generateRequestMessage();
+ ServiceMessage responseMsg = sendMessage(asPoint, authnRequest,
req.getSecurityToken());
+ Element response = responseMsg.getElement();
- resp=AuthNResponse.getAuthNResponse(response);
- logger.debug("Authentication response:
("+resp.getResultCode()+","+resp.getStatus()+")");
+ resp = AuthNResponse.getAuthNResponse(response);
+ LOGGER.debug("Authentication response: (" + resp.getResultCode()
+ "," + resp.getStatus() + ")");
- } catch (ClassCastException e) {
- e.printStackTrace();
- String m = "AADispatchSOAPProtocol.getAuthentication:
We didn't get a Vector of SOAPBodyElements!";
- System.out.println(m);
- throw new PerfSONARException("error.as.body",m);
- } catch (Exception e) {
- e.printStackTrace();
- String m="AADispatchSOAPProtocol.getAuthentication:
General exception while retrieving report";
- System.out.println(m);
- throw new PerfSONARException("error.as.query",m);
- }
+ } catch (ClassCastException e) {
+ e.printStackTrace();
+ String m = "AADispatchSOAPProtocol.getAuthentication: We didn't
get a Vector of SOAPBodyElements!";
+ System.out.println(m);
+ throw new PerfSONARException("error.as.body", m);
+ } catch (Exception e) {
+ e.printStackTrace();
+ String m = "AADispatchSOAPProtocol.getAuthentication: General
exception while retrieving report";
+ System.out.println(m);
+ throw new PerfSONARException("error.as.query", m);
+ }
- return resp;
- }
+ return resp;
+ }
- public AuthRResponse getAuthorization(AuthRRequest req) throws
PerfSONARException {
- // prepare to call - set service elements
- try {
+ public AuthRResponse getAuthorization(AuthRRequest req) throws
PerfSONARException {
+ // prepare to call - set service elements
+ try {
- Message authrRequest = new
AuthREERequestGenerator().generateRequestMessage();
+ Message authrRequest = new
AuthREERequestGenerator().generateRequestMessage();
- SimpleRequest simpleRequest = null;
- if
(SecTokenSOAPManager.isDelegated(req.getSecurityToken())) {
- simpleRequest =
RequestFactory.getDefaultSimpleDelegatedRequest();
- }
- else {
- simpleRequest =
RequestFactory.getDefaultSimpleRequest();
- }
- simpleRequest.setResource(req.getResource());
- simpleRequest.setAction(req.getAction());
- simpleRequest.setSubject(req.getSubject());
- if
(SecTokenSOAPManager.isDelegated(req.getSecurityToken())) {
- SimpleDelegatedRequest
sdr=(SimpleDelegatedRequest)simpleRequest;
-
sdr.setClient(getClient(req.getSecurityToken()));
- }
- String reqString=simpleRequest.getMessage();
- reqString = reqString.replaceAll("\n", "");
- reqString = reqString.replaceAll("\r", "");
- reqString = reqString.replaceAll("\t", "");
- reqString = reqString.replaceAll(" ", "");
- Element authrElement = new Element("subject", "aa",
"http://ggf.org/ns/nmwg/tools/org/perfsonar/service/as/authr/1.0/");
- authrElement.setText(reqString);
-
authrRequest.getMetadata("authRmetadata").addChild(authrElement);
+ SimpleRequest simpleRequest = null;
+ if (SecTokenSOAPManager.isDelegated(req.getSecurityToken())) {
+ simpleRequest =
RequestFactory.getDefaultSimpleDelegatedRequest();
+ } else {
+ simpleRequest = RequestFactory.getDefaultSimpleRequest();
+ }
+ simpleRequest.setResource(req.getResource());
+ simpleRequest.setAction(req.getAction());
+ simpleRequest.setSubject(req.getSubject());
+ if (SecTokenSOAPManager.isDelegated(req.getSecurityToken())) {
+ SimpleDelegatedRequest sdr = (SimpleDelegatedRequest)
simpleRequest;
+ sdr.setClient(getClient(req.getSecurityToken()));
+ }
+ String reqString = simpleRequest.getMessage();
+ reqString = reqString.replaceAll("\n", "");
+ reqString = reqString.replaceAll("\r", "");
+ reqString = reqString.replaceAll("\t", "");
+ reqString = reqString.replaceAll(" ", "");
+ Element authrElement = new Element("subject", "aa",
+
"http://ggf.org/ns/nmwg/tools/org/perfsonar/service/as/authr/1.0/");
+ authrElement.setText(reqString);
+ authrRequest.getMetadata("authRmetadata").addChild(authrElement);
- ServiceMessage responseMsg = sendMessage(asPoint,
authrRequest, req.getSecurityToken());
- Element response = responseMsg.getElement();
+ ServiceMessage responseMsg = sendMessage(asPoint, authrRequest,
req.getSecurityToken());
+ Element response = responseMsg.getElement();
- AuthRResponse
respAuth=AuthRResponse.getAuthRResponse(response);
- logger.debug("Authorization response:
("+respAuth.getResultCode()+","+respAuth.getStatus()+")");
+ AuthRResponse respAuth =
AuthRResponse.getAuthRResponse(response);
+ LOGGER.debug("Authorization response: (" +
respAuth.getResultCode() + "," + respAuth.getStatus() + ")");
- return respAuth;
- } catch (ClassCastException e) {
- e.printStackTrace();
- String m = "AADispatchSOAPProtocol.getAuthorization:
We didn't get a Vector of SOAPBodyElements!";
- System.out.println(m);
- throw new PerfSONARException("error.as.body",m);
- } catch (Exception e) {
- e.printStackTrace();
- String m="AADispatchSOAPProtocol.getAuthorization:
General exception while retrieving report";
- System.out.println(m);
- throw new PerfSONARException("error.as.query",m);
- }
+ return respAuth;
+ } catch (ClassCastException e) {
+ e.printStackTrace();
+ String m = "AADispatchSOAPProtocol.getAuthorization: We didn't
get a Vector of SOAPBodyElements!";
+ System.out.println(m);
+ throw new PerfSONARException("error.as.body", m);
+ } catch (Exception e) {
+ e.printStackTrace();
+ String m = "AADispatchSOAPProtocol.getAuthorization: General
exception while retrieving report";
+ System.out.println(m);
+ throw new PerfSONARException("error.as.query", m);
+ }
- }
+ }
- public AttrResponse getAttributes(AttrRequest req) throws
PerfSONARException {
- // prepare to call - set service elements
- try {
+ public AttrResponse getAttributes(AttrRequest req) throws
PerfSONARException {
+ // prepare to call - set service elements
+ try {
- Message attrRequest = new
AttrEERequestGenerator().generateRequestMessage();
+ Message attrRequest = new
AttrEERequestGenerator().generateRequestMessage();
+ ServiceMessage responseMsg = sendMessage(asPoint, attrRequest,
req.getSecurityToken());
+ Element response = responseMsg.getElement();
- ServiceMessage responseMsg = sendMessage(asPoint,
attrRequest, req.getSecurityToken());
- Element response = responseMsg.getElement();
+ AttrResponse respAttr = AttrResponse.getAttrResponse(response);
+ LOGGER.debug("Attribte response: (" + respAttr.getResultCode() +
"," + respAttr.getStatus() + ")");
+ LOGGER.debug("SAML Response: " + respAttr.getSAMLResponse());
- AttrResponse
respAttr=AttrResponse.getAttrResponse(response);
- logger.debug("Attribte response:
("+respAttr.getResultCode()+","+respAttr.getStatus()+")");
- logger.debug("SAML Response:
"+respAttr.getSAMLResponse());
+ return respAttr;
- return respAttr;
+ } catch (ClassCastException e) {
+ e.printStackTrace();
+ String m = "AADispatchSOAPProtocol.getAttributes: We didn't get
a Vector of SOAPBodyElements!";
+ System.out.println(m);
+ throw new PerfSONARException("error.as.body", m);
+ } catch (Exception e) {
+ e.printStackTrace();
+ String m = "AADispatchSOAPProtocol.getAttributes: General
exception while retrieving report";
+ System.out.println(m);
+ throw new PerfSONARException("error.as.query", m);
+ }
- } catch (ClassCastException e) {
- e.printStackTrace();
- String m = "AADispatchSOAPProtocol.getAttributes: We
didn't get a Vector of SOAPBodyElements!";
- System.out.println(m);
- throw new PerfSONARException("error.as.body",m);
- } catch (Exception e) {
- e.printStackTrace();
- String m="AADispatchSOAPProtocol.getAttributes:
General exception while retrieving report";
- System.out.println(m);
- throw new PerfSONARException("error.as.query",m);
- }
+ }
-
- }
-
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/AttrRequest.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/AttrRequest.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/AttrRequest.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -7,51 +7,51 @@
import org.perfsonar.base2.service.authn.tokens.SecurityToken;
public class AttrRequest extends AuthNRequest {
- String issuer;
- String subject;
- Map<String, Map<String, List<String>>> attrs;
+ private String issuer;
+ private String subject;
+ private Map<String, Map<String, List<String>>> attrs;
- public AttrRequest() {
- super();
- attrs = new HashMap<String, Map<String,List<String>>>();
- }
+ public AttrRequest() {
+ super();
+ attrs = new HashMap<String, Map<String, List<String>>>();
+ }
- public AttrRequest(SecurityToken st) {
- super(st);
- attrs = new HashMap<String, Map<String,List<String>>>();
- }
+ public AttrRequest(SecurityToken st) {
+ super(st);
+ attrs = new HashMap<String, Map<String, List<String>>>();
+ }
- public String getIssuer() {
- return issuer;
- }
+ public String getIssuer() {
+ return issuer;
+ }
- public void setIssuer(String issuer) {
- this.issuer = issuer;
- }
+ public void setIssuer(String issuer) {
+ this.issuer = issuer;
+ }
- public String getSubject() {
- return subject;
- }
+ public String getSubject() {
+ return subject;
+ }
- public void setSubject(String subject) {
- this.subject = subject;
- }
+ public void setSubject(String subject) {
+ this.subject = subject;
+ }
- public void addAttribute(String urn, String friendlyName,
List<String> values) {
- Map<String, List<String>> data = new HashMap<String,
List<String>>();
- data.put(friendlyName, values);
- attrs.put(urn, data);
- }
+ public void addAttribute(String urn, String friendlyName, List<String>
values) {
+ Map<String, List<String>> data = new HashMap<String, List<String>>();
+ data.put(friendlyName, values);
+ attrs.put(urn, data);
+ }
- public void removeAttribute(String urn) {
- attrs.remove(urn);
- }
+ public void removeAttribute(String urn) {
+ attrs.remove(urn);
+ }
- public void clearAttributes() {
- attrs.clear();
- }
+ public void clearAttributes() {
+ attrs.clear();
+ }
- public Map<String, Map<String, List<String>>> getAttributes() {
- return attrs;
- }
+ public Map<String, Map<String, List<String>>> getAttributes() {
+ return attrs;
+ }
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/AttrResponse.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/AttrResponse.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/AttrResponse.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -22,49 +22,50 @@
import org.w3c.dom.NodeList;
public class AttrResponse extends AuthNResponse {
- public static final int ATTR_OK_RESPONSE=1;
- public static final int ATTR_BAD_RESPONSE=1;
- public static final String NS_SUBJECT_AA =
"http://ggf.org/ns/nmwg/tools/org/perfsonar/service/as/attr/1.0/";
+ public static final int ATTR_OK_RESPONSE = 1;
+ public static final int ATTR_BAD_RESPONSE = 1;
+ public static final String NS_SUBJECT_AA =
"http://ggf.org/ns/nmwg/tools/org/perfsonar/service/as/attr/1.0/";
- private Map<String, List<String>> attributes;
- private String samlRawResponse;
- private XPath xpath;
+ private Map<String, List<String>> attributes;
+ private String samlRawResponse;
+ private XPath xpath;
- public AttrResponse() {
- super();
+ public AttrResponse() {
+ super();
- XPathFactory xfactory = XPathFactory.newInstance();
- xpath = xfactory.newXPath();
- NamespaceContext ctx = new NamespaceContext() {
- public String getNamespaceURI(String prefix) {
- String uri;
- if (prefix.equals("samlp"))
- uri =
"urn:oasis:names:tc:SAML:2.0:protocol";
- else if (prefix.equals("saml"))
- uri =
"urn:oasis:names:tc:SAML:2.0:assertion";
- else
- uri = null;
- return uri;
- }
+ XPathFactory xfactory = XPathFactory.newInstance();
+ xpath = xfactory.newXPath();
+ NamespaceContext ctx = new NamespaceContext() {
+ public String getNamespaceURI(String prefix) {
+ String uri;
+ if (prefix.equals("samlp")) {
+ uri = "urn:oasis:names:tc:SAML:2.0:protocol";
+ } else if (prefix.equals("saml")) {
+ uri = "urn:oasis:names:tc:SAML:2.0:assertion";
+ } else {
+ uri = null;
+ }
+ return uri;
+ }
- // Dummy implementation - not used!
- public Iterator<?> getPrefixes(String val) {
- return null;
- }
+ // Dummy implementation - not used!
+ public Iterator<?> getPrefixes(String val) {
+ return null;
+ }
- // Dummy implemenation - not used!
- public String getPrefix(String uri) {
- return null;
- }
- };
- xpath.setNamespaceContext(ctx);
+ // Dummy implemenation - not used!
+ public String getPrefix(String uri) {
+ return null;
+ }
+ };
+ xpath.setNamespaceContext(ctx);
- attributes = new HashMap<String, List<String>>();
- }
+ attributes = new HashMap<String, List<String>>();
+ }
- public static AttrResponse getAttrResponse(Element message) {
- AttrResponse res=new AttrResponse();
- res.setStatus(AttrResponse.ATTR_OK_RESPONSE);
+ public static AttrResponse getAttrResponse(Element message) {
+ AttrResponse res = new AttrResponse();
+ res.setStatus(AttrResponse.ATTR_OK_RESPONSE);
Element responseMetadata = null;
Element eventType = null;
@@ -76,88 +77,87 @@
}
if (eventType != null) {
if (eventType.getText().trim().contains("success.as.attr")) {
- res.setStatus(AttrResponse.ATTR_BAD_RESPONSE);
+ res.setStatus(AttrResponse.ATTR_BAD_RESPONSE);
}
}
- if (res.getStatus()==AttrResponse.ATTR_OK_RESPONSE) {
- Collection<Element> list =
responseMetadata.getChildren("subject",
"http://ggf.org/ns/nmwg/tools/org/perfsonar/service/as/attr/1.0/");
- Iterator<Element> it = list.iterator();
- Element e = it.next();
- String samlResponse=e.getText();
- res.setSAMLResponse(samlResponse);
- res.loadAttributes();
+ if (res.getStatus() == AttrResponse.ATTR_OK_RESPONSE) {
+ Collection<Element> list =
responseMetadata.getChildren("subject",
+
"http://ggf.org/ns/nmwg/tools/org/perfsonar/service/as/attr/1.0/");
+ Iterator<Element> it = list.iterator();
+ Element e = it.next();
+ String samlResponse = e.getText();
+ res.setSAMLResponse(samlResponse);
+ res.loadAttributes();
}
- return res;
- }
+ return res;
+ }
- public void loadAttributes() {
- Document doc = getDocumentFromString(getSAMLResponse());
- try {
- XPathExpression expression =
xpath.compile("//samlp:Response/saml:Assertion/saml:AttributeStatement/saml:Attribute");
- NodeList nodes = (NodeList) expression.evaluate(doc,
XPathConstants.NODESET);
- for (int i = 0; i < nodes.getLength(); i++) {
- org.w3c.dom.Element
elem=(org.w3c.dom.Element)nodes.item(i);
- String friendlyName =
elem.getAttribute("FriendlyName");
- NodeList nodes2 =
elem.getElementsByTagName("saml:AttributeValue");
- for (int j=0; j<nodes2.getLength(); j++) {
- org.w3c.dom.Element
value=(org.w3c.dom.Element)nodes2.item(j);
- String attributeValue =
value.getTextContent().trim();
- addAttribute(friendlyName,
attributeValue);
- }
- }
- } catch (XPathExpressionException e) {
+ public void loadAttributes() {
+ Document doc = getDocumentFromString(getSAMLResponse());
+ try {
+ XPathExpression expression = xpath
+
.compile("//samlp:Response/saml:Assertion/saml:AttributeStatement/saml:Attribute");
+ NodeList nodes = (NodeList) expression.evaluate(doc,
XPathConstants.NODESET);
+ for (int i = 0; i < nodes.getLength(); i++) {
+ org.w3c.dom.Element elem = (org.w3c.dom.Element)
nodes.item(i);
+ String friendlyName = elem.getAttribute("FriendlyName");
+ NodeList nodes2 =
elem.getElementsByTagName("saml:AttributeValue");
+ for (int j = 0; j < nodes2.getLength(); j++) {
+ org.w3c.dom.Element value = (org.w3c.dom.Element)
nodes2.item(j);
+ String attributeValue = value.getTextContent().trim();
+ addAttribute(friendlyName, attributeValue);
+ }
+ }
+ } catch (XPathExpressionException e) {
- }
- }
+ }
+ }
- public void addAttribute(String key,String value) {
- if (!attributes.containsKey(key)) {
- List<String> list=new LinkedList<String>();
- attributes.put(key, list);
- }
- List<String> list = attributes.get(key);
- list.add(value);
- }
+ public void addAttribute(String key, String value) {
+ if (!attributes.containsKey(key)) {
+ List<String> list = new LinkedList<String>();
+ attributes.put(key, list);
+ }
+ List<String> list = attributes.get(key);
+ list.add(value);
+ }
- public void clearAttributes() {
- attributes.clear();
- }
+ public void clearAttributes() {
+ attributes.clear();
+ }
- public void removeAttribute(String key) {
- if (attributes.containsKey(key)) {
- attributes.remove(key);
- }
- }
+ public void removeAttribute(String key) {
+ if (attributes.containsKey(key)) {
+ attributes.remove(key);
+ }
+ }
- public Map<String, List<String>> getAttributes() {
- return attributes;
- }
+ public Map<String, List<String>> getAttributes() {
+ return attributes;
+ }
- private Document getDocumentFromString(String message) {
- try {
- Document request = null;
- DocumentBuilderFactory factory =
DocumentBuilderFactory
- .newInstance();
- factory.setNamespaceAware(true);
+ private Document getDocumentFromString(String message) {
+ try {
+ Document request = null;
+ DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
+ factory.setNamespaceAware(true);
- DocumentBuilder builder =
factory.newDocumentBuilder();
- request = builder
- .parse(new
ByteArrayInputStream(message.getBytes()));
+ DocumentBuilder builder = factory.newDocumentBuilder();
+ request = builder.parse(new
ByteArrayInputStream(message.getBytes()));
- return request;
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- }
+ return request;
+ } catch (Exception e) {
+ e.printStackTrace();
+ return null;
+ }
+ }
+ public String getSAMLResponse() {
+ return samlRawResponse;
+ }
- public String getSAMLResponse() {
- return samlRawResponse;
- }
-
- public void setSAMLResponse(String samlMessage) {
- this.samlRawResponse = samlMessage;
- }
+ public void setSAMLResponse(String samlMessage) {
+ this.samlRawResponse = samlMessage;
+ }
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/AuthNRequest.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/AuthNRequest.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/AuthNRequest.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -3,23 +3,23 @@
import org.perfsonar.base2.service.authn.tokens.SecurityToken;
public class AuthNRequest {
- private SecurityToken st;
+ private SecurityToken st;
- public AuthNRequest() {
- st=null;
- }
+ public AuthNRequest() {
+ st = null;
+ }
- public AuthNRequest(SecurityToken st) {
- this();
- this.st=st;
- }
+ public AuthNRequest(SecurityToken st) {
+ this();
+ this.st = st;
+ }
- public SecurityToken getSecurityToken() {
- return st;
- }
+ public SecurityToken getSecurityToken() {
+ return st;
+ }
- public void setSecurityToken(SecurityToken st) {
- this.st = st;
- }
+ public void setSecurityToken(SecurityToken st) {
+ this.st = st;
+ }
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/AuthNResponse.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/AuthNResponse.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/AuthNResponse.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -3,37 +3,37 @@
import org.perfsonar.base2.xml.Element;
public class AuthNResponse {
- public static final int AUTHENTICATED=0;
- public static final int NOT_AUTHENTICATED=1;
+ public static final int AUTHENTICATED = 0;
+ public static final int NOT_AUTHENTICATED = 1;
- private int status;
- private String resultCode;
+ private int status;
+ private String resultCode;
- public AuthNResponse() {
- status=AuthNResponse.NOT_AUTHENTICATED;
- resultCode="";
- }
+ public AuthNResponse() {
+ status = AuthNResponse.NOT_AUTHENTICATED;
+ resultCode = "";
+ }
- public int getStatus() {
- return status;
- }
+ public int getStatus() {
+ return status;
+ }
- public void setStatus(int status) {
- this.status = status;
- }
+ public void setStatus(int status) {
+ this.status = status;
+ }
- public String getResultCode() {
- return resultCode;
- }
+ public String getResultCode() {
+ return resultCode;
+ }
- public void setResultCode(String codeResult) {
- this.resultCode = codeResult;
- }
+ public void setResultCode(String codeResult) {
+ this.resultCode = codeResult;
+ }
- public static AuthNResponse getAuthNResponse(Element message) {
- AuthNResponse res=new AuthNResponse();
+ public static AuthNResponse getAuthNResponse(Element message) {
+ AuthNResponse res = new AuthNResponse();
- res.setStatus(AuthNResponse.NOT_AUTHENTICATED);
+ res.setStatus(AuthNResponse.NOT_AUTHENTICATED);
Element responseMetadata = null;
Element eventType = null;
if (message != null) {
@@ -44,10 +44,10 @@
}
if (eventType != null) {
if (eventType.getText().trim().contains("success.as.authn")) {
- res.setStatus(AuthNResponse.AUTHENTICATED);
+ res.setStatus(AuthNResponse.AUTHENTICATED);
}
}
- return res;
- }
+ return res;
+ }
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/AuthRRequest.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/AuthRRequest.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/AuthRRequest.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -3,55 +3,55 @@
import org.perfsonar.base2.service.authn.tokens.SecurityToken;
public class AuthRRequest extends AuthNRequest {
- public static final String URN_PREFIX_ACTION =
"urn:geant:edugain:action:perfsonar:";
- public static final String DEFAULT_ACTION = "send";
+ public static final String URN_PREFIX_ACTION =
"urn:geant:edugain:action:perfsonar:";
+ public static final String DEFAULT_ACTION = "send";
- String messageType;
- String resource;
- String action;
- String subject;
+ private String messageType;
+ private String resource;
+ private String action;
+ private String subject;
- public AuthRRequest() {
- super();
- }
+ public AuthRRequest() {
+ super();
+ }
- public AuthRRequest(SecurityToken st,String messageType) {
- super(st);
+ public AuthRRequest(SecurityToken st, String messageType) {
+ super(st);
- this.messageType = messageType;
- setAction(messageType);
- }
+ this.messageType = messageType;
+ setAction(messageType);
+ }
- public String getMessageType() {
- return messageType;
- }
+ public String getMessageType() {
+ return messageType;
+ }
- public void setMessageType(String messageType) {
- this.messageType = messageType;
- }
+ public void setMessageType(String messageType) {
+ this.messageType = messageType;
+ }
- public String getAction() {
- return action;
- }
+ public String getAction() {
+ return action;
+ }
- public void setAction(String action) {
- this.action = URN_PREFIX_ACTION + action;
- }
+ public void setAction(String action) {
+ this.action = URN_PREFIX_ACTION + action;
+ }
- public String getResource() {
- return resource;
- }
+ public String getResource() {
+ return resource;
+ }
- public void setResource(String resource) {
- this.resource = resource;
- }
+ public void setResource(String resource) {
+ this.resource = resource;
+ }
- public String getSubject() {
- return subject;
- }
+ public String getSubject() {
+ return subject;
+ }
- public void setSubject(String subject) {
- this.subject = subject;
- }
+ public void setSubject(String subject) {
+ this.subject = subject;
+ }
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/AuthRResponse.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/AuthRResponse.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/AuthRResponse.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -3,12 +3,12 @@
import org.perfsonar.base2.xml.Element;
public class AuthRResponse extends AuthNResponse {
- public static final int AUTHORIZED=0;
- public static final int NOT_AUTHORIZED=1;
+ public static final int AUTHORIZED = 0;
+ public static final int NOT_AUTHORIZED = 1;
- public static AuthRResponse getAuthRResponse(Element message) {
- AuthRResponse res=new AuthRResponse();
- res.setStatus(AuthRResponse.NOT_AUTHORIZED);
+ public static AuthRResponse getAuthRResponse(Element message) {
+ AuthRResponse res = new AuthRResponse();
+ res.setStatus(AuthRResponse.NOT_AUTHORIZED);
Element responseMetadata = null;
Element eventType = null;
@@ -20,10 +20,10 @@
}
if (eventType != null) {
if (eventType.getText().trim().contains("success.as.authr")) {
- res.setStatus(AuthRResponse.AUTHENTICATED);
+ res.setStatus(AuthRResponse.AUTHENTICATED);
}
}
- return res;
- }
+ return res;
+ }
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/component/AuthNComponent.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/component/AuthNComponent.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/component/AuthNComponent.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -4,16 +4,16 @@
import org.perfsonar.base2.service.exceptions.PerfSONARException;
public abstract class AuthNComponent extends Component {
- public static final String CHECK_AUTHN_PARAM =
"service.as.authn_active";
- public static final String YES_CHECK_AUTHN = "on";
- public static final String LIST_MSG_AUTHN =
"service.as.authn_for_msg_types";
+ public static final String CHECK_AUTHN_PARAM = "service.as.authn_active";
+ public static final String YES_CHECK_AUTHN = "on";
+ public static final String LIST_MSG_AUTHN =
"service.as.authn_for_msg_types";
- public static final String CHECK_AUTHR_PARAM =
"service.as.authr_active";
- public static final String YES_CHECK_AUTHR = "on";
- public static final String LIST_MSG_AUTHR =
"service.as.authr_for_msg_types";
+ public static final String CHECK_AUTHR_PARAM = "service.as.authr_active";
+ public static final String YES_CHECK_AUTHR = "on";
+ public static final String LIST_MSG_AUTHR =
"service.as.authr_for_msg_types";
- public abstract void requestAuthN(String messageType) throws
PerfSONARException;
+ public abstract void requestAuthN(String messageType) throws
PerfSONARException;
- public abstract void requestAuthR(String messageType,String
eventType) throws PerfSONARException;
+ public abstract void requestAuthR(String messageType, String eventType)
throws PerfSONARException;
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/component/DynamicCrypto.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/component/DynamicCrypto.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/component/DynamicCrypto.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -40,30 +40,30 @@
protected static CertificateFactory certFact;
protected Properties properties = null;
protected KeyStore keystore = null;
- static String SKI_OID = "2.5.29.14";
-
+ private static String skiOID = "2.5.29.14";
+
public DynamicCrypto() throws CredentialException {
- properties=new Properties();
- try {
- keystore= KeyStore.getInstance("PKCS12");
- keystore.load(null, "petete".toCharArray());
- } catch (Exception e) {
+ properties = new Properties();
+ try {
+ keystore = KeyStore.getInstance("PKCS12");
+ keystore.load(null, "petete".toCharArray());
+ } catch (Exception e) {
e.printStackTrace();
throw new CredentialException(3, "cryptError00", e);
- }
+ }
}
-
+
public DynamicCrypto(KeyStore ks) {
- properties=new Properties();
- this.keystore=ks;
+ properties = new Properties();
+ this.keystore = ks;
}
- public String getAliasForX509Cert(Certificate cert)
- throws WSSecurityException {
+ public String getAliasForX509Cert(Certificate cert) throws
WSSecurityException {
try {
String alias = keystore.getCertificateAlias(cert);
- if (alias != null)
+ if (alias != null) {
return alias;
+ }
// Use brute force search
Enumeration<String> e = keystore.aliases();
while (e.hasMoreElements()) {
@@ -74,17 +74,16 @@
}
}
} catch (KeyStoreException e) {
- throw new WSSecurityException(WSSecurityException.FAILURE,
- "keystore");
+ throw new WSSecurityException(WSSecurityException.FAILURE,
"keystore");
}
return null;
- }
+ }
- public String getAliasForX509Cert(String issuer) throws
WSSecurityException {
+ public String getAliasForX509Cert(String issuer) throws
WSSecurityException {
return getAliasForX509Cert(issuer, null, false);
- }
+ }
- public String getAliasForX509Cert(byte[] skiBytes) throws
WSSecurityException {
+ public String getAliasForX509Cert(byte[] skiBytes) throws
WSSecurityException {
Certificate cert = null;
try {
@@ -92,7 +91,8 @@
String alias = e.nextElement();
Certificate[] certs = keystore.getCertificateChain(alias);
if (certs == null || certs.length == 0) {
- // no cert chain, so lets check if getCertificate gives
us a result.
+ // no cert chain, so lets check if getCertificate gives
us a
+ // result.
cert = keystore.getCertificate(alias);
if (cert == null) {
return null;
@@ -112,83 +112,76 @@
}
}
} catch (KeyStoreException e) {
- throw new WSSecurityException(WSSecurityException.FAILURE,
- "keystore");
+ throw new WSSecurityException(WSSecurityException.FAILURE,
"keystore");
}
return null;
- }
+ }
- public String getAliasForX509Cert(String issuer, BigInteger
serialNumber)
- throws WSSecurityException {
+ public String getAliasForX509Cert(String issuer, BigInteger
serialNumber) throws WSSecurityException {
return getAliasForX509Cert(issuer, serialNumber, true);
- }
+ }
/*
- * need to check if "getCertificateChain" also finds certificates
that are
- * used for enryption only, i.e. they may not be signed by a CA
- * Otherwise we must define a restriction how to use certificate:
- * each certificate must be signed by a CA or is a self signed
Certificate
- * (this should work as well).
- * --- remains to be tested in several ways --
- */
- private String getAliasForX509Cert(String issuer, BigInteger
serialNumber,
- boolean useSerialNumber)
- throws WSSecurityException {
- Vector<String> issuerRDN = splitAndTrim(issuer);
- X509Certificate x509cert = null;
- Vector<String> certRDN = null;
- Certificate cert = null;
+ * need to check if "getCertificateChain" also finds certificates that
are
+ * used for enryption only, i.e. they may not be signed by a CA
Otherwise we
+ * must define a restriction how to use certificate: each certificate
must
+ * be signed by a CA or is a self signed Certificate (this should work as
+ * well). --- remains to be tested in several ways --
+ */
+ private String getAliasForX509Cert(String issuer, BigInteger
serialNumber, boolean useSerialNumber)
+ throws WSSecurityException {
+ Vector<String> issuerRDN = splitAndTrim(issuer);
+ X509Certificate x509cert = null;
+ Vector<String> certRDN = null;
+ Certificate cert = null;
- try {
- for (Enumeration<String> e = keystore.aliases();
e.hasMoreElements();) {
- String alias = e.nextElement();
- Certificate[] certs =
keystore.getCertificateChain(alias);
- if (certs == null || certs.length == 0) {
- // no cert chain, so lets check if getCertificate
gives us a result.
- cert = keystore.getCertificate(alias);
- if (cert == null) {
- return null;
- }
- } else {
- cert = certs[0];
- }
- if (!(cert instanceof X509Certificate)) {
- continue;
- }
- x509cert = (X509Certificate) cert;
- if (!useSerialNumber ||
- useSerialNumber &&
x509cert.getSerialNumber().compareTo(serialNumber) == 0) {
- certRDN =
splitAndTrim(x509cert.getIssuerDN().getName());
- if (certRDN.equals(issuerRDN)) {
- return alias;
- }
- }
- }
- } catch (KeyStoreException e) {
- throw new WSSecurityException(WSSecurityException.FAILURE,
- "keystore");
- }
- return null;
- }
+ try {
+ for (Enumeration<String> e = keystore.aliases();
e.hasMoreElements();) {
+ String alias = e.nextElement();
+ Certificate[] certs = keystore.getCertificateChain(alias);
+ if (certs == null || certs.length == 0) {
+ // no cert chain, so lets check if getCertificate gives
us a
+ // result.
+ cert = keystore.getCertificate(alias);
+ if (cert == null) {
+ return null;
+ }
+ } else {
+ cert = certs[0];
+ }
+ if (!(cert instanceof X509Certificate)) {
+ continue;
+ }
+ x509cert = (X509Certificate) cert;
+ if (!useSerialNumber || useSerialNumber &&
x509cert.getSerialNumber().compareTo(serialNumber) == 0) {
+ certRDN = splitAndTrim(x509cert.getIssuerDN().getName());
+ if (certRDN.equals(issuerRDN)) {
+ return alias;
+ }
+ }
+ }
+ } catch (KeyStoreException e) {
+ throw new WSSecurityException(WSSecurityException.FAILURE,
"keystore");
+ }
+ return null;
+ }
- public String getAliasForX509CertThumb(byte[] thumb)
- throws WSSecurityException {
+ public String getAliasForX509CertThumb(byte[] thumb) throws
WSSecurityException {
Certificate cert = null;
MessageDigest sha = null;
try {
sha = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e1) {
- throw new WSSecurityException(
- 0,
- "noSHA1availabe");
+ throw new WSSecurityException(0, "noSHA1availabe");
}
try {
for (Enumeration<String> e = keystore.aliases();
e.hasMoreElements();) {
String alias = e.nextElement();
Certificate[] certs = keystore.getCertificateChain(alias);
if (certs == null || certs.length == 0) {
- // no cert chain, so lets check if getCertificate gives
us a result.
+ // no cert chain, so lets check if getCertificate gives
us a
+ // result.
cert = keystore.getCertificate(alias);
if (cert == null) {
return null;
@@ -203,9 +196,7 @@
try {
sha.update(cert.getEncoded());
} catch (CertificateEncodingException e1) {
- throw new WSSecurityException(
- WSSecurityException.SECURITY_TOKEN_UNAVAILABLE,
- "encodeError");
+ throw new
WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE,
"encodeError");
}
byte[] data = sha.digest();
@@ -214,11 +205,10 @@
}
}
} catch (KeyStoreException e) {
- throw new WSSecurityException(WSSecurityException.FAILURE,
- "keystore");
+ throw new WSSecurityException(WSSecurityException.FAILURE,
"keystore");
}
return null;
- }
+ }
private Vector<String> splitAndTrim(String inString) {
X509NameTokenizer nmTokens = new X509NameTokenizer(inString);
@@ -231,7 +221,7 @@
return vr;
}
- public String[] getAliasesForDN(String subjectDN) throws
WSSecurityException {
+ public String[] getAliasesForDN(String subjectDN) throws
WSSecurityException {
// Store the aliases found
Vector<String> aliases = new Vector<String>();
@@ -248,12 +238,13 @@
Certificate[] certs = keystore.getCertificateChain(alias);
if (certs == null || certs.length == 0) {
- // no cert chain, so lets check if getCertificate gives
us a result.
+ // no cert chain, so lets check if getCertificate gives
us a
+ // result.
cert = keystore.getCertificate(alias);
if (cert == null) {
return null;
}
- certs = new Certificate[]{cert};
+ certs = new Certificate[] {cert };
} else {
cert = certs[0];
}
@@ -266,20 +257,19 @@
}
}
} catch (KeyStoreException e) {
- throw new WSSecurityException(WSSecurityException.FAILURE,
- "keystore");
+ throw new WSSecurityException(WSSecurityException.FAILURE,
"keystore");
}
// Convert the vector into an array
String[] result = new String[aliases.size()];
- for (int i = 0; i < aliases.size(); i++)
+ for (int i = 0; i < aliases.size(); i++) {
result[i] = aliases.elementAt(i);
+ }
return result;
- }
+ }
- public byte[] getCertificateData(boolean reverse, X509Certificate[]
certs)
- throws WSSecurityException {
+ public byte[] getCertificateData(boolean reverse, X509Certificate[]
certs) throws WSSecurityException {
Vector<X509Certificate> list = new Vector<X509Certificate>();
for (X509Certificate cert : certs) {
if (reverse) {
@@ -292,16 +282,13 @@
CertPath path = getCertificateFactory().generateCertPath(list);
return path.getEncoded();
} catch (CertificateEncodingException e) {
- throw new
WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE,
- "encodeError");
+ throw new
WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE,
"encodeError");
} catch (CertificateException e) {
- throw new
WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE,
- "parseError");
+ throw new
WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE,
"parseError");
}
- }
+ }
- public synchronized CertificateFactory getCertificateFactory()
- throws WSSecurityException {
+ public synchronized CertificateFactory getCertificateFactory() throws
WSSecurityException {
if (certFact == null) {
try {
String provider =
properties.getProperty("org.apache.ws.security.crypto.merlin.cert.provider");
@@ -311,52 +298,49 @@
certFact = CertificateFactory.getInstance("X.509",
provider);
}
} catch (CertificateException e) {
- throw new
WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE,
- "unsupportedCertType");
+ throw new
WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE,
"unsupportedCertType");
} catch (NoSuchProviderException e) {
- throw new
WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE,
- "noSecProvider");
+ throw new
WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE,
"noSecProvider");
}
}
return certFact;
- }
+ }
- public X509Certificate[] getCertificates(String alias)
- throws WSSecurityException {
+ public X509Certificate[] getCertificates(String alias) throws
WSSecurityException {
Certificate[] certs = null;
try {
certs = keystore.getCertificateChain(alias);
if (certs == null || certs.length == 0) {
- // no cert chain, so lets check if getCertificate gives us a
result.
+ // no cert chain, so lets check if getCertificate gives us a
+ // result.
Certificate cert = keystore.getCertificate(alias);
if (cert == null) {
return null;
}
- certs = new Certificate[]{cert};
+ certs = new Certificate[] {cert };
}
} catch (KeyStoreException e) {
- throw new WSSecurityException(WSSecurityException.FAILURE,
- "keystore");
+ throw new WSSecurityException(WSSecurityException.FAILURE,
"keystore");
}
X509Certificate[] x509certs = new X509Certificate[certs.length];
for (int i = 0; i < certs.length; i++) {
x509certs[i] = (X509Certificate) certs[i];
}
return x509certs;
- }
+ }
- public String getDefaultX509Alias() {
+ public String getDefaultX509Alias() {
if (properties == null) {
return null;
}
return
properties.getProperty("org.apache.ws.security.crypto.merlin.keystore.alias");
- }
+ }
- public KeyStore getKeyStore() {
+ public KeyStore getKeyStore() {
return this.keystore;
- }
+ }
- public PrivateKey getPrivateKey(String alias, String password) throws
Exception {
+ public PrivateKey getPrivateKey(String alias, String password) throws
Exception {
if (alias == null) {
throw new Exception("alias is null");
}
@@ -370,63 +354,56 @@
throw new Exception("Key is not a private key, alias: " + alias);
}
return (PrivateKey) keyTmp;
- }
+ }
- public byte[] getSKIBytesFromCert(X509Certificate cert)
- throws WSSecurityException {
+ public byte[] getSKIBytesFromCert(X509Certificate cert) throws
WSSecurityException {
/*
* Gets the DER-encoded OCTET string for the extension value
(extnValue)
* identified by the passed-in oid String. The oid string is
represented
* by a set of positive whole numbers separated by periods.
*/
- byte[] derEncodedValue = cert.getExtensionValue(SKI_OID);
+ byte[] derEncodedValue = cert.getExtensionValue(skiOID);
- if (cert.getVersion() < 3 || derEncodedValue == null) {
- PublicKey key = cert.getPublicKey();
- if (!(key instanceof RSAPublicKey)) {
- throw new WSSecurityException(
- 1,
- "noSKIHandling",
- new Object[]{"Support for RSA key only"});
- }
- byte[] encoded = key.getEncoded();
- // remove 22-byte algorithm ID and header
- byte[] value = new byte[encoded.length - 22];
- System.arraycopy(encoded, 22, value, 0, value.length);
- MessageDigest sha;
- try {
- sha = MessageDigest.getInstance("SHA-1");
- } catch (NoSuchAlgorithmException ex) {
- throw new WSSecurityException(
- 1,
- "noSKIHandling",
- new Object[]{"Wrong certificate version (<3) and no
SHA1 message digest availabe"});
- }
- sha.reset();
- sha.update(value);
- return sha.digest();
- }
+ if (cert.getVersion() < 3 || derEncodedValue == null) {
+ PublicKey key = cert.getPublicKey();
+ if (!(key instanceof RSAPublicKey)) {
+ throw new WSSecurityException(1, "noSKIHandling", new
Object[] {"Support for RSA key only" });
+ }
+ byte[] encoded = key.getEncoded();
+ // remove 22-byte algorithm ID and header
+ byte[] value = new byte[encoded.length - 22];
+ System.arraycopy(encoded, 22, value, 0, value.length);
+ MessageDigest sha;
+ try {
+ sha = MessageDigest.getInstance("SHA-1");
+ } catch (NoSuchAlgorithmException ex) {
+ throw new WSSecurityException(1, "noSKIHandling",
+ new Object[] {"Wrong certificate version (<3) and no
SHA1 message digest availabe" });
+ }
+ sha.reset();
+ sha.update(value);
+ return sha.digest();
+ }
- /**
- * Strip away first four bytes from the DerValue (tag and length of
- * ExtensionValue OCTET STRING and KeyIdentifier OCTET STRING)
- */
- byte abyte0[] = new byte[derEncodedValue.length - 4];
+ /**
+ * Strip away first four bytes from the DerValue (tag and length of
+ * ExtensionValue OCTET STRING and KeyIdentifier OCTET STRING)
+ */
+ byte[] abyte0 = new byte[derEncodedValue.length - 4];
- System.arraycopy(derEncodedValue, 4, abyte0, 0, abyte0.length);
- return abyte0;
- }
+ System.arraycopy(derEncodedValue, 4, abyte0, 0, abyte0.length);
+ return abyte0;
+ }
- @SuppressWarnings("unchecked") // the data must only contain
X509Certificates
- public X509Certificate[] getX509Certificates(byte[] data, boolean
reverse)
- throws WSSecurityException {
+ @SuppressWarnings("unchecked")
+ // the data must only contain X509Certificates
+ public X509Certificate[] getX509Certificates(byte[] data, boolean
reverse) throws WSSecurityException {
InputStream in = new ByteArrayInputStream(data);
CertPath path = null;
try {
path = getCertificateFactory().generateCertPath(in);
} catch (CertificateException e) {
- throw new
WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE,
- "parseError");
+ throw new
WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE,
"parseError");
}
List<X509Certificate> l = (List<X509Certificate>)
path.getCertificates();
X509Certificate[] certs = new X509Certificate[l.size()];
@@ -435,54 +412,43 @@
certs[(reverse) ? (l.size() - 1 - i) : i] = iterator.next();
}
return certs;
- }
+ }
- public X509Certificate loadCertificate(InputStream in)
- throws WSSecurityException {
+ public X509Certificate loadCertificate(InputStream in) throws
WSSecurityException {
X509Certificate cert = null;
try {
- cert =
- (X509Certificate)
getCertificateFactory().generateCertificate(in);
+ cert = (X509Certificate)
getCertificateFactory().generateCertificate(in);
} catch (CertificateException e) {
- throw new
WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE,
- "parseError");
+ throw new
WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE,
"parseError");
}
return cert;
- }
+ }
- public boolean validateCertPath(X509Certificate[] certs)
- throws WSSecurityException {
- try {
- // Generate cert path
- List<X509Certificate> certList =
java.util.Arrays.asList(certs);
- CertPath path =
this.getCertificateFactory().generateCertPath(certList);
+ public boolean validateCertPath(X509Certificate[] certs) throws
WSSecurityException {
+ try {
+ // Generate cert path
+ List<X509Certificate> certList = java.util.Arrays.asList(certs);
+ CertPath path =
this.getCertificateFactory().generateCertPath(certList);
- // Use the certificates in the keystore as
TrustAnchors
- PKIXParameters param = new
PKIXParameters(this.keystore);
+ // Use the certificates in the keystore as TrustAnchors
+ PKIXParameters param = new PKIXParameters(this.keystore);
- // Do not check a revocation list
- param.setRevocationEnabled(false);
+ // Do not check a revocation list
+ param.setRevocationEnabled(false);
- // Verify the trust path using the above settings
- String provider = properties
-
.getProperty("org.apache.ws.security.crypto.merlin.cert.provider");
- CertPathValidator certPathValidator;
- if (provider == null || provider.length() == 0) {
- certPathValidator =
CertPathValidator.getInstance("PKIX");
- } else {
- certPathValidator =
CertPathValidator.getInstance("PKIX",
-
provider);
- }
- certPathValidator.validate(path, param);
- } catch (GeneralSecurityException ex) {
- throw new WSSecurityException(
- WSSecurityException.FAILURE,
- "certpath",
- new Object[] { ex.getMessage() },
- ex
- );
- }
- return true;
- }
+ // Verify the trust path using the above settings
+ String provider =
properties.getProperty("org.apache.ws.security.crypto.merlin.cert.provider");
+ CertPathValidator certPathValidator;
+ if (provider == null || provider.length() == 0) {
+ certPathValidator = CertPathValidator.getInstance("PKIX");
+ } else {
+ certPathValidator = CertPathValidator.getInstance("PKIX",
provider);
+ }
+ certPathValidator.validate(path, param);
+ } catch (GeneralSecurityException ex) {
+ throw new WSSecurityException(WSSecurityException.FAILURE,
"certpath", new Object[] {ex.getMessage() }, ex);
+ }
+ return true;
+ }
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/component/wssec/WSSecAuthNComponent.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/component/wssec/WSSecAuthNComponent.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/component/wssec/WSSecAuthNComponent.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -16,90 +16,79 @@
import org.perfsonar.base2.service.exceptions.PerfSONARException;
public class WSSecAuthNComponent extends AuthNComponent {
- private final String AS_POINT = "as_endpoint";
- private final String COMP_ID_SERVICE = "comp_id";
+ private final String asPoint = "as_endpoint";
+ private final String compIdService = "comp_id";
- @Override
- public void destroy() throws PerfSONARException {
- logger.debug("WSSecAuthNComponent: destroy");
- }
+ @Override
+ public void destroy() throws PerfSONARException {
+ LOGGER.debug("WSSecAuthNComponent: destroy");
+ }
- @Override
- public void run() throws PerfSONARException {
- // do nothing
- }
+ @Override
+ public void run() throws PerfSONARException {
+ // do nothing
+ }
- @Override
- public void init() throws PerfSONARException {
- logger.debug("WSSecAuthNComponent: init");
- }
+ @Override
+ public void init() throws PerfSONARException {
+ LOGGER.debug("WSSecAuthNComponent: init");
+ }
- public void requestAuthN(String messageType) throws
PerfSONARException {
- SecurityToken st = new SecurityToken(SecTokenManagerFactory
- .getDefaultSecTokenManager());
- if (!st.hasSecTokenInRequest()) {
- logger
- .error("WSSecAuthNComponent: It has
not sent any Security Token");
- throw new PerfSONARException("authn_not_sectoken");
- }
- st.setSecTokenFromRequest();
- AuthNRequest authnReq = new AuthNRequest(st);
- AADispatchProtocol aadp = AADispatchProtocolFactory
- .getDefaultAADispatchProtocol();
- aadp.setAuthService(getOption(AS_POINT).getValue());
- AADispatchManager aadm = new AADispatchManager(aadp);
- AuthNResponse authnRes = aadm.getAuthentication(authnReq);
- if (authnRes.getStatus() != AuthNResponse.AUTHENTICATED) {
- logger.error("WSSecAuthNComponent: Authentication
failed ("
- + authnRes.getResultCode() + ")");
- throw new
PerfSONARException(authnRes.getResultCode());
- }
- }
+ public void requestAuthN(String messageType) throws PerfSONARException {
+ SecurityToken st = new
SecurityToken(SecTokenManagerFactory.getDefaultSecTokenManager());
+ if (!st.hasSecTokenInRequest()) {
+ LOGGER.error("WSSecAuthNComponent: It has not sent any Security
Token");
+ throw new PerfSONARException("authn_not_sectoken");
+ }
+ st.setSecTokenFromRequest();
+ AuthNRequest authnReq = new AuthNRequest(st);
+ AADispatchProtocol aadp =
AADispatchProtocolFactory.getDefaultAADispatchProtocol();
+ aadp.setAuthService(getOption(asPoint).getValue());
+ AADispatchManager aadm = new AADispatchManager(aadp);
+ AuthNResponse authnRes = aadm.getAuthentication(authnReq);
+ if (authnRes.getStatus() != AuthNResponse.AUTHENTICATED) {
+ LOGGER.error("WSSecAuthNComponent: Authentication failed (" +
authnRes.getResultCode() + ")");
+ throw new PerfSONARException(authnRes.getResultCode());
+ }
+ }
- private String getResource() throws PerfSONARException {
- String res = this.getOption(COMP_ID_SERVICE).getValue();
- if (res == null) {
- logger.error("Component ID not configured");
- throw new PerfSONARException("as_edugain");
- }
- return res;
- }
+ private String getResource() throws PerfSONARException {
+ String res = this.getOption(compIdService).getValue();
+ if (res == null) {
+ LOGGER.error("Component ID not configured");
+ throw new PerfSONARException("as_edugain");
+ }
+ return res;
+ }
- @SuppressWarnings("deprecation")
- public void requestAuthR(String messageType, String eventType)
- throws PerfSONARException {
- SecurityToken st = new SecurityToken(SecTokenManagerFactory
- .getDefaultSecTokenManager());
- if (!st.hasSecTokenInRequest()) {
- logger
- .error("WSSecAuthNComponent: It has
not sent any Security Token");
- throw new PerfSONARException("authn_not_sectoken");
- }
- st.setSecTokenFromRequest();
- AuthRRequest authrReq = new AuthRRequest(st, messageType);
- authrReq.setResource(getResource());
- if (!(eventType == null || eventType.equals(""))) {
- authrReq.setAction(URLEncoder.encode(messageType) +
":"
- + URLEncoder.encode(eventType));
- }
- try {
-
authrReq.setSubject(SecTokenSOAPManager.getSubject(st));
- } catch (Exception e) {
- e.printStackTrace();
- logger
- .error("WSSecAuthNComponent: Cannot
get authR data from the Security Token");
- throw new PerfSONARException("authn_not_sectoken");
- }
+ @SuppressWarnings("deprecation")
+ public void requestAuthR(String messageType, String eventType) throws
PerfSONARException {
+ SecurityToken st = new
SecurityToken(SecTokenManagerFactory.getDefaultSecTokenManager());
+ if (!st.hasSecTokenInRequest()) {
+ LOGGER.error("WSSecAuthNComponent: It has not sent any Security
Token");
+ throw new PerfSONARException("authn_not_sectoken");
+ }
+ st.setSecTokenFromRequest();
+ AuthRRequest authrReq = new AuthRRequest(st, messageType);
+ authrReq.setResource(getResource());
+ if (!(eventType == null || eventType.equals(""))) {
+ authrReq.setAction(URLEncoder.encode(messageType) + ":" +
URLEncoder.encode(eventType));
+ }
+ try {
+ authrReq.setSubject(SecTokenSOAPManager.getSubject(st));
+ } catch (Exception e) {
+ e.printStackTrace();
+ LOGGER.error("WSSecAuthNComponent: Cannot get authR data from
the Security Token");
+ throw new PerfSONARException("authn_not_sectoken");
+ }
- AADispatchProtocol prot = AADispatchProtocolFactory
- .getDefaultAADispatchProtocol();
- prot.setAuthService(getOption("as_endpoint").getValue());
- AADispatchManager aadm = new AADispatchManager(prot);
- AuthRResponse authrRes = aadm.getAuthorization(authrReq);
- if (authrRes.getStatus() != AuthRResponse.AUTHORIZED) {
- logger.error("WSSecAuthNComponent: Authentication
failed ("
- + authrRes.getResultCode() + ")");
- throw new
PerfSONARException(authrRes.getResultCode());
- }
- }
+ AADispatchProtocol prot =
AADispatchProtocolFactory.getDefaultAADispatchProtocol();
+ prot.setAuthService(getOption("as_endpoint").getValue());
+ AADispatchManager aadm = new AADispatchManager(prot);
+ AuthRResponse authrRes = aadm.getAuthorization(authrReq);
+ if (authrRes.getStatus() != AuthRResponse.AUTHORIZED) {
+ LOGGER.error("WSSecAuthNComponent: Authentication failed (" +
authrRes.getResultCode() + ")");
+ throw new PerfSONARException(authrRes.getResultCode());
+ }
+ }
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/tokens/SecTokenManager.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/tokens/SecTokenManager.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/tokens/SecTokenManager.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -3,7 +3,9 @@
import org.perfsonar.base2.service.exceptions.PerfSONARException;
public interface SecTokenManager {
- public boolean hasSTInRequest() throws PerfSONARException;
- public Object getSTFromRequest() throws PerfSONARException;
- public Object getSTValue() throws PerfSONARException;
+ boolean hasSTInRequest() throws PerfSONARException;
+
+ Object getSTFromRequest() throws PerfSONARException;
+
+ Object getSTValue() throws PerfSONARException;
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/tokens/SecTokenManagerFactory.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/tokens/SecTokenManagerFactory.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/tokens/SecTokenManagerFactory.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -3,7 +3,7 @@
import org.perfsonar.base2.service.exceptions.PerfSONARException;
public class SecTokenManagerFactory {
- public static SecTokenManager getDefaultSecTokenManager() throws
PerfSONARException {
- return new SecTokenSOAPManager();
- }
+ public static SecTokenManager getDefaultSecTokenManager() throws
PerfSONARException {
+ return new SecTokenSOAPManager();
+ }
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/tokens/SecTokenSOAPManager.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/tokens/SecTokenSOAPManager.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/tokens/SecTokenSOAPManager.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -46,120 +46,122 @@
import org.w3c.dom.NodeList;
public class SecTokenSOAPManager implements SecTokenManager {
- private static final String
WSSECHEADER_NS="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
- private static final String WSSECHEADER="Security";
- protected static final String
SOAPENV_NS="http://schemas.xmlsoap.org/soap/envelope/";
- protected static final String WSSECHEADER_ACTOR="actor";
- private static final String URN_USER_FED = ":user:";
+ private static final String WSSECHEADER_NS =
"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
+ private static final String WSSECHEADER = "Security";
+ protected static final String SOAPENV_NS =
"http://schemas.xmlsoap.org/soap/envelope/";
+ protected static final String WSSECHEADER_ACTOR = "actor";
+ private static final String URN_USER_FED = ":user:";
- protected static final Logger logger =
LoggerFactory.getLogger(SecTokenSOAPManager.class);
+ protected static final Logger LOGGER =
LoggerFactory.getLogger(SecTokenSOAPManager.class);
- public Object getSTFromRequest() throws PerfSONARException {
- if (!hasSTInRequest())
- return null;
+ public Object getSTFromRequest() throws PerfSONARException {
+ if (!hasSTInRequest()) {
+ return null;
+ }
- MessageContext mc=MessageContext.getCurrentMessageContext();
- SOAPEnvelope se = mc.getEnvelope();
- SOAPHeader sh = se.getHeader();
+ MessageContext mc = MessageContext.getCurrentMessageContext();
+ SOAPEnvelope se = mc.getEnvelope();
+ SOAPHeader sh = se.getHeader();
- return sh;
- }
+ return sh;
+ }
- public boolean hasSTInRequest() throws PerfSONARException {
- MessageContext mc=MessageContext.getCurrentMessageContext();
- SOAPEnvelope se = mc.getEnvelope();
- SOAPHeader sh = se.getHeader();
- if (sh!=null) {
- Iterator<?> it = sh.examineAllHeaderBlocks();
- while (it.hasNext()) {
- SOAPHeaderBlock shb =
(SOAPHeaderBlock)it.next();
- if (shb.getLocalName().equals(WSSECHEADER)&&
-
shb.getNamespace().getNamespaceURI().equals(WSSECHEADER_NS)) {
- return true;
- }
- }
- }
- return false;
- }
+ public boolean hasSTInRequest() throws PerfSONARException {
+ MessageContext mc = MessageContext.getCurrentMessageContext();
+ SOAPEnvelope se = mc.getEnvelope();
+ SOAPHeader sh = se.getHeader();
+ if (sh != null) {
+ Iterator<?> it = sh.examineAllHeaderBlocks();
+ while (it.hasNext()) {
+ SOAPHeaderBlock shb = (SOAPHeaderBlock) it.next();
+ if (shb.getLocalName().equals(WSSECHEADER)
+ &&
shb.getNamespace().getNamespaceURI().equals(WSSECHEADER_NS)) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
- public Object getSTValue() throws PerfSONARException {
- if (!hasSTInRequest()) {
- return null;
- }
- Object res=null;
- if (getSTFromRequest()!=null) {
- SOAPHeader sh = (SOAPHeader)getSTFromRequest();
- ArrayList<?> list =
sh.getHeaderBlocksWithNSURI(WSSECHEADER_NS);
- SOAPHeaderBlock shb = (SOAPHeaderBlock) list.get(0);
- try {
- MessageContext
mc=MessageContext.getCurrentMessageContext();
- SOAPEnvelope se = mc.getEnvelope();
- Document
doc=Axis2Util.getDocumentFromSOAPEnvelope(se, true);
- Crypto crypto = new DynamicCrypto();
- WSSecurityEngine secEngine = new
WSSecurityEngine();
- String actor=shb.getAttribute(new
QName(SOAPENV_NS, WSSECHEADER_ACTOR)).getAttributeValue();
- Vector<?> resultSignature =
secEngine.processSecurityHeader(doc, actor, null, crypto);
- if (resultSignature==null) {
- throw new
PerfSONARException("error.authn.wssec","Null response checking the
signature");
- }
+ public Object getSTValue() throws PerfSONARException {
+ if (!hasSTInRequest()) {
+ return null;
+ }
+ Object res = null;
+ if (getSTFromRequest() != null) {
+ SOAPHeader sh = (SOAPHeader) getSTFromRequest();
+ ArrayList<?> list = sh.getHeaderBlocksWithNSURI(WSSECHEADER_NS);
+ SOAPHeaderBlock shb = (SOAPHeaderBlock) list.get(0);
+ try {
+ MessageContext mc =
MessageContext.getCurrentMessageContext();
+ SOAPEnvelope se = mc.getEnvelope();
+ Document doc = Axis2Util.getDocumentFromSOAPEnvelope(se,
true);
+ Crypto crypto = new DynamicCrypto();
+ WSSecurityEngine secEngine = new WSSecurityEngine();
+ String actor = shb.getAttribute(new QName(SOAPENV_NS,
WSSECHEADER_ACTOR)).getAttributeValue();
+ Vector<?> resultSignature =
secEngine.processSecurityHeader(doc, actor, null, crypto);
+ if (resultSignature == null) {
+ throw new PerfSONARException("error.authn.wssec", "Null
response checking the signature");
+ }
- XPathFactory factory =
XPathFactory.newInstance();
- XPath xpath = factory.newXPath();
- xpath.setNamespaceContext(new
WSSENamespaceContext());
- XPathExpression expr =
xpath.compile("//wsse:BinarySecurityToken");
- Object result = expr.evaluate(doc,
XPathConstants.NODESET);
- NodeList nodes = (NodeList) result;
- for (int i = 0; i < nodes.getLength(); i++) {
- Element e=(Element)nodes.item(i);
- if
(e.getAttribute("ValueType").equals("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3"))
{
- NodeList listNodes =
e.getChildNodes();
- Node n1 = listNodes.item(0);
- TextImpl ti = (TextImpl) n1;
- byte[]
bytes=Base64.decode(ti.getData());
- ByteArrayInputStream bais=new
ByteArrayInputStream(bytes);
- X509Certificate
cert=crypto.loadCertificate(bais);
- res=cert;
- }
- else if
(e.getAttribute("ValueType").equals("#SAMLBase64Binary")) {
- NodeList listNodes =
e.getChildNodes();
- Node n1 = listNodes.item(0);
- TextImpl ti = (TextImpl) n1;
- byte[]
bytes=Base64.decode(ti.getData());
- ByteArrayInputStream bais=new
ByteArrayInputStream(bytes);
- SAMLAssertion as=new
SAMLAssertion(bais);
- res=as;
- }
- }
- } catch (Throwable t) {
- throw new
PerfSONARException("authn_getting_sec_token");
- }
- }
+ XPathFactory factory = XPathFactory.newInstance();
+ XPath xpath = factory.newXPath();
+ xpath.setNamespaceContext(new WSSENamespaceContext());
+ XPathExpression expr =
xpath.compile("//wsse:BinarySecurityToken");
+ Object result = expr.evaluate(doc, XPathConstants.NODESET);
+ NodeList nodes = (NodeList) result;
+ for (int i = 0; i < nodes.getLength(); i++) {
+ Element e = (Element) nodes.item(i);
+ if (e.getAttribute("ValueType").equals(
+
"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3"))
{
+ NodeList listNodes = e.getChildNodes();
+ Node n1 = listNodes.item(0);
+ TextImpl ti = (TextImpl) n1;
+ byte[] bytes = Base64.decode(ti.getData());
+ ByteArrayInputStream bais = new
ByteArrayInputStream(bytes);
+ X509Certificate cert = crypto.loadCertificate(bais);
+ res = cert;
+ } else if
(e.getAttribute("ValueType").equals("#SAMLBase64Binary")) {
+ NodeList listNodes = e.getChildNodes();
+ Node n1 = listNodes.item(0);
+ TextImpl ti = (TextImpl) n1;
+ byte[] bytes = Base64.decode(ti.getData());
+ ByteArrayInputStream bais = new
ByteArrayInputStream(bytes);
+ SAMLAssertion as = new SAMLAssertion(bais);
+ res = as;
+ }
+ }
+ } catch (Throwable t) {
+ throw new PerfSONARException("authn_getting_sec_token");
+ }
+ }
return res;
- }
+ }
- public static boolean isDelegated(SecurityToken token) throws
TransformerException {
- boolean isDelegated=false;
+ public static boolean isDelegated(SecurityToken token) throws
TransformerException {
+ boolean isDelegated = false;
- SOAPHeader header=(SOAPHeader)token.getSecToken();
+ SOAPHeader header = (SOAPHeader) token.getSecToken();
ArrayList<?> list = header.getHeaderBlocksWithNSURI(WSSECHEADER_NS);
SOAPHeaderBlock shb = (SOAPHeaderBlock) list.get(0);
- Iterator<?> it =
shb.getChildrenWithLocalName("BinarySecurityToken");
- while (it.hasNext()) {
- OMElement e = (OMElement)it.next();
- if (e.getAttributeValue(new
QName("ValueType"))!=null&&
- e.getAttributeValue(new
QName("ValueType")).equals("#SAMLBase64Binary")) {
- isDelegated = true;
- }
- }
+ Iterator<?> it = shb.getChildrenWithLocalName("BinarySecurityToken");
+ while (it.hasNext()) {
+ OMElement e = (OMElement) it.next();
+ if (e.getAttributeValue(new QName("ValueType")) != null
+ && e.getAttributeValue(new
QName("ValueType")).equals("#SAMLBase64Binary")) {
+ isDelegated = true;
+ }
+ }
- return isDelegated;
- }
+ return isDelegated;
+ }
- public static String getSubject(SecurityToken token) throws
TransformerException, CertificateParsingException,
UnsupportedEncodingException, SAMLException {
- Object stValue=token.getSecTokenValue();
- if (!isDelegated(token)) {
- X509Certificate cert=(X509Certificate)stValue;
- Collection<List<?>> subjectAltNames =
cert.getSubjectAlternativeNames();
+ public static String getSubject(SecurityToken token) throws
TransformerException, CertificateParsingException,
+ UnsupportedEncodingException, SAMLException {
+ Object stValue = token.getSecTokenValue();
+ if (!isDelegated(token)) {
+ X509Certificate cert = (X509Certificate) stValue;
+ Collection<List<?>> subjectAltNames =
cert.getSubjectAlternativeNames();
if (subjectAltNames != null) {
for (List<?> values : subjectAltNames) {
if (values.size() == 2) {
@@ -171,41 +173,41 @@
}
}
}
- }
- else {
- SAMLAssertion assertion=(SAMLAssertion)stValue;
- Iterator<?> it=assertion.getStatements();
- while (it.hasNext()) {
- SAMLStatement
statement=(SAMLStatement)it.next();
- if (statement instanceof
SAMLAuthenticationStatement) {
- SAMLAuthenticationStatement
authSt=(SAMLAuthenticationStatement)statement;
- SAMLSubject
subject=authSt.getSubject();
+ } else {
+ SAMLAssertion assertion = (SAMLAssertion) stValue;
+ Iterator<?> it = assertion.getStatements();
+ while (it.hasNext()) {
+ SAMLStatement statement = (SAMLStatement) it.next();
+ if (statement instanceof SAMLAuthenticationStatement) {
+ SAMLAuthenticationStatement authSt =
(SAMLAuthenticationStatement) statement;
+ SAMLSubject subject = authSt.getSubject();
- Element
confData=subject.getConfirmationData();
- SAMLAssertion relayed=new
SAMLAssertion((Element)confData.getFirstChild());
+ Element confData = subject.getConfirmationData();
+ SAMLAssertion relayed = new SAMLAssertion((Element)
confData.getFirstChild());
- return
relayed.getIssuer()+SecTokenSOAPManager.URN_USER_FED+subject.getNameIdentifier().getName();
- }
- }
- }
+ return relayed.getIssuer() +
SecTokenSOAPManager.URN_USER_FED
+ + subject.getNameIdentifier().getName();
+ }
+ }
+ }
- return "";
- }
+ return "";
+ }
- class WSSENamespaceContext implements NamespaceContext {
+ class WSSENamespaceContext implements NamespaceContext {
- public String getNamespaceURI(String prefix) {
- return
"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
- }
+ public String getNamespaceURI(String prefix) {
+ return
"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
+ }
- // This method isn't necessary for XPath processing either.
- public String getPrefix(String uri) {
- throw new UnsupportedOperationException();
- }
+ // This method isn't necessary for XPath processing either.
+ public String getPrefix(String uri) {
+ throw new UnsupportedOperationException();
+ }
- // This method isn't necessary for XPath processing either.
- public Iterator<?> getPrefixes(String uri) {
- throw new UnsupportedOperationException();
- }
- }
-}
\ No newline at end of file
+ // This method isn't necessary for XPath processing either.
+ public Iterator<?> getPrefixes(String uri) {
+ throw new UnsupportedOperationException();
+ }
+ }
+}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/tokens/SecurityToken.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/tokens/SecurityToken.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/authn/tokens/SecurityToken.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -3,38 +3,38 @@
import org.perfsonar.base2.service.exceptions.PerfSONARException;
public class SecurityToken {
- private SecTokenManager tm;
- private Object secToken;
- private Object secTokenValue;
+ private SecTokenManager tm;
+ private Object secToken;
+ private Object secTokenValue;
- public SecurityToken(SecTokenManager tm) {
- this.tm=tm;
- this.secToken=null;
- this.secTokenValue=null;
- }
+ public SecurityToken(SecTokenManager tm) {
+ this.tm = tm;
+ this.secToken = null;
+ this.secTokenValue = null;
+ }
- public Object getSecToken() {
- return secToken;
- }
+ public Object getSecToken() {
+ return secToken;
+ }
- public void setSecToken(Object secToken) {
- this.secToken = secToken;
- }
+ public void setSecToken(Object secToken) {
+ this.secToken = secToken;
+ }
- public void setSecTokenFromRequest() throws PerfSONARException {
- setSecToken(tm.getSTFromRequest());
- setSecTokenValue(tm.getSTValue());
- }
+ public void setSecTokenFromRequest() throws PerfSONARException {
+ setSecToken(tm.getSTFromRequest());
+ setSecTokenValue(tm.getSTValue());
+ }
- public boolean hasSecTokenInRequest() throws PerfSONARException {
- return tm.hasSTInRequest();
- }
+ public boolean hasSecTokenInRequest() throws PerfSONARException {
+ return tm.hasSTInRequest();
+ }
- public Object getSecTokenValue() {
- return secTokenValue;
- }
+ public Object getSecTokenValue() {
+ return secTokenValue;
+ }
- public void setSecTokenValue(Object secTokenValue) {
- this.secTokenValue = secTokenValue;
- }
+ public void setSecTokenValue(Object secTokenValue) {
+ this.secTokenValue = secTokenValue;
+ }
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/axis2interface/PerfsonarService.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/axis2interface/PerfsonarService.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/axis2interface/PerfsonarService.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -1,6 +1,5 @@
package org.perfsonar.base2.service.axis2interface;
-
import org.apache.axiom.om.OMElement;
import org.apache.axis2.context.ServiceContext;
import org.slf4j.Logger;
@@ -15,21 +14,20 @@
* @author Roman Lapacz
* @author Maciej Glowiak
* @author <a
href="mailto:">Blazej
Pietrzak</a>
- *
+ *
*/
public class PerfsonarService {
-
/**
* Axis2 Service Context
*/
private ServiceContext serviceContext;
-
/**
* Runs perfSONAR request handler (Axis2-based one)
- *
- * @param inOMElement input as OMElement
+ *
+ * @param inOMElement
+ * input as OMElement
* @return
*/
public OMElement message(OMElement inOMElement) {
@@ -40,33 +38,32 @@
}
-
/**
* Run by Axis2 while starting
*/
public void init(ServiceContext sc) {
- //runs while starting
- // TODO: Does perfSONAR services work with Java 7?
- final JREVersion jreVersion = new JREVersion();
- if (!jreVersion.isJRECompatibleWith(1, 6)) {
- LoggerFactory.getLogger(PerfsonarService.class).error("In
order to run the perfSONAR service, the JRE version must be from the 1.6.0
series."
- + "JRE version is " + jreVersion.getJREVersion() + "."
- + "The application will terminate the servlet
container.");
- System.exit(1);
- }
+ // runs while starting
+ // TODO: Does perfSONAR services work with Java 7?
+ final JREVersion jreVersion = new JREVersion();
+ if (!jreVersion.isJRECompatibleWith(1, 6)) {
+ LoggerFactory.getLogger(PerfsonarService.class).error(
+ "In order to run the perfSONAR service, the JRE version
must be from the 1.6.0 series."
+ + "JRE version is " + jreVersion.getJREVersion()
+ "."
+ + "The application will terminate the servlet
container.");
+ System.exit(1);
+ }
serviceContext = sc;
try {
- //init manager for the first time while starting service
+ // init manager for the first time while starting service
ConfigurationManager.getInstance();
- } catch (Exception ex) {}
+ } catch (Exception ex) {
+ }
}
-
/**
* Run by Axis2 while shutting down
*/
public void destroy(ServiceContext serviceContext) {
}
-
-} //PerfsonarService
+} // PerfsonarService
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/Action.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/Action.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/Action.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -4,27 +4,20 @@
*/
package org.perfsonar.base2.service.configuration;
-
public class Action extends Entry {
-
// ----------------------------------------------------------- Variables
-
protected String className = null;
-
// -----------------------------------------------------------
Constructor
-
public Action() {
- super();
+ super();
}
-
// ----------------------------------------------------------- Methods
-
public String getClassName() {
return className;
}
@@ -33,5 +26,4 @@
this.className = className;
}
-
-} //Action
\ No newline at end of file
+} // Action
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/Actions.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/Actions.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/Actions.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -7,40 +7,32 @@
import java.util.LinkedHashMap;
import java.util.Map;
-
public class Actions extends Entry {
-
// ----------------------------------------------------------- Variables
+ private Map<String, Action> actions = new LinkedHashMap<String,
Action>();
- private Map<String,Action> actions = new LinkedHashMap<String,Action>();
-
-
// -----------------------------------------------------------
Constructors
-
public Actions() {
- super();
+ super();
}
-
// ----------------------------------------------------------- Methods
-
public void addAction(Action action) {
actions.put(action.getName(), action);
- logger.debug("Action " + action.getName() + " to the scheduler");
+ LOGGER.debug("Action " + action.getName() + " to the scheduler");
}
public Action getAction(String name) {
return actions.get(name);
}
- public Map<String,Action> getActions() {
+ public Map<String, Action> getActions() {
return actions;
}
-
-} //Actions
\ No newline at end of file
+} // Actions
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/AuxiliaryComponents.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/AuxiliaryComponents.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/AuxiliaryComponents.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -4,36 +4,28 @@
*/
package org.perfsonar.base2.service.configuration;
-
import java.util.LinkedHashMap;
import java.util.Map;
-
public class AuxiliaryComponents extends Entry {
-
// ----------------------------------------------------------- Variables
-
/**
- * Map of components. LinkedHashMap saves order of elements, so
- * components will be initialized in right order (FCFS)
+ * Map of components. LinkedHashMap saves order of elements, so
components
+ * will be initialized in right order (FCFS)
*/
- private Map<String,Component> components = new
LinkedHashMap<String,Component>();
+ private Map<String, Component> components = new LinkedHashMap<String,
Component>();
-
// -----------------------------------------------------------
Constructor
-
public AuxiliaryComponents() {
- super();
- name = Configuration.AUXILIARY_COMPONENTS;
+ super();
+ name = Configuration.AUXILIARY_COMPONENTS;
}
-
// ----------------------------------------------------------- Methods
-
public void addComponent(Component component) {
components.put(component.getName(), component);
}
@@ -42,9 +34,8 @@
return components.get(name);
}
- public Map<String,Component> getComponents() {
+ public Map<String, Component> getComponents() {
return components;
}
-
-} //AuxiliaryComponents
+} // AuxiliaryComponents
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/Configuration.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/Configuration.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/Configuration.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -12,191 +12,152 @@
public class Configuration {
- public static final String MESSAGE_HANDLER = "MessageHandler";
- public static final String AUXILIARY_COMPONENTS =
"AuxiliaryComponents";
- public static final String COMPONENT = "Component";
- public static final String LOOKUP_INFORMATION = "LookupInformation";
- public static final String PROTOCOL_MAPPINGS = "ProtocolMappings";
- public static final String SERVICE_ENGINE = "ServiceEngine";
+ public static final String MESSAGE_HANDLER = "MessageHandler";
+ public static final String AUXILIARY_COMPONENTS = "AuxiliaryComponents";
+ public static final String COMPONENT = "Component";
+ public static final String LOOKUP_INFORMATION = "LookupInformation";
+ public static final String PROTOCOL_MAPPINGS = "ProtocolMappings";
+ public static final String SERVICE_ENGINE = "ServiceEngine";
- // -----------------------------------------------------------
Variables
+ // ----------------------------------------------------------- Variables
- private Map<String, Service> services = null;
+ private Map<String, Service> services = null;
- // -----------------------------------------------------------
Constructor
+ // -----------------------------------------------------------
Constructor
- public Configuration() {
- services = new HashMap<String, Service>();
- }
+ public Configuration() {
+ services = new HashMap<String, Service>();
+ }
- // ----------------------------------------------------------- Methods
+ // ----------------------------------------------------------- Methods
- public void addService(Service service) {
- services.put(service.getName(), service);
- }
+ public void addService(Service service) {
+ services.put(service.getName(), service);
+ }
- public Service getService(String name) throws PerfSONARException {
- Service service = services.get(name);
- if (service == null) {
- // TODO: url event types
- throw new PerfSONARException("error.configuration",
- "Could not find a service " + name
- + " in the
configuration");
- }
- return service;
- }
+ public Service getService(String name) throws PerfSONARException {
+ Service service = services.get(name);
+ if (service == null) {
+ // TODO: url event types
+ throw new PerfSONARException("error.configuration", "Could not
find a service " + name
+ + " in the configuration");
+ }
+ return service;
+ }
- public Map<String, Service> getServices() {
- return services;
- }
+ public Map<String, Service> getServices() {
+ return services;
+ }
- public Service getService() throws PerfSONARException {
+ public Service getService() throws PerfSONARException {
- String serviceName =
System.getenv("PERFSONAR_CONF_SERVICE_NAME");
- Service s = null;
- if (serviceName != null) {
- s = getService(serviceName);
- }
+ String serviceName = System.getenv("PERFSONAR_CONF_SERVICE_NAME");
+ Service s = null;
+ if (serviceName != null) {
+ s = getService(serviceName);
+ }
- if (s == null) {
- for (String sname : services.keySet()) {
- s = getService(sname);
- break;
- }
- }
+ if (s == null) {
+ for (String sname : services.keySet()) {
+ s = getService(sname);
+ break;
+ }
+ }
- return s;
- }
+ return s;
+ }
- // ----------------------------------------------------------- Facade
- // methods
+ // ----------------------------------------------------------- Facade
+ // methods
- public String getLookupInformationOption(String optionName)
- throws PerfSONARException {
- return getService().getEntry(
-
Configuration.LOOKUP_INFORMATION).getOption(optionName)
- .getValue();
- }
+ public String getLookupInformationOption(String optionName) throws
PerfSONARException {
+ return
getService().getEntry(Configuration.LOOKUP_INFORMATION).getOption(optionName).getValue();
+ }
- public String getLookupInformationOption(String serviceName,
- String optioName) throws PerfSONARException {
- return getService(serviceName).getEntry(
-
Configuration.LOOKUP_INFORMATION).getOption(optioName)
- .getValue();
- }
+ public String getLookupInformationOption(String serviceName, String
optioName) throws PerfSONARException {
+ return
getService(serviceName).getEntry(Configuration.LOOKUP_INFORMATION).getOption(optioName).getValue();
+ }
- public Iterator<String> getLookupInformationIterator() throws
PerfSONARException {
- return getService().getEntry(
-
Configuration.LOOKUP_INFORMATION).getOptions().keySet()
- .iterator();
- }
+ public Iterator<String> getLookupInformationIterator() throws
PerfSONARException {
+ return
getService().getEntry(Configuration.LOOKUP_INFORMATION).getOptions().keySet().iterator();
+ }
- public Iterator<String> getLookupInformationIterator(String
serviceName)
- throws PerfSONARException {
- return getService(serviceName).getEntry(
-
Configuration.LOOKUP_INFORMATION).getOptions().keySet()
- .iterator();
- }
+ public Iterator<String> getLookupInformationIterator(String serviceName)
throws PerfSONARException {
+ return
getService(serviceName).getEntry(Configuration.LOOKUP_INFORMATION).getOptions().keySet().iterator();
+ }
- public String getMessageHandlerClassName(String messageType)
- throws PerfSONARException {
- return ((MessageHandler) getService().getEntry(
-
Configuration.MESSAGE_HANDLER)).getMessage(messageType)
- .getHandler();
- }
+ public String getMessageHandlerClassName(String messageType) throws
PerfSONARException {
+ return ((MessageHandler)
getService().getEntry(Configuration.MESSAGE_HANDLER)).getMessage(messageType)
+ .getHandler();
+ }
- public String getMessageHandlerClassName(String serviceName,
- String messageType) throws PerfSONARException {
- return ((MessageHandler) getService(serviceName).getEntry(
-
Configuration.MESSAGE_HANDLER)).getMessage(messageType)
- .getHandler();
- }
+ public String getMessageHandlerClassName(String serviceName, String
messageType) throws PerfSONARException {
+ return ((MessageHandler)
getService(serviceName).getEntry(Configuration.MESSAGE_HANDLER)).getMessage(
+ messageType).getHandler();
+ }
- public Message getMessageHandler(String messageType)
- throws PerfSONARException {
- return ((MessageHandler) getService().getEntry(
-
Configuration.MESSAGE_HANDLER)).getMessage(messageType);
- }
+ public Message getMessageHandler(String messageType) throws
PerfSONARException {
+ return ((MessageHandler)
getService().getEntry(Configuration.MESSAGE_HANDLER)).getMessage(messageType);
+ }
- public Message getMessageHandler(String serviceName, String
messageType)
- throws PerfSONARException {
- return ((MessageHandler) getService(serviceName).getEntry(
-
Configuration.MESSAGE_HANDLER)).getMessage(messageType);
- }
+ public Message getMessageHandler(String serviceName, String messageType)
throws PerfSONARException {
+ return ((MessageHandler)
getService(serviceName).getEntry(Configuration.MESSAGE_HANDLER))
+ .getMessage(messageType);
+ }
- public String getProtocolMappingElement(String elementName)
- throws PerfSONARException {
- return ((ProtocolMappings) getService().getEntry(
-
Configuration.PROTOCOL_MAPPINGS)).getElement(elementName)
- .getMapping();
- }
+ public String getProtocolMappingElement(String elementName) throws
PerfSONARException {
+ return ((ProtocolMappings)
getService().getEntry(Configuration.PROTOCOL_MAPPINGS)).getElement(elementName)
+ .getMapping();
+ }
- public String getProtocolMappingElement(String serviceName,
- String elementName) throws PerfSONARException {
- return ((ProtocolMappings) getService(serviceName).getEntry(
-
Configuration.PROTOCOL_MAPPINGS)).getElement(elementName)
- .getMapping();
- }
+ public String getProtocolMappingElement(String serviceName, String
elementName) throws PerfSONARException {
+ return ((ProtocolMappings)
getService(serviceName).getEntry(Configuration.PROTOCOL_MAPPINGS)).getElement(
+ elementName).getMapping();
+ }
- public Iterator<String> getProtocolMappingsIterator() throws
PerfSONARException {
- return ((ProtocolMappings) getService().getEntry(
-
Configuration.PROTOCOL_MAPPINGS)).getElements().keySet()
- .iterator();
- }
+ public Iterator<String> getProtocolMappingsIterator() throws
PerfSONARException {
+ return ((ProtocolMappings)
getService().getEntry(Configuration.PROTOCOL_MAPPINGS)).getElements().keySet()
+ .iterator();
+ }
- public Iterator<String> getProtocolMappingsIterator(String
serviceName)
- throws PerfSONARException {
- return ((ProtocolMappings) getService(serviceName).getEntry(
-
Configuration.PROTOCOL_MAPPINGS)).getElements().keySet()
- .iterator();
- }
+ public Iterator<String> getProtocolMappingsIterator(String serviceName)
throws PerfSONARException {
+ return ((ProtocolMappings)
getService(serviceName).getEntry(Configuration.PROTOCOL_MAPPINGS)).getElements()
+ .keySet().iterator();
+ }
- public String getExtensionOption(String extensionName, String
optionName)
- throws PerfSONARException {
- return getService().getEntry(extensionName).getOption(
- optionName).getValue();
- }
+ public String getExtensionOption(String extensionName, String
optionName) throws PerfSONARException {
+ return
getService().getEntry(extensionName).getOption(optionName).getValue();
+ }
- public String getExtensionOption(String serviceName, String
extensionName,
- String optionName) throws PerfSONARException {
- return getService(serviceName).getEntry(extensionName)
- .getOption(optionName).getValue();
- }
+ public String getExtensionOption(String serviceName, String
extensionName, String optionName)
+ throws PerfSONARException {
+ return
getService(serviceName).getEntry(extensionName).getOption(optionName).getValue();
+ }
- public Iterator<String> getExtensionOptionsIterator(String
extensionName,
- String optionName) throws PerfSONARException {
- return getService().getEntry(extensionName).getOptions()
- .keySet().iterator();
- }
+ public Iterator<String> getExtensionOptionsIterator(String
extensionName, String optionName)
+ throws PerfSONARException {
+ return
getService().getEntry(extensionName).getOptions().keySet().iterator();
+ }
- public Iterator<String> getExtensionOptionsIterator(String
serviceName,
- String extensionName, String optionName) throws
PerfSONARException {
- return getService(serviceName).getEntry(extensionName)
- .getOptions().keySet().iterator();
- }
+ public Iterator<String> getExtensionOptionsIterator(String serviceName,
String extensionName, String optionName)
+ throws PerfSONARException {
+ return
getService(serviceName).getEntry(extensionName).getOptions().keySet().iterator();
+ }
- public String getServiceEngineOption(String serviceName, String
messageType)
- throws PerfSONARException {
- return getMessageHandler(serviceName, messageType).getOption(
- SERVICE_ENGINE).getValue();
- }
+ public String getServiceEngineOption(String serviceName, String
messageType) throws PerfSONARException {
+ return getMessageHandler(serviceName,
messageType).getOption(SERVICE_ENGINE).getValue();
+ }
- public String getServiceEngineOption(String messageType)
- throws PerfSONARException {
- return
getMessageHandler(messageType).getOption(SERVICE_ENGINE)
- .getValue();
- }
+ public String getServiceEngineOption(String messageType) throws
PerfSONARException {
+ return
getMessageHandler(messageType).getOption(SERVICE_ENGINE).getValue();
+ }
- public AuxiliaryComponents getAuxiliaryComponents()
- throws PerfSONARException {
- return ((AuxiliaryComponents) getService().getEntry(
- Configuration.AUXILIARY_COMPONENTS));
- }
+ public AuxiliaryComponents getAuxiliaryComponents() throws
PerfSONARException {
+ return ((AuxiliaryComponents)
getService().getEntry(Configuration.AUXILIARY_COMPONENTS));
+ }
- public Component getAuxiliaryComponent(String name)
- throws PerfSONARException {
- return ((AuxiliaryComponents) getService().getEntry(
-
Configuration.AUXILIARY_COMPONENTS)).getComponent(name);
- }
+ public Component getAuxiliaryComponent(String name) throws
PerfSONARException {
+ return ((AuxiliaryComponents)
getService().getEntry(Configuration.AUXILIARY_COMPONENTS)).getComponent(name);
+ }
} // Configuration
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/ConfigurationManager.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/ConfigurationManager.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/ConfigurationManager.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -1,6 +1,5 @@
package org.perfsonar.base2.service.configuration;
-
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
@@ -16,44 +15,43 @@
/**
*
- * This class is a singleton which creates one instance of configuration
+ * This class is a singleton which creates one instance of configuration
*
* @author roman,trzaszcz
- *
+ *
*/
public class ConfigurationManager {
-
// ----------------------------------------------------------- Variables
-
/**
- * The resource directory path where config files can be located
+ * The resource directory path where config files can be located
*/
- protected static String DEFAULT_CONFIG_DIR_PREFIX = "perfsonar/conf";
+ protected static final String DEFAULT_CONFIG_DIR_PREFIX =
"perfsonar/conf";
/**
- * Configuration rules file.
+ * Configuration rules file.
*/
- protected static String DEFAULT_CONFIG_RULES= "configuration-rules.xml";
+ protected static final String DEFAULT_CONFIG_RULES =
"configuration-rules.xml";
/**
- * Service configuration file.
+ * Service configuration file.
*/
- protected static String DEFAULT_CONFIG_INPUT = "configuration.xml";
+ protected static final String DEFAULT_CONFIG_INPUT = "configuration.xml";
/**
- * The name of env variable which can contain the directory path of
configuration files.
+ * The name of env variable which can contain the directory path of
+ * configuration files.
*/
- protected static String CONFIG_DIR_SYS_ENV_VAR_NAME =
"PERFSONAR_CONFIG_DIR";
+ protected static final String CONFIG_DIR_SYS_ENV_VAR_NAME =
"PERFSONAR_CONFIG_DIR";
protected String digesterRules = DEFAULT_CONFIG_DIR_PREFIX + "/" +
DEFAULT_CONFIG_RULES;
protected String digesterInput = DEFAULT_CONFIG_DIR_PREFIX + "/" +
DEFAULT_CONFIG_INPUT;
- protected static final Logger logger =
LoggerFactory.getLogger(ConfigurationManager.class);
+ protected static final Logger LOGGER =
LoggerFactory.getLogger(ConfigurationManager.class);
private static ConfigurationManager configurationManager = new
ConfigurationManager();
-
+
private static volatile Object initialiseMutex = new Object();
private static boolean initialised;
private static boolean isInitialising;
@@ -62,80 +60,73 @@
private boolean envVariableExist = false;
-
// -----------------------------------------------------------
Constructor
-
/**
- * Initializes the instance of configuration manager and invokes run
method on components (scheduler is activated)
+ * Initializes the instance of configuration manager and invokes run
method
+ * on components (scheduler is activated)
*
- *
+ *
* @return an instance of ConfigurationManager
- * @throws PerfSONARExceptiona
+ * @throws PerfSONARExceptiona
*/
public static ConfigurationManager getInstance() throws
PerfSONARException {
- return initializeConfigurationManager(true);
+ return initializeConfigurationManager(true);
}
-
+
/**
*
- * Initializes the instance of configuration manager without invoking
run method on created components (scheduler is deactivated)
+ * Initializes the instance of configuration manager without invoking run
+ * method on created components (scheduler is deactivated)
*
* @return an instance of ConfigurationManager
* @throws PerfSONARExceptiona
*/
public static ConfigurationManager getInstanceWithoutRunningComponents()
throws PerfSONARException {
- return initializeConfigurationManager(false);
+ return initializeConfigurationManager(false);
}
-
-
- private static ConfigurationManager
initializeConfigurationManager(boolean runComponents) throws
PerfSONARException{
-
- if (!initialised) {
- synchronized (initialiseMutex) {
- logger.info("Initialize Configuration Manager");
- if(!initialised && !isInitialising) {
- isInitialising = true;
- initialised =
configurationManager.initConfiguration(runComponents);
- isInitialising = false;
- }
- }
- }
- initialised = true;
- return configurationManager;
- }
+ private static ConfigurationManager
initializeConfigurationManager(boolean runComponents) throws
PerfSONARException {
+ if (!initialised) {
+ synchronized (initialiseMutex) {
+ LOGGER.info("Initialize Configuration Manager");
+ if (!initialised && !isInitialising) {
+ isInitialising = true;
+ initialised =
configurationManager.initConfiguration(runComponents);
+ isInitialising = false;
+ }
+ }
+ }
+ initialised = true;
+ return configurationManager;
+ }
+
// ----------------------------------------------------------- Methods
-
protected boolean initConfiguration(boolean runComponents) throws
PerfSONARException {
- //check and read sys env variable with the path of config directory
+ // check and read sys env variable with the path of config directory
readEnvVariable();
- //read the configuration
+ // read the configuration
URL digesterRulesURL = getDigesterRulesURL();
InputStream digesterInputStream = getDigesterInputStream();
Digester digester = DigesterLoader.createDigester(digesterRulesURL);
- //digester.setNamespaceAware(true);
+ // digester.setNamespaceAware(true);
try {
- configuration =
- (Configuration) digester.parse(digesterInputStream);
+ configuration = (Configuration)
digester.parse(digesterInputStream);
digesterInputStream.close();
} catch (Exception ex) {
- logger.error(
- "Can not parse " + digesterInput +", "
- + ex.toString());
- //TODO: url event types
- throw new PerfSONARException(
- "error.configuration",
- "Can not parse " + digesterInput+". Nested exception
was: "+ex.toString());
+ LOGGER.error("Can not parse " + digesterInput + ", " +
ex.toString());
+ // TODO: url event types
+ throw new PerfSONARException("error.configuration", "Can not
parse " + digesterInput
+ + ". Nested exception was: " + ex.toString());
}
@@ -145,97 +136,96 @@
}
-
private URL getDigesterRulesURL() throws PerfSONARException {
- logger.debug("Read ibatis configuration rules from the file [" +
digesterRules + "]");
+ LOGGER.debug("Read ibatis configuration rules from the file [" +
digesterRules + "]");
URL digesterRulesURL = null;
try {
- if (!envVariableExist)
- digesterRulesURL =
-
Thread.currentThread().getContextClassLoader().getResource(digesterRules);
- else
+ if (!envVariableExist) {
+ digesterRulesURL =
Thread.currentThread().getContextClassLoader().getResource(digesterRules);
+ } else {
digesterRulesURL = (new File(digesterRules)).toURI().toURL();
- if (digesterRulesURL == null)
+ }
+ if (digesterRulesURL == null) {
throw new IOException("Can not find resource " +
digesterRulesURL);
+ }
} catch (Exception ex) {
- logger.error("Can not find xml config file, " + ex.toString());
+ LOGGER.error("Can not find xml config file, " + ex.toString());
}
if (digesterRulesURL == null) {
- throw new PerfSONARException(
- "error/configuration",
- "Can not find xml config file " + digesterRules+".");
+ throw new PerfSONARException("error/configuration", "Can not
find xml config file " + digesterRules + ".");
}
return digesterRulesURL;
}
-
private InputStream getDigesterInputStream() throws PerfSONARException {
- logger.debug("Read configuration settings from the file [" +
digesterInput + "]");
+ LOGGER.debug("Read configuration settings from the file [" +
digesterInput + "]");
InputStream digesterInputStream = null;
try {
- if (!envVariableExist)
- digesterInputStream =
-
Thread.currentThread().getContextClassLoader().getResourceAsStream(digesterInput);
- else
+ if (!envVariableExist) {
+ digesterInputStream =
Thread.currentThread().getContextClassLoader().getResourceAsStream(digesterInput);
+ } else {
digesterInputStream = new FileInputStream(new
File(digesterInput));
- if (digesterInputStream == null)
+ }
+ if (digesterInputStream == null) {
throw new IOException("Can not find resource " +
digesterInput);
+ }
} catch (Exception ex) {
- logger.error("Can not find xml file, " + ex.toString());
+ LOGGER.error("Can not find xml file, " + ex.toString());
}
if (digesterInputStream == null) {
- //TODO: url event types
- throw new PerfSONARException(
- "error.configuration",
- "Can not create an input stream of xml config file "
+ // TODO: url event types
+ throw new PerfSONARException("error.configuration", "Can not
create an input stream of xml config file "
+ digesterInput);
}
return digesterInputStream;
}
-
/**
*
- * Initializes auxiliary components
+ * Initializes auxiliary components
*
- * @param runComponents - if the value is true then in all components
run method is invoked (in case of SchedulerComponents - scheduler is
activated)
+ * @param runComponents
+ * - if the value is true then in all components run method is
+ * invoked (in case of SchedulerComponents - scheduler is
+ * activated)
* @throws PerfSONARException
*/
private void initializeAuxiliaryComponents(boolean runComponents) throws
PerfSONARException {
AuxiliaryComponents ac = configuration.getAuxiliaryComponents();
- if (ac == null) return;
+ if (ac == null) {
+ return;
+ }
- for (Component c : ac.getComponents().values()) {
+ for (Component c : ac.getComponents().values()) {
try {
- logger.info("Initialize component ["+c.getName()+"] as
["+c.getClassName()+"]");
- c.init();
- if(runComponents){
- c.run();
- }
-
+ LOGGER.info("Initialize component [" + c.getName() + "] as
[" + c.getClassName() + "]");
+ c.init();
+ if (runComponents) {
+ c.run();
+ }
+
} catch (Exception ex) {
- logger.error("Can not initialize auxiliary component ["+
- c.getClass()+"]. Nested exception is:
"+ex.toString());
+ LOGGER.error("Can not initialize auxiliary component [" +
c.getClass() + "]. Nested exception is: "
+ + ex.toString());
}
}
}
-
/**
- * Read configuration directory from $PERFSONAR_CONFIG_DIR env or
- * take the default one
+ * Read configuration directory from $PERFSONAR_CONFIG_DIR env or take
the
+ * default one
*/
private String readEnvVariable() {
@@ -249,27 +239,27 @@
return configDir;
}
-
public Configuration getConfiguration() {
return configuration;
}
-
public void flush() throws PerfSONARException {
AuxiliaryComponents ac = configuration.getAuxiliaryComponents();
- if (ac == null) return;
+ if (ac == null) {
+ return;
+ }
Collection<Component> components = ac.getComponents().values();
- for (Component c : components) {
+ for (Component c : components) {
try {
- logger.info("Destroy component ["+c.getName()+"]");
+ LOGGER.info("Destroy component [" + c.getName() + "]");
c.destroy();
components.remove(c);
} catch (Exception ex) {
- logger.error("Can not destroy auxiliary component ["+
- c.getClass()+"]. Nested exception is:
"+ex.toString());
+ LOGGER.error("Can not destroy auxiliary component [" +
c.getClass() + "]. Nested exception is: "
+ + ex.toString());
}
}
@@ -278,53 +268,49 @@
}
-
// ----------------------------------------------------------- Test
method
-
public static void main(String[] args) {
try {
- ConfigurationManager configurationManager = getInstance();
- Configuration configuration =
- configurationManager.getConfiguration();
+ Configuration configuration =
configurationManager.getConfiguration();
Service service = configuration.getService("SimpleService");
- LookupInformation li = (LookupInformation)
- service.getEntry("LookupInformation");
+ LookupInformation li = (LookupInformation)
service.getEntry("LookupInformation");
String value1 = li.getOption("accessPoint").getValue();
String value2 = li.getOption("name").getValue();
System.out.println("Test service name: " + service.getName());
System.out.println("Li op value 1: " + value1);
System.out.println("Li op value 2: " + value2);
- Message message =
-
((MessageHandler)service.getEntry("MessageHandler")).getMessage("EchoRequest");
+ Message message = ((MessageHandler)
service.getEntry("MessageHandler")).getMessage("EchoRequest");
System.out.println("Message handler: " + message.getHandler());
System.out.println("Message op value 1: " +
message.getOption("authN").getValue());
/*
- AuxiliaryComponents auxiliaryComponents =
-
((AuxiliaryComponents)service.getEntry("AuxiliaryComponents"));
- Component component =
auxiliaryComponents.getComponent("scheduler");
- System.out.println("Component: " + component.getClassName());
- System.out.println("Component: " +
component.getOption("wakeupTime").getValue());
- System.out.println("AuxiliaryComponents option: "
- +
auxiliaryComponents.getOption("persistentManager").getValue());
- */
- ProtocolMappings protocolMappings =
- ((ProtocolMappings)service.getEntry("ProtocolMappings"));
- ElementConf element =
-
protocolMappings.getElement("{http://ggf.org/ns/nmwg/base/2.0/}metadata");
+ * AuxiliaryComponents auxiliaryComponents =
+ *
((AuxiliaryComponents)service.getEntry("AuxiliaryComponents"));
+ * Component component =
+ * auxiliaryComponents.getComponent("scheduler");
+ * System.out.println("Component: " + component.getClassName());
+ * System.out.println("Component: " +
+ * component.getOption("wakeupTime").getValue());
+ * System.out.println("AuxiliaryComponents option: " +
+ *
auxiliaryComponents.getOption("persistentManager").getValue());
+ */
+ ProtocolMappings protocolMappings = ((ProtocolMappings)
service.getEntry("ProtocolMappings"));
+ ElementConf element =
protocolMappings.getElement("{http://ggf.org/ns/nmwg/base/2.0/}metadata");
System.out.println("Mapping element: " + element.getMapping());
/*
- Extension extension =
((Extension)service.getEntry("metadataStore"));
- System.out.println("Extension op value of access_type: "
- + extension.getOption("access_type").getValue());
- */
+ * Extension extension =
+ * ((Extension)service.getEntry("metadataStore"));
+ * System.out.println("Extension op value of access_type: " +
+ * extension.getOption("access_type").getValue());
+ */
System.out.println("--------------------------------------------------------");
System.out.println(configuration.getLookupInformationOption("accessPoint"));
System.out.println(configuration.getMessageHandlerClassName("EchoRequest"));
System.out.println(configuration.getProtocolMappingElement("{http://ggf.org/ns/nmwg/base/2.0/}metadata"));
-
//System.out.println(configuration.getExtensionOption("metadataStore",
"access_type"));
+ //
System.out.println(configuration.getExtensionOption("metadataStore",
+ // "access_type"));
} catch (Exception e) {
e.printStackTrace();
@@ -332,5 +318,4 @@
}
-
-} //ConfigurationManager
+} // ConfigurationManager
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/ElementConf.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/ElementConf.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/ElementConf.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -4,31 +4,25 @@
*/
package org.perfsonar.base2.service.configuration;
-
public class ElementConf {
-
// ----------------------------------------------------------- Variables
-
- protected String name = null;
+ protected String name = null;
protected String mapping = null;
-
// -----------------------------------------------------------
Constructor
+ public ElementConf() {
+ }
- public ElementConf() {}
-
public ElementConf(String name, String mapping) {
this.name = name;
this.mapping = mapping;
}
-
// ----------------------------------------------------------- Methods
-
public void setName(String name) {
this.name = name;
}
@@ -45,5 +39,4 @@
return mapping;
}
-
-} //Element
+} // Element
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/Entry.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/Entry.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/Entry.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -4,28 +4,21 @@
*/
package org.perfsonar.base2.service.configuration;
-
public abstract class Entry extends OptionEntry {
-
// ----------------------------------------------------------- Variables
-
protected String name = null;
-
// -----------------------------------------------------------
Constructor
-
public Entry() {
- super();
+ super();
name = "";
}
-
// ----------------------------------------------------------- Methods
-
public String getName() {
return name;
}
@@ -34,4 +27,4 @@
this.name = name;
}
-} //Entry
+} // Entry
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/Extension.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/Extension.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/Extension.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -4,16 +4,12 @@
*/
package org.perfsonar.base2.service.configuration;
-
public class Extension extends Entry {
-
// -----------------------------------------------------------
Constructor
-
- public Extension() {
+ public Extension() {
super();
- }
+ }
-
-} //Extension
+} // Extension
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/LookupInformation.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/LookupInformation.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/LookupInformation.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -4,17 +4,13 @@
*/
package org.perfsonar.base2.service.configuration;
-
public class LookupInformation extends Entry {
-
// -----------------------------------------------------------
Constructor
+ public LookupInformation() {
+ super();
+ name = Configuration.LOOKUP_INFORMATION;
+ }
- public LookupInformation() {
- super();
- name = Configuration.LOOKUP_INFORMATION;
- }
-
-
-} //LookupInformation
+} // LookupInformation
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/Message.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/Message.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/Message.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -4,33 +4,27 @@
*/
package org.perfsonar.base2.service.configuration;
-
public class Message extends OptionEntry {
-
// ----------------------------------------------------------- Variables
-
private String type = null;
private String handler = null;
-
// -----------------------------------------------------------
Constructor
public Message() {
- super();
+ super();
}
public Message(String type, String handler) {
- super();
+ super();
this.type = type;
this.handler = handler;
}
-
// ----------------------------------------------------------- Methods
-
public String getType() {
return type;
}
@@ -47,5 +41,4 @@
this.handler = handler;
}
-
} // Message
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/MessageHandler.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/MessageHandler.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/MessageHandler.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -4,35 +4,27 @@
*/
package org.perfsonar.base2.service.configuration;
-
import java.util.Map;
import java.util.HashMap;
import org.perfsonar.base2.service.exceptions.PerfSONARException;
-
public class MessageHandler extends Entry {
-
// ----------------------------------------------------------- Variables
+ private Map<String, Message> messages = null;
- private Map<String,Message> messages = null;
-
-
// -----------------------------------------------------------
Constructor
-
public MessageHandler() {
super();
name = Configuration.MESSAGE_HANDLER;
- messages = new HashMap<String,Message>();
+ messages = new HashMap<String, Message>();
}
-
// ----------------------------------------------------------- Methods
-
public void addMessage(Message message) {
messages.put(message.getType(), message);
}
@@ -41,9 +33,8 @@
return messages.get(type);
}
- public Map<String,Message> getMessages() {
+ public Map<String, Message> getMessages() {
return messages;
}
-
-} //MessageHandler
+} // MessageHandler
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/Option.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/Option.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/Option.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -4,31 +4,25 @@
*/
package org.perfsonar.base2.service.configuration;
-
public class Option {
-
// ----------------------------------------------------------- Variables
-
- protected String name = null;
+ protected String name = null;
protected String value = null;
-
// -----------------------------------------------------------
Constructor
+ public Option() {
+ }
- public Option() {}
-
public Option(String name, String value) {
this.name = name;
this.value = value;
}
-
// ----------------------------------------------------------- Methods
-
public void setName(String name) {
this.name = name;
}
@@ -45,17 +39,14 @@
return value;
}
- public int getValueAsInteger() throws RuntimeException {
+ public int getValueAsInteger() {
int iv = Integer.parseInt(value);
return iv;
}
public boolean getValueAsBoolean() {
- if (value.equalsIgnoreCase("TRUE") ||
- value.equalsIgnoreCase("ON") ||
- value.equalsIgnoreCase("YES") ||
- value.equalsIgnoreCase("1")) return true;
- else return false;
+ return value.equalsIgnoreCase("TRUE") ||
value.equalsIgnoreCase("ON") || value.equalsIgnoreCase("YES")
+ || value.equalsIgnoreCase("1");
}
-
-} //Option
+
+} // Option
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/OptionEntry.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/OptionEntry.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/OptionEntry.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -4,7 +4,6 @@
*/
package org.perfsonar.base2.service.configuration;
-
import java.util.HashMap;
import java.util.Map;
@@ -13,31 +12,26 @@
/**
* Configuration: Options
+ *
* @author Maciej Glowiak
- *
+ *
*/
public abstract class OptionEntry {
-
// ----------------------------------------------------------- Variables
+ protected Map<String, Option> options = null;
- protected Map<String,Option> options = null;
+ protected static final Logger LOGGER =
LoggerFactory.getLogger("org.perfsonar.base2.service.configuration");
- protected static final Logger logger =
LoggerFactory.getLogger("org.perfsonar.base2.service.configuration");
-
-
// -----------------------------------------------------------
Constructor
-
public OptionEntry() {
- options = new HashMap<String,Option>();
+ options = new HashMap<String, Option>();
}
-
// ----------------------------------------------------------- Methods
-
public void addOption(String name, String value) {
Option option = new Option(name, value);
options.put(name, option);
@@ -45,17 +39,14 @@
public void addOption(Option option) {
options.put(option.getName(), option);
- }
+ }
-
public Option getOption(String name) {
return options.get(name);
}
-
- public Map<String,Option> getOptions() {
+ public Map<String, Option> getOptions() {
return options;
}
-
-} //OptionEntry
+} // OptionEntry
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/ProtocolMappings.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/ProtocolMappings.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/ProtocolMappings.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -4,36 +4,27 @@
*/
package org.perfsonar.base2.service.configuration;
-
import java.util.Map;
import java.util.HashMap;
import org.perfsonar.base2.service.exceptions.PerfSONARException;
-
public class ProtocolMappings extends Entry {
-
-
// ----------------------------------------------------------- Variables
+ private Map<String, ElementConf> elements = null;
- private Map<String,ElementConf> elements = null;
-
-
// -----------------------------------------------------------
Constructor
-
public ProtocolMappings() {
super();
name = Configuration.PROTOCOL_MAPPINGS;
- elements = new HashMap<String,ElementConf>();
+ elements = new HashMap<String, ElementConf>();
}
-
// ----------------------------------------------------------- Methods
-
public void addElement(ElementConf element) {
elements.put(element.getName(), element);
}
@@ -42,9 +33,8 @@
return elements.get(name);
}
- public Map<String,ElementConf> getElements() {
+ public Map<String, ElementConf> getElements() {
return elements;
}
-
-} //ProtocolMappings
+} // ProtocolMappings
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/SchedulingComponent.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/SchedulingComponent.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/SchedulingComponent.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -6,35 +6,27 @@
import org.perfsonar.base2.service.exceptions.PerfSONARException;
-
public abstract class SchedulingComponent extends Component {
-
// ----------------------------------------------------------- Variables
-
private Actions actions = new Actions();
-
// -----------------------------------------------------------
Constructor
-
public SchedulingComponent() {
super();
}
-
// ----------------------------------------------------------- Methods
-
public abstract void init() throws PerfSONARException;
public abstract void destroy() throws PerfSONARException;
-
public void addActions(Actions actions) {
- this.actions = actions;
+ this.actions = actions;
}
@@ -42,5 +34,4 @@
return actions;
}
-
-} //SchedulingComponent
\ No newline at end of file
+} // SchedulingComponent
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/Service.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/Service.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/Service.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -4,34 +4,26 @@
*/
package org.perfsonar.base2.service.configuration;
-
import java.util.Map;
import java.util.HashMap;
import org.perfsonar.base2.service.exceptions.PerfSONARException;
-
public class Service extends Entry {
-
// ----------------------------------------------------------- Variables
+ protected Map<String, Entry> childs = null;
- protected Map<String,Entry> childs = null;
-
-
// -----------------------------------------------------------
Constructor
-
public Service() {
super();
- childs = new HashMap<String,Entry>();
+ childs = new HashMap<String, Entry>();
}
-
// ----------------------------------------------------------- Methods
-
public void addEntry(Entry entry) {
childs.put(entry.getName(), entry);
}
@@ -40,9 +32,8 @@
return childs.get(name);
}
- public Map<String,Entry> getEntries() {
+ public Map<String, Entry> getEntries() {
return childs;
}
-
-} //Service
+} // Service
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/ConfigFilesCollection.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/ConfigFilesCollection.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/ConfigFilesCollection.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -19,101 +19,112 @@
/**
* Represents a collection of psbase-1 configuration files.
*
- * It is assumed that all configuration files matching
- * the regular expression <i>".*[.]properties"</i> are psbase-1
- * configuration files.
+ * It is assumed that all configuration files matching the regular expression
+ * <i>".*[.]properties"</i> are psbase-1 configuration files.
*
* @author <a
href="mailto:">Blazej
Pietrzak</a>
- *
+ *
*/
public class ConfigFilesCollection {
- private static final String RENAME_SUFFIX = ".remove";
- protected static final String DEFAULT_CONFIG_PATH = "perfsonar" +
File.separator + "conf";
- protected final File configPath;
- protected static final Pattern filenamePattern =
Pattern.compile(".*[.]properties([.]rpm.*)?");
+ private static final String RENAME_SUFFIX = ".remove";
+ protected static final String DEFAULT_CONFIG_PATH = "perfsonar" +
File.separator + "conf";
+ protected final File configPath;
+ protected static final Pattern FILENAMEPATTERN =
Pattern.compile(".*[.]properties([.]rpm.*)?");
- public ConfigFilesCollection(File configPath) {
- this.configPath = configPath;
- }
- public ConfigFilesCollection() {
- this.configPath = null;
- }
-
- private File getConfigPath() throws FileNotFoundException,
IOException {
- if (configPath != null)
- return configPath;
-
- try {
- return new File(getFullPath(DEFAULT_CONFIG_PATH));
- } catch (URISyntaxException ex) {
- throw new IOException(ex.getMessage(), ex);
- }
- }
- private URI getFullPath(String path) throws URISyntaxException,
FileNotFoundException {
- final URL result =
Thread.currentThread().getContextClassLoader().getResource(path);
- if (result == null)
- throw new FileNotFoundException("File: " + path + "
does not exist.");
- return result.toURI();
- }
-
- /**
- * @return a collection of psbase-1 configuration files
- * @throws IOException if I/O error occurs.
- */
- protected Collection<File> getFiles() throws IOException {
- final Collection<File> result = new ArrayList<File>();
- final File file = getConfigPath();
+ public ConfigFilesCollection(File configPath) {
+ this.configPath = configPath;
+ }
- if (!file.exists())
- return result;
- if (!file.isDirectory())
- throw new IOException("Invalid directory path: " +
configPath);
+ public ConfigFilesCollection() {
+ this.configPath = null;
+ }
+ private File getConfigPath() throws IOException {
+ if (configPath != null) {
+ return configPath;
+ }
+
+ try {
+ return new File(getFullPath(DEFAULT_CONFIG_PATH));
+ } catch (URISyntaxException ex) {
+ throw new IOException(ex.getMessage(), ex);
+ }
+ }
+
+ private URI getFullPath(String path) throws URISyntaxException,
FileNotFoundException {
+ final URL result =
Thread.currentThread().getContextClassLoader().getResource(path);
+ if (result == null) {
+ throw new FileNotFoundException("File: " + path + " does not
exist.");
+ }
+ return result.toURI();
+ }
+
+ /**
+ * @return a collection of psbase-1 configuration files
+ * @throws IOException
+ * if I/O error occurs.
+ */
+ protected Collection<File> getFiles() throws IOException {
+ final Collection<File> result = new ArrayList<File>();
+ final File file = getConfigPath();
+
+ if (!file.exists()) {
+ return result;
+ }
+ if (!file.isDirectory()) {
+ throw new IOException("Invalid directory path: " + configPath);
+ }
+
Collections.addAll(result, file.listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
return matchesFileName(file.getName());
}
}));
-
- return result;
- }
- protected boolean matchesFileName(String name) {
- return filenamePattern.matcher(name).matches();
- }
-
- /**
- * Returns the properties from all psbase-1 configuration files.
- *
- * @return properties from all configuration files
- * @throws IOException if I/O error occurs
- */
- public Properties loadProperties() throws IOException {
- final Properties result = new Properties();
- for (File file : getFiles()) {
- final Properties temp = new Properties();
- final InputStream in = new BufferedInputStream(new
FileInputStream(file));
- temp.load(in);
- in.close();
- result.putAll(temp);
- }
- return result;
- }
+ return result;
+ }
- /**
- * Renames the psbase-1 configuration files to *.remove
- *
- * @throws IOException if I/O error occurs
- */
- public void removeFiles() throws IOException {
- for (File file : getFiles()) {
- final File newFile = new File(file.getAbsolutePath()
+ RENAME_SUFFIX);
- if (newFile.exists())
- throw new IOException("Cannot rename the file
" + file.getAbsolutePath() + " to " + newFile.getName() + ", because the file
with the given name already exists.");
- if (!file.renameTo(newFile))
- throw new IOException("Cannot rename the file
" + file.getAbsolutePath() + " to " + newFile.getName());
- }
- }
+ protected boolean matchesFileName(String name) {
+ return FILENAMEPATTERN.matcher(name).matches();
+ }
+
+ /**
+ * Returns the properties from all psbase-1 configuration files.
+ *
+ * @return properties from all configuration files
+ * @throws IOException
+ * if I/O error occurs
+ */
+ public Properties loadProperties() throws IOException {
+ final Properties result = new Properties();
+ for (File file : getFiles()) {
+ final Properties temp = new Properties();
+ final InputStream in = new BufferedInputStream(new
FileInputStream(file));
+ temp.load(in);
+ in.close();
+ result.putAll(temp);
+ }
+ return result;
+ }
+
+ /**
+ * Renames the psbase-1 configuration files to *.remove
+ *
+ * @throws IOException
+ * if I/O error occurs
+ */
+ public void removeFiles() throws IOException {
+ for (File file : getFiles()) {
+ final File newFile = new File(file.getAbsolutePath() +
RENAME_SUFFIX);
+ if (newFile.exists()) {
+ throw new IOException("Cannot rename the file " +
file.getAbsolutePath() + " to " + newFile.getName()
+ + ", because the file with the given name already
exists.");
+ }
+ if (!file.renameTo(newFile)) {
+ throw new IOException("Cannot rename the file " +
file.getAbsolutePath() + " to " + newFile.getName());
+ }
+ }
+ }
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/MigratorComponent.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/MigratorComponent.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/MigratorComponent.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -5,7 +5,7 @@
import java.net.URISyntaxException;
import java.net.URL;
-import org.slf4j.Logger;
+import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.perfsonar.base2.service.configuration.Component;
import org.perfsonar.base2.service.exceptions.PerfSONARException;
@@ -14,100 +14,104 @@
* The component that rewrites configuration files from base-1 to base-2.
*
* @author <a
href="mailto:">Blazej
Pietrzak</a>
- *
+ *
*/
public class MigratorComponent extends Component {
- private static Logger logger =
LoggerFactory.getLogger(MigratorComponent.class);
-
- private TemplateEngine engine;
- private ConfigFilesCollection configFiles;
-
- /**
- * @see org.perfsonar.base2.service.configuration.Component#destroy()
- */
- @Override
- public void destroy() throws PerfSONARException { }
+ private static Logger logger =
LoggerFactory.getLogger(MigratorComponent.class);
- /**
- * @see org.perfsonar.base2.service.configuration.Component#init()
- */
- @Override
- public void init() throws PerfSONARException {
- if (getConfigDirectory() == null) {
- configFiles = new ConfigFilesCollection();
- logger.info("The directory for configuration files
that should be "
- + "rewritten to the new format was not
specified. The directory "
- + getDefaultConfigDirectory() + " will be
used instead.");
- } else {
- configFiles = new
ConfigFilesCollection(getConfigDirectory());
- logger.debug("Configuration files from " +
getConfigDirectory().getAbsolutePath()
- + " will be rewritten to the new format.");
- }
-
- try {
- setTemplateEngine(new
SimpleTemplateEngine(configFiles.loadProperties()));
- } catch (IOException ex) {
- logger.error(ex.getMessage(), ex);
- throw new PerfSONARException(ex.getMessage());
- }
- }
+ private TemplateEngine engine;
+ private ConfigFilesCollection configFiles;
- protected File getConfigDirectory() {
- if (getOption("config-directory") == null)
- return null;
- if (getOption("config-directory").getValue().length() <= 0)
- return null;
- return new File(getOption("config-directory").getValue());
- }
-
- protected void setTemplateEngine(TemplateEngine engine) {
- this.engine = engine;
- }
+ /**
+ * @see org.perfsonar.base2.service.configuration.Component#destroy()
+ */
+ @Override
+ public void destroy() throws PerfSONARException {
+ }
- /**
- * Converts psbase-1 configuration files to psbase-2 format.
- *
- * It reads template from configuration.xml.template file,
- * parses the psbase-1 configuration files with that template
- * and writes the result to the configuration.xml file.
- * If the configuration.xml file is successfully created
- * it then renames all the psbase-1 config to *.properties.remove
- *
- * @see org.perfsonar.base2.service.configuration.Component#run()
- */
- @Override
- public void run() throws PerfSONARException {
- try {
- if (configFiles.getFiles().size() <= 0) {
- logger.debug("psbase-1 configuration files
were not found.");
- return;
- }
- final String templateFilePath =
getFullPath("configuration.xml.template");
- final String configurationFile =
getFullPath("configuration.xml");
- logger.debug("Creating configuration file: "
- + configurationFile + " from template: " +
templateFilePath + "...");
-
- engine.createFileFromTemplate(new
File(templateFilePath), configurationFile);
-
- logger.info("Old configuration files were
successfully rewritten "
- + "to the new format. Please check, if the
rewritten configuration file ("
- + configurationFile + ") is valid."
- + " You must restart the service for the
changes to take effect.");
-
- configFiles.removeFiles();
- } catch (IOException ex) {
- logger.error(ex.getMessage(), ex);
- throw new PerfSONARException(ex.getMessage());
- } catch (URISyntaxException ex) {
- logger.error(ex.getMessage(), ex);
- throw new PerfSONARException(ex.getMessage());
- }
- }
-
- private String getFullPath(String fileName) throws URISyntaxException
{
- return new
File(Thread.currentThread().getContextClassLoader().getResource("perfsonar" +
File.separator + "conf" + File.separator +
fileName).toURI()).getAbsolutePath();
- }
- private URL getDefaultConfigDirectory() {
- return
Thread.currentThread().getContextClassLoader().getResource("perfsonar" +
File.separator + "conf");
- }
+ /**
+ * @see org.perfsonar.base2.service.configuration.Component#init()
+ */
+ @Override
+ public void init() throws PerfSONARException {
+ if (getConfigDirectory() == null) {
+ configFiles = new ConfigFilesCollection();
+ logger.info("The directory for configuration files that should
be "
+ + "rewritten to the new format was not specified. The
directory " + getDefaultConfigDirectory()
+ + " will be used instead.");
+ } else {
+ configFiles = new ConfigFilesCollection(getConfigDirectory());
+ logger.debug("Configuration files from " +
getConfigDirectory().getAbsolutePath()
+ + " will be rewritten to the new format.");
+ }
+
+ try {
+ setTemplateEngine(new
SimpleTemplateEngine(configFiles.loadProperties()));
+ } catch (IOException ex) {
+ logger.error(ex.getMessage(), ex);
+ throw new PerfSONARException(ex.getMessage());
+ }
+ }
+
+ protected File getConfigDirectory() {
+ if (getOption("config-directory") == null) {
+ return null;
+ }
+ if (getOption("config-directory").getValue().length() <= 0) {
+ return null;
+ }
+ return new File(getOption("config-directory").getValue());
+ }
+
+ protected void setTemplateEngine(TemplateEngine engine) {
+ this.engine = engine;
+ }
+
+ /**
+ * Converts psbase-1 configuration files to psbase-2 format.
+ *
+ * It reads template from configuration.xml.template file, parses the
+ * psbase-1 configuration files with that template and writes the result
to
+ * the configuration.xml file. If the configuration.xml file is
successfully
+ * created it then renames all the psbase-1 config to *.properties.remove
+ *
+ * @see org.perfsonar.base2.service.configuration.Component#run()
+ */
+ @Override
+ public void run() throws PerfSONARException {
+ try {
+ if (configFiles.getFiles().size() <= 0) {
+ logger.debug("psbase-1 configuration files were not found.");
+ return;
+ }
+ final String templateFilePath =
getFullPath("configuration.xml.template");
+ final String configurationFile =
getFullPath("configuration.xml");
+ logger.debug("Creating configuration file: " + configurationFile
+ " from template: " + templateFilePath
+ + "...");
+
+ engine.createFileFromTemplate(new File(templateFilePath),
configurationFile);
+
+ logger.info("Old configuration files were successfully rewritten
"
+ + "to the new format. Please check, if the rewritten
configuration file (" + configurationFile
+ + ") is valid." + " You must restart the service for the
changes to take effect.");
+
+ configFiles.removeFiles();
+ } catch (IOException ex) {
+ logger.error(ex.getMessage(), ex);
+ throw new PerfSONARException(ex.getMessage());
+ } catch (URISyntaxException ex) {
+ logger.error(ex.getMessage(), ex);
+ throw new PerfSONARException(ex.getMessage());
+ }
+ }
+
+ private String getFullPath(String fileName) throws URISyntaxException {
+ return new File(Thread.currentThread().getContextClassLoader()
+ .getResource("perfsonar" + File.separator + "conf" +
File.separator + fileName).toURI())
+ .getAbsolutePath();
+ }
+
+ private URL getDefaultConfigDirectory() {
+ return
Thread.currentThread().getContextClassLoader().getResource("perfsonar" +
File.separator + "conf");
+ }
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/SimpleTemplateEngine.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/SimpleTemplateEngine.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/SimpleTemplateEngine.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -16,92 +16,116 @@
*
* The following expressions are implemented in the template engine:
* <ul>
- * <li>property expressions <code>${property_name}</code></li>
- * <li>function expressions <code>#function-name(arg1 "value1" arg2
"value2" .. argN "valueN")</code></li>
- * <li>loop expressions <code>#for(var variable string "string" split
"regular expression")...#end()</code></li>
+ * <li>property expressions <code>${property_name}</code></li>
+ * <li>function expressions
+ * <code>#function-name(arg1 "value1" arg2 "value2" .. argN
"valueN")</code></li>
+ * <li>loop expressions
+ * <code>#for(var variable string "string" split "regular
expression")...#end()</code>
+ * </li>
* </ul>
*
- * <p>Property expressions are expressions where the variable is substituted
by its value.
- * Properties are provided in the constructor of TemplateEngine class.</p>
+ * <p>
+ * Property expressions are expressions where the variable is substituted by
its
+ * value. Properties are provided in the constructor of TemplateEngine class.
+ * </p>
*
- * <p>Function expressions are used to perform a function.
- * The following functions are supported:<br />
+ * <p>
+ * Function expressions are used to perform a function. The following
functions
+ * are supported:<br />
* <ul>
- * <li><code>replace</code> - replaces a substring specified with regular
expression with another string</li>
- * <li><code>indexer</code> - writes a current index value and increments
the index</li>
+ * <li><code>replace</code> - replaces a substring specified with regular
+ * expression with another string</li>
+ * <li><code>indexer</code> - writes a current index value and increments the
+ * index</li>
* </ul>
*
* <i>Replace</i> function is represented with the following syntax:<br />
- * <code>#replace(string </code><i>"string"</i><code> regexp
</code><i>"regexp"</i><code> with </code><i>"replacement
string"</i><code>)</code><br />
+ * <code>#replace(string </code><i>"string"</i><code> regexp </code>
+ * <i>"regexp"</i><code> with </code><i>"replacement
string"</i><code>)</code><br />
* where:<br />
* <ul>
- * <li><i>string</i> - the string on which the replace function will be
performed</li>
- * <li><i>regexp</i> - the regular expression describing the substring to
replace</li>
- * <li><i>with</i> - the replacement string</li>
+ * <li><i>string</i> - the string on which the replace function will be
+ * performed</li>
+ * <li><i>regexp</i> - the regular expression describing the substring to
+ * replace</li>
+ * <li><i>with</i> - the replacement string</li>
* </ul>
* Example:<br />
* #replace(string "http://somewhere" regexp "http" with "https")<br />
- * <br />
+ * <br />
* <i>Indexer</i> function is represented with the following syntax:<br />
* <code>#indexer()</code><br />
* </p>
*
- * <p>Loop expression is used to iterate substrings that are a result of
- * a string split.<br />
+ * <p>
+ * Loop expression is used to iterate substrings that are a result of a
string
+ * split.<br />
* Loop expression is represented by the following expression:<br />
- * <code>#for(var </code><i>variable-name</i><code> string </code><i>"string
to be splited"</i><code> split </code><i>"regular
expression"</i><code>)</code><br />
+ * <code>#for(var </code><i>variable-name</i><code> string </code>
+ * <i>"string to be splited"</i><code> split </code><i>"regular
expression"</i>
+ * <code>)</code><br />
* <code> ... </code><br />
* <code>#end()</code><br />
* <br />
* where: <br />
* <ul>
- * <li><i>variable-name</i> is a name of the property that stores the
substring<br /></li>
- * <li><i>string to be splited</i> is the string on which the split
function will be executed<br /></li>
- * <li><i>regular expression</i> is a regexp used to split the string<br
/></li>
+ * <li><i>variable-name</i> is a name of the property that stores the
substring<br />
+ * </li>
+ * <li><i>string to be splited</i> is the string on which the split function
+ * will be executed<br />
+ * </li>
+ * <li><i>regular expression</i> is a regexp used to split the string<br />
+ * </li>
* </ul>
* <br />
* Example:<br />
* <code>#for(var lsAddress string "${service.r.ls_url}" split
",")</code><br />
- * <code><option name="lsAddress-#indexer()" value="${lsAddress}"
/></code><br />
+ * <code><option name="lsAddress-#indexer()" value="${lsAddress}"
/></code>
+ * <br />
* <code>#end()</code><br />
*
* @author <a
href="mailto:">Blazej
Pietrzak</a>
- *
+ *
*/
public class SimpleTemplateEngine implements TemplateEngine {
- private final Interpreter interpreter;
-
- /**
- * Creates the engine.
- *
- * @param props properties store the variables and their values
- */
- public SimpleTemplateEngine(Properties props) {
- interpreter = new Interpreter(props);
- }
-
- /**
- * @see
org.perfsonar.base2.service.configuration.migration.TemplateEngine#createFileFromTemplate(java.io.File,
java.lang.String)
- */
- public File createFileFromTemplate(File template, String newFileName)
throws IOException {
- if (!template.exists())
- throw new FileNotFoundException("File: " +
template.getAbsolutePath() + " does not exist.");
- if (!template.isFile())
- throw new IOException("Template must be an existing
file.");
- final File result = new File(newFileName);
- if (result.exists() && !result.isFile())
- throw new IOException("Output must be a file.");
-
- final BufferedReader reader = new BufferedReader(new
FileReader(template));
- final BufferedWriter writer = new BufferedWriter(new
FileWriter(result));
- for (String line = reader.readLine(); line != null; line =
reader.readLine()) {
- interpreter.interpret(writer, line);
- writer.newLine();
- }
- writer.flush();
- writer.close();
- reader.close();
-
- return result;
- }
+ private final Interpreter interpreter;
+
+ /**
+ * Creates the engine.
+ *
+ * @param props
+ * properties store the variables and their values
+ */
+ public SimpleTemplateEngine(Properties props) {
+ interpreter = new Interpreter(props);
+ }
+
+ /**
+ * @see
org.perfsonar.base2.service.configuration.migration.TemplateEngine#createFileFromTemplate(java.io.File,
+ * java.lang.String)
+ */
+ public File createFileFromTemplate(File template, String newFileName)
throws IOException {
+ if (!template.exists()) {
+ throw new FileNotFoundException("File: " +
template.getAbsolutePath() + " does not exist.");
+ }
+ if (!template.isFile()) {
+ throw new IOException("Template must be an existing file.");
+ }
+ final File result = new File(newFileName);
+ if (result.exists() && !result.isFile()) {
+ throw new IOException("Output must be a file.");
+ }
+
+ final BufferedReader reader = new BufferedReader(new
FileReader(template));
+ final BufferedWriter writer = new BufferedWriter(new
FileWriter(result));
+ for (String line = reader.readLine(); line != null; line =
reader.readLine()) {
+ interpreter.interpret(writer, line);
+ writer.newLine();
+ }
+ writer.flush();
+ writer.close();
+ reader.close();
+
+ return result;
+ }
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/TemplateEngine.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/TemplateEngine.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/TemplateEngine.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -4,22 +4,24 @@
import java.io.IOException;
/**
- * Interface for template engines that are used to create a file
- * from the template.
- *
+ * Interface for template engines that are used to create a file from the
+ * template.
+ *
* @author <a
href="mailto:">Blazej
Pietrzak</a>
*/
public interface TemplateEngine {
- /**
- * Creates a file from the template.
- *
- * @param template template file
- * @param newFileName name of the file to be created
- * @return file created from the template
- * @throws IOException if I/O error occurs
- */
- public File createFileFromTemplate(File template, String newFileName)
- throws IOException;
+ /**
+ * Creates a file from the template.
+ *
+ * @param template
+ * template file
+ * @param newFileName
+ * name of the file to be created
+ * @return file created from the template
+ * @throws IOException
+ * if I/O error occurs
+ */
+ File createFileFromTemplate(File template, String newFileName) throws
IOException;
-}
\ No newline at end of file
+}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/grammar/BaseExpression.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/grammar/BaseExpression.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/grammar/BaseExpression.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -10,42 +10,49 @@
* @author <a
href="mailto:">Blazej
Pietrzak</a>
*/
public abstract class BaseExpression implements Expression {
- protected abstract Pattern getPattern();
- protected abstract void interpret();
-
- private Matcher regexpMatcher;
- protected Matcher getRegexpMatcher() {
- return regexpMatcher;
- }
- protected void setRegexpMatcher(Matcher value) {
- regexpMatcher = value;
- }
-
- private final StringBuffer buffer = new StringBuffer();
+ protected abstract Pattern getPattern();
- /**
- * @see
org.perfsonar.service.configuration.migration.Expression#interpret(java.lang.String)
- */
- @Override
- public String interpret(String line) throws IOException {
- buffer.delete(0, buffer.length());
- setRegexpMatcher(getPattern().matcher(line));
- while (getRegexpMatcher().find())
- interpret();
-
- getRegexpMatcher().appendTail(buffer);
- return buffer.toString();
- }
-
- /**
- * Appends the string provided as an argument to the interpreted line.
- * @param string to be appended to the resultant string representing
the interpreted input.
- */
- protected void append(String string) {
- getRegexpMatcher().appendReplacement(buffer, encode(string));
- }
+ protected abstract void interpret();
- private String encode(String string) {
- return string.replace("$", "\\$");
- }
+ private Matcher regexpMatcher;
+
+ protected Matcher getRegexpMatcher() {
+ return regexpMatcher;
+ }
+
+ protected void setRegexpMatcher(Matcher value) {
+ regexpMatcher = value;
+ }
+
+ private final StringBuffer buffer = new StringBuffer();
+
+ /**
+ * @see
org.perfsonar.service.configuration.migration.Expression#interpret(java.lang.String)
+ */
+ @Override
+ public String interpret(String line) throws IOException {
+ buffer.delete(0, buffer.length());
+ setRegexpMatcher(getPattern().matcher(line));
+ while (getRegexpMatcher().find()) {
+ interpret();
+ }
+
+ getRegexpMatcher().appendTail(buffer);
+ return buffer.toString();
+ }
+
+ /**
+ * Appends the string provided as an argument to the interpreted line.
+ *
+ * @param string
+ * to be appended to the resultant string representing the
+ * interpreted input.
+ */
+ protected void append(String string) {
+ getRegexpMatcher().appendReplacement(buffer, encode(string));
+ }
+
+ private String encode(String string) {
+ return string.replace("$", "\\$");
+ }
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/grammar/Expression.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/grammar/Expression.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/grammar/Expression.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -6,16 +6,18 @@
* Represents the expression in the grammar.
*
* @author <a
href="mailto:">Blazej
Pietrzak</a>
- *
+ *
*/
public interface Expression {
-
- /**
- * Interprets the expression provided as an argument.
- *
- * @param line line to be interpreted
- * @return interpreted line
- * @throws IOException when input/output error occurs
- */
- String interpret(String line) throws IOException;
-}
\ No newline at end of file
+
+ /**
+ * Interprets the expression provided as an argument.
+ *
+ * @param line
+ * line to be interpreted
+ * @return interpreted line
+ * @throws IOException
+ * when input/output error occurs
+ */
+ String interpret(String line) throws IOException;
+}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/grammar/Interpreter.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/grammar/Interpreter.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/grammar/Interpreter.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -4,28 +4,31 @@
import java.io.IOException;
import java.util.Properties;
-
/**
* Facade for the grammar expressions.
*
* @author <a
href="mailto:">Blazej
Pietrzak</a>
- *
+ *
*/
public class Interpreter {
- private final LoopExpression loopExpr;
- public Interpreter(Properties properties) {
- loopExpr = new LoopExpression(properties);
- }
+ private final LoopExpression loopExpr;
- /**
- * Interprets the line and writes the result in the writer.
- *
- * @param writer where to write the interpreted result
- * @param line line to be interpreted
- * @throws IOException if I/O error occurs
- */
- public void interpret(BufferedWriter writer, String line) throws
IOException {
- loopExpr.interpret(writer, line);
- }
+ public Interpreter(Properties properties) {
+ loopExpr = new LoopExpression(properties);
+ }
+
+ /**
+ * Interprets the line and writes the result in the writer.
+ *
+ * @param writer
+ * where to write the interpreted result
+ * @param line
+ * line to be interpreted
+ * @throws IOException
+ * if I/O error occurs
+ */
+ public void interpret(BufferedWriter writer, String line) throws
IOException {
+ loopExpr.interpret(writer, line);
+ }
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/grammar/Loop.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/grammar/Loop.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/grammar/Loop.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -10,46 +10,47 @@
* @author <a
href="mailto:">Blazej
Pietrzak</a>
*/
class Loop {
- private final Matcher matcher;
- protected Loop(Matcher matcher) {
- this.matcher = matcher;
- }
+ private final Matcher matcher;
- protected String getVariableName() {
- return matcher.group(2);
- }
+ protected Loop(Matcher matcher) {
+ this.matcher = matcher;
+ }
- protected String getString() {
- return matcher.group(3);
- }
+ protected String getVariableName() {
+ return matcher.group(2);
+ }
- protected String getSplitRegexp() {
- return matcher.group(4);
- }
+ protected String getString() {
+ return matcher.group(3);
+ }
- private boolean insideLoop = false;
+ protected String getSplitRegexp() {
+ return matcher.group(4);
+ }
- protected boolean isEndStatement() {
- if (matcher.group().contains("#end()")) {
- insideLoop = false;
- return true;
- }
- return false;
- }
+ private boolean insideLoop = false;
- protected boolean isForStatement() {
- if (matcher.group().startsWith("#for(")) {
- insideLoop = true;
- return true;
- }
- return false;
- }
+ protected boolean isEndStatement() {
+ if (matcher.group().contains("#end()")) {
+ insideLoop = false;
+ return true;
+ }
+ return false;
+ }
- protected boolean isInsideLoop() {
- return insideLoop;
- }
+ protected boolean isForStatement() {
+ if (matcher.group().startsWith("#for(")) {
+ insideLoop = true;
+ return true;
+ }
+ return false;
+ }
- public String[] split() {
- return getString().split(getSplitRegexp());
- }
+ protected boolean isInsideLoop() {
+ return insideLoop;
+ }
+
+ public String[] split() {
+ return getString().split(getSplitRegexp());
+ }
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/grammar/LoopExpression.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/grammar/LoopExpression.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/grammar/LoopExpression.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -10,136 +10,150 @@
import
org.perfsonar.base2.service.configuration.migration.grammar.function.FunctionExpression;
-
/**
- * Represents the loop expression.
- * Loop expression is used to iterate substrings that are a result of
- * a string split.
+ * Represents the loop expression. Loop expression is used to iterate
substrings
+ * that are a result of a string split.
*
* Loop expression is represented by the following expression:
- * <code>#for(var </code><i>variable-name</i><code> string </code><i>"string
to be splited"</i><code split </code><i>"regular
expression"</i><code>)</code><br />
+ * <code>#for(var </code><i>variable-name</i><code> string </code>
+ * <i>"string to be split"</i><code> split </code><i>"regular expression"</i>
+ * <code>)</code><br />
* <code> ... </code><br />
* <code>#end()</code><br />
* <br />
* where: <br />
* <i>variable-name</i> is a name of the property that stores the
substring<br />
- * <i>string to be splited</i> is the string on which the split function
will be executed<br />
+ * <i>string to be splited</i> is the string on which the split function
will be
+ * executed<br />
* <i>regular expression</i> is a regexp used to split the string<br />
* <br />
* Example:<br />
* <code>#for(var lsAddress string "${service.r.ls_url}" split
",")</code><br />
- * <code><option name="lsAddress-#indexer()" value="${lsAddress}"
/></code><br />
+ * <code><option name="lsAddress-#indexer()" value="${lsAddress}"
/></code>
+ * <br />
* <code>#end()</code><br />
*
* @author <a
href="mailto:">Blazej
Pietrzak</a>
*/
public class LoopExpression {
- private final static Pattern loopPattern =
Pattern.compile("([#]for\\(var\\s([a-zA-Z0-9_]+)\\sstring\\s\"(.+)\"\\ssplit\\s\"(.+)\"\\))|([#]end\\(\\))");
- protected Pattern getPattern() {
- return loopPattern;
- }
-
- private List<Expression> expressions = new ArrayList<Expression>();
- public LoopExpression(Properties props) {
- expressions.add(new PropertyExpression(props));
- expressions.add(new FunctionExpression());
- }
-
- private boolean insideLoop = false;
- private Loop loop;
+ private static final Pattern LOOP_PATTERN = Pattern
+
.compile("([#]for\\(var\\s([a-zA-Z0-9_]+)\\sstring\\s\"(.+)\"\\ssplit\\s\"(.+)\"\\))|([#]end\\(\\))");
- protected boolean isEndStatement() {
- if (loop == null)
- return false;
- if (loop.isEndStatement()) {
- insideLoop = false;
- return true;
- }
- return false;
- }
+ protected Pattern getPattern() {
+ return LOOP_PATTERN;
+ }
- protected boolean isForStatement() {
- if (loop == null)
- return false;
- if (loop.isForStatement()) {
- insideLoop = true;
- return true;
- }
- return false;
- }
+ private List<Expression> expressions = new ArrayList<Expression>();
- private final List<String> lines = new ArrayList<String>();
- private String[] strings = new String[0];
- private String varName = null;
+ public LoopExpression(Properties props) {
+ expressions.add(new PropertyExpression(props));
+ expressions.add(new FunctionExpression());
+ }
- /**
- * Interprets the line and writes the result in the writer.
- *
- * @param writer where to write the interpreted result
- * @param line line to be interpreted
- * @throws IOException if I/O error occurs
- */
- public void interpret(Writer writer, String line) throws IOException {
- filter(writer, interpretProperty(line),
getPattern().matcher(interpretProperty(line)));
- }
+ private boolean insideLoop = false;
+ private Loop loop;
- private void filter(Writer writer, String line,
- final Matcher regexpMatcher) throws IOException {
-
- final boolean isLoopStatement = regexpMatcher.find();
- if (isLoopStatement)
- loop = new Loop(regexpMatcher);
- else
- loop = null;
-
- if (!insideLoop && !isLoopStatement)
- writer.write(interpret(line));
- else if (isForStatement()) {
- this.strings = loop.split();
- final StringBuffer buffer = new StringBuffer();
- regexpMatcher.appendReplacement(buffer, "");
- writer.write(interpret(buffer.toString()));
- buffer.delete(0, buffer.length());
- regexpMatcher.appendTail(buffer);
- varName = loop.getVariableName();
- filter(writer, buffer.toString(), regexpMatcher);
- } else if (isEndStatement()) {
- final StringBuffer buffer = new StringBuffer();
- regexpMatcher.appendReplacement(buffer, "");
- if (buffer.length() > 0)
- lines.add(buffer.toString());
+ protected boolean isEndStatement() {
+ if (loop == null) {
+ return false;
+ }
+ if (loop.isEndStatement()) {
+ insideLoop = false;
+ return true;
+ }
+ return false;
+ }
+
+ protected boolean isForStatement() {
+ if (loop == null) {
+ return false;
+ }
+ if (loop.isForStatement()) {
+ insideLoop = true;
+ return true;
+ }
+ return false;
+ }
+
+ private final List<String> lines = new ArrayList<String>();
+ private String[] strings = new String[0];
+ private String varName = null;
+
+ /**
+ * Interprets the line and writes the result in the writer.
+ *
+ * @param writer
+ * where to write the interpreted result
+ * @param line
+ * line to be interpreted
+ * @throws IOException
+ * if I/O error occurs
+ */
+ public void interpret(Writer writer, String line) throws IOException {
+ filter(writer, interpretProperty(line),
getPattern().matcher(interpretProperty(line)));
+ }
+
+ private void filter(Writer writer, String line, final Matcher
regexpMatcher) throws IOException {
+
+ final boolean isLoopStatement = regexpMatcher.find();
+ if (isLoopStatement) {
+ loop = new Loop(regexpMatcher);
+ } else {
+ loop = null;
+ }
+
+ if (!insideLoop && !isLoopStatement) {
+ writer.write(interpret(line));
+ } else if (isForStatement()) {
+ this.strings = loop.split();
+ final StringBuffer buffer = new StringBuffer();
+ regexpMatcher.appendReplacement(buffer, "");
+ writer.write(interpret(buffer.toString()));
+ buffer.delete(0, buffer.length());
+ regexpMatcher.appendTail(buffer);
+ varName = loop.getVariableName();
+ filter(writer, buffer.toString(), regexpMatcher);
+ } else if (isEndStatement()) {
+ final StringBuffer buffer = new StringBuffer();
+ regexpMatcher.appendReplacement(buffer, "");
+ if (buffer.length() > 0) {
+ lines.add(buffer.toString());
+ }
for (String string : strings) {
((PropertyExpression)
expressions.get(0)).setProperty(varName, string);
boolean first = true;
for (String tempLine : lines) {
- if (!first)
+ if (!first) {
newLine(writer);
- else
+ } else {
first = false;
+ }
writer.write(interpret(tempLine));
}
((PropertyExpression)
expressions.get(0)).removeProperty(varName);
}
- buffer.delete(0, buffer.length());
- regexpMatcher.appendTail(buffer);
- filter(writer, buffer.toString(), regexpMatcher);
- } else if (insideLoop)
- lines.add(line);
- }
-
- private void newLine(Writer writer) throws IOException {
- writer.write(System.getProperty("line.separator"));
- }
-
- private String interpret(String line) throws IOException {
- String result = line;
- for (Expression expr : expressions)
- result = expr.interpret(result);
-
- return result;
- }
-
- private String interpretProperty(String line) throws IOException {
- return expressions.get(0).interpret(line);
- }
+ buffer.delete(0, buffer.length());
+ regexpMatcher.appendTail(buffer);
+ filter(writer, buffer.toString(), regexpMatcher);
+ } else if (insideLoop) {
+ lines.add(line);
+ }
+ }
+
+ private void newLine(Writer writer) throws IOException {
+ writer.write(System.getProperty("line.separator"));
+ }
+
+ private String interpret(String line) throws IOException {
+ String result = line;
+ for (Expression expr : expressions) {
+ result = expr.interpret(result);
+ }
+
+ return result;
+ }
+
+ private String interpretProperty(String line) throws IOException {
+ return expressions.get(0).interpret(line);
+ }
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/grammar/PropertyExpression.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/grammar/PropertyExpression.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/grammar/PropertyExpression.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -6,9 +6,8 @@
/**
* Represents the property expression.
*
- * Property expressions are the expressions where the variable
- * is substituted by its value.
- * Properties are read from the configuration files.
+ * Property expressions are the expressions where the variable is
substituted by
+ * its value. Properties are read from the configuration files.
*
* Properties are represented with the following expression:
* <code>${property_name}</code>
@@ -17,32 +16,33 @@
*/
public class PropertyExpression extends BaseExpression {
- private final Pattern propertyPattern =
Pattern.compile("[$]\\{([a-zA-Z0-9_.]+)\\}");
- private final Properties props;
+ private final Pattern propertyPattern =
Pattern.compile("[$]\\{([a-zA-Z0-9_.]+)\\}");
+ private final Properties props;
- public PropertyExpression(Properties props) {
- this.props = props;
- }
+ public PropertyExpression(Properties props) {
+ this.props = props;
+ }
- protected Pattern getPattern() {
- return propertyPattern;
- }
+ protected Pattern getPattern() {
+ return propertyPattern;
+ }
- /**
- * @see
org.perfsonar.base2.service.configuration.migration.grammar.BaseExpression#interpret()
- */
- @Override
- public void interpret() {
- if (props.getProperty(getRegexpMatcher().group(1)) != null)
-
append(props.getProperty(getRegexpMatcher().group(1)));
- }
+ /**
+ * @see
org.perfsonar.base2.service.configuration.migration.grammar.BaseExpression#interpret()
+ */
+ @Override
+ public void interpret() {
+ if (props.getProperty(getRegexpMatcher().group(1)) != null) {
+ append(props.getProperty(getRegexpMatcher().group(1)));
+ }
+ }
- public void setProperty(String name, String value) {
- props.setProperty(name, value);
- }
+ public void setProperty(String name, String value) {
+ props.setProperty(name, value);
+ }
- public void removeProperty(String name) {
- props.remove(name);
- }
+ public void removeProperty(String name) {
+ props.remove(name);
+ }
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/grammar/function/Function.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/grammar/function/Function.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/grammar/function/Function.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -11,63 +11,71 @@
* Used internally by the FunctionExpression class.
*
* @author <a
href="mailto:>Blazej
Pietrzak</a>
- *
+ *
*/
class Function {
- interface Executor {
- String execute(Function function);
- void reset();
- }
-
- private final Matcher functionMatcher;
- protected Matcher getFunctionMatcher() {
- return functionMatcher;
- }
-
- private static final Pattern argsPattern =
Pattern.compile("([a-zA-Z]+)\\s+\"([^\"]*)\"");
- private final Map<String, Executor> executors = new Hashtable<String,
Executor>();
-
- protected Function(Matcher function) {
- this.functionMatcher = function;
-
- executors.put("replace", new ReplaceFunction());
- executors.put("indexer", new IndexerFunction());
- }
-
- protected void reset() {
- for (Executor exec : executors.values())
- exec.reset();
- }
-
- /**
- * @return function name
- */
- public String getName() {
- return getFunctionMatcher().group(1);
- }
-
- /**
- * @return map of function's arguments where the key is the argument
name and the value is argument value
- */
- public Map<String, String> getArguments() {
- final Map<String, String> result = new Hashtable<String,
String>();
- final Matcher args =
argsPattern.matcher(getFunctionMatcher().group(2));
-
- while (args.find())
- for (int i = 0; i < args.groupCount() - 1; i += 2)
- result.put(args.group(i + 1), args.group(i +
2));
-
- return result;
- }
+ interface Executor {
+ String execute(Function function);
- /**
- * Executes the function.
- * @return result of the function
- */
- public String execute() {
- if (executors.get(getName()) == null)
- return getFunctionMatcher().group();
-
- return executors.get(getName()).execute(this);
- }
+ void reset();
+ }
+
+ private final Matcher functionMatcher;
+
+ protected Matcher getFunctionMatcher() {
+ return functionMatcher;
+ }
+
+ private static final Pattern ARGS_PATTERN =
Pattern.compile("([a-zA-Z]+)\\s+\"([^\"]*)\"");
+ private final Map<String, Executor> executors = new Hashtable<String,
Executor>();
+
+ protected Function(Matcher function) {
+ this.functionMatcher = function;
+
+ executors.put("replace", new ReplaceFunction());
+ executors.put("indexer", new IndexerFunction());
+ }
+
+ protected void reset() {
+ for (Executor exec : executors.values()) {
+ exec.reset();
+ }
+ }
+
+ /**
+ * @return function name
+ */
+ public String getName() {
+ return getFunctionMatcher().group(1);
+ }
+
+ /**
+ * @return map of function's arguments where the key is the argument name
+ * and the value is argument value
+ */
+ public Map<String, String> getArguments() {
+ final Map<String, String> result = new Hashtable<String, String>();
+ final Matcher args =
ARGS_PATTERN.matcher(getFunctionMatcher().group(2));
+
+ while (args.find()) {
+ for (int i = 0; i < args.groupCount() - 1; i += 2) {
+ result.put(args.group(i + 1), args.group(i + 2));
+ }
+ }
+
+ return result;
+ }
+
+ /**
+ * Executes the function.
+ *
+ * @return result of the function
+ */
+ public String execute() {
+ if (executors.get(getName()) == null) {
+ return getFunctionMatcher().group();
+ }
+
+ return executors.get(getName()).execute(this);
+ }
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/grammar/function/FunctionExpression.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/grammar/function/FunctionExpression.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/grammar/function/FunctionExpression.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -7,33 +7,36 @@
/**
* Represents the function expression.
*
- * Function expressions are used to perform a function.
- * The following functions are supported:
+ * Function expressions are used to perform a function. The following
functions
+ * are supported:
* <ul>
- * <li><code>replace</code> - replaces a substring specified with regular
expression with another string</li>
- * <li><code>indexer</code> - writes a current index value and increments
the index</li>
+ * <li><code>replace</code> - replaces a substring specified with regular
+ * expression with another string</li>
+ * <li><code>indexer</code> - writes a current index value and increments the
+ * index</li>
* </ul>
*
* <i>Replace</i> function is represented with the following syntax:<br />
- * <code>#replace(string </code><i>"string"</i><code> regexp
</code><i>"reg-exp"</i><code> with </code><i>"replacement
string"</i><code>)</code><br />
+ * <code>#replace(string </code><i>"string"</i><code> regexp </code>
+ * <i>"reg-exp"</i><code> with </code><i>"replacement
string"</i><code>)</code><br />
* where:<br />
* <i>string</i> - the string on which the replace function will be performed
* <i>reg-exp</i> - the regular expression describing the substring to
replace
- * <i>with</i> - the replacement string
- * <i>Indexer</i> function is represented with the following syntax:<br />
+ * <i>with</i> - the replacement string <i>Indexer</i> function is
represented
+ * with the following syntax:<br />
* <code>#indexer</code><br />
*
* @author <a
href="mailto:>Blazej
Pietrzak</a>
- *
+ *
*/
public class FunctionExpression extends BaseExpression {
- private final Pattern functionPattern =
Pattern.compile("[#]([a-zA-Z0-9_]+)\\((([a-zA-Z]+\\s+\"[^\"]*\"\\s*)*)\\)");
-
- protected Pattern getPattern() {
- return functionPattern;
- }
-
- public void interpret() {
- append(new Function(getRegexpMatcher()).execute());
- }
+ private final Pattern functionPattern =
Pattern.compile("[#]([a-zA-Z0-9_]+)\\((([a-zA-Z]+\\s+\"[^\"]*\"\\s*)*)\\)");
+
+ protected Pattern getPattern() {
+ return functionPattern;
+ }
+
+ public void interpret() {
+ append(new Function(getRegexpMatcher()).execute());
+ }
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/grammar/function/IndexerFunction.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/grammar/function/IndexerFunction.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/grammar/function/IndexerFunction.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -5,34 +5,36 @@
/**
* Represents the indexer function.
*
- * Used internally by the FunctionExpression class.
+ * Used internally by the FunctionExpression class.
*
* @author <a
href="mailto:">Blazej
Pietrzak</a>
- *
+ *
*/
public class IndexerFunction implements Executor {
- public IndexerFunction() { }
-
- private static int index = 0;
+ public IndexerFunction() {
+ }
- /**
- * @see
org.perfsonar.service.configuration.migration.grammar.Function.Executor#execute()
- */
- @Override
- public String execute(Function function) {
- if (function.getArguments().size() != 0)
- return function.getFunctionMatcher().group();
-
- index++;
- return Integer.toString(index);
- }
+ private static int index = 0;
- /**
- * @see
org.perfsonar.base2.service.configuration.migration.grammar.function.Function.Executor#reset()
- */
- @Override
- public void reset() {
- index = 0;
- }
+ /**
+ * @see
org.perfsonar.service.configuration.migration.grammar.Function.Executor#execute()
+ */
+ @Override
+ public String execute(Function function) {
+ if (function.getArguments().size() != 0) {
+ return function.getFunctionMatcher().group();
+ }
+ index++;
+ return Integer.toString(index);
+ }
+
+ /**
+ * @see
org.perfsonar.base2.service.configuration.migration.grammar.function.Function.Executor#reset()
+ */
+ @Override
+ public void reset() {
+ index = 0;
+ }
+
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/grammar/function/ReplaceFunction.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/grammar/function/ReplaceFunction.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/configuration/migration/grammar/function/ReplaceFunction.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -12,27 +12,30 @@
* @author <a
href="">Blazej
Pietrzak</a>
*/
class ReplaceFunction implements Executor {
- protected ReplaceFunction() { }
+ protected ReplaceFunction() {
+ }
- /**
- * Invokes replaceAll method from the String class.
- *
- * @see
org.perfsonar.service.configuration.migration.grammar.Function.Executor#execute()
- */
- @Override
- public String execute(Function function) {
- final Map<String, String> args = function.getArguments();
- if (args.size() < 3)
- return function.getFunctionMatcher().group();
-
- return args.get("string").replaceAll(args.get("regexp"),
args.get("with"));
- }
+ /**
+ * Invokes replaceAll method from the String class.
+ *
+ * @see
org.perfsonar.service.configuration.migration.grammar.Function.Executor#execute()
+ */
+ @Override
+ public String execute(Function function) {
+ final Map<String, String> args = function.getArguments();
+ if (args.size() < 3) {
+ return function.getFunctionMatcher().group();
+ }
- /**
- * Does nothing.
- *
- * @see
org.perfsonar.base2.service.configuration.migration.grammar.function.Function.Executor#reset()
- */
- @Override
- public void reset() { }
+ return args.get("string").replaceAll(args.get("regexp"),
args.get("with"));
+ }
+
+ /**
+ * Does nothing.
+ *
+ * @see
org.perfsonar.base2.service.configuration.migration.grammar.function.Function.Executor#reset()
+ */
+ @Override
+ public void reset() {
+ }
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/exceptions/PerfSONARException.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/exceptions/PerfSONARException.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/exceptions/PerfSONARException.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -6,149 +6,137 @@
* All other Exception classes should be derived from this class.
*
* @author Maciej Glowiak
- *
+ *
*/
public class PerfSONARException extends Exception {
-
// ----------------------------------------------------- Constants
-
/**
* Serial ID
*/
private static final long serialVersionUID = 4352758945385997927L;
-// TODO: url event types
+ // TODO: url event types
public static final String RESULT_CODE_PREFIX = "";
-// public static final String RESULT_CODE_PREFIX =
"http://perfsonar.net/result/";
+ // public static final String RESULT_CODE_PREFIX =
+ // "http://perfsonar.net/result/";
/**
* Default result code, used if no result code was set
*/
- private static final String UNKNOWN_RESULT_CODE =
RESULT_CODE_PREFIX+"unknown";
+ private static final String UNKNOWN_RESULT_CODE = RESULT_CODE_PREFIX +
"unknown";
-
// --------------------------------------------- Private variables
+ private String resultCode = UNKNOWN_RESULT_CODE;
- String resultCode = UNKNOWN_RESULT_CODE;
-
- String resultDescription = "";
+ private String resultDescription = "";
-
// -------------------------------------------------- Constructors
-
-
+
public PerfSONARException() {
super();
resetResult();
-
+
}
-
public PerfSONARException(String message) {
-
- super(message);
+
+ super(message);
setResult(message);
-
+
}
-
-
+
public PerfSONARException(String message, Throwable t) {
-
- super(message, t);
+
+ super(message, t);
setResult(message);
}
-
/**
* PerfSONAR Exception - result code support
- * @param resultCode - textual result code
- * @param message - textual result description (message)
+ *
+ * @param resultCode
+ * - textual result code
+ * @param message
+ * - textual result description (message)
*/
public PerfSONARException(String resultCode, String message) {
-
+
super(message);
setResult(resultCode, message);
-
+
}
-
/**
* PerfSONAR Exception - result code support
- * @param resultCode - textual result code
- * @param message - textual result description (message)
+ *
+ * @param resultCode
+ * - textual result code
+ * @param message
+ * - textual result description (message)
*/
public PerfSONARException(String resultCode, String message, Throwable
t) {
-
- super(message,t);
+
+ super(message, t);
setResult(resultCode, message);
-
+
}
-
-
+
// ------------------------------------------------ Public methods
-
-
+
@Override
public String getMessage() {
-
- return "[" + resultCode + "]: "+super.getMessage();
-
+
+ return "[" + resultCode + "]: " + super.getMessage();
+
}
-
/**
* Returns result code (or "unknown")
*/
public String getResultCode() {
return resultCode;
-
+
}
-
/**
* Return result code description (or empty String)
*/
public String getResultDescription() {
-
+
return resultDescription;
-
+
}
-
+
// ----------------------------------------------- private methods
-
private void setResult(String rc, String rd) {
-
- resultCode = RESULT_CODE_PREFIX+rc;
+
+ resultCode = RESULT_CODE_PREFIX + rc;
resultDescription = rd;
-
+
}
-
private void setResult(String desc) {
-
+
resultCode = UNKNOWN_RESULT_CODE;
resultDescription = desc;
-
+
}
-
-
+
private void resetResult() {
-
+
setResult(UNKNOWN_RESULT_CODE, "");
-
+
}
-
+
public String toString() {
- return "PerfSONARException: code=["+resultCode+"],
description=["+resultCode+"]. Nested exception was: "+super.toString();
+ return "PerfSONARException: code=[" + resultCode + "],
description=[" + resultCode
+ + "]. Nested exception was: " + super.toString();
}
-
-
-
-} //PerfSONARException
+} // PerfSONARException
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/messages/GenericMessageHandler.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/messages/GenericMessageHandler.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/messages/GenericMessageHandler.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -25,132 +25,124 @@
import org.perfsonar.base2.xml.nmwg.Message;
import org.perfsonar.base2.xml.nmwg.Metadata;
-
/**
- * Abstract class that does all the things that a "request" message
- * handler will need to do.
- *
- * @author Maciej Glowiak
- * @author Roman Lapacz
- * @author Jeff Boote
+ * Abstract class that does all the things that a "request" message handler
will
+ * need to do.
+ *
+ * @author Maciej Glowiak
+ * @author Roman Lapacz
+ * @author Jeff Boote
*/
public class GenericMessageHandler implements MessageHandler {
+ private static final Logger LOGGER =
LoggerFactory.getLogger(GenericMessageHandler.class);
- private static final Logger logger =
LoggerFactory.getLogger(GenericMessageHandler.class);
-
-
public GenericMessageHandler() throws PerfSONARException {
}
+ protected ServiceEngine getServiceEngine(String serviceEngineClassName)
throws Exception {
- protected ServiceEngine getServiceEngine(String serviceEngineClassName)
- throws Exception {
+ ServiceEngine se = (ServiceEngine)
Class.forName(serviceEngineClassName).newInstance();
- ServiceEngine se = (ServiceEngine)Class.forName(
- serviceEngineClassName ).newInstance();
-
- return se;
+ return se;
}
protected void checkAuth(Configuration c, String messageType) throws
PerfSONARException {
try {
String authR =
c.getMessageHandler(messageType).getOption("authR").getValue();
- logger.debug("Checking authorization: "+authR);
+ LOGGER.debug("Checking authorization: " + authR);
if ("yes".equals(authR)) {
- AuthNComponent authComponent =
(AuthNComponent)c.getAuxiliaryComponent("auth");
+ AuthNComponent authComponent = (AuthNComponent)
c.getAuxiliaryComponent("auth");
authComponent.requestAuthR(messageType, null);
- }
- else {
+ } else {
String authN =
c.getMessageHandler(messageType).getOption("authN").getValue();
- logger.debug("Checking authentication: "+authN);
+ LOGGER.debug("Checking authentication: " + authN);
if ("yes".equals(authN)) {
- AuthNComponent authComponent =
(AuthNComponent)c.getAuxiliaryComponent("auth");
+ AuthNComponent authComponent = (AuthNComponent)
c.getAuxiliaryComponent("auth");
authComponent.requestAuthN(messageType);
}
}
- } catch (RuntimeException ex) { }
+ } catch (RuntimeException ex) {
+ }
}
- public void execute(ServiceMessage request, ServiceMessage response)
- throws PerfSONARException {
+ public void execute(ServiceMessage request, ServiceMessage response)
throws PerfSONARException {
Message reqMessage = (Message) request.getElement();
- logger.debug("Message Handler started for message type
["+reqMessage.getType()+"]");
-
//logger.debug("--------------------\n"+reqMessage+"\n------------------------\n");
+ LOGGER.debug("Message Handler started for message type [" +
reqMessage.getType() + "]");
+ //
LOGGER.debug("--------------------\n"+reqMessage+"\n------------------------\n");
- //get Service engine for this message
+ // get Service engine for this message
String messageType = null;
String serviceEngineClassName = null;
ServiceEngine serviceEngine = null;
try {
messageType = reqMessage.getType();
Configuration c =
ConfigurationManager.getInstance().getConfiguration();
- //authentication
+ // authentication
checkAuth(c, messageType);
- //service engine
+ // service engine
serviceEngineClassName = c.getServiceEngineOption(messageType);
serviceEngine = getServiceEngine(serviceEngineClassName);
- if (serviceEngine == null) throw new NullPointerException(
- "Cannot Instantiate ServiceEngine class
["+serviceEngineClassName+"]");
+ if (serviceEngine == null) {
+ throw new NullPointerException("Cannot Instantiate
ServiceEngine class [" + serviceEngineClassName
+ + "]");
+ }
} catch (Exception ex) {
- String m = "Cannot find ServiceEngine ["+serviceEngineClassName +
- "] for message type ["+messageType+"], nested exception
was:"+
- ex.toString();
- PerfSONARException pse = new PerfSONARException(
- "no_service_engine", m);
- logger.error(m,ex);
+ String m = "Cannot find ServiceEngine [" +
serviceEngineClassName + "] for message type [" + messageType
+ + "], nested exception was:" + ex.toString();
+ PerfSONARException pse = new
PerfSONARException("no_service_engine", m);
+ LOGGER.error(m, ex);
- response.setElement(
- ResultCodesUtil.generateResultMessage(null, pse));
- return; //finish when cannot execute ServiceEngine
+ response.setElement(ResultCodesUtil.generateResultMessage(null,
pse));
+ return; // finish when cannot execute ServiceEngine
}
-
ArrayList<MessagePair> output = new ArrayList<MessagePair>();
- List<Message> inputMessages=extractMultipleRequests(reqMessage);
- if(inputMessages.isEmpty()){
- //TODO: url event types
- throw new
PerfSONARException("error.common.no_metadata_data_pair","There were no
metadata/data pairs found in the message");
+ List<Message> inputMessages = extractMultipleRequests(reqMessage);
+ if (inputMessages.isEmpty()) {
+ // TODO: url event types
+ throw new
PerfSONARException("error.common.no_metadata_data_pair",
+ "There were no metadata/data pairs found in the
message");
}
-
- for (Message inputMessage: inputMessages) {
+ for (Message inputMessage : inputMessages) {
+
ServiceMessage reqSM = new ServiceMessage(inputMessage);
ServiceMessage resSM = new ServiceMessage();
try {
- logger.debug("Request.execute: run Service Engine for
extracted request");
+ LOGGER.debug("Request.execute: run Service Engine for
extracted request");
- //run service engine and add result to output list
+ // run service engine and add result to output list
try {
serviceEngine.takeAction(reqSM, resSM);
} catch (RuntimeException rex) {
- //just in case of unexpected runtime exception such as
- //null, indexoutofbounds, classcast, etc.
- logger.error("Service engine failed", rex);
- throw new PerfSONARException(
- "runtime_exception", "Runtime exception in
ServiceEngine: "+rex.getMessage(), rex);
+ // just in case of unexpected runtime exception such as
+ // null, indexoutofbounds, classcast, etc.
+ LOGGER.error("Service engine failed", rex);
+ throw new PerfSONARException("runtime_exception",
"Runtime exception in ServiceEngine: "
+ + rex.getMessage(), rex);
}
} catch (PerfSONARException e) {
- //if an exception was thrown, convert it to result code
- //and add as a new message (to be joined) to array
- logger.info("Message handler result code: " + e);
-
resSM.setElement(ResultCodesUtil.generateResultMessage(e.getResultCode(),e.getMessage()));
+ // if an exception was thrown, convert it to result code
+ // and add as a new message (to be joined) to array
+ LOGGER.info("Message handler result code: " + e);
+
resSM.setElement(ResultCodesUtil.generateResultMessage(e.getResultCode(),
e.getMessage()));
}
- //add response from ServiceEngine or Result code generated above
+ // add response from ServiceEngine or Result code generated above
output.add(new MessagePair(reqSM, resSM));
}
@@ -167,7 +159,6 @@
}
-
protected ArrayList<Message> extractMultipleRequests(Message reqMessage)
{
ArrayList<Message> messages = new ArrayList<Message>();
@@ -179,13 +170,13 @@
Message message = new Message();
try {
- Map<String,Metadata> metadatas = new
HashMap<String,Metadata>();
+ Map<String, Metadata> metadatas = new HashMap<String,
Metadata>();
getChaining(reqMessage, metadataIdRef, metadatas);
- Map<String,Metadata> mergedMetadatas =
mergeAllMetadata(metadatas);
+ Map<String, Metadata> mergedMetadatas =
mergeAllMetadata(metadatas);
-
- for (Metadata metadata : mergedMetadatas.values())
+ for (Metadata metadata : mergedMetadatas.values()) {
message.setMetadata(metadata);
+ }
message.setId(reqMessage.getId());
message.setType(reqMessage.getType());
@@ -194,8 +185,9 @@
messages.add(message);
} catch (NoSuchMetadataException e) {
- //wrong MetadataIdRef, remove it
- logger.warn("metadataIdRef is empty or there is no Metadata
with the given metadataIdRef, metadataIdRef=" + metadataIdRef);
+ // wrong MetadataIdRef, remove it
+ LOGGER.warn("metadataIdRef is empty or there is no Metadata
with the given metadataIdRef, metadataIdRef="
+ + metadataIdRef);
}
}
@@ -203,106 +195,116 @@
}
-
class MessagePair {
private ServiceMessage request = null;
private ServiceMessage response = null;
+
public MessagePair(ServiceMessage request, ServiceMessage response) {
this.request = request;
this.response = response;
}
- public void setRequest(ServiceMessage request) { this.request =
request; }
- public void setResponse(ServiceMessage response) { this.response =
response; }
- public ServiceMessage getRequest() { return request; }
- public ServiceMessage getResponse() { return response; }
+
+ public void setRequest(ServiceMessage request) {
+ this.request = request;
+ }
+
+ public void setResponse(ServiceMessage response) {
+ this.response = response;
+ }
+
+ public ServiceMessage getRequest() {
+ return request;
+ }
+
+ public ServiceMessage getResponse() {
+ return response;
+ }
}
-
protected MessagePair mergeMultipleResponses(ArrayList<MessagePair>
messagePairs) {
-
- final Map<String, String> ids = new Hashtable<String, String>();
- if (messagePairs == null || messagePairs.size() == 0)
+ final Map<String, String> ids = new Hashtable<String, String>();
+
+ if (messagePairs == null || messagePairs.size() == 0) {
return null;
- else if (messagePairs.size() == 1)
+ } else if (messagePairs.size() == 1) {
return messagePairs.get(0);
- else {
+ } else {
- int metaid=0;
- int dataid=0;
+ int metaid = 0;
+ int dataid = 0;
- //create new common response message
+ // create new common response message
Message respMessage = new Message();
for (MessagePair messagePair : messagePairs) {
- //ServiceMessage request = messagePair.getRequest();
+ // ServiceMessage request = messagePair.getRequest();
ServiceMessage response = messagePair.getResponse();
Message m = (Message) response.getElement();
- if (m == null) return messagePair;
+ if (m == null) {
+ return messagePair;
+ }
Collection<Metadata> metadatas = m.getMetadataMap().values();
Collection<Data> datas = m.getDataMap().values();
- //for each metadata
+ // for each metadata
for (Metadata meta1 : metadatas) {
- //get old meta id
+ // get old meta id
String meta1id = meta1.getId();
- //compute new meta id
- String newMeta1id = meta1id+"_"+metaid;
+ // compute new meta id
+ String newMeta1id = meta1id + "_" + metaid;
- //set new id
+ // set new id
meta1.setId(newMeta1id);
metaid++;
-
+
ids.put(meta1id, newMeta1id);
/*
- * TODO:
- * subject chaining reference
- * if there is metadata/subject with
- * metadataRefId, it should be changed
- *
- * perhaps some metadata-id mapping table
- * should be prepared and then all metadata
- * should be iterated and subjects changed?
- *
+ * TODO: subject chaining reference if there is
+ * metadata/subject with metadataRefId, it should be
changed
+ *
+ * perhaps some metadata-id mapping table should be
prepared
+ * and then all metadata should be iterated and subjects
+ * changed?
+ *
* something like:
- *
- * mapping.add(oldId, newId);
- *
+ *
+ * mapping.add(oldId, newId);
*/
- if ((meta1.getSubject() != null)
- && (meta1.getSubject().getMetadataIdRef() !=
null)) {
- if (ids.get(meta1.getSubject().getMetadataIdRef()) !=
null)
-
meta1.getSubject().setMetadataIdRef(ids.get(meta1.getSubject().getMetadataIdRef()));
+ if ((meta1.getSubject() != null) &&
(meta1.getSubject().getMetadataIdRef() != null)) {
+ if (ids.get(meta1.getSubject().getMetadataIdRef())
!= null) {
+
meta1.getSubject().setMetadataIdRef(ids.get(meta1.getSubject().getMetadataIdRef()));
+ }
}
- //put metadata to new common response message
+ // put metadata to new common response message
respMessage.setMetadata(meta1);
- //find all data linked to meta
+ // find all data linked to meta
for (Data data1 : datas) {
- //if data's metadata id res == metadata id
- //put data
+ // if data's metadata id res == metadata id
+ // put data
if (data1.getMetadataIdRef().equals(meta1id)) {
- data1.setId(data1.getId() + "_"+dataid);
- //change data metadata id ref to new meta id
+ data1.setId(data1.getId() + "_" + dataid);
+ // change data metadata id ref to new meta id
data1.setMetadataIdRef(newMeta1id);
- //put changed data to response common message
+ // put changed data to response common message
respMessage.setData(data1);
dataid++;
- } //if
- } //datas
- } //metadata
+ } // if
+ } // datas
+ } // metadata
}
@@ -312,73 +314,72 @@
}
-
/**
* Find metadata chain for metadata ID (the last metadata in chain)
- *
- * @param inputMessage message to process (won't be changed)
- * @param lastMetadataId id of metadata which is last in chain
+ *
+ * @param inputMessage
+ * message to process (won't be changed)
+ * @param lastMetadataId
+ * id of metadata which is last in chain
* @return map <id,metadata>
- * @throws NoSuchMetadataException thrown if there is no metadata with
given ID
+ * @throws NoSuchMetadataException
+ * thrown if there is no metadata with given ID
*/
- protected Map<String,Metadata> getChaining(
- Message inputMessage, String metadataId, Map<String,Metadata>
metadatas)
- throws NoSuchMetadataException {
+ protected Map<String, Metadata> getChaining(Message inputMessage, String
metadataId, Map<String, Metadata> metadatas)
+ throws NoSuchMetadataException {
- if (metadataId == null) throw new NoSuchMetadataException();
- Metadata metadata = inputMessage.getMetadata(metadataId);
- if (metadata == null) throw new NoSuchMetadataException();
+ if (metadataId == null) {
+ throw new NoSuchMetadataException();
+ }
+ Metadata metadata = inputMessage.getMetadata(metadataId);
+ if (metadata == null) {
+ throw new NoSuchMetadataException();
+ }
metadatas.put(metadata.getId(), metadata);
- //metadataIdRef in Subject
- //prevent endless loop
+ // metadataIdRef in Subject
+ // prevent endless loop
if (metadata.getSubject() != null) {
- if ( (metadata.getSubject().getMetadataIdRef()!=null)&&
- !("".equals(metadata.getSubject().getMetadataIdRef()))&&
-
!(metadata.getId().equals(metadata.getSubject().getMetadataIdRef()))) {
+ if ((metadata.getSubject().getMetadataIdRef() != null)
+ && !("".equals(metadata.getSubject().getMetadataIdRef()))
+ &&
!(metadata.getId().equals(metadata.getSubject().getMetadataIdRef()))) {
- getChaining(
- inputMessage,
- metadata.getSubject().getMetadataIdRef(),
- metadatas);
+ getChaining(inputMessage,
metadata.getSubject().getMetadataIdRef(), metadatas);
}
}
String chainedMetadataId = metadata.getMetadataIdRef();
- //get other chain, prevent endless loop
- if ( (chainedMetadataId!=null)&&
- !("".equals(chainedMetadataId))&&
- !(metadata.getId().equals(chainedMetadataId))) {
+ // get other chain, prevent endless loop
+ if ((chainedMetadataId != null) && !("".equals(chainedMetadataId))
+ && !(metadata.getId().equals(chainedMetadataId))) {
getChaining(inputMessage, chainedMetadataId, metadatas);
}
-
return metadatas;
}
-
/**
* Merge chained metadata elements
- * @param metadatas map of metadata elements
+ *
+ * @param metadatas
+ * map of metadata elements
* @return metadatas map of merged metadata elements
*/
- public Map<String,Metadata> mergeAllMetadata(Map<String,Metadata>
metadatas) {
+ public Map<String, Metadata> mergeAllMetadata(Map<String, Metadata>
metadatas) {
return metadatas;
};
-
/**
- * Exception thrown when Metadata could not be found. It's internal
- * Message Handler
- * exception.
- *
+ * Exception thrown when Metadata could not be found. It's internal
Message
+ * Handler exception.
+ *
* @author Maciej Glowiak
- *
+ *
*/
protected class NoSuchMetadataException extends Exception {
@@ -386,5 +387,4 @@
}
-
-} //GenericMessageHandler
+} // GenericMessageHandler
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/messages/MessageHandler.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/messages/MessageHandler.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/messages/MessageHandler.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -3,23 +3,19 @@
import org.perfsonar.base2.service.requesthandler.ServiceMessage;
import org.perfsonar.base2.service.exceptions.PerfSONARException;
-
/**
- *
+ *
* @author Maciej Glowiak
- *
- * Originally done by J.Boote
- *
+ *
+ * Originally done by J.Boote
+ *
*/
public interface MessageHandler {
-
/**
- * Runs the correct ServiceEngine for the given request message
- * and returns the result. Supports chaining.
+ * Runs the correct ServiceEngine for the given request message and
returns
+ * the result. Supports chaining.
*/
- public void execute(ServiceMessage request, ServiceMessage response)
- throws PerfSONARException;
+ void execute(ServiceMessage request, ServiceMessage response) throws
PerfSONARException;
-
-} //MessageHandler
+} // MessageHandler
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/registration/AbstractRegistrationAction.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/registration/AbstractRegistrationAction.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/registration/AbstractRegistrationAction.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -33,431 +33,399 @@
/**
*
- * This class provides support for Registration. It consists of methods
that are helpful to work with
- * receive/process responses.
- *
- * LSRegistrationActions bases on configuration file - configuration.xml
where are defined addresses.
- *
- * This addresses can be defined in two form :
- * - single direct address
- * - address to hint.roots that contains addresses
+ * This class provides support for Registration. It consists of methods that
are
+ * helpful to work with receive/process responses.
*
+ * LSRegistrationActions bases on configuration file - configuration.xml
where
+ * are defined addresses.
+ *
+ * This addresses can be defined in two form : - single direct address -
address
+ * to hint.roots that contains addresses
+ *
* @author Slawomir Trzaszczka
*
*/
-public abstract class AbstractRegistrationAction extends Action implements
- SchedulerAction {
+public abstract class AbstractRegistrationAction extends Action implements
SchedulerAction {
- private boolean initialized = false;
-
- private Logger logger =
LoggerFactory.getLogger(AbstractRegistrationAction.class);
+ private boolean initialized = false;
- private final String KEEP_ALIVE_OPTION="keepAlive";
-
- /**
- * Message type.
- */
- protected static final String REGISTRATION_REQUEST_MESSAGE_TYPE =
"LSRegisterRequest";
+ private Logger logger =
LoggerFactory.getLogger(AbstractRegistrationAction.class);
- /**
- * EventType name which is included in the metadata of
LSRegisterRequest
- * message.
- */
- private static final String DEFAULT_REGISTRATION_EVENT_TYPE =
"http://ogf.org/ns/nmwg/tools/org/perfsonar/service/lookup/registration/service/2.0";
+ private static final String KEEP_ALIVE_OPTION = "keepAlive";
- /**
- * Provides metadatata configuration which is sent to LS(s).
- */
- protected RegisterDataSource dataSource = null;
+ /**
+ * Message type.
+ */
+ protected static final String REGISTRATION_REQUEST_MESSAGE_TYPE =
"LSRegisterRequest";
- protected String registrationEventType =
DEFAULT_REGISTRATION_EVENT_TYPE;
+ /**
+ * EventType name which is included in the metadata of LSRegisterRequest
+ * message.
+ */
+ private static final String DEFAULT_REGISTRATION_EVENT_TYPE =
+
"http://ogf.org/ns/nmwg/tools/org/perfsonar/service/lookup/registration/service/2.0";
- /**
- * Set of information about the service taken from the configuration.
- */
- protected LookupInformation lookupInformation = null;
+ /**
+ * Provides metadatata configuration which is sent to LS(s).
+ */
+ protected RegisterDataSource dataSource = null;
- /**
- * Sends messages to LS(s).
- */
- protected LSRegistrator registrator;
+ protected String registrationEventType = DEFAULT_REGISTRATION_EVENT_TYPE;
- public AbstractRegistrationAction() {
- super();
- }
+ /**
+ * Set of information about the service taken from the configuration.
+ */
+ protected LookupInformation lookupInformation = null;
- /**
- * main action of this class, in first step initialization is
executed
- *
- */
- public void runAction() {
+ /**
+ * Sends messages to LS(s).
+ */
+ protected LSRegistrator registrator;
- if (!initialized) {
- try {
- init();
- initialized = true;
- } catch (PerfSONARException e) {
- logger.warn("Cannot initialize " +
getClass().getCanonicalName(), e);
- }
- }
- execute();
- refresh();
+ public AbstractRegistrationAction() {
+ super();
+ }
- }
-
- /**
- * initializes this class
- *
- * @throws PerfSONARException
- */
- protected abstract void init() throws PerfSONARException;
+ /**
+ * main action of this class, in first step initialization is executed
+ *
+ */
+ public void runAction() {
- /**
- * business logic of this class
- */
- protected abstract void execute();
+ if (!initialized) {
+ try {
+ init();
+ initialized = true;
+ } catch (PerfSONARException e) {
+ logger.warn("Cannot initialize " +
getClass().getCanonicalName(), e);
+ }
+ }
+ execute();
+ refresh();
- /**
- * Removes all existing keys
- */
- protected abstract void refresh();
+ }
- /**
- *
- * returns RegisterDataSource configured in configuration.xml file
- *
- * @return
- * @throws PerfSONARException
- */
- protected RegisterDataSource getRegisterDataSource()
- throws PerfSONARException {
+ /**
+ * initializes this class
+ *
+ * @throws PerfSONARException
+ */
+ protected abstract void init() throws PerfSONARException;
- String className = getOption("registerDataSource").getValue();
- if (className == null || className.trim().equals("")) {
- logger
- .warn("registerDataSource option of
register action is empty");
- return null;
- }
+ /**
+ * business logic of this class
+ */
+ protected abstract void execute();
- RegisterDataSource registerDataSource = null;
+ /**
+ * Removes all existing keys
+ */
+ protected abstract void refresh();
- try {
- registerDataSource = (RegisterDataSource)
Class.forName(className)
- .newInstance();
- } catch (InstantiationException e) {
- e.printStackTrace();
- throwException(e);
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- throwException(e);
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- throwException(e);
- }
+ /**
+ *
+ * returns RegisterDataSource configured in configuration.xml file
+ *
+ * @return
+ * @throws PerfSONARException
+ */
+ protected RegisterDataSource getRegisterDataSource() throws
PerfSONARException {
- return registerDataSource;
+ String className = getOption("registerDataSource").getValue();
+ if (className == null || className.trim().equals("")) {
+ logger.warn("registerDataSource option of register action is
empty");
+ return null;
+ }
- }
-
-
- /**
- *
- * returns keepAlive option configured in configuration.xml file
- *
- * @return
- * @throws PerfSONARException
- */
- protected boolean isKeepAliveEnabled()
- throws PerfSONARException {
+ RegisterDataSource registerDataSource = null;
- Option option=getOption(KEEP_ALIVE_OPTION);
- if(option!=null){
- String keepAlive =
getOption(KEEP_ALIVE_OPTION).getValue();
- if (keepAlive == null || keepAlive.trim().equals(""))
{
- return false;
- }
- if(keepAlive.equals("on")){
- return true;
- }else{
- return false;
- }
- }else{
- return false;
- }
-
- }
+ try {
+ registerDataSource = (RegisterDataSource)
Class.forName(className).newInstance();
+ } catch (InstantiationException e) {
+ e.printStackTrace();
+ throwException(e);
+ } catch (IllegalAccessException e) {
+ e.printStackTrace();
+ throwException(e);
+ } catch (ClassNotFoundException e) {
+ e.printStackTrace();
+ throwException(e);
+ }
- /**
- * get registerEventType option value. If not present, take default
- *
- * @return
- */
- protected String getRegistrationEventType() {
- String evt = getOption("registerEventType").getValue();
- if (evt != null) {
- logger
- .debug("Found [registerEventType]
option value [" + evt
- + "]");
- return evt;
- } else {
- logger.debug("Taking default [registerEventType]
value ["
- + DEFAULT_REGISTRATION_EVENT_TYPE +
"]");
- return DEFAULT_REGISTRATION_EVENT_TYPE;
- }
- }
+ return registerDataSource;
- /**
- *
- * returns LookupInformation configured in configuration.xml file
- *
- * @return
- * @throws PerfSONARException
- */
- protected LookupInformation getLookupInformation() throws
PerfSONARException {
+ }
- Configuration configuration =
ConfigurationManager.getInstance()
- .getConfiguration();
- LookupInformation lookupInformation = (LookupInformation)
configuration
-
.getService().getEntry(Configuration.LOOKUP_INFORMATION);
- return lookupInformation;
- }
+ /**
+ *
+ * returns keepAlive option configured in configuration.xml file
+ *
+ * @return
+ * @throws PerfSONARException
+ */
+ protected boolean isKeepAliveEnabled() throws PerfSONARException {
- /**
- *
- * throws exception
- *
- * @param ex
- * @throws PerfSONARException
- */
- private void throwException(Exception ex) throws PerfSONARException {
- throw new PerfSONARException("error",
- "Unable to create an object of : " +
className + ": "
- + ex.toString());
- }
+ Option option = getOption(KEEP_ALIVE_OPTION);
+ if (option != null) {
+ String keepAlive = getOption(KEEP_ALIVE_OPTION).getValue();
+ if (keepAlive == null || keepAlive.trim().equals("")) {
+ return false;
+ }
+ return keepAlive.equals("on");
+ } else {
+ return false;
+ }
- /**
- * Get list of URLs to Lookup Services to register to.
- * Addresses returned from this method are shuffled - aim of this
operation is avoiding
- * registration to first address
- *
- * @return
- * @throws PerfSONARException
- */
- protected LinkedList<URL> getLSAddresses() {
+ }
- List<URL> addressesList = new ArrayList<URL>();
+ /**
+ * get registerEventType option value. If not present, take default
+ *
+ * @return
+ */
+ protected String getRegistrationEventType() {
+ String evt = getOption("registerEventType").getValue();
+ if (evt != null) {
+ logger.debug("Found [registerEventType] option value [" + evt +
"]");
+ return evt;
+ } else {
+ logger.debug("Taking default [registerEventType] value [" +
DEFAULT_REGISTRATION_EVENT_TYPE + "]");
+ return DEFAULT_REGISTRATION_EVENT_TYPE;
+ }
+ }
- // get values from options lsAddress-1, lsAddress-2,
lsAddress-3, ...
- // and get LSes lists from URLs
+ /**
+ *
+ * returns LookupInformation configured in configuration.xml file
+ *
+ * @return
+ * @throws PerfSONARException
+ */
+ protected LookupInformation getLookupInformation() throws
PerfSONARException {
- for (String optName : options.keySet()) {
+ Configuration configuration =
ConfigurationManager.getInstance().getConfiguration();
+ LookupInformation myLookupInformation = (LookupInformation)
configuration.getService().getEntry(
+ Configuration.LOOKUP_INFORMATION);
+ return myLookupInformation;
+ }
- // TODO: Shouldn't we allow using both types of
option at the same time: lsAddress-n *and* lsList-n?
- // Or can we use the file:/// URL with a local list?
(idea is to permit having both a globally defined list and a local one)
-
- // First, handles lsAddress-1, lsAddress-2,
lsAddress-3, ...
- if (optName.startsWith("lsAddress")) {
+ /**
+ *
+ * throws exception
+ *
+ * @param ex
+ * @throws PerfSONARException
+ */
+ private void throwException(Exception ex) throws PerfSONARException {
+ throw new PerfSONARException("error", "Unable to create an object of
: " + className + ": " + ex.toString());
+ }
- try {
- URL url = new
URL(getOption(optName).getValue());
- addressesList.add(url);
- } catch (MalformedURLException ex) {
- logger.warn("Unable to convert LS
address [" + optName
- + "] into URL object.
Exception was: "
- + ex.getMessage());
- }
+ /**
+ * Get list of URLs to Lookup Services to register to. Addresses returned
+ * from this method are shuffled - aim of this operation is avoiding
+ * registration to first address
+ *
+ * @return
+ * @throws PerfSONARException
+ */
+ protected LinkedList<URL> getLSAddresses() {
- // Then handles lsList-1, lsList-2, ...
- } else if (optName.startsWith("lsList")) {
+ List<URL> addressesList = new ArrayList<URL>();
- try {
- String remoteResource =
getOption(optName).getValue();
- addLSAddressesFromURL(addressesList,
remoteResource);
- } catch (MalformedURLException ex) {
- logger.warn("Unable to read LS list
from URL address ["
- + optName + "] into
URL object. Exception was: "
- + ex.getMessage());
- } catch (IOException ex) {
- logger.warn("Unable to read LS list
from URL address ["
- + optName + "] into
URL object. Exception was: "
- + ex.getMessage());
- }
+ // get values from options lsAddress-1, lsAddress-2, lsAddress-3, ...
+ // and get LSes lists from URLs
- }
- }
+ for (String optName : options.keySet()) {
- if (addressesList.size() == 0) {
- return null;
- } else {
- LinkedList<URL> glsAddresses = new LinkedList<URL>();
- // shuffle addresses to randomize order of the GLS
- Collections.shuffle(addressesList);
- for (URL url : addressesList) {
- glsAddresses.add(url);
- }
- return glsAddresses;
- }
- }
+ // TODO: Shouldn't we allow using both types of option at the
same
+ // time: lsAddress-n *and* lsList-n?
+ // Or can we use the file:/// URL with a local list? (idea is to
+ // permit having both a globally defined list and a local one)
- /**
- * Populates urls collection with urls/lines downloaded from urlString
- *
- * @param urls
- * @param urlString
- * @throws MalformedURLException
- * @throws IOException
- */
- private void addLSAddressesFromURL(List<URL> urls, String urlString)
- throws MalformedURLException, IOException {
+ // First, handles lsAddress-1, lsAddress-2, lsAddress-3, ...
+ if (optName.startsWith("lsAddress")) {
- URL rootHintsUrl = new URL(urlString);
- URLConnection rhc = rootHintsUrl.openConnection();
- BufferedReader in = new BufferedReader(new
InputStreamReader(rhc
- .getInputStream()));
- String line;
- while ((line = in.readLine()) != null) {
- String s = line.trim();
- if ((s.length() > 0) && // not empty
- (!s.startsWith("#")) &&
(!s.startsWith("//"))) { // not
- // commentary
- // # or
- // //
+ try {
+ URL url = new URL(getOption(optName).getValue());
+ addressesList.add(url);
+ } catch (MalformedURLException ex) {
+ logger.warn("Unable to convert LS address [" + optName +
"] into URL object. Exception was: "
+ + ex.getMessage());
+ }
- URL lsUrl = new URL(line);
- urls.add(lsUrl);
- }
- }
- in.close();
+ // Then handles lsList-1, lsList-2, ...
+ } else if (optName.startsWith("lsList")) {
- }
-
- /**
- *
- * returns message that will contains summarized data
- *
- * @return
- * @throws PerfSONARException
- */
- protected ServiceMessage getLSRegisterMessage() throws
PerfSONARException {
+ try {
+ String remoteResource = getOption(optName).getValue();
+ addLSAddressesFromURL(addressesList, remoteResource);
+ } catch (MalformedURLException ex) {
+ logger.warn("Unable to read LS list from URL address ["
+ optName
+ + "] into URL object. Exception was: " +
ex.getMessage());
+ } catch (IOException ex) {
+ logger.warn("Unable to read LS list from URL address ["
+ optName
+ + "] into URL object. Exception was: " +
ex.getMessage());
+ }
- ServiceMessage serviceMessage = new ServiceMessage();
+ }
+ }
- Message message = new Message();
- message.setType(REGISTRATION_REQUEST_MESSAGE_TYPE);
- serviceMessage.setElement(message);
+ if (addressesList.size() == 0) {
+ return null;
+ } else {
+ LinkedList<URL> glsAddresses = new LinkedList<URL>();
+ // shuffle addresses to randomize order of the GLS
+ Collections.shuffle(addressesList);
+ for (URL url : addressesList) {
+ glsAddresses.add(url);
+ }
+ return glsAddresses;
+ }
+ }
- Metadata metadata = new Metadata();
- metadata.setId("serviceLookupInfo");
- message.setMetadata(metadata);
+ /**
+ * Populates urls collection with urls/lines downloaded from urlString
+ *
+ * @param urls
+ * @param urlString
+ * @throws MalformedURLException
+ * @throws IOException
+ */
+ private void addLSAddressesFromURL(List<URL> urls, String urlString)
throws IOException {
- EventType eventType = new EventType();
- eventType.setEventType(registrationEventType);
- metadata.setEventType(eventType);
+ URL rootHintsUrl = new URL(urlString);
+ URLConnection rhc = rootHintsUrl.openConnection();
+ BufferedReader in = new BufferedReader(new
InputStreamReader(rhc.getInputStream()));
+ String line;
+ while ((line = in.readLine()) != null) {
+ String s = line.trim();
+ if ((s.length() > 0) && // not empty
+ (!s.startsWith("#")) && (!s.startsWith("//"))) { // not
+ // commentary
+ // # or
+ // //
- Subject subject = new Subject("perfsonar");
- subject.setId("commonParameters");
- metadata.setSubject(subject);
+ URL lsUrl = new URL(line);
+ urls.add(lsUrl);
+ }
+ }
+ in.close();
- Element service = new Element("service", "psservice",
-
NMWGNamespaceFactory.getNamespace("psservice"));
- service.setId("serviceParameters");
- subject.addChild(service);
+ }
- Collection<String> keys =
lookupInformation.getOptions().keySet();
- for (String name : keys) {
- Element element = new Element(name, "psservice",
-
NMWGNamespaceFactory.getNamespace("psservice"));
-
element.setText(lookupInformation.getOption(name).getValue());
- service.addChild(element);
- }
+ /**
+ *
+ * returns message that will contains summarized data
+ *
+ * @return
+ * @throws PerfSONARException
+ */
+ protected ServiceMessage getLSRegisterMessage() throws
PerfSONARException {
- Data data = null;
- Message msg = (Message)
dataSource.getRegisterData().getElement();
- Collection<Metadata> c = msg.getMetadataCollection();
- if (!c.isEmpty()) {
- for (Metadata m : c) {
- data = new Data();
- data.setMetadataIdRef(metadata.getId());
- data.addChild(m);
- message.addChild(data);
- }
- } else {
- data = new Data();
- data.setMetadataIdRef(metadata.getId());
- message.addChild(data);
- }
- return serviceMessage;
- }
+ ServiceMessage serviceMessage = new ServiceMessage();
- protected Element getResponseMetadata(ServiceMessage response) {
- Element responseMessage = response.getElement();
+ Message message = new Message();
+ message.setType(REGISTRATION_REQUEST_MESSAGE_TYPE);
+ serviceMessage.setElement(message);
- if (responseMessage != null) {
- Element responseMetadata = responseMessage
- .getFirstChild("metadata");
- return responseMetadata;
- }
+ Metadata metadata = new Metadata();
+ metadata.setId("serviceLookupInfo");
+ message.setMetadata(metadata);
- return null;
- }
+ EventType eventType = new EventType();
+ eventType.setEventType(registrationEventType);
+ metadata.setEventType(eventType);
- protected boolean isResponseSuccess(Element responseMetadata) {
- Element eventType =
responseMetadata.getFirstChild("eventType");
- if (eventType != null &&
eventType.getText().trim().contains("success")) {
- return true;
- } else {
- return false;
- }
- }
+ Subject subject = new Subject("perfsonar");
+ subject.setId("commonParameters");
+ metadata.setSubject(subject);
- protected Element getKeyFromResponse(ServiceMessage response) {
+ Element service = new Element("service", "psservice",
NMWGNamespaceFactory.getNamespace("psservice"));
+ service.setId("serviceParameters");
+ subject.addChild(service);
- Element responseMetadata = null;
- responseMetadata = getResponseMetadata(response);
+ Collection<String> keys = lookupInformation.getOptions().keySet();
+ for (String name : keys) {
+ Element element = new Element(name, "psservice",
NMWGNamespaceFactory.getNamespace("psservice"));
+ element.setText(lookupInformation.getOption(name).getValue());
+ service.addChild(element);
+ }
- if (responseMetadata != null) {
- if (isResponseSuccess(responseMetadata)) {
- return responseMetadata.getFirstChild("key");
- }
- }
+ Data data = null;
+ Message msg = (Message) dataSource.getRegisterData().getElement();
+ Collection<Metadata> c = msg.getMetadataCollection();
+ if (!c.isEmpty()) {
+ for (Metadata m : c) {
+ data = new Data();
+ data.setMetadataIdRef(metadata.getId());
+ data.addChild(m);
+ message.addChild(data);
+ }
+ } else {
+ data = new Data();
+ data.setMetadataIdRef(metadata.getId());
+ message.addChild(data);
+ }
+ return serviceMessage;
+ }
- return null;
- }
-
- /**
- *
- * returns LSRegistrator configured in configuration.xml
- *
- * @return
- * @throws PerfSONARException
- */
- protected LSRegistrator getLSRegistrator() throws PerfSONARException {
+ protected Element getResponseMetadata(ServiceMessage response) {
+ Element responseMessage = response.getElement();
- String className = getOption("registrator").getValue();
- LSRegistrator registrator = null;
+ if (responseMessage != null) {
+ Element responseMetadata =
responseMessage.getFirstChild("metadata");
+ return responseMetadata;
+ }
- try {
- registrator = (LSRegistrator) Class.forName(className)
- .newInstance();
- } catch (InstantiationException e) {
- e.printStackTrace();
- throw new PerfSONARException("error",
- "Unable to create an object of : " +
className + ": "
- + e.toString());
+ return null;
+ }
- } catch (IllegalAccessException e) {
- throw new PerfSONARException("error",
- "Unable to create an object of : " +
className + ": "
- + e.toString());
+ protected boolean isResponseSuccess(Element responseMetadata) {
+ Element eventType = responseMetadata.getFirstChild("eventType");
+ return eventType != null &&
eventType.getText().trim().contains("success");
+ }
- } catch (ClassNotFoundException e) {
- throw new PerfSONARException("error",
- "Unable to create an object of : " +
className + ": "
- + e.toString());
- }
+ protected Element getKeyFromResponse(ServiceMessage response) {
- return registrator;
+ Element responseMetadata = null;
+ responseMetadata = getResponseMetadata(response);
- }
+ if (responseMetadata != null) {
+ if (isResponseSuccess(responseMetadata)) {
+ return responseMetadata.getFirstChild("key");
+ }
+ }
-}
\ No newline at end of file
+ return null;
+ }
+
+ /**
+ *
+ * returns LSRegistrator configured in configuration.xml
+ *
+ * @return
+ * @throws PerfSONARException
+ */
+ protected LSRegistrator getLSRegistrator() throws PerfSONARException {
+
+ String className = getOption("registrator").getValue();
+ LSRegistrator myRegistrator = null;
+
+ try {
+ myRegistrator = (LSRegistrator)
Class.forName(className).newInstance();
+ } catch (InstantiationException e) {
+ e.printStackTrace();
+ throw new PerfSONARException("error", "Unable to create an
object of : " + className + ": " + e.toString());
+
+ } catch (IllegalAccessException e) {
+ throw new PerfSONARException("error", "Unable to create an
object of : " + className + ": " + e.toString());
+
+ } catch (ClassNotFoundException e) {
+ throw new PerfSONARException("error", "Unable to create an
object of : " + className + ": " + e.toString());
+ }
+
+ return myRegistrator;
+
+ }
+
+}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/registration/GenericLSRegistrator.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/registration/GenericLSRegistrator.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/registration/GenericLSRegistrator.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -21,48 +21,39 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-
public class GenericLSRegistrator implements LSRegistrator {
-
// ----------------------------------------------------------- Variables
- private static final Logger logger =
LoggerFactory.getLogger(GenericLSRegistrator.class);
+ private static final Logger LOGGER =
LoggerFactory.getLogger(GenericLSRegistrator.class);
-
// ----------------------------------------------------------- Methods
-
public ServiceMessage register(Message requestMessage, URL lsUrl) throws
PerfSONARException {
return send(requestMessage, lsUrl);
}
+ public ServiceMessage deregister(Key key, URL lsUrl) throws
PerfSONARException {
+ // TODO: url event types
+ throw new PerfSONARException("error.common.action_not_supported",
"Action deregister is not implemented yet");
- public ServiceMessage deregister(Key key, URL lsUrl)
- throws PerfSONARException {
- //TODO: url event types
- throw new
PerfSONARException("error.common.action_not_supported","Action deregister is
not implemented yet");
-
}
+ public ServiceMessage update(Key key, URL lsUrl) throws
PerfSONARException {
+ // TODO: url event types
+ throw new PerfSONARException("error.common.action_not_supported",
"Action update is not implemented yet");
- public ServiceMessage update(Key key, URL lsUrl)
- throws PerfSONARException {
- //TODO: url event types
- throw new
PerfSONARException("error.common.action_not_supported","Action update is not
implemented yet");
-
}
+ public ServiceMessage keepalive(Element key, URL lsUrl) throws
PerfSONARException {
- public ServiceMessage keepalive(Element key, URL lsUrl)
- throws PerfSONARException {
-
Message requestMessage = new Message("LSKeepaliveRequest", "msg");
Metadata requestMetadata = new Metadata("key_to_keepalive", "nmwg");
requestMessage.setMetadata(requestMetadata);
Data requestData = new Data("d1", "key_to_keepalive", "nmwg");
- //Data requestData = new Data("d1",
requestMetadata.getMetadataIdRef(), "nmwg");
+ // Data requestData = new Data("d1",
requestMetadata.getMetadataIdRef(),
+ // "nmwg");
requestMessage.setData(requestData);
requestMetadata.addChild(key);
@@ -70,18 +61,15 @@
}
- protected ServiceMessage send(Element element, URL lsUrl)
- throws PerfSONARException {
+ protected ServiceMessage send(Element element, URL lsUrl) throws
PerfSONARException {
Client client = new Axis2Client();
Element responseElement = client.send(lsUrl.toString(), element);
ServiceMessage serviceResponseMessage = new
ServiceMessage(responseElement.getCopy());
- logger.debug("LS request sent to the LS " + lsUrl.toString());
+ LOGGER.debug("LS request sent to the LS " + lsUrl.toString());
return serviceResponseMessage;
}
-
-
-} //GenericLSRegistrator
\ No newline at end of file
+} // GenericLSRegistrator
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/registration/LSRegistrationAction.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/registration/LSRegistrationAction.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/registration/LSRegistrationAction.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -21,124 +21,119 @@
*/
public class LSRegistrationAction extends AbstractRegistrationAction {
- private Logger logger =
LoggerFactory.getLogger(LSRegistrationAction.class);
+ private Logger logger =
LoggerFactory.getLogger(LSRegistrationAction.class);
- private boolean keepAliveEnabled=false;
-
- private LinkedList<URL> lsAddresses;
+ private boolean keepAliveEnabled = false;
- /**
- * number of registration to GLS in one iteration
- *
- */
- private int nrOfLSRegistration = 1;
- private List<Element> registeredKeys = new ArrayList<Element>();
+ private LinkedList<URL> lsAddresses;
- public void init() throws PerfSONARException {
- dataSource = getRegisterDataSource();
- registrationEventType = getRegistrationEventType();
- lookupInformation = getLookupInformation();
- lsAddresses = getLSAddresses();
- registrator = getLSRegistrator();
- keepAliveEnabled=isKeepAliveEnabled();
- }
+ /**
+ * number of registration to GLS in one iteration
+ *
+ */
+ private int nrOfLSRegistration = 1;
+ private List<Element> registeredKeys = new ArrayList<Element>();
- public void execute() {
- ServiceMessage response;
+ public void init() throws PerfSONARException {
+ dataSource = getRegisterDataSource();
+ registrationEventType = getRegistrationEventType();
+ lookupInformation = getLookupInformation();
+ lsAddresses = getLSAddresses();
+ registrator = getLSRegistrator();
+ keepAliveEnabled = isKeepAliveEnabled();
+ }
- if (keepAliveEnabled) {
-
- for (int c = 0; c < registeredKeys.size(); c++) {
- Element registeredKey = registeredKeys.get(c);
+ public void execute() {
+ ServiceMessage response;
- // send keep alive to last used GLS
- URL glsAddress = lsAddresses.getFirst();
- try {
- response =
registrator.keepalive(registeredKey, glsAddress);
- logger.debug("KeepAlive message
registered " + glsAddress);
+ if (keepAliveEnabled) {
- if
(isResponseSuccess(getResponseMetadata(response))) {
- logger.debug("KEEP ALIVE
accepted");
- } else {
-
registeredKeys.remove(registeredKey);
- logger.debug("KEEP ALIVE
rejected !");
- }
+ for (int c = 0; c < registeredKeys.size(); c++) {
+ Element registeredKey = registeredKeys.get(c);
- } catch (PerfSONARException e) {
- logger.debug("Problem with sending
KeepAlive message to :"
- +
glsAddress.toString());
- poolElement(lsAddresses);
- registeredKeys.remove(registeredKey);
- }
- }
- }else{
- registeredKeys.clear();
- }
+ // send keep alive to last used GLS
+ URL glsAddress = lsAddresses.getFirst();
+ try {
+ response = registrator.keepalive(registeredKey,
glsAddress);
+ logger.debug("KeepAlive message registered " +
glsAddress);
- // if registration using KeepAlive message failed or there
wasn't any
- // registration before ...
- if (registeredKeys.isEmpty()) {
+ if (isResponseSuccess(getResponseMetadata(response))) {
+ logger.debug("KEEP ALIVE accepted");
+ } else {
+ registeredKeys.remove(registeredKey);
+ logger.debug("KEEP ALIVE rejected !");
+ }
- ServiceMessage serviceRequestMessage = null;
- try {
- serviceRequestMessage =
getLSRegisterMessage();
- } catch (PerfSONARException e) {
- logger.warn("Cannot build registration
message !", e);
- }
+ } catch (PerfSONARException e) {
+ logger.debug("Problem with sending KeepAlive message to
:" + glsAddress.toString());
+ poolElement(lsAddresses);
+ registeredKeys.remove(registeredKey);
+ }
+ }
+ } else {
+ registeredKeys.clear();
+ }
- int nrOfAddresses = lsAddresses.size();
+ // if registration using KeepAlive message failed or there wasn't any
+ // registration before ...
+ if (registeredKeys.isEmpty()) {
- if (serviceRequestMessage != null) {
- // try to register to first n-working GLS
from list of all (n is a nrOfGLSRegistration)
- while (nrOfAddresses > 0) {
+ ServiceMessage serviceRequestMessage = null;
+ try {
+ serviceRequestMessage = getLSRegisterMessage();
+ } catch (PerfSONARException e) {
+ logger.warn("Cannot build registration message !", e);
+ }
- Message requestMessage = (Message)
serviceRequestMessage
- .getElement();
+ int nrOfAddresses = lsAddresses.size();
- URL glsAddress =
lsAddresses.get(registeredKeys.size());
- try {
- response =
registrator.register(requestMessage,
- glsAddress);
+ if (serviceRequestMessage != null) {
+ // try to register to first n-working GLS from list of all
(n is
+ // a nrOfGLSRegistration)
+ while (nrOfAddresses > 0) {
- logger.info("Registration
message sent");
- Element registeredKey =
getKeyFromResponse(response);
- if (registeredKey == null) {
- logger
-
.debug("no registerd key in registration response");
-
poolElement(lsAddresses);
- } else {
- // element registered
-
registeredKeys.add(registeredKey);
- if
(registeredKeys.size() == nrOfLSRegistration) {
- break;
- }
- }
- } catch (PerfSONARException e) {
- logger
-
.warn("Problem with sending registration message to :"
-
+ glsAddress.toString());
- poolElement(lsAddresses);
- }
- nrOfAddresses--;
- }
- } else {
- logger.warn("Cannot build
glsRegistrationMessage");
- }
- }
+ Message requestMessage = (Message)
serviceRequestMessage.getElement();
- if (registeredKeys.isEmpty()) {
- logger.warn("Registration to LS failed !!");
- } else {
- logger.debug("Registration completed");
- }
- }
+ URL glsAddress = lsAddresses.get(registeredKeys.size());
+ try {
+ response = registrator.register(requestMessage,
glsAddress);
- private void poolElement(LinkedList<URL> glsAddresses) {
- URL brokenGLSURL = glsAddresses.poll();
- glsAddresses.add(brokenGLSURL);
- }
+ logger.info("Registration message sent");
+ Element registeredKey = getKeyFromResponse(response);
+ if (registeredKey == null) {
+ logger.debug("no registerd key in registration
response");
+ poolElement(lsAddresses);
+ } else {
+ // element registered
+ registeredKeys.add(registeredKey);
+ if (registeredKeys.size() == nrOfLSRegistration)
{
+ break;
+ }
+ }
+ } catch (PerfSONARException e) {
+ logger.warn("Problem with sending registration
message to :" + glsAddress.toString());
+ poolElement(lsAddresses);
+ }
+ nrOfAddresses--;
+ }
+ } else {
+ logger.warn("Cannot build glsRegistrationMessage");
+ }
+ }
- public void refresh() {
+ if (registeredKeys.isEmpty()) {
+ logger.warn("Registration to LS failed !!");
+ } else {
+ logger.debug("Registration completed");
+ }
+ }
- }
+ private void poolElement(LinkedList<URL> glsAddresses) {
+ URL brokenGLSURL = glsAddresses.poll();
+ glsAddresses.add(brokenGLSURL);
+ }
+
+ public void refresh() {
+
+ }
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/registration/LSRegistrator.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/registration/LSRegistrator.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/registration/LSRegistrator.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -12,24 +12,17 @@
import org.perfsonar.base2.xml.nmwg.Key;
import org.perfsonar.base2.xml.nmwg.Message;
-
public interface LSRegistrator {
+ ServiceMessage register(Message requestMessage, URL lsUrl) throws
PerfSONARException;
- public ServiceMessage register(Message requestMessage, URL lsUrl)
- throws PerfSONARException;
+ // TODO: why Key, not String?
+ ServiceMessage deregister(Key key, URL lsUrl) throws PerfSONARException;
- //TODO: why Key, not String?
- public ServiceMessage deregister(Key key, URL lsUrl)
- throws PerfSONARException;
+ // TODO: why Key, not String?
+ ServiceMessage update(Key key, URL lsUrl) throws PerfSONARException;
- //TODO: why Key, not String?
- public ServiceMessage update(Key key, URL lsUrl)
- throws PerfSONARException;
+ // TODO: why Key, not String?
+ ServiceMessage keepalive(Element key, URL lsUrl) throws
PerfSONARException;
- //TODO: why Key, not String?
- public ServiceMessage keepalive(Element key, URL lsUrl)
- throws PerfSONARException;
-
-
-} //LSRegistrator
\ No newline at end of file
+} // LSRegistrator
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/registration/MetadataExistDBRegisterDataSource.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/registration/MetadataExistDBRegisterDataSource.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/registration/MetadataExistDBRegisterDataSource.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -16,76 +16,69 @@
import org.perfsonar.base2.xml.Element;
import org.perfsonar.base2.xml.nmwg.Message;
-
-
public class MetadataExistDBRegisterDataSource implements RegisterDataSource
{
+ // ------------------------------------------------------------- Class
+ // fields
- // ------------------------------------------------------------- Class
fields
+ private static final String GET_METADATA_XPATH = "declare namespace
nmwg='http://ggf.org/ns/nmwg/base/2.0/'; \n"
+ + "/nmwg:store/nmwg:metadata";
+ protected static final String DEFAULT_EXIST_COMPONENT = "exist";
- private static final String GET_METADATA_XPATH =
- "declare namespace nmwg='http://ggf.org/ns/nmwg/base/2.0/'; \n"
- + "/nmwg:store/nmwg:metadata";
+ protected static final String REGISTER_DATA_SOURCE_EXTENSION_NAME =
"registerExtension-registerDataSource";
- protected final static String DEFAULT_EXIST_COMPONENT = "exist";
+ // private static final Logger LOGGER =
+ // LoggerFactory.getLogger(ExistDBRegisterDataSource.class);
- protected final static String
REGISTER_DATA_SOURCE_EXTENSION_NAME="registerExtension-registerDataSource";
-
- //private static final Logger logger =
LoggerFactory.getLogger(ExistDBRegisterDataSource.class);
-
-
// ------------------------------------------------------------- Methods
-
public ServiceMessage getRegisterData() throws PerfSONARException {
- Configuration configuration =
- ConfigurationManager.
- getInstance().
- getConfiguration();
+ Configuration configuration =
ConfigurationManager.getInstance().getConfiguration();
- XMLDBComponent xmlDbComponent =
- (XMLDBComponent)
configuration.getAuxiliaryComponent(getExistComponentName(configuration));
+ XMLDBComponent xmlDbComponent = (XMLDBComponent) configuration
+ .getAuxiliaryComponent(getExistComponentName(configuration));
/*
- // getting mmetadata elements from the xmldb in the form of String
object
+ * // getting mmetadata elements from the xmldb in the form of String
+ * object
+ *
+ * ExtendedExistHTTPDataStorage dataStorage = new
+ * ExtendedExistHTTPDataStorage(); String results =
+ * dataStorage.getXQueryStringResult( GET_METADATA_XPATH,
+ * xmlDbComponent.getUri(), xmlDbComponent.getCredential());
+ *
+ * return (new ServiceMessage(results));
+ */
- ExtendedExistHTTPDataStorage dataStorage = new
ExtendedExistHTTPDataStorage();
- String results =
- dataStorage.getXQueryStringResult(
- GET_METADATA_XPATH, xmlDbComponent.getUri(),
xmlDbComponent.getCredential());
+ // getting mmetadata elements from the xmldb in the form of Element
+ // object
- return (new ServiceMessage(results));
- */
-
- // getting mmetadata elements from the xmldb in the form of Element
object
-
ExistHTTPDataStorage dataStorage = new ExistHTTPDataStorage();
- XMLDBResult xmldbResults =
- dataStorage.performXQuery(
- GET_METADATA_XPATH, xmlDbComponent.getUri(),
xmlDbComponent.getCredential());
+ XMLDBResult xmldbResults =
dataStorage.performXQuery(GET_METADATA_XPATH, xmlDbComponent.getUri(),
+ xmlDbComponent.getCredential());
- Collection <Element> elements = xmldbResults.getResults();
+ Collection<Element> elements = xmldbResults.getResults();
Message message = new Message();
- for (Element element : elements)
+ for (Element element : elements) {
message.addChild(element);
+ }
return (new ServiceMessage(message));
}
+ protected String getExistComponentName(Configuration configuration)
throws PerfSONARException {
- protected String getExistComponentName(Configuration configuration)
- throws PerfSONARException {
-
String name =
configuration.getExtensionOption(REGISTER_DATA_SOURCE_EXTENSION_NAME,
"exist-config");
- if (name != null)
- if (!name.trim().equals(""))
+ if (name != null) {
+ if (!name.trim().equals("")) {
return name;
+ }
+ }
return DEFAULT_EXIST_COMPONENT;
}
-
-} //ExistDBRegisterDataSource
\ No newline at end of file
+} // ExistDBRegisterDataSource
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/registration/RegisterDataSource.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/registration/RegisterDataSource.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/registration/RegisterDataSource.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -5,6 +5,6 @@
public interface RegisterDataSource {
- public ServiceMessage getRegisterData() throws PerfSONARException;
+ ServiceMessage getRegisterData() throws PerfSONARException;
-} //RegisterDataSource
\ No newline at end of file
+} // RegisterDataSource
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/requesthandler/EchoServiceEngine.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/requesthandler/EchoServiceEngine.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/requesthandler/EchoServiceEngine.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -1,8 +1,6 @@
package org.perfsonar.base2.service.requesthandler;
import org.perfsonar.base2.service.exceptions.PerfSONARException;
-import org.perfsonar.base2.service.requesthandler.ServiceEngine;
-import org.perfsonar.base2.service.requesthandler.ServiceMessage;
import org.perfsonar.base2.service.util.ResultCodesUtil;
import org.perfsonar.base2.xml.nmwg.Message;
import org.perfsonar.base2.xml.nmwg.Metadata;
@@ -24,7 +22,7 @@
// ------------------------------------------------------------- class
// fields
- private static final Logger logger =
LoggerFactory.getLogger(EchoServiceEngine.class);
+ private static final Logger LOGGER =
LoggerFactory.getLogger(EchoServiceEngine.class);
public static final String ECHO_EVENT_TYPE =
"http://schemas.perfsonar.net/tools/admin/echo/2.0";
@@ -34,23 +32,20 @@
public static final String ECHO_SELF_TEST =
"http://schemas.perfsonar.net/tools/admin/selftest";
-
-
// ------------------------------------------------------------- methods
- public void takeAction(ServiceMessage serviceRequest,
- ServiceMessage serviceResponse) throws PerfSONARException {
+ public void takeAction(ServiceMessage serviceRequest, ServiceMessage
serviceResponse) throws PerfSONARException {
- logger.debug("Simple echo ServiceEngine started.");
+ LOGGER.debug("Simple echo ServiceEngine started.");
Message request = serviceRequest.getMessageElement();
String eventType = getEventType(request);
- if (!eventType.equals(ECHO_EVENT_TYPE))
- throw new PerfSONARException(
- "Wrong echo eventType value in the request");
+ if (!eventType.equals(ECHO_EVENT_TYPE)) {
+ throw new PerfSONARException("Wrong echo eventType value in the
request");
+ }
- Message response = ResultCodesUtil.generateResultMessage(
- ECHO_SUCCESS_RESULT_CODE, ECHO_SUCCESS_RESULT_CODE_DSC);
+ Message response = ResultCodesUtil
+ .generateResultMessage(ECHO_SUCCESS_RESULT_CODE,
ECHO_SUCCESS_RESULT_CODE_DSC);
response.setId("Resp_" + request.getAttribute("id"));
response.addAttribute("type", "EchoResponse");
@@ -58,29 +53,27 @@
serviceResponse.setElement(response);
}
-
protected String getEventType(Message request) throws PerfSONARException
{
- Metadata reqMetadata = request.getMetadataCollection().iterator()
- .next();
+ Metadata reqMetadata =
request.getMetadataCollection().iterator().next();
- if (reqMetadata == null)
+ if (reqMetadata == null) {
throw new PerfSONARException("There is no metadata in the
request.");
+ }
- if (reqMetadata.getEventTypes() == null)
- throw new PerfSONARException(
- "The metadata element does not contain eventType
element.");
+ if (reqMetadata.getEventTypes() == null) {
+ throw new PerfSONARException("The metadata element does not
contain eventType element.");
+ }
- if (reqMetadata.getEventTypes().size() != 1)
- throw new PerfSONARException(
- "The metadata element does not contain only one
eventType element.");
+ if (reqMetadata.getEventTypes().size() != 1) {
+ throw new PerfSONARException("The metadata element does not
contain only one eventType element.");
+ }
EventType reqEventType = reqMetadata.getEventTypes().get(0);
return reqEventType.getEventType().trim();
}
-
protected Message getResultMessage(String eventType, String description)
{
Metadata meta = new Metadata("result-code", "nmwg");
@@ -88,8 +81,7 @@
meta.addChild(evt);
Data data = new Data("result-code-description", "result-code",
"nmwg");
- Element datum = new Element("datum", "nmwgr",
- "http://ggf.org/ns/nmwg/result/2.0/");
+ Element datum = new Element("datum", "nmwgr",
"http://ggf.org/ns/nmwg/result/2.0/");
datum.setText(description);
data.addChild(datum);
@@ -97,7 +89,6 @@
}
-
protected Message getResultMessage(String eventType, Data data) {
Metadata meta = new Metadata("result-code", "nmwg");
@@ -109,7 +100,6 @@
}
-
protected Message getResultMessage(Metadata meta, Data data) {
Message message = new Message();
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/requesthandler/RequestHandler.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/requesthandler/RequestHandler.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/requesthandler/RequestHandler.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -8,124 +8,109 @@
import org.perfsonar.base2.xml.Element;
import org.perfsonar.base2.xml.nmwg.Message;
-
/**
* Base class for all Request Handlers
*
* @author Maciej Glowiak
- *
+ *
*/
public abstract class RequestHandler {
-
// ----------------------------------------------------- instance
variables
+ private static final Logger LOGGER =
LoggerFactory.getLogger(RequestHandler.class);
- private static final Logger logger =
LoggerFactory.getLogger(RequestHandler.class);
-
-
// -----------------------------------------------------------
Constructor
-
protected RequestHandler() {
}
-
// ---------------------------------------------------------------
methods
-
/**
* MessageHandler factory. Creates proper MessageHandler basing on class
* name
*/
- protected MessageHandler getMessageHandler(String className)
- throws PerfSONARException {
+ protected MessageHandler getMessageHandler(String className) throws
PerfSONARException {
MessageHandler mh = null;
- //try to create a message handler for the given message type.
+ // try to create a message handler for the given message type.
// get a new class for that classname
try {
- mh = (MessageHandler)Class.forName(className).newInstance();
+ mh = (MessageHandler) Class.forName(className).newInstance();
} catch (Exception e) {
- //InstantiationException, IllegalAccessException,
ClassNotFoundException
- //NullPointerException, etc.
- throw new PerfSONARException(
- "error",
- "Cannot create MessageHandler, nested exception is: "+
- e.toString());
+ // InstantiationException, IllegalAccessException,
+ // ClassNotFoundException
+ // NullPointerException, etc.
+ throw new PerfSONARException("error", "Cannot create
MessageHandler, nested exception is: " + e.toString());
}
if (mh == null) {
- throw new PerfSONARException(
- "error",
- "Cannot create MessageHandler for unknown reason");
- } else
+ throw new PerfSONARException("error", "Cannot create
MessageHandler for unknown reason");
+ } else {
return mh;
+ }
}
-
/**
- * Return mapping (classname) for particular message type
- * or throws an exception
+ * Return mapping (classname) for particular message type or throws an
+ * exception
+ *
* @param e
* @return
* @throws PerfSONARException
*/
- protected String getClassNameFromType(Element e)
- throws PerfSONARException {
+ protected String getClassNameFromType(Element e) throws
PerfSONARException {
String type = e.getAttribute("type");
- if (type==null){
- //TODO: url event types
- throw new PerfSONARException("error.no_message_type","No
message type in request. Cannot find MessageHandler");
+ if (type == null) {
+ // TODO: url event types
+ throw new PerfSONARException("error.no_message_type",
+ "No message type in request. Cannot find
MessageHandler");
}
-
- logger.debug("Message type is ["+type+"]");
+ LOGGER.debug("Message type is [" + type + "]");
- //get Message Handler for message type (from mapping)
+ // get Message Handler for message type (from mapping)
String className = null;
try {
- className= ConfigurationManager.getInstance().
-
getConfiguration().getMessageHandlerClassName(type);
+ className =
ConfigurationManager.getInstance().getConfiguration().getMessageHandlerClassName(type);
} catch (Exception ex) {
- logger.warn("Message type ["+type+
- "] not supported or missing mapping/configuration.");
+ LOGGER.warn("Message type [" + type + "] not supported or
missing mapping/configuration.");
}
- if (className == null) throw new PerfSONARException(
- "error/message_type_not_supported","Message type ["+type+
- "] not supported or missing mapping in configuration file. "
+
- "Cannot find proper MessageHandler.");
+ if (className == null) {
+ throw new PerfSONARException("error/message_type_not_supported",
"Message type [" + type
+ + "] not supported or missing mapping in configuration
file. "
+ + "Cannot find proper MessageHandler.");
+ }
return className;
}
-
/**
* Main method of all message handlers
*
- * @param request incoming message
+ * @param request
+ * incoming message
* @return outgoing message
* @throws PerfSONARException
*/
- protected void runService(ServiceMessage request, ServiceMessage
response)
- throws PerfSONARException {
+ protected void runService(ServiceMessage request, ServiceMessage
response) throws PerfSONARException {
- logger.debug("Run service handler");
+ LOGGER.debug("Run service handler");
Element requestElement = request.getElement();
- if (requestElement == null){
- //TODO : URL event types
- throw new
PerfSONARException("error.no_element_object_in_request","No element object in
request.");
+ if (requestElement == null) {
+ // TODO : URL event types
+ throw new
PerfSONARException("error.no_element_object_in_request", "No element object
in request.");
}
-
String className = getClassNameFromType(requestElement);
MessageHandler mh = getMessageHandler(className);
@@ -134,13 +119,13 @@
mh.execute(request, response);
- } else{
- //TODO : URL event types
- throw new
PerfSONARException("error.common.parse_error","Object
["+request.getClass()+"] is not a valid Message ["+Message.class+"] element.
Check parser mapping in the configuration file");
+ } else {
+ // TODO : URL event types
+ throw new PerfSONARException("error.common.parse_error", "Object
[" + request.getClass()
+ + "] is not a valid Message [" + Message.class
+ + "] element. Check parser mapping in the configuration
file");
}
-
}
-
-} //RequestHandler
\ No newline at end of file
+} // RequestHandler
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/requesthandler/ServiceEngine.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/requesthandler/ServiceEngine.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/requesthandler/ServiceEngine.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -4,15 +4,12 @@
/**
* This interface is a base for all Service Engine classes.
+ *
* @author Maciej Glowiak
- *
+ *
*/
public interface ServiceEngine {
+ void takeAction(ServiceMessage request, ServiceMessage response) throws
PerfSONARException;
-
- public void takeAction(ServiceMessage request, ServiceMessage response)
- throws PerfSONARException;
-
-
-} //ServiceEngine
+} // ServiceEngine
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/requesthandler/ServiceMessage.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/requesthandler/ServiceMessage.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/requesthandler/ServiceMessage.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -5,35 +5,32 @@
/**
* Container for request / response between base2 and service modules
+ *
* @author Roman Lapacz
* @author Maciej Glowiak
- *
+ *
*/
public class ServiceMessage {
-
protected Element element = null;
protected String text = null;
-
public ServiceMessage() {
}
-
public ServiceMessage(String text) {
super();
this.text = text;
}
-
public ServiceMessage(Element element) {
super();
setElement(element);
}
-
/**
* Sets Element value
+ *
* @param element
*/
public void setElement(Element element) {
@@ -41,7 +38,8 @@
}
/**
- * gets as NMWG Element
+ * gets as NMWG Element
+ *
* @return
*/
public Element getElement() {
@@ -50,34 +48,35 @@
/**
* Tries to get element as Message object, otherwise returns null
+ *
* @return
*/
public Message getMessageElement() {
try {
- Message m = (Message)element;
+ Message m = (Message) element;
return m;
} catch (RuntimeException rex) {
return null;
}
-
+
}
/**
* Sets textual value
+ *
* @param text
*/
public void setText(String text) {
this.text = text;
}
-
/**
* Gets textual value (if set)
+ *
* @param text
*/
public String getText() {
return text;
}
-
-}
\ No newline at end of file
+}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/requesthandler/axis2/Axis2RequestHandler.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/requesthandler/axis2/Axis2RequestHandler.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/requesthandler/axis2/Axis2RequestHandler.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -27,19 +27,16 @@
import java.io.StringReader;
-
/**
* PerfSONAR service main class. Handles requests from Axis2 and runs a
service
*
* @author Maciej Glowiak
- *
+ *
*/
public class Axis2RequestHandler extends RequestHandler {
-
// ----------------------------------------------------- instance
variables
-
/**
* axis2 service context, will be set by PerfsonarService Axis2 class
*/
@@ -47,70 +44,66 @@
private ConfigurationManager configurationManager = null;
- private static final Logger logger =
LoggerFactory.getLogger(Axis2RequestHandler.class);
+ private static final Logger LOGGER =
LoggerFactory.getLogger(Axis2RequestHandler.class);
-
// ------------------------------------------------------------
constructor
-
public Axis2RequestHandler() {
}
-
// --------------------------------------------------------- public
methods
-
public OMElement message(OMElement inOMElement) {
- //start time measurement
+ // start time measurement
long t1 = System.currentTimeMillis();
- if (serviceContext != null) {
- //print data taken from ServiceContext
- logger.debug("PerfSONAR Request Handler for Axis2 started.
Service name is ["+
- serviceContext.getName()+"], URL is
["+serviceContext.getMyEPR()+"]");
+ if (serviceContext != null) {
+ // print data taken from ServiceContext
+ LOGGER.debug("PerfSONAR Request Handler for Axis2 started.
Service name is [" + serviceContext.getName()
+ + "], URL is [" + serviceContext.getMyEPR() + "]");
} else {
- logger.debug("PerfSONAR Request Handler for Axis2 started. " +
- "WARNING: Axis2 ServiceContext is null, perhaps service
is " +
- "just tested without Axis2 or Axis2 is misconfigured");
+ LOGGER.debug("PerfSONAR Request Handler for Axis2 started. "
+ + "WARNING: Axis2 ServiceContext is null, perhaps
service is "
+ + "just tested without Axis2 or Axis2 is misconfigured");
}
- //get configuration
+ // get configuration
try {
configurationManager = ConfigurationManager.getInstance();
Configuration configuration =
configurationManager.getConfiguration();
Service service = configuration.getService();
- logger.debug("Service name from perfSONAR configuration is [" +
service.getName()+"]");
+ LOGGER.debug("Service name from perfSONAR configuration is [" +
service.getName() + "]");
- //response object
+ // response object
OMElement outOMElement = null;
- //Get stream reader from Axis2 AXIOM
+ // Get stream reader from Axis2 AXIOM
XMLStreamReader xmlStreamReader =
inOMElement.getXMLStreamReader();
- //Parse and build NMWG objects tree
+ // Parse and build NMWG objects tree
StaxParser sp = new ConfigurationStaxParser();
Element inElement = sp.parse(xmlStreamReader);
ServiceMessage requestServiceMessage = new
ServiceMessage(inElement);
ServiceMessage responseServiceMessage = new ServiceMessage();
- //Run PerfSONAR Service
+ // Run PerfSONAR Service
runService(requestServiceMessage, responseServiceMessage);
- //select proper response type - String or NMWG classes
+ // select proper response type - String or NMWG classes
Element outElement = responseServiceMessage.getElement();
String outText = responseServiceMessage.getText();
if (outElement != null) {
- //convert Element to AXIOM OMElement
+ // convert Element to AXIOM OMElement
AXIOMCreator omCreator = new AXIOMCreator();
outOMElement = omCreator.getElement(outElement);
} else if (outText != null) {
- //read directly from string
+ // read directly from string
StringReader stringReader = new StringReader(outText);
XMLInputFactory xif = XMLInputFactory.newInstance();
XMLStreamReader reader =
xif.createXMLStreamReader(stringReader);
@@ -120,57 +113,54 @@
} else {
- throw new PerfSONARException(
- "exception_response",
- "something wrong with response. It is empty");
+ throw new PerfSONARException("exception_response",
"something wrong with response. It is empty");
}
- //stop time measurement
+ // stop time measurement
long t2 = System.currentTimeMillis();
- logger.debug("Service done successfuly in ["+(t2-t1)+"ms]");
+ LOGGER.debug("Service done successfuly in [" + (t2 - t1) +
"ms]");
- //return successful response
+ // return successful response
return outOMElement;
- }catch(PerfSONARException ex){
- return generateErrorMessage(ex);
+ } catch (PerfSONARException ex) {
+ return generateErrorMessage(ex);
} catch (Exception excp) {
- //perfSONAR result code if request message cannot be server
(parsing, etc.)
- logger.error("Parse error: "+excp.toString());
+ // perfSONAR result code if request message cannot be server
+ // (parsing, etc.)
+ LOGGER.error("Parse error: " + excp.toString());
- //return error response
- //TODO: URL event types
+ // return error response
+ // TODO: URL event types
return generateErrorMessage(new
PerfSONARException("error.request",
- "Error in Request Handler, nested exception was: "
- +excp.toString()));
+ "Error in Request Handler, nested exception was: " +
excp.toString()));
}
}
-
-
/**
* Generates OMElement containing error message
- * @param code result code
- * @param description result code description
+ *
+ * @param code
+ * result code
+ * @param description
+ * result code description
* @return
*/
protected OMElement generateErrorMessage(PerfSONARException ex) {
/*
- Generates error code:
- <nmwg:message type='ResultCode' id='error'
xmlns:nmwg='http://ggf.org/ns/nmwg/base/2.0/'>
- <nmwg:metadata id='result-code1'>
- <nmwg:eventType>"+code+"</nmwg:eventType>
- </nmwg:metadata>
- <nmwg:data id='result-code-description1'
metadataIdRef='result-code1'>
- <nmwgr:datum>"+description+"</nmwgr:datum>
- </nmwg:data>
- </nmwg:message>
- */
-
- //TODO : common error message builder
+ * Generates error code: <nmwg:message type='ResultCode' id='error'
+ * xmlns:nmwg='http://ggf.org/ns/nmwg/base/2.0/'> <nmwg:metadata
+ * id='result-code1'> <nmwg:eventType>"+code+"</nmwg:eventType>
+ * </nmwg:metadata> <nmwg:data id='result-code-description1'
+ * metadataIdRef='result-code1'>
+ * <nmwgr:datum>"+description+"</nmwgr:datum> </nmwg:data>
+ * </nmwg:message>
+ */
+
+ // TODO : common error message builder
OMFactory fac = OMAbstractFactory.getOMFactory();
OMNamespace def = fac.createOMNamespace("", "");
OMNamespace nmwg =
fac.createOMNamespace("http://ggf.org/ns/nmwg/base/2.0/", "nmwg");
@@ -180,10 +170,10 @@
message.addAttribute(fac.createOMAttribute("type", def,
"ErrorResponse"));
message.addAttribute(fac.createOMAttribute("id", def, "error"));
- String metadataId="rescode";
-
+ String metadataId = "rescode";
+
OMElement meta = fac.createOMElement("metadata", nmwg);
- meta.addAttribute(fac.createOMAttribute("id",def,metadataId));
+ meta.addAttribute(fac.createOMAttribute("id", def, metadataId));
message.addChild(meta);
OMElement evt = fac.createOMElement("eventType", nmwg);
@@ -191,8 +181,8 @@
meta.addChild(evt);
OMElement data = fac.createOMElement("data", nmwg);
- data.addAttribute(fac.createOMAttribute("id",def,"rescode-desc"));
-
data.addAttribute(fac.createOMAttribute("metadataIdRef",def,metadataId));
+ data.addAttribute(fac.createOMAttribute("id", def, "rescode-desc"));
+ data.addAttribute(fac.createOMAttribute("metadataIdRef", def,
metadataId));
message.addChild(data);
OMElement datum = fac.createOMElement("datum", nmwgr);
@@ -203,15 +193,12 @@
}
-
public void setServiceContext(ServiceContext serviceContext) {
this.serviceContext = serviceContext;
}
-
// ---------------------------------------------------------- axis2
context
-
-} //Axis2RequestHandler
\ No newline at end of file
+} // Axis2RequestHandler
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/requesthandler/file/FileRequestHandler.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/requesthandler/file/FileRequestHandler.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/requesthandler/file/FileRequestHandler.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -16,18 +16,17 @@
* Simple RequestHandler for Files
*
* @author Maciej Glowiak
- *
+ *
*/
public class FileRequestHandler extends RequestHandler {
-
public void runService(String inFile, String outFile) throws
PerfSONARException {
try {
- //read file to input stream
+ // read file to input stream
File file = new File(inFile);
FileInputStream fis = new FileInputStream(file);
- //parse - result in Element
+ // parse - result in Element
StaxParser sp = new StaxParser();
Element e = sp.parse(fis);
@@ -35,8 +34,7 @@
ServiceMessage response = new ServiceMessage();
runService(request, response);
-
- //serialize to AXIOM
+ // serialize to AXIOM
AXIOMCreator cr = new AXIOMCreator();
OMElement omel = cr.getElement(response.getElement());
@@ -46,13 +44,13 @@
fos.close();
} catch (Exception e) {
if (e instanceof PerfSONARException) {
- throw (PerfSONARException)e;
+ throw (PerfSONARException) e;
} else {
- throw new PerfSONARException("error", "Cannot run service by
Request Handler, nested exception is: "+e.toString());
+ throw new PerfSONARException("error", "Cannot run service by
Request Handler, nested exception is: "
+ + e.toString());
}
}
-
}
/**
@@ -71,5 +69,4 @@
}
-
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/scheduler/Scheduler.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/scheduler/Scheduler.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/scheduler/Scheduler.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -11,42 +11,49 @@
/**
* Starts scheduling tasks
*/
- public void start();
+ void start();
/**
* Finishes scheduling tasks
*/
- public void finish();
+ void finish();
/**
* Set interval between two subsequent runs
- * @param interval in seconds
+ *
+ * @param interval
+ * in seconds
*/
- public void setInterval(int interval);
+ void setInterval(int interval);
/**
* Get interval between two subsequent runs
+ *
* @return seconds
*/
- public int getInterval();
+ int getInterval();
/**
* Adds scheduler task with default interval for the task
- * @param t task
+ *
+ * @param t
+ * task
*/
- public void addTask(SchedulerTask t);
+ void addTask(SchedulerTask t);
/**
* Adds SchedulerAction encapsuled in a SchedulerTask with specific
interval
- * @param interval in seconds
- * @param action any action to be run each <code>interval</code> seconds
+ *
+ * @param interval
+ * in seconds
+ * @param action
+ * any action to be run each <code>interval</code> seconds
*/
- public void addTask(int interval, SchedulerAction action);
+ void addTask(int interval, SchedulerAction action);
/**
* Removes task containing specific action
*/
- public void removeTask(SchedulerAction action);
+ void removeTask(SchedulerAction action);
-
-} //Scheduler
\ No newline at end of file
+} // Scheduler
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/scheduler/SchedulerAction.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/scheduler/SchedulerAction.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/scheduler/SchedulerAction.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -1,13 +1,13 @@
package org.perfsonar.base2.service.scheduler;
-
/**
* Interface that represents simple scheduler action
+ *
* @author Maciej Glowiak
- *
+ *
*/
public interface SchedulerAction {
- public void runAction();
+ void runAction();
-}
\ No newline at end of file
+}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/scheduler/SchedulerTask.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/scheduler/SchedulerTask.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/scheduler/SchedulerTask.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -13,212 +13,209 @@
*/
public class SchedulerTask {
- protected static final Logger logger =
LoggerFactory.getLogger(SchedulerTask.class);
+ protected static final Logger LOGGER =
LoggerFactory.getLogger(SchedulerTask.class);
- // --------------------------------------------- Variables
+ // --------------------------------------------- Variables
- private long MIN_INTERVAL = 1; // seconds
+ private static final long MIN_INTERVAL = 1; // seconds
- private long interval = MIN_INTERVAL; // minimal interval (in seconds)
-
// between actions
+ private long interval = MIN_INTERVAL; // minimal interval (in seconds)
+ // between actions
- private long timestamp = 0; // last timestamp when action was
performed; 0 -
- // never
+ private long timestamp = 0; // last timestamp when action was performed;
0 -
+ // never
- private SchedulerAction action;
+ private SchedulerAction action;
- private Thread thread;
+ private Thread thread;
- public SchedulerTask(long interval, final SchedulerAction action) {
+ public SchedulerTask(long interval, final SchedulerAction action) {
- // check whether interval isn't lower than minimal
- if (interval < MIN_INTERVAL) {
- logger.debug("Requested interval for action [" +
action.getClass()
- + "] too low. Taking [" +
MIN_INTERVAL + "] seconds");
- this.interval = MIN_INTERVAL;
- } else {
- logger.debug("Interval for action [" +
action.getClass()
- + "] set to [" + interval + "]
seconds");
- this.interval = interval;
- }
- this.action = action;
- this.timestamp = 0;
+ // check whether interval isn't lower than minimal
+ if (interval < MIN_INTERVAL) {
+ LOGGER.debug("Requested interval for action [" +
action.getClass() + "] too low. Taking [" + MIN_INTERVAL
+ + "] seconds");
+ this.interval = MIN_INTERVAL;
+ } else {
+ LOGGER.debug("Interval for action [" + action.getClass() + "]
set to [" + interval + "] seconds");
+ this.interval = interval;
+ }
+ this.action = action;
+ this.timestamp = 0;
- thread = createThread();
- }
+ thread = createThread();
+ }
- private Thread createThread() {
- return new Thread() {
- @Override
- public void run() {
- action.runAction();
- }
- };
- }
+ private Thread createThread() {
+ return new Thread() {
+ @Override
+ public void run() {
+ action.runAction();
+ }
+ };
+ }
- /**
- * This constructor is used, when some action should be run in the
future
- *
- * @param interval
- * interval for running action in seconds
- * @param action
- * action to run
- * @param startTimestamp
- * when should we start running action
- */
- public SchedulerTask(long interval, final SchedulerAction action,
- long startTimestamp) {
- this(interval, action); // interval in seconds
- timestamp = startTimestamp - (interval * 1000);
- }
-
- /**
- * checks whether action can start
- *
- * @return
- */
- public boolean canRun() {
- return (timestamp + (interval * 1000) -
System.currentTimeMillis())<= 0;
- }
+ /**
+ * This constructor is used, when some action should be run in the future
+ *
+ * @param interval
+ * interval for running action in seconds
+ * @param action
+ * action to run
+ * @param startTimestamp
+ * when should we start running action
+ */
+ public SchedulerTask(long interval, final SchedulerAction action, long
startTimestamp) {
+ this(interval, action); // interval in seconds
+ timestamp = startTimestamp - (interval * 1000);
+ }
- /**
- * Runs proper action as new Thread (only if time is out)
- */
- public boolean runAction() {
+ /**
+ * checks whether action can start
+ *
+ * @return
+ */
+ public boolean canRun() {
+ return (timestamp + (interval * 1000) - System.currentTimeMillis())
<= 0;
+ }
- logger.debug("Scheduler Task [" + this.getClass() + "] -
interval ["
- + interval + "] seconds");
+ /**
+ * Runs proper action as new Thread (only if time is out)
+ */
+ public boolean runAction() {
- // if timestamp older than current - interval
+ LOGGER.debug("Scheduler Task [" + this.getClass() + "] - interval ["
+ interval + "] seconds");
- logger.debug("Scheduler run action [" + action.getClass() +
"]");
+ // if timestamp older than current - interval
- timestamp = System.currentTimeMillis();
+ LOGGER.debug("Scheduler run action [" + action.getClass() + "]");
- // TODO: to be changed - should be thread pool?
- // run action in thread
+ timestamp = System.currentTimeMillis();
- if (thread.isAlive()) {
- // do nothing
- logger.debug("last action is already running");
- } else {
- thread = createThread();
- thread.start();
- }
+ // TODO: to be changed - should be thread pool?
+ // run action in thread
- // if action is being performed return true
- return true;
+ if (thread.isAlive()) {
+ // do nothing
+ LOGGER.debug("last action is already running");
+ } else {
+ thread = createThread();
+ thread.start();
+ }
- }
+ // if action is being performed return true
+ return true;
- /**
- * get encapsulated SchedulerAction
- *
- * @return
- */
- public SchedulerAction getAction() {
+ }
- return action;
+ /**
+ * get encapsulated SchedulerAction
+ *
+ * @return
+ */
+ public SchedulerAction getAction() {
- }
+ return action;
- /**
- * sets Action that will be run as a task
- *
- * @param action
- */
- public void setAction(SchedulerAction action) {
+ }
- this.action = action;
+ /**
+ * sets Action that will be run as a task
+ *
+ * @param action
+ */
+ public void setAction(SchedulerAction action) {
- }
+ this.action = action;
- /**
- * Get interval (in seconds) between two subsequence runs of action
- *
- * @param interval
- */
- public long getInterval() {
+ }
- return interval;
+ /**
+ * Get interval (in seconds) between two subsequence runs of action
+ *
+ * @param interval
+ */
+ public long getInterval() {
- }
+ return interval;
- /**
- * Set interval between two subsequence runs of action,
- *
- * @param interval
- * in seconds
- */
- public void setInterval(long interval) {
+ }
- this.interval = interval;
+ /**
+ * Set interval between two subsequence runs of action,
+ *
+ * @param interval
+ * in seconds
+ */
+ public void setInterval(long interval) {
- }
+ this.interval = interval;
- /**
- * Returns timestamp of recent run of action
- *
- * @return
- */
- public long getTimestamp() {
+ }
- return timestamp;
+ /**
+ * Returns timestamp of recent run of action
+ *
+ * @return
+ */
+ public long getTimestamp() {
- }
+ return timestamp;
- /**
- * Set timestamp of recent run of action on the beginning of epoch
(1970),
- * so action should be run immediately (in the next cycle of
Scheduler)
- *
- */
- public void resetTimestamp() {
+ }
- this.timestamp = 0;
+ /**
+ * Set timestamp of recent run of action on the beginning of epoch
(1970),
+ * so action should be run immediately (in the next cycle of Scheduler)
+ *
+ */
+ public void resetTimestamp() {
- }
+ this.timestamp = 0;
- /**
- * Return hash code for this SchedulerTask, which in turn returns
action's
- * hash code or 0 if action is null.
- *
- * @return hash code
- */
- public int hashCode() {
+ }
- return action == null ? 0 : action.hashCode();
+ /**
+ * Return hash code for this SchedulerTask, which in turn returns
action's
+ * hash code or 0 if action is null.
+ *
+ * @return hash code
+ */
+ public int hashCode() {
- }
+ return action == null ? 0 : action.hashCode();
- /**
- * Return equality of this object based only on equality of action
objects.
- *
- * @param o
- * other objects (should be instanceof SchedulerTask
- * @return true if both action objects are equal
- */
- public boolean equals(Object o) {
+ }
- if (o == null)
- return false;
+ /**
+ * Return equality of this object based only on equality of action
objects.
+ *
+ * @param o
+ * other objects (should be instanceof SchedulerTask
+ * @return true if both action objects are equal
+ */
+ public boolean equals(Object o) {
- return o instanceof SchedulerTask ? (((SchedulerTask)
o).action == null ? action == null
- : ((SchedulerTask) o).action.equals(action))
- : false;
+ if (o == null) {
+ return false;
+ }
- }
+ return o instanceof SchedulerTask ? (((SchedulerTask) o).action ==
null ? action == null
+ : ((SchedulerTask) o).action.equals(action)) : false;
- /**
- * checks whether action thread is alive
- *
- * @return
- */
- public boolean isThreadAlive() {
- if (thread != null) {
- return thread.isAlive();
- } else {
- return false;
- }
- }
+ }
+ /**
+ * checks whether action thread is alive
+ *
+ * @return
+ */
+ public boolean isThreadAlive() {
+ if (thread != null) {
+ return thread.isAlive();
+ } else {
+ return false;
+ }
+ }
+
} // SchedulerTask
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/scheduler/SchedulingComponent.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/scheduler/SchedulingComponent.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/scheduler/SchedulingComponent.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -4,15 +4,15 @@
import org.perfsonar.base2.service.configuration.Action;
import org.perfsonar.base2.service.exceptions.PerfSONARException;
+
/**
- * Scheduling component is loaded automatically by ConfigurationManager
- * when there exists a scheduler entry in configuration file.
+ * Scheduling component is loaded automatically by ConfigurationManager when
+ * there exists a scheduler entry in configuration file.
*
* @author Maciej Glowiak
* @author Roman Lapacz
*/
-public class SchedulingComponent extends
- org.perfsonar.base2.service.configuration.SchedulingComponent {
+public class SchedulingComponent extends
org.perfsonar.base2.service.configuration.SchedulingComponent {
// ----------------------------------------------------------- Variables
@@ -24,8 +24,6 @@
public static final int DEFAULT_INTERVAL = 10; // seconds
-
-
// ----------------------------------------------------------- Methods
@Override
@@ -34,11 +32,11 @@
loadSettings();
createScheduler();
}
-
+
@Override
- public void run() throws PerfSONARException {
- runScheduler();
- }
+ public void run() throws PerfSONARException {
+ runScheduler();
+ }
@Override
public void destroy() throws PerfSONARException {
@@ -47,82 +45,76 @@
scheduler = null;
}
-
/**
* gets settings from configuration file
+ *
* @throws PerfSONARException
*/
protected void loadSettings() throws PerfSONARException {
- logger.debug("SchedulingComponent - loading configuration");
-
- //get classname
+ LOGGER.debug("SchedulingComponent - loading configuration");
+
+ // get classname
schedulerClassName = getOption("schedulerClassName").getValue();
-
- //get interval in seconds
+
+ // get interval in seconds
String intervalStr = getOption("interval").getValue();
try {
interval = Integer.parseInt(intervalStr);
} catch (Exception ex) {
- logger
- .warn("Can not get correct interval value for scheduling
from the configuration. "
- + " Default value is taken. Nester exception is:
"+ex.getMessage());
+ LOGGER.warn("Can not get correct interval value for scheduling
from the configuration. "
+ + " Default value is taken. Nester exception is: " +
ex.getMessage());
interval = DEFAULT_INTERVAL;
}
-
}
-
protected Scheduler createScheduler() throws PerfSONARException {
try {
- scheduler = (Scheduler) Class.forName(schedulerClassName)
- .newInstance();
+ scheduler = (Scheduler)
Class.forName(schedulerClassName).newInstance();
registerActions();
} catch (Exception e) {
- //TODO: url event types
- throw new
PerfSONARException("error.scheduler.wrong_data_storage",
- "\n Cannot instantiate Scheduler [" + e.getMessage());
+ // TODO: url event types
+ throw new
PerfSONARException("error.scheduler.wrong_data_storage", "\n Cannot
instantiate Scheduler ["
+ + e.getMessage());
}
return scheduler;
}
-
protected void runScheduler() throws PerfSONARException {
if (scheduler != null) {
- scheduler.setInterval(interval); //seconds
+ scheduler.setInterval(interval); // seconds
scheduler.start();
- } else
- logger.error("Can not start the scheduler because it does not
exist");
+ } else {
+ LOGGER.error("Can not start the scheduler because it does not
exist");
+ }
}
-
protected void stopScheduler() throws PerfSONARException {
- if (scheduler != null)
+ if (scheduler != null) {
scheduler.finish();
- else
- logger.warn("Can not stop the scheduler because it does not
exist");
+ } else {
+ LOGGER.warn("Can not stop the scheduler because it does not
exist");
+ }
}
-
public Scheduler getScheduler() {
return this.scheduler;
}
-
public void setScheduler(Scheduler scheduler) {
this.scheduler = scheduler;
}
-
/**
* Returns interval in seconds
+ *
* @return
*/
public int getInterval() {
@@ -131,7 +123,8 @@
}
/**
- * Sets interval in seconds
+ * Sets interval in seconds
+ *
* @param interval
*/
public void setInterval(int interval) {
@@ -139,51 +132,47 @@
this.interval = interval;
}
-
/**
- * Adds all actions from configuration file
- * Each action may have two common parameters (in option parameter):
- * - <code>interval</code> in seconds
- * - <code>status</code> = on / off
- * If status is off, action won't be loaded by the scheduler
- *
+ * Adds all actions from configuration file Each action may have two
common
+ * parameters (in option parameter): - <code>interval</code> in seconds -
+ * <code>status</code> = on / off If status is off, action won't be
loaded
+ * by the scheduler
+ *
*/
public void registerActions() {
- logger.debug("RegisterActions: Start of registering schedulling
tasks. Default interval is ["+interval+"] sec");
+ LOGGER.debug("RegisterActions: Start of registering schedulling
tasks. Default interval is [" + interval
+ + "] sec");
if (scheduler != null) {
-
+
Collection<Action> actions = getActions().getActions().values();
-
+
for (Action action : actions) {
-
+
// get option "interval" from action and try to convert it to
// int
int actionInterval = this.interval;
try {
- actionInterval = Integer.parseInt(action.getOption(
- "interval").getValue());
+ actionInterval =
Integer.parseInt(action.getOption("interval").getValue());
} catch (Exception ex) {
- //NullPointer if no option or NumberFormatException
- logger.warn("Taking default ["+actionInterval+"] value
of action interval");
+ // NullPointer if no option or NumberFormatException
+ LOGGER.warn("Taking default [" + actionInterval + "]
value of action interval");
}
-
+
// get option status - on/off
String actionStatus = "on";
try {
actionStatus = action.getOption("status").getValue();
- } catch (Exception ex) { }
-
+ } catch (Exception ex) {
+ }
+
if ("on".equals(actionStatus)) {
scheduler.addTask(actionInterval, (SchedulerAction)
action);
- logger.debug("Action [" + action.getName() + "] class ["
- + action.getClass()
- + "] registered to the scheduler with interval ["
- + actionInterval + "] seconds");
+ LOGGER.debug("Action [" + action.getName() + "] class ["
+ action.getClass()
+ + "] registered to the scheduler with interval
[" + actionInterval + "] seconds");
} else {
- logger.info("Action [" + action.getName() + "] class ["
- + action.getClass()
+ LOGGER.info("Action [" + action.getName() + "] class ["
+ action.getClass()
+ "] not loaded, status set to [OFF]");
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/scheduler/SimpleAction.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/scheduler/SimpleAction.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/scheduler/SimpleAction.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -9,37 +9,31 @@
import org.slf4j.LoggerFactory;
/**
- * This is an example of scheduler action. It just prints a message into Log
+ * This is an example of scheduler action. It just prints a message into Log
*
* @author Maciej Glowiak
* @author Roman Lapacz
*/
public class SimpleAction extends Action implements SchedulerAction {
+ // ----------------------------------------------------------- Variables
- // ----------------------------------------------------------- Variables
+ protected static final Logger LOGGER =
LoggerFactory.getLogger(SimpleAction.class);
+ private int counter = 0;
- protected static final Logger logger =
LoggerFactory.getLogger(SimpleAction.class);
-
- int counter = 0;
-
// -----------------------------------------------------------
Constructors
-
public SimpleAction() {
- super();
+ super();
}
- // ----------------------------------------------------------- Methods
+ // ----------------------------------------------------------- Methods
-
public void runAction() {
- logger.info("This is simple SchedulerAction called [" + getName()+"]"
- + " and run ["+counter+"] time");
+ LOGGER.info("This is simple SchedulerAction called [" + getName() +
"]" + " and run [" + counter + "] time");
}
-
-} //SimpleAction
\ No newline at end of file
+} // SimpleAction
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/scheduler/SimpleScheduler.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/scheduler/SimpleScheduler.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/scheduler/SimpleScheduler.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -9,17 +9,16 @@
import org.slf4j.LoggerFactory;
/**
- * Simple and default implementation of Scheduler for perfSONAR services
- * It starts after <code>startDelayTime</code> (seconds) and runs all tasks
- * each <code>interval</code> seconds. The intervals for all actions may be
- * set separately.
+ * Simple and default implementation of Scheduler for perfSONAR services It
+ * starts after <code>startDelayTime</code> (seconds) and runs all tasks each
+ * <code>interval</code> seconds. The intervals for all actions may be set
+ * separately.
*
* @author Maciej Glowiak
* @author Roman Lapacz
*/
public class SimpleScheduler extends Thread implements Scheduler {
-
// ----------------------------------------------------------- Variables
/**
@@ -39,19 +38,17 @@
/**
* Scheduler will start after this time (in seconds)
*/
- protected int startDelayTime = 40; //sec
+ protected int startDelayTime = 40; // sec
- protected static final Logger logger =
LoggerFactory.getLogger(SimpleScheduler.class);
+ protected static final Logger LOGGER =
LoggerFactory.getLogger(SimpleScheduler.class);
-
// ----------------------------------------------------------- Methods
-
public void start() {
- //start scheduler Thread
+ // start scheduler Thread
super.start();
- logger.debug("Scheduler started");
+ LOGGER.debug("Scheduler started");
}
/**
@@ -62,22 +59,25 @@
this.working = false;
}
-
public void run() {
int iteration = 0;
paused = false;
- try {
- logger.info("Scheduler run. Waiting ["+startDelayTime+"] sec
for initialization of other components...");
- Thread.sleep(startDelayTime * 1000); //seconds
- } catch (Exception ex) { logger.warn(ex.toString());}
+ try {
+ LOGGER.info("Scheduler run. Waiting [" + startDelayTime
+ + "] sec for initialization of other components...");
+ Thread.sleep(startDelayTime * 1000); // seconds
+ } catch (Exception ex) {
+ LOGGER.warn(ex.toString());
+ }
- while (working) { //infinite loop until stopScheduler()
+ while (working) { // infinite loop until stopScheduler()
try {
- //if paused - not schedule any tasks
+ // if paused - not schedule any tasks
if (!paused) {
- logger.debug("Scheduler iteration [#"+iteration+"].
Running ["+tasks.size()+"] Scheduled Tasks");
+ LOGGER.debug("Scheduler iteration [#" + iteration + "].
Running [" + tasks.size()
+ + "] Scheduled Tasks");
// Let's protect iteration over tasks by
// corrupted iterator exception catcher,
// which prevents this thread from dieing
@@ -86,30 +86,30 @@
for (SchedulerTask task : tasks) {
// run action in new thread
- task.runAction();
+ task.runAction();
}
} catch (ConcurrentModificationException cme) {
- logger.error("Transient failure in scheduler", cme);
+ LOGGER.error("Transient failure in scheduler", cme);
}
}
- //logger.debug("Scheduler waits ["+interval+"] ms");
- Thread.sleep(interval * 1000); //wait seconds
- iteration++; //increase iteration counter
+ // LOGGER.debug("Scheduler waits ["+interval+"] ms");
+ Thread.sleep(interval * 1000); // wait seconds
+ iteration++; // increase iteration counter
} catch (InterruptedException e) {
- logger.warn("Sleep error");
+ LOGGER.warn("Sleep error");
}
}
}
-
/**
* Checks if scheduler is active and working
+ *
* @return
*/
public boolean isWorking() {
@@ -126,16 +126,14 @@
return interval;
}
-
/**
* set Interval in seconds
*/
public void setInterval(int intervalSec) {
- this.interval = intervalSec;
+ this.interval = intervalSec;
}
-
/**
* Add task to scheduler
*/
@@ -155,8 +153,9 @@
/**
* Remove scheduler task specified by action.
- *
- * @param action to remove
+ *
+ * @param action
+ * to remove
*/
public void removeTask(SchedulerAction action) {
@@ -165,9 +164,9 @@
}
-
/**
* Checks if scheduler is temporarly paused
+ *
* @return
*/
public boolean isPaused() {
@@ -175,10 +174,10 @@
return paused;
}
-
/**
- * Set scheduler paused. It'll be still working but won't be
- * scheduling and running tasks
+ * Set scheduler paused. It'll be still working but won't be scheduling
and
+ * running tasks
+ *
* @param paused
*/
public void setPaused(boolean paused) {
@@ -186,5 +185,5 @@
this.paused = paused;
}
-} //SimpleScheduler
+} // SimpleScheduler
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/scheduler/singleThread/SchedulerTaskComparator.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/scheduler/singleThread/SchedulerTaskComparator.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/scheduler/singleThread/SchedulerTaskComparator.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -5,23 +5,22 @@
import org.perfsonar.base2.service.scheduler.SchedulerTask;
/**
- * simple Comparator that is used to sort TaskComparators.
- * Comparison depends on SchedulerTask's interval.
+ * simple Comparator that is used to sort TaskComparators. Comparison
depends on
+ * SchedulerTask's interval.
*
* @author Slawomir Trzaszczka
*/
-class SchedulerTaskComparator implements Comparator<SchedulerTask>{
+class SchedulerTaskComparator implements Comparator<SchedulerTask> {
- public int compare(SchedulerTask o1, SchedulerTask o2) {
-
- if(o1.getInterval()<o2.getInterval()){
- return -1;
- }else if (o1.getInterval()>o2.getInterval()){
- return 1;
- }else{
- return 0;
- }
- }
+ public int compare(SchedulerTask o1, SchedulerTask o2) {
+ if (o1.getInterval() < o2.getInterval()) {
+ return -1;
+ } else if (o1.getInterval() > o2.getInterval()) {
+ return 1;
+ } else {
+ return 0;
+ }
+ }
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/scheduler/singleThread/SingleThreadScheduler.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/scheduler/singleThread/SingleThreadScheduler.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/scheduler/singleThread/SingleThreadScheduler.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -12,133 +12,133 @@
import org.perfsonar.base2.service.scheduler.SchedulerTask;
/**
- * manages pool of actions where only one action can be processed in moment.
- * If one action is invoked others are added to waitQueue.
+ * manages pool of actions where only one action can be processed in moment.
If
+ * one action is invoked others are added to waitQueue.
*
* @author Slawomir Trzaszczka
*
*/
public class SingleThreadScheduler extends Thread implements Scheduler {
- /**
- * a set of scheduled tasks
- */
- protected List<SchedulerTask> tasks = new ArrayList<SchedulerTask>();
+ /**
+ * a set of scheduled tasks
+ */
+ protected List<SchedulerTask> tasks = new ArrayList<SchedulerTask>();
- /**
- * queue contains waiting tasks, queue consists only of different
tasks
- */
- private LinkedList<SchedulerTask> waitQueue = new
LinkedList<SchedulerTask>();
- /**
- * interval for scheduler, in seconds
- */
- protected int interval = 10;
- private SchedulerTask lastSchedulerTask;
+ /**
+ * queue contains waiting tasks, queue consists only of different tasks
+ */
+ private LinkedList<SchedulerTask> waitQueue = new
LinkedList<SchedulerTask>();
+ /**
+ * interval for scheduler, in seconds
+ */
+ protected int interval = 10;
+ private SchedulerTask lastSchedulerTask;
- /**
- * Scheduler will start after this time (in seconds)
- */
- protected int startDelayTime = 40; // sec
+ /**
+ * Scheduler will start after this time (in seconds)
+ */
+ protected int startDelayTime = 40; // sec
- protected final Logger logger =
LoggerFactory.getLogger(SingleThreadScheduler.class);
+ protected static final Logger LOGGER =
LoggerFactory.getLogger(SingleThreadScheduler.class);
- public void start() {
+ public void start() {
- super.start();
- logger.debug("Scheduler started");
- Collections.sort(tasks, new SchedulerTaskComparator());
- }
+ super.start();
+ LOGGER.debug("Scheduler started");
+ Collections.sort(tasks, new SchedulerTaskComparator());
+ }
- public void run() {
-
- int iteration = 0;
- try {
- logger.debug("Scheduler run. Waiting [" +
startDelayTime
- + "] sec for initialization of other
components...");
- Thread.sleep(startDelayTime * 1000);
- } catch (InterruptedException e1) {
- logger.warn(e1.toString());
- }
+ public void run() {
- logger.debug("SingleThreadScheduler starts");
-
- while (true) {
- for (SchedulerTask task : tasks) {
- if(task.canRun()){
- logger.debug("task
"+task.getAction()+" can run");
- if (lastSchedulerTask!=null &&
lastSchedulerTask.isThreadAlive()) {
- logger.debug("Queue is not
empty");
- if
(!waitQueue.contains(task)) {
-
waitQueue.addLast(task);
-
logger.debug("SchedulerTask is added to queue");
- }
- } else {
-
logger.debug("lastSchedulerTask is empty or thread is not alive");
- if(waitQueue.isEmpty()){
- logger.debug("new
thread started");
-
lastSchedulerTask=task;
- }else{
- logger.debug("polled
from wait queue");
-
lastSchedulerTask=waitQueue.poll();
- }
- lastSchedulerTask.runAction();
- }
- }else{
- logger.debug("task
"+task.getAction()+" CAN'T run");
- }
- }
- try {
- Thread.sleep(interval * 1000);
- iteration++;
- } catch (InterruptedException e) {
- logger.warn("Sleep error after " + iteration
+ " iterations.");
- }
+ int iteration = 0;
+ try {
+ LOGGER.debug("Scheduler run. Waiting [" + startDelayTime
+ + "] sec for initialization of other components...");
+ Thread.sleep(startDelayTime * 1000);
+ } catch (InterruptedException e1) {
+ LOGGER.warn(e1.toString());
+ }
- }
- }
+ LOGGER.debug("SingleThreadScheduler starts");
- /**
- * get Interval in seconds
- */
- public int getInterval() {
- return interval;
- }
+ while (true) {
+ for (SchedulerTask task : tasks) {
+ if (task.canRun()) {
+ LOGGER.debug("task " + task.getAction() + " can run");
+ if (lastSchedulerTask != null &&
lastSchedulerTask.isThreadAlive()) {
+ LOGGER.debug("Queue is not empty");
+ if (!waitQueue.contains(task)) {
+ waitQueue.addLast(task);
+ LOGGER.debug("SchedulerTask is added to queue");
+ }
+ } else {
+ LOGGER.debug("lastSchedulerTask is empty or thread
is not alive");
+ if (waitQueue.isEmpty()) {
+ LOGGER.debug("new thread started");
+ lastSchedulerTask = task;
+ } else {
+ LOGGER.debug("polled from wait queue");
+ lastSchedulerTask = waitQueue.poll();
+ }
+ lastSchedulerTask.runAction();
+ }
+ } else {
+ LOGGER.debug("task " + task.getAction() + " CAN'T run");
+ }
+ }
+ try {
+ Thread.sleep(interval * 1000);
+ iteration++;
+ } catch (InterruptedException e) {
+ LOGGER.warn("Sleep error after " + iteration + "
iterations.");
+ }
- /**
- * set Interval in seconds
- */
- public void setInterval(int intervalSec) {
- this.interval = intervalSec;
- }
+ }
+ }
- /**
- * Add task to scheduler
- */
- public void addTask(SchedulerTask t) {
- tasks.add(t);
- }
+ /**
+ * get Interval in seconds
+ */
+ public int getInterval() {
+ return interval;
+ }
- /**
- * Add scheduler action and set an interval for it (in seconds)
- */
- public void addTask(int intervalSec, SchedulerAction action) {
+ /**
+ * set Interval in seconds
+ */
+ public void setInterval(int intervalSec) {
+ this.interval = intervalSec;
+ }
- tasks.add(new SchedulerTask(intervalSec, action));
+ /**
+ * Add task to scheduler
+ */
+ public void addTask(SchedulerTask t) {
+ tasks.add(t);
+ }
- }
+ /**
+ * Add scheduler action and set an interval for it (in seconds)
+ */
+ public void addTask(int intervalSec, SchedulerAction action) {
- /**
- * Remove scheduler task specified by action.
- *
- * @param action
- * to remove
- */
- public void removeTask(SchedulerAction action) {
- tasks.remove(new SchedulerTask(0, action));
- }
+ tasks.add(new SchedulerTask(intervalSec, action));
- public void finish() {
+ }
- }
+ /**
+ * Remove scheduler task specified by action.
+ *
+ * @param action
+ * to remove
+ */
+ public void removeTask(SchedulerAction action) {
+ tasks.remove(new SchedulerTask(0, action));
+ }
+ public void finish() {
+
+ }
+
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/DataCredential.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/DataCredential.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/DataCredential.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -2,18 +2,17 @@
/**
* The class represents username and password
+ *
* @author Maciej Glowiak
*/
public class DataCredential {
// ----------------------------------------------------- instance
variables
- String username;
+ private String username;
- String password;
+ private String password;
-
-
// ------------------------------------------------------------
Constructor
public DataCredential(String username, String password) {
@@ -23,7 +22,6 @@
}
-
// --------------------------------------------------------- Public
methods
public String getUsername() {
@@ -31,7 +29,6 @@
return username;
}
-
public String getPassword() {
return password;
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/XMLDBComponent.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/XMLDBComponent.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/XMLDBComponent.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -1,22 +1,23 @@
package org.perfsonar.base2.service.storage.xml;
+
import org.perfsonar.base2.service.configuration.Component;
import org.perfsonar.base2.service.exceptions.PerfSONARException;
import org.perfsonar.base2.service.storage.xml.exist.ExistHTTPDataStorage;
-
/**
* PerfSONAR component for eXist DB XML
+ *
* @author Maciej Glowiak
- *
+ *
*/
public class XMLDBComponent extends Component {
-
+
private String dataStorageClassName = null;
private String uri = null;
private String username = null;
private String password = null;
- private XMLDataStorage dataStorage = null;
+ private XMLDataStorage dataStorage = null;
private DataCredential credential = null;
@Override
@@ -25,15 +26,15 @@
loadSettings();
createCredential();
createDataStorage();
- logger.debug("XMLDB Component created with
["+dataStorage.getClass()+"] XML data storage");
+ LOGGER.debug("XMLDB Component created with [" +
dataStorage.getClass() + "] XML data storage");
checkConfiguration();
}
-
+
@Override
- public void run() throws PerfSONARException {
- //do nothing
- }
+ public void run() throws PerfSONARException {
+ // do nothing
+ }
@Override
public void destroy() throws PerfSONARException {
@@ -43,21 +44,21 @@
username = null;
password = null;
- dataStorage = null;
+ dataStorage = null;
credential = null;
}
protected void checkConfiguration() {
- logger.debug("Checking DB configuration:");
- logger.debug(" - uri: "+uri);
- logger.debug(" - username: "+username);
- logger.debug(" - password: "+password);
- logger.debug(" - dataStorageClassName: "+dataStorageClassName);
- logger.debug(" - dataStorage: "+dataStorage);
- logger.debug(" - dataCredential: "+credential);
-
+ LOGGER.debug("Checking DB configuration:");
+ LOGGER.debug(" - uri: " + uri);
+ LOGGER.debug(" - username: " + username);
+ LOGGER.debug(" - password: " + password);
+ LOGGER.debug(" - dataStorageClassName: " + dataStorageClassName);
+ LOGGER.debug(" - dataStorage: " + dataStorage);
+ LOGGER.debug(" - dataCredential: " + credential);
+
}
protected boolean loadSettings() throws PerfSONARException {
@@ -68,102 +69,95 @@
username = getOption("username").getValue();
password = getOption("password").getValue();
} catch (Exception ex) {
- //TODO: url event types
- throw new PerfSONARException("error.xmldb.no_settings", "Cannot
load XML DB settings from configuration file");
+ // TODO: url event types
+ throw new PerfSONARException("error.xmldb.no_settings",
+ "Cannot load XML DB settings from configuration file");
}
return true;
}
-
-
+
protected XMLDataStorage createDataStorage() throws PerfSONARException {
dataStorage = null;
try {
// get a new class for that classname
- logger.debug(dataStorageClassName);
- dataStorage =
(XMLDataStorage)Class.forName(dataStorageClassName).newInstance();
+ LOGGER.debug(dataStorageClassName);
+ dataStorage = (XMLDataStorage)
Class.forName(dataStorageClassName).newInstance();
} catch (Exception e) {
- //TODO: url event types
- throw new PerfSONARException("error.wrong_data_storage",
- "\n Cannot instantiate XMLDataStorage ["+
- dataStorageClassName+"]:\n "+e.getMessage()); }
- if (dataStorage == null) dataStorage = new ExistHTTPDataStorage();
+ // TODO: url event types
+ throw new PerfSONARException("error.wrong_data_storage", "\n
Cannot instantiate XMLDataStorage ["
+ + dataStorageClassName + "]:\n " + e.getMessage());
+ }
+ if (dataStorage == null) {
+ dataStorage = new ExistHTTPDataStorage();
+ }
return dataStorage;
-
+
}
-
public XMLDataStorage getDataStorage() throws PerfSONARException {
-
- if (dataStorage == null) throw new
PerfSONARException("data_storage_not_initialized");
- else return dataStorage;
-
+
+ if (dataStorage == null) {
+ throw new PerfSONARException("data_storage_not_initialized");
+ } else {
+ return dataStorage;
+ }
+
}
-
public DataCredential getCredential() {
-
+
return credential;
}
-
public void createCredential() {
-
+
credential = new DataCredential(username, password);
-
+
}
-
public String getDataStorageClassName() {
-
+
return dataStorageClassName;
}
-
public void setDataStorageClassName(String dataStorageClassName) {
-
+
this.dataStorageClassName = dataStorageClassName;
}
-
public String getPassword() {
-
+
return password;
}
-
public void setPassword(String password) {
-
+
this.password = password;
}
-
public String getUri() {
-
+
return uri;
}
-
public void setUri(String uri) {
-
+
this.uri = uri;
}
-
public String getUsername() {
-
+
return username;
}
-
public void setUsername(String username) {
-
+
this.username = username;
}
-
public void setDataStorage(XMLDataStorage dataStorage) {
-
+
this.dataStorage = dataStorage;
}
-
+
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/XMLDBConstants.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/XMLDBConstants.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/XMLDBConstants.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -5,17 +5,16 @@
/**
* Return results as XmlDbResult
*/
- public static final int RETURN_XML_DB_RESULT = 0x0100;
-
+ int RETURN_XML_DB_RESULT = 0x0100;
+
/**
* Return results as XmlDbResult
*/
- public static final int RETURN_STRING_ARRAY = 0x0200;
+ int RETURN_STRING_ARRAY = 0x0200;
/**
* Return results as String
*/
- public static final int RETURN_STRING = 0x0400;
+ int RETURN_STRING = 0x0400;
-
-} //XmlDbConstants
+} // XmlDbConstants
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/XMLDBResult.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/XMLDBResult.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/XMLDBResult.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -6,41 +6,33 @@
import org.perfsonar.base2.xml.Element;
/**
- * Result from XML database. The class contain
- * counter of total hits, first element returned (start) and
- * number of returned elements (count)
- *
+ * Result from XML database. The class contain counter of total hits, first
+ * element returned (start) and number of returned elements (count)
+ *
* @author Maciej Glowiak
*
*/
public class XMLDBResult {
-
// -------------------------------------------- Instance variables
+ private Collection<Element> elements = null;
+ private int total = 0; // total results
+ private int start = 0; // number of first result returned
+ private int count = 0; // number of total results returned
- private Collection<Element> elements = null;
- private int total = 0; //total results
- private int start = 0; //number of first result returned
- private int count = 0; //number of total results returned
-
-
// --------------------------------------------------- Constructor
+ public XMLDBResult(Collection<Element> elements, int total, int start,
int count) {
- public XMLDBResult(
- Collection<Element> elements, int total, int start, int count) {
-
this.elements = elements;
this.total = total;
this.start = start;
this.count = count;
}
-
// ------------------------------------------------ Public methods
-
/**
* Returns elements as collection of Element objects
*/
@@ -52,44 +44,44 @@
/**
* Extracts text values from results and returns String array
+ *
* @return
*/
public String[] getTextResults() {
String[] list = new String[elements.size()];
- int i=0;
- for (Element e : elements) list[i++] = e.getText();
+ int i = 0;
+ for (Element e : elements) {
+ list[i++] = e.getText();
+ }
return list;
}
-
public int getCount() {
return count;
}
-
public int getStart() {
return start;
}
-
public int getTotal() {
return total;
}
-
public int getElementsCount() {
return elements.size();
}
-
public Element getFirstElement() {
Iterator<Element> i = elements.iterator();
- if (i.hasNext()) return i.next();
- else return null;
+ if (i.hasNext()) {
+ return i.next();
+ } else {
+ return null;
+ }
}
-
public String toString() {
StringBuilder sb = new StringBuilder();
@@ -100,13 +92,15 @@
sb.append(", start=");
sb.append(start);
sb.append(", elements=");
- if (elements!=null) sb.append(elements.size());
- else sb.append("null");
+ if (elements != null) {
+ sb.append(elements.size());
+ } else {
+ sb.append("null");
+ }
sb.append(")");
return sb.toString();
}
-
-} //XmlDbResult
+} // XmlDbResult
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/XMLDataStorage.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/XMLDataStorage.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/XMLDataStorage.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -1,54 +1,43 @@
package org.perfsonar.base2.service.storage.xml;
-import org.omg.CORBA.SystemException;
import org.perfsonar.base2.service.exceptions.PerfSONARException;
/**
- * Interface for performing basic data operations on XML storage
- * put - store document
- * delete - remove document
- * performXQuery - perform XQuery operation
+ * Interface for performing basic data operations on XML storage put - store
+ * document delete - remove document performXQuery - perform XQuery operation
*
* @author Maciej Glowiak
- *
+ *
*/
public interface XMLDataStorage {
-
/**
* Put document to the storage
+ *
* @param xmlDocument
* @param dataTarget
- * @throws SystemException
- * @throws PerfSONARException
+ * @throws SystemException
+ * @throws PerfSONARException
*/
- public void put(
- String xmlDocument,
- String collection,
- DataCredential credential) throws PerfSONARException;
+ void put(String xmlDocument, String collection, DataCredential
credential) throws PerfSONARException;
-
/**
* Remove document from the storage
+ *
* @param dataTarget
- * @throws SystemException
+ * @throws SystemException
*/
- public void delete(
- String collection,
- DataCredential credential) throws PerfSONARException;
+ void delete(String collection, DataCredential credential) throws
PerfSONARException;
-
/**
* Perform XQuery operation on the storage
+ *
* @param xquery
* @param dataTarget
* @return
- * @throws SystemException
+ * @throws SystemException
*/
- public XMLDBResult performXQuery(
- String xquery,
- String collection,
- DataCredential credential) throws PerfSONARException;
+ XMLDBResult performXQuery(String xquery, String collection,
DataCredential credential)
+ throws PerfSONARException;
-
-} //DataStorage
+} // DataStorage
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/exist/ExistDbErrorException.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/exist/ExistDbErrorException.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/exist/ExistDbErrorException.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -1,77 +1,65 @@
package org.perfsonar.base2.service.storage.xml.exist;
/**
- * Represents Exist XML DB error or response message (e.g.Unauthorized...)
+ * Represents Exist XML DB error or response message (e.g.Unauthorized...)
*
* @author Maciej Glowiak
*
- * $id$
+ * $id$
*/
public class ExistDbErrorException extends Exception {
-
// ----------------------------------------------------- Constants
-
-
+
private static final long serialVersionUID = 2780526000258753818L;
-
- // -------------------------------------------- Instance variables
-
-
+ // -------------------------------------------- Instance variables
+
/**
* HTTP code of error returned by exist DB
*/
private int httpCode = -1;
-
+
/**
* HTTP message of error returned by exist DB
*/
private String httpMessage = null;
-
-
+
// --------------------------------------------------- Constructor
-
-
+
public ExistDbErrorException(int code, String description) {
-
- super("eXist DB responsed with HTTP error code code ["+
- code+"] additional message was ["+description+"]");
+
+ super("eXist DB responsed with HTTP error code code [" + code + "]
additional message was [" + description
+ + "]");
httpCode = code;
httpMessage = description;
-
+
}
-
// ------------------------------------------------ Public methods
-
-
+
public int getHttpCode() {
-
+
return httpCode;
-
+
}
-
public void setHttpCode(int httpCode) {
-
+
this.httpCode = httpCode;
-
+
}
-
public String getHttpMessage() {
-
+
return httpMessage;
-
+
}
-
public void setHttpMessage(String httpMessage) {
-
+
this.httpMessage = httpMessage;
-
+
}
-
-} //ExistDbErrorException
+} // ExistDbErrorException
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/exist/ExistDbHTTPAccess.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/exist/ExistDbHTTPAccess.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/exist/ExistDbHTTPAccess.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -12,50 +12,42 @@
import org.perfsonar.base2.xml.StaxParser;
/**
- * HTTP Access to eXist DB XML (exist-db.org)
- * Supports HTTP authorization, results parsing
+ * HTTP Access to eXist DB XML (exist-db.org) Supports HTTP authorization,
+ * results parsing
*
* @author Maciej Glowiak
*
- * $Id: ExistDbHTTPAccess.java 4684 2008-11-03 13:07:33Z roman $
- *
+ * $Id: ExistDbHTTPAccess.java 4684 2008-11-03 13:07:33Z roman $
+ *
*/
public class ExistDbHTTPAccess extends HTTPAccess implements XMLDBConstants {
-
// ---------------------------------------------Instance variables
-
+
private boolean debug = false;
-
-
+
// -------------------------------------------------- other
-
+
/**
* Start from first element
*/
public static final int FIRST = 1;
-
-
+
/**
* Return all results
*/
public static final int ALL_RESULTS = 0;
-
-
+
// ------------------------------------------------ public methods
-
-
- public int sendExistXUpdateRequest(
- String url,
- String updateString,
- String username,
- String password) throws IOException, ExistDbErrorException {
-
- HTTPResult result = sendPOSTRequest(url, updateString,username,
password);
+
+ public int sendExistXUpdateRequest(String url, String updateString,
String username, String password)
+ throws IOException, ExistDbErrorException {
+
+ HTTPResult result = sendPOSTRequest(url, updateString, username,
password);
return result.getResultCode();
-
+
}
-
+
/**
*
* @param url
@@ -67,254 +59,160 @@
* @return
* @throws IOException
*/
- public HTTPResult sendXQueryPOSTRequest(
- String url,
- String content,
- String username,
- String password,
- int start,
+ public HTTPResult sendXQueryPOSTRequest(String url, String content,
String username, String password, int start,
int limit) throws IOException {
-
- //prepare XQuery
- content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+
- "<query xmlns=\"http://exist.sourceforge.net/NS/exist\" "+
- "start=\""+String.valueOf(start)+"\" max=\""+
- String.valueOf(limit)+"\"> "+
- " <text>" +
- "<![CDATA["+
- content +
- "]]>" +
- "</text> "+
- "</query>";
-
+
+ // prepare XQuery
+ content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ + "<query xmlns=\"http://exist.sourceforge.net/NS/exist\" "
+ "start=\"" + String.valueOf(start)
+ + "\" max=\"" + String.valueOf(limit) + "\"> " + " <text>" +
"<![CDATA[" + content + "]]>" + "</text> "
+ + "</query>";
+
return sendPOSTRequest(url, content, username, password);
-
- }
-
-
- public XMLDBResult sendExistXQueryRequest(
- String url,
- String query,
- String username,
- String password,
- int start,
+
+ }
+
+ public XMLDBResult sendExistXQueryRequest(String url, String query,
String username, String password, int start,
int limit) throws IOException, ExistDbErrorException,
XMLStreamException {
-
+
/* ******************************************************** */
-
- //send HTTP request and encapsulate query
- HTTPResult httpResult = sendXQueryPOSTRequest(
- url, query, username, password, start, limit);
-
+
+ // send HTTP request and encapsulate query
+ HTTPResult httpResult = sendXQueryPOSTRequest(url, query, username,
password, start, limit);
+
/* ******************************************************** */
-
+
int resultCode = httpResult.getResultCode();
- if (resultCode == 200) { //HTTP OK
-
- //parse XML result returned by eXist DB XML
- XMLDBResult xmlResult = parseExistXMLReponse(
- httpResult.getResponse());
-
+ if (resultCode == 200) { // HTTP OK
+
+ // parse XML result returned by eXist DB XML
+ XMLDBResult xmlResult =
parseExistXMLReponse(httpResult.getResponse());
+
return xmlResult;
-
+
} else {
- throw new ExistDbErrorException(
- resultCode, httpResult.getResultMessage());
+ throw new ExistDbErrorException(resultCode,
httpResult.getResultMessage());
}
-
+
}
-
-
- protected XMLDBResult parseExistXMLReponse(
- InputStream inputStream) throws IOException, XMLStreamException {
-
- //parse
+ protected XMLDBResult parseExistXMLReponse(InputStream inputStream)
throws IOException, XMLStreamException {
+
+ // parse
StaxParser sp = new ConfigurationStaxParser();
Element e = sp.parse(inputStream);
-
- //get numbers
- int hits = e.getAttributeAsInt("hits");
+
+ // get numbers
+ int hits = e.getAttributeAsInt("hits");
int count = e.getAttributeAsInt("count");
int first = e.getAttributeAsInt("start");
- if (count > -1) {
+ if (count > -1) {
return new XMLDBResult(e.getChildren(), hits, count, first);
- } else return null;
-
- //TODO: handle <exist:value>
-
+ } else {
+ return null;
+ }
+
+ // TODO: handle <exist:value>
+
}
+ protected XMLDBResult parseExistXMLReponse(InputStream inputStream,
StaxParser sp) throws IOException,
+ XMLStreamException {
- protected XMLDBResult parseExistXMLReponse(
- InputStream inputStream, StaxParser sp)
- throws IOException, XMLStreamException {
-
- //parse
+ // parse
Element e = sp.parse(inputStream);
-
- //get numbers
- int hits = e.getAttributeAsInt("hits");
+
+ // get numbers
+ int hits = e.getAttributeAsInt("hits");
int count = e.getAttributeAsInt("count");
int first = e.getAttributeAsInt("start");
- if (count > -1) {
+ if (count > -1) {
return new XMLDBResult(e.getChildren(), hits, count, first);
- } else return null;
-
- //TODO: handle <exist:value>
-
+ } else {
+ return null;
+ }
+
+ // TODO: handle <exist:value>
+
}
-
public boolean isDebug() {
-
+
return debug;
-
+
}
-
public void setDebug(boolean debug) {
-
+
this.debug = debug;
-
+
}
-
/**
* Extracts attribute value from string
- * @param a string
- * @param attribute attribute name
+ *
+ * @param a
+ * string
+ * @param attribute
+ * attribute name
* @return
*/
- protected String extractXMLAttributeValue(
- String str,
- String attribute) {
-
- try { //just in case of a RuntimeException
-
- int ind1 = str.indexOf(attribute);
-
- if (ind1>-1) { ind1 = str.indexOf('\"', ind1); }
- else return null; //attribute not found
-
- if (ind1>-1) {
- ind1+=1;
- int ind2 = str.indexOf('\"',ind1);
- if (ind2>-1) {
- return str.substring(ind1,ind2); //return value of
attribute
+ protected String extractXMLAttributeValue(String str, String attribute) {
+
+ try { // just in case of a RuntimeException
+
+ int ind1 = str.indexOf(attribute);
+
+ if (ind1 > -1) {
+ ind1 = str.indexOf('\"', ind1);
+ } else {
+ return null; // attribute not found
+ }
+
+ if (ind1 > -1) {
+ ind1 += 1;
+ int ind2 = str.indexOf('\"', ind1);
+ if (ind2 > -1) {
+ return str.substring(ind1, ind2); // return value of
+ // attribute
}
}
-
- } catch (Exception ex) {}
-
- return null; //bad xml?
+ } catch (Exception ex) {
+ }
+
+ return null; // bad xml?
+
}
protected String extractXMLTag(String str, String tag) {
-
- //trim from blank spaces
+
+ // trim from blank spaces
str = str.trim();
-
- //find starting tag
- int indexStartTag1 = str.indexOf("<"+tag);
- if (indexStartTag1==-1) return null;
-
- //find end of starting tag
+
+ // find starting tag
+ int indexStartTag1 = str.indexOf("<" + tag);
+ if (indexStartTag1 == -1) {
+ return null;
+ }
+
+ // find end of starting tag
int indexStartTag2 = str.indexOf(">", indexStartTag1);
- if (indexStartTag2==-1) return null;
-
- //find closing tag
- int indexEndTag1 = str.indexOf("</"+tag, indexStartTag2);
- if (indexEndTag1==-1) return null;
+ if (indexStartTag2 == -1) {
+ return null;
+ }
- String substr = str.substring(indexStartTag2+1, indexEndTag1);
+ // find closing tag
+ int indexEndTag1 = str.indexOf("</" + tag, indexStartTag2);
+ if (indexEndTag1 == -1) {
+ return null;
+ }
+
+ String substr = str.substring(indexStartTag2 + 1, indexEndTag1);
return substr;
-
- }
-
-
-
-
- // --------------------------------------------------- test method
-
- /**
- * Test method
- */
- public static void main(String[] args) throws Exception {
-
-// String query =
-// "declare namespace " +
-// "nmwg='http://ggf.org/ns/nmwg/base/2.0/'; " +
-// "/nmwg:store/nmwg:metadata";
-// String query =
-// "declare namespace " +
-// "nmwg='http://ggf.org/ns/nmwg/base/2.0/'; " +
-// "data(/nmwg:store/nmwg:metadata/@id)";
-
-// String query = "declare namespace
nmwg=\"http://ggf.org/ns/nmwg/base/2.0/\"; "+
-//
"/nmwg:store[@type='LSStore-control']/nmwg:metadata[@id='entry-1']/nmwg:parameters"+
-//
"/nmwg:parameter[@name='timestamp']/text()";
-
-// String query = "/";
-
-// String query = "<xu:modifications version='1.0'
xmlns:xu='http://www.xmldb.org/xupdate'
xmlns:perfsonar='http://ggf.org/ns/nmwg/tools/org/perfsonar/1.0/'
xmlns:nmwg='http://ggf.org/ns/nmwg/base/2.0/'
xmlns:psservice='http://ggf.org/ns/nmwg/tools/org/perfsonar/service/1.0/'
xmlns:nmwgt='http://ggf.org/ns/nmwg/topology/2.0/'
xmlns:netutil='http://ggf.org/ns/nmwg/characteristic/utilization/2.0/'>" +
-// "<xu:append
select=\"/nmwg:store[@type='LSStore']\"
child=\"last()\">" +
-// "<nmwg:data" +
-// "
id=\"http://reed.man.poznan.pl:8080/axis/services/MA/1153214921123/0\"" +
-// "
metadataIdRef=\"http://reed.man.poznan.pl:8080/axis/services/MA\"
xmlns:nmwg=\"http://ggf.org/ns/nmwg/base/2.0/\">" +
-// " <nmwg:metadata id=\"meta1\">" +
-// " <perfsonar:subject id=\"subj1\"
xmlns:perfsonar=\"http://ggf.org/ns/nmwg/tools/org/perfsonar/1.0/\">" +
-// " <nmwgt:interface
xmlns:nmwgt=\"http://ggf.org/ns/nmwg/topology/2.0/\">" +
-// "
<nmwgt:hostName>atlang-hstnng.abilene.ucaid.edu</nmwgt:hostName>" +
-// "
<nmwgt:ifName>unknown</nmwgt:ifName>" +
-// "
<nmwgt:ifDescription>hstn:oc192(p2p)::show:intracloud</nmwgt:ifDescription>" +
-// " <nmwgt:ifAddress
type=\"ipv4\">198.32.8.34</nmwgt:ifAddress>" +
-// "
<nmwgt:direction>in</nmwgt:direction>" +
-// "
<nmwgt:capacity>10000000000</nmwgt:capacity>" +
-// " </nmwgt:interface>" +
-// " </perfsonar:subject>" +
-// "
<nmwg:eventType>utilization</nmwg:eventType>" +
-// " </nmwg:metadata>" +
-// "</nmwg:data>" +
-// "</xu:append>" +
-// "</xu:modifications>";
-
-// String query = "<xu:modifications version='1.0'
xmlns:xu='http://www.xmldb.org/xupdate'
xmlns:nmwg='http://ggf.org/ns/nmwg/base/2.0/'>" +
-// "<xu:append
select=\"/nmwg:store[@type='LSStore']\"
child=\"last()\">" +
-// " <xxxxxxxxxxxxxxxxx/>" +
-// "</xu:append>" +
-// "</xu:modifications>";
-
-// long t0 = System.currentTimeMillis(); //----------------time 0
-//
-// String query = "data(/test/a/@id)";
-// ExistDbHTTPAccess a = new ExistDbHTTPAccess();
-// a.setDebug(true);
-// XmlDbResult result = a.sendExistXQueryRequest(
-// "http://localhost:8680/exist/rest/db/test",
-// query,
-// "lookupservice",
-// "sonar",
-// FIRST,
-// ALL_RESULTS);
-// a.disconnectHTTPServer();
-//
-// long t1 = System.currentTimeMillis(); //----------------time 1
-//
-// for (int i=0; i<result.getResultAsStringArray().length; i++) {
-// String x = result.getResultAsStringArray()[i];
-// System.out.println("RESULT["+i+"]:
"+((x.length()<1000)?x:"..."+x.substring(1000)+"..."));
-// }
-//
-// System.out.println("TIME: "+(t1-t0)+"ms");
-
-
-
-
}
-
-} //ExistDbHTTPAccess
+
+} // ExistDbHTTPAccess
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/exist/ExistHTTPDataStorage.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/exist/ExistHTTPDataStorage.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/exist/ExistHTTPDataStorage.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -7,87 +7,72 @@
public class ExistHTTPDataStorage implements XMLDataStorage {
- // ----------------------------------------------------- Instance
variables
+ // ----------------------------------------------------- Instance
variables
- protected ExistDbHTTPAccess httpAccess;
+ protected ExistDbHTTPAccess httpAccess;
- // ------------------------------------------------------------
Constructor
+ // ------------------------------------------------------------
Constructor
- public ExistHTTPDataStorage() {
+ public ExistHTTPDataStorage() {
- httpAccess = new ExistDbHTTPAccess();
+ httpAccess = new ExistDbHTTPAccess();
- }
+ }
- // --------------------------------------------------------- Public
methods
+ // --------------------------------------------------------- Public
methods
- public void put(String xmlDocument, String collection,
- DataCredential credential) throws PerfSONARException {
+ public void put(String xmlDocument, String collection, DataCredential
credential) throws PerfSONARException {
- try {
+ try {
- httpAccess.sendPUTRequest(collection, xmlDocument,
credential
- .getUsername(),
credential.getPassword());
+ httpAccess.sendPUTRequest(collection, xmlDocument,
credential.getUsername(), credential.getPassword());
- } catch (Exception ex) {
- throw new
PerfSONARException("error.common.storage.xmldb.open",
- "PUT HTTP request of resource [" +
collection + "] failed."
- + "Could not connect
to eXist via pure http, "
- + " nested exception
was: " + ex.getClass() + " : "
- + ex.getMessage());
- }
+ } catch (Exception ex) {
+ throw new PerfSONARException("error.common.storage.xmldb.open",
"PUT HTTP request of resource ["
+ + collection + "] failed." + "Could not connect to eXist
via pure http, "
+ + " nested exception was: " + ex.getClass() + " : " +
ex.getMessage());
+ }
- }
+ }
- public void delete(String collection, DataCredential credential)
- throws PerfSONARException {
+ public void delete(String collection, DataCredential credential) throws
PerfSONARException {
- try {
- httpAccess.sendDELETERequest(collection,
credential.getUsername(),
- credential.getPassword());
+ try {
+ httpAccess.sendDELETERequest(collection,
credential.getUsername(), credential.getPassword());
- } catch (Exception ex) {
- throw new
PerfSONARException("error.common.storage.xmldb.open",
- "DELETE HTTP request of resource [" +
collection
- + "] failed. "
- + "Could not connect
to eXist via pure http, "
- + " nested exception
was: " + ex.getClass() + " : "
- + ex.getMessage());
- }
+ } catch (Exception ex) {
+ throw new PerfSONARException("error.common.storage.xmldb.open",
"DELETE HTTP request of resource ["
+ + collection + "] failed. " + "Could not connect to
eXist via pure http, "
+ + " nested exception was: " + ex.getClass() + " : " +
ex.getMessage());
+ }
- }
+ }
- public XMLDBResult performXQuery(String xquery, String collection,
- DataCredential credential) throws PerfSONARException {
- XMLDBResult results = null;
+ public XMLDBResult performXQuery(String xquery, String collection,
DataCredential credential)
+ throws PerfSONARException {
+ XMLDBResult results = null;
- try {
- results =
httpAccess.sendExistXQueryRequest(collection, xquery,
- credential.getUsername(),
credential.getPassword(),
- ExistDbHTTPAccess.FIRST,
ExistDbHTTPAccess.ALL_RESULTS);
-
- } catch (ExistDbErrorException ex) {
- if (ex.getHttpCode() == 202) {
- // incorrect xquery
- throw new PerfSONARException("error.xpath",
- "XQuery by HTTP failed.
Incorrect XQuery");
- } else {
- throw new
PerfSONARException("error.common.storage.xmldb.open",
- "XQuery by HTTP failed. Error
code " + ex.getHttpCode()
- + " nested
exception was: " + ex.getClass()
- + " : " +
ex.getMessage());
- }
- } catch (Exception ex) {
-
- throw new
PerfSONARException("error.common.storage.xmldb.open",
- "XQuery by HTTP failed. "
- + "Could not connect
to eXist via pure http, "
- + " nested exception
was: " + ex.getClass() + " : "
- + ex.getMessage());
-
- }
- return results;
+ try {
+ results = httpAccess.sendExistXQueryRequest(collection, xquery,
credential.getUsername(),
+ credential.getPassword(), ExistDbHTTPAccess.FIRST,
ExistDbHTTPAccess.ALL_RESULTS);
- }
+ } catch (ExistDbErrorException ex) {
+ if (ex.getHttpCode() == 202) {
+ // incorrect xquery
+ throw new PerfSONARException("error.xpath", "XQuery by HTTP
failed. Incorrect XQuery");
+ } else {
+ throw new
PerfSONARException("error.common.storage.xmldb.open", "XQuery by HTTP failed.
Error code "
+ + ex.getHttpCode() + " nested exception was: " +
ex.getClass() + " : " + ex.getMessage());
+ }
+ } catch (Exception ex) {
+ throw new PerfSONARException("error.common.storage.xmldb.open",
"XQuery by HTTP failed. "
+ + "Could not connect to eXist via pure http, " + "
nested exception was: " + ex.getClass() + " : "
+ + ex.getMessage());
+
+ }
+ return results;
+
+ }
+
} // ExistHTTPDataStorage
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/exist/ExtendedExistHTTPDataStorage.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/exist/ExtendedExistHTTPDataStorage.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/exist/ExtendedExistHTTPDataStorage.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -7,43 +7,33 @@
import java.io.InputStreamReader;
import java.io.BufferedReader;
-
public class ExtendedExistHTTPDataStorage extends ExistHTTPDataStorage {
-
// -------------------------------------------------------------
Constructor
-
public ExtendedExistHTTPDataStorage() {
super();
}
-
// ------------------------------------------------------------- Methods
+ public String getXQueryStringResult(String xquery, String collection,
DataCredential credential)
+ throws PerfSONARException {
- public String getXQueryStringResult(
- String xquery,
- String collection,
- DataCredential credential) throws PerfSONARException {
-
try {
- HTTPResult httpResult =
- httpAccess.sendXQueryPOSTRequest(
- collection,
- xquery,
- credential.getUsername(),
- credential.getPassword(),
-
org.perfsonar.base2.service.storage.xml.exist.ExistDbHTTPAccess.FIRST,
-
org.perfsonar.base2.service.storage.xml.exist.ExistDbHTTPAccess.ALL_RESULTS);
+ HTTPResult httpResult =
httpAccess.sendXQueryPOSTRequest(collection, xquery, credential.getUsername(),
+ credential.getPassword(),
org.perfsonar.base2.service.storage.xml.exist.ExistDbHTTPAccess.FIRST,
+
org.perfsonar.base2.service.storage.xml.exist.ExistDbHTTPAccess.ALL_RESULTS);
InputStream is = httpResult.getResponse();
BufferedReader reader = new BufferedReader(new
InputStreamReader(is));
StringBuffer sb = new StringBuffer();
int c;
- while((c = reader.read()) != -1) sb.append((char)c);
+ while ((c = reader.read()) != -1) {
+ sb.append((char) c);
+ }
reader.close();
String result = sb.toString();
@@ -59,38 +49,39 @@
return result;
} catch (Exception ex) {
- throw new PerfSONARException(
- "error.common.storage.xmldb.open",
- "XQuery by HTTP failed. "
- + "Could not connect to eXist via pure http, "
- + " nested exception was: "
- + ex.getClass()+" : "+ex.getMessage());
+ throw new PerfSONARException("error.common.storage.xmldb.open",
"XQuery by HTTP failed. "
+ + "Could not connect to eXist via pure http, " + "
nested exception was: " + ex.getClass() + " : "
+ + ex.getMessage());
}
}
-
protected String extractXMLTag(String str, String tag) {
- //trim from blank spaces
+ // trim from blank spaces
str = str.trim();
- //find starting tag
- int indexStartTag1 = str.indexOf("<"+tag);
- if (indexStartTag1==-1) return null;
+ // find starting tag
+ int indexStartTag1 = str.indexOf("<" + tag);
+ if (indexStartTag1 == -1) {
+ return null;
+ }
- //find end of starting tag
+ // find end of starting tag
int indexStartTag2 = str.indexOf(">", indexStartTag1);
- if (indexStartTag2==-1) return null;
+ if (indexStartTag2 == -1) {
+ return null;
+ }
- //find closing tag
- int indexEndTag1 = str.indexOf("</"+tag, indexStartTag2);
- if (indexEndTag1==-1) return null;
+ // find closing tag
+ int indexEndTag1 = str.indexOf("</" + tag, indexStartTag2);
+ if (indexEndTag1 == -1) {
+ return null;
+ }
- String substr = str.substring(indexStartTag2+1, indexEndTag1);
+ String substr = str.substring(indexStartTag2 + 1, indexEndTag1);
return substr;
}
-
-} //ExtendedExistHTTPDataStorage
\ No newline at end of file
+} // ExtendedExistHTTPDataStorage
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/exist/HTTPAccess.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/exist/HTTPAccess.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/exist/HTTPAccess.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -8,29 +8,25 @@
import org.apache.commons.codec.binary.Base64;
-
-
/**
- * This class implements basic HTTP methods of eXist DB XML
- * document manipulating. Most of them may be used in communication
- * to other HTTP databases or servers
- *
+ * This class implements basic HTTP methods of eXist DB XML document
+ * manipulating. Most of them may be used in communication to other HTTP
+ * databases or servers
+ *
* @author Maciej Glowiak
- *
+ *
*/
public class HTTPAccess {
// --------------------------------------------- Private variables
-
-
-
+
// -------------------------------------------------- Constructors
-
+
// ------------------------------------------------ Public methods
-
-
+
/**
* POST - Sends text content to the server
+ *
* @param url
* @param content
* @param username
@@ -38,94 +34,62 @@
* @return
* @throws IOException
*/
- public HTTPResult sendPOSTRequest(
- String url,
- String content,
- String username,
- String password) throws IOException {
-
- return sendHTTPRequest(
- url,
- "POST",
- "application/x- www-form-urlencoded",
- content,
- true, true,
- username, password);
-
+ public HTTPResult sendPOSTRequest(String url, String content, String
username, String password) throws IOException {
+
+ return sendHTTPRequest(url, "POST", "application/x-
www-form-urlencoded", content, true, true, username,
+ password);
+
}
-
-
+
/**
* DELETE - removes remote resource from the server
+ *
* @param url
* @param username
* @param password
* @return
- * @throws IOException
+ * @throws IOException
*/
- public HTTPResult sendDELETERequest(
- String url,
- String username,
- String password) throws IOException {
-
- return sendHTTPRequest(
- url,
- "DELETE",
- null, null,
- false, true, //no input, output=result
- username, password);
-
+ public HTTPResult sendDELETERequest(String url, String username, String
password) throws IOException {
+
+ return sendHTTPRequest(url, "DELETE", null, null, false, true, // no
+ //
input,
+ //
output=result
+ username, password);
+
}
-
-
+
/**
* PUT - sends resource to the server
+ *
* @param url
* @param content
* @param username
* @param password
* @return
- * @throws IOException
+ * @throws IOException
*/
- public HTTPResult sendPUTRequest(
- String url,
- String content,
- String username,
- String password) throws IOException {
-
- return sendHTTPRequest(
- url,
- "PUT",
- null, content,
- true, true,
- username, password);
-
+ public HTTPResult sendPUTRequest(String url, String content, String
username, String password) throws IOException {
+
+ return sendHTTPRequest(url, "PUT", null, content, true, true,
username, password);
+
}
-
-
+
/**
* GET - downloads remote document from the server
+ *
* @param url
* @param username
* @param password
* @return
- * @throws IOException
+ * @throws IOException
*/
- public HTTPResult sendGETRequest(
- String url,
- String username,
- String password) throws IOException {
-
- return sendHTTPRequest(
- url,
- "GET",
- null, null,
- false, true,
- username, password);
-
+ public HTTPResult sendGETRequest(String url, String username, String
password) throws IOException {
+
+ return sendHTTPRequest(url, "GET", null, null, false, true,
username, password);
+
}
-
-
+
/**
* Generic operation on the HTTP server
*
@@ -140,82 +104,71 @@
* @return
* @throws IOException
*/
- private HTTPResult sendHTTPRequest(
- String url,
- String method,
- String contentType,
- String content,
- boolean isRequest,
- boolean isResponse,
- String username,
- String password) throws IOException {
-
-
- //connect by HTTP with /exist/rest/db/COLLECTION
- URL _url = new URL(url);
-
- //create HTTP URL Connection
- HttpURLConnection httpUrlConnection = (HttpURLConnection)
_url.openConnection();
-
- //set HTTP method
+ private HTTPResult sendHTTPRequest(String url, String method, String
contentType, String content,
+ boolean isRequest, boolean isResponse, String username, String
password) throws IOException {
+
+ // connect by HTTP with /exist/rest/db/COLLECTION
+ URL myURL = new URL(url);
+
+ // create HTTP URL Connection
+ HttpURLConnection httpUrlConnection = (HttpURLConnection)
myURL.openConnection();
+
+ // set HTTP method
httpUrlConnection.setRequestMethod(method);
-
- //set content type
- if (contentType != null)
+
+ // set content type
+ if (contentType != null) {
httpUrlConnection.setRequestProperty("Content-Type",
contentType);
-
- httpUrlConnection.setDoOutput(isRequest);
+ }
+
+ httpUrlConnection.setDoOutput(isRequest);
httpUrlConnection.setDoInput(isResponse);
-
- //set content length
- if (content!=null)
- httpUrlConnection.setRequestProperty(
- "Content-Length",
- String.valueOf(content.length()));
-
- //HTTP Authorization, set "Authorization: Basic " if necessary
- if (username!=null) {
-
- if (password==null) password=""; //if null make it empty String
-
+
+ // set content length
+ if (content != null) {
+ httpUrlConnection.setRequestProperty("Content-Length",
String.valueOf(content.length()));
+ }
+
+ // HTTP Authorization, set "Authorization: Basic " if necessary
+ if (username != null) {
+
+ if (password == null)
+ {
+ password = ""; // if null make it empty String
+ }
+
if (!("".equals(username))) {
- //encode BASE 64
- String userAndPass = username+":"+password;
+ // encode BASE 64
+ String userAndPass = username + ":" + password;
Base64 base64encoder = new Base64();
- String userAndPass64 = new String(base64encoder.encode(
- userAndPass.getBytes()));
-
+ String userAndPass64 = new
String(base64encoder.encode(userAndPass.getBytes()));
+
String basicAuth = "Basic " + userAndPass64;
-
- httpUrlConnection.setRequestProperty(
- "Authorization", basicAuth);
-
+
+ httpUrlConnection.setRequestProperty("Authorization",
basicAuth);
+
}
}
-
-
- //send via HTTP
+
+ // send via HTTP
if (isRequest) {
OutputStream out = httpUrlConnection.getOutputStream();
out.write(content.getBytes());
out.flush();
-// out.close();
+ // out.close();
}
-
- //HTTP response available now
+
+ // HTTP response available now
int responseCode = httpUrlConnection.getResponseCode();
String responseMessage = httpUrlConnection.getResponseMessage();
-
+
InputStream response = null;
if (isResponse) {
response = httpUrlConnection.getInputStream();
}
-
- return new HTTPResult(response, responseCode, responseMessage);
+
+ return new HTTPResult(response, responseCode, responseMessage);
}
-
-
-
-} //HTTPAccess
+} // HTTPAccess
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/exist/HTTPResult.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/exist/HTTPResult.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/storage/xml/exist/HTTPResult.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -6,7 +6,7 @@
* Represents HTTP results
*
* @author Maciej Glowiak
- *
+ *
*/
public class HTTPResult {
@@ -14,25 +14,23 @@
private int resultCode;
private String resultMessage;
- public HTTPResult(
- InputStream response,
- int resultCode,
- String resultMessage
- ) {
+ public HTTPResult(InputStream response, int resultCode, String
resultMessage) {
this.response = response;
this.resultCode = resultCode;
- //this.resultMessage = resultMessage;
+ // this.resultMessage = resultMessage;
}
public InputStream getResponse() {
return response;
}
+
public int getResultCode() {
return resultCode;
}
+
public String getResultMessage() {
return resultMessage;
}
-} //HTTPResult
\ No newline at end of file
+} // HTTPResult
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/util/ResultCodesUtil.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/util/ResultCodesUtil.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/util/ResultCodesUtil.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -9,34 +9,38 @@
/**
* This class contains useful methods for result codes
+ *
* @author Maciej Glowiak
- *
+ *
*/
public class ResultCodesUtil {
-
/**
* Generates result code
*
- * @param reqMessage message to be populated with the result code. If
null,
- * the new Message will be created.
- * @param code result code
- * @param description result additional description
+ * @param reqMessage
+ * message to be populated with the result code. If null, the
new
+ * Message will be created.
+ * @param code
+ * result code
+ * @param description
+ * result additional description
* @return
*/
public static Message generateResultMessage(Message reqMessage, String
code, String description) {
Message message = reqMessage;
- if (message == null)
+ if (message == null) {
message = new Message("ResultCode", "msg1");
+ }
Metadata meta = new Metadata("result-code", "nmwg");
-
- if(!code.startsWith(PerfSONARException.RESULT_CODE_PREFIX)){
- code=PerfSONARException.RESULT_CODE_PREFIX+code;
+
+ if (!code.startsWith(PerfSONARException.RESULT_CODE_PREFIX)) {
+ code = PerfSONARException.RESULT_CODE_PREFIX + code;
}
-
+
EventType evt = new EventType(code, "nmwg");
meta.addChild(evt);
@@ -53,56 +57,62 @@
}
-
/**
* Creating result code basing on PerfSONARException
- * @param reqMessage message to be populated with the result code. If
null,
- * the new Message will be created.
- * @param ex exception containing result code
+ *
+ * @param reqMessage
+ * message to be populated with the result code. If null, the
new
+ * Message will be created.
+ * @param ex
+ * exception containing result code
* @return
*/
public static Message generateResultMessage(Message reqMessage,
PerfSONARException ex) {
return generateResultMessage(reqMessage, ex.getResultCode(),
ex.getResultDescription());
}
-
/**
* New Message with result code will be created.
- * @param code result code
- * @param description result additional description
+ *
+ * @param code
+ * result code
+ * @param description
+ * result additional description
* @return
*/
public static Message generateResultMessage(String code, String
description) {
return generateResultMessage(null, code, description);
}
-
/**
- * Creating result code basing on PerfSONARException, will create new
Message
+ * Creating result code basing on PerfSONARException, will create new
+ * Message
*/
public static Message generateResultMessage(PerfSONARException ex) {
return generateResultMessage(null, ex.getResultCode(),
ex.getResultDescription());
}
-
/**
- * TODO: why is it needed??? Need description or move to another
class/package
+ * TODO: why is it needed??? Need description or move to another
+ * class/package
*/
public static Message generateOldResultMessage(Message reqMessage,
String code, String description) {
Message message = reqMessage;
- if (message == null)
+ if (message == null) {
message = new Message("ResultCode", "msg1");
+ }
Metadata meta = new Metadata("result-code", "nmwg");
EventType evt = new EventType(code, "nmwg");
meta.addChild(evt);
Data data = new Data("result-code-description", "result-code",
"nmwg");
-// Element datum = new Element("datum", "nmwgr",
"http://ggf.org/ns/nmwg/result/2.0/");
- // datum.setText(description);
- // data.addChild(datum);
+ // Element datum = new Element("datum", "nmwgr",
+ // "http://ggf.org/ns/nmwg/result/2.0/");
+ // datum.setText(description);
+ // data.addChild(datum);
message.addChild(meta);
message.addChild(data);
@@ -111,17 +121,14 @@
}
-
public static Message generateOldResultMessage(Message reqMessage,
PerfSONARException ex) {
return generateOldResultMessage(reqMessage, ex.getResultCode(),
ex.getResultDescription());
}
-
public static Message generateOldResultMessage(String code, String
description) {
return generateOldResultMessage(null, code, description);
}
-
public static Message generateOldResultMessage(PerfSONARException ex) {
return generateOldResultMessage(null, ex.getResultCode(),
ex.getResultDescription());
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/validation/JREVersion.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/validation/JREVersion.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/service/validation/JREVersion.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -5,40 +5,47 @@
/**
* Represents JRE version details.
+ *
* @author <a
href="mailto:">Blazej
Pietrzak</a>
*/
public class JREVersion {
- private String jreVersion;
-
- public JREVersion() {
- setJREVersion(System.getProperty("java.runtime.version"));
- }
+ private String jreVersion;
- /**
- * Compares the provided version with the JRE version.
- *
- * @return <code>true</code> if the version provided is greater equal
to JRE version
- */
- public boolean isJRECompatibleWith(int major, int minor) {
- final Pattern pattern =
Pattern.compile("([0-9])\\.([0-9])\\.([0-9])(?:_([0-9]{2}))?(?:-([a-zA-Z0-9]+))?");
- final Matcher m = pattern.matcher(getJREVersion());
-
- if (!m.find())
- return false;
- if (major < Integer.parseInt(m.group(1)))
- return false;
- if (major > Integer.parseInt(m.group(1)))
- return true;
- if (minor < Integer.parseInt(m.group(2)))
- return false;
-
- return true;
- }
+ public JREVersion() {
+ setJREVersion(System.getProperty("java.runtime.version"));
+ }
- protected void setJREVersion(String version) {
- this.jreVersion = version;
- }
- public String getJREVersion() {
- return jreVersion;
- }
+ /**
+ * Compares the provided version with the JRE version.
+ *
+ * @return <code>true</code> if the version provided is greater equal to
JRE
+ * version
+ */
+ public boolean isJRECompatibleWith(int major, int minor) {
+ final Pattern pattern =
Pattern.compile("([0-9])\\.([0-9])\\.([0-9])(?:_([0-9]{2}))?(?:-([a-zA-Z0-9]+))?");
+ final Matcher m = pattern.matcher(getJREVersion());
+
+ if (!m.find()) {
+ return false;
+ }
+ if (major < Integer.parseInt(m.group(1))) {
+ return false;
+ }
+ if (major > Integer.parseInt(m.group(1))) {
+ return true;
+ }
+ if (minor < Integer.parseInt(m.group(2))) {
+ return false;
+ }
+
+ return true;
+ }
+
+ protected void setJREVersion(String version) {
+ this.jreVersion = version;
+ }
+
+ public String getJREVersion() {
+ return jreVersion;
+ }
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/servlets/AuthServlet.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/servlets/AuthServlet.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/servlets/AuthServlet.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -22,88 +22,82 @@
@SuppressWarnings("serial")
public abstract class AuthServlet extends HttpServlet {
- private Logger logger = LoggerFactory.getLogger(AuthServlet.class);
+ private Logger logger = LoggerFactory.getLogger(AuthServlet.class);
- private String username;
- private String password;
+ private String username;
+ private String password;
- public String getUsername() {
- return username;
- }
+ public String getUsername() {
+ return username;
+ }
- public String getPassword() {
- return password;
- }
+ public String getPassword() {
+ return password;
+ }
- /*
- * returns username for allowed user
- */
- protected abstract String getUsername(ConfigurationManager
configManager)
- throws PerfSONARException;
+ /*
+ * returns username for allowed user
+ */
+ protected abstract String getUsername(ConfigurationManager
configManager) throws PerfSONARException;
- /*
- * returns password for allowed user;
- */
- protected abstract String getPassword(ConfigurationManager
configManager)
- throws PerfSONARException;
+ /*
+ * returns password for allowed user;
+ */
+ protected abstract String getPassword(ConfigurationManager
configManager) throws PerfSONARException;
- /**
- *
- * this method is executed whether user privileges are correct
- *
- * @param req
- * @param resp
- */
- protected abstract void processRequest(HttpServletRequest req,
- HttpServletResponse resp) throws PerfSONARException;
+ /**
+ *
+ * this method is executed whether user privileges are correct
+ *
+ * @param req
+ * @param resp
+ */
+ protected abstract void processRequest(HttpServletRequest req,
HttpServletResponse resp) throws PerfSONARException;
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
- String auth = req.getHeader("Authorization");
- String[] credentials = receiveCredentials(auth);
- if (credentials == null) {
- resp.setHeader("WWW-Authenticate", "BASIC
realm=\"users\"");
- resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
- } else {
- username = credentials[0];
- password = credentials[1];
- try {
- processRequest(req, resp);
- } catch (PerfSONARException e) {
- logger.warn("Request processing failed", e);
- resp.setHeader("WWW-Authenticate", "BASIC
realm=\"users\"");
-
resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
- }
- }
- }
+ @Override
+ protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
+ String auth = req.getHeader("Authorization");
+ String[] credentials = receiveCredentials(auth);
+ if (credentials == null) {
+ resp.setHeader("WWW-Authenticate", "BASIC realm=\"users\"");
+ resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
+ } else {
+ username = credentials[0];
+ password = credentials[1];
+ try {
+ processRequest(req, resp);
+ } catch (PerfSONARException e) {
+ logger.warn("Request processing failed", e);
+ resp.setHeader("WWW-Authenticate", "BASIC realm=\"users\"");
+ resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
+ }
+ }
+ }
- private String[] receiveCredentials(String authHeader) {
- String[] loginAndPassword = null;
+ private String[] receiveCredentials(String authHeader) {
+ String[] loginAndPassword = null;
- if (authHeader != null) {
- java.util.StringTokenizer st = new
java.util.StringTokenizer(
- authHeader);
- if (st.hasMoreTokens()) {
- String basic = st.nextToken();
+ if (authHeader != null) {
+ java.util.StringTokenizer st = new
java.util.StringTokenizer(authHeader);
+ if (st.hasMoreTokens()) {
+ String basic = st.nextToken();
- if (basic.equalsIgnoreCase("Basic")) {
- String credentials = st.nextToken();
+ if (basic.equalsIgnoreCase("Basic")) {
+ String credentials = st.nextToken();
- String userPass;
- userPass = new String(Base64
- .decodeBase64(credentials.getBytes()));
- int p = userPass.indexOf(":");
- if (p != -1) {
- loginAndPassword = new
String[2];
- loginAndPassword[0] =
userPass.substring(0, p);
- loginAndPassword[1] =
userPass.substring(p + 1);
- }
+ String userPass;
+ userPass = new
String(Base64.decodeBase64(credentials.getBytes()));
+ int p = userPass.indexOf(":");
+ if (p != -1) {
+ loginAndPassword = new String[2];
+ loginAndPassword[0] = userPass.substring(0, p);
+ loginAndPassword[1] = userPass.substring(p + 1);
+ }
- }
- }
- }
- return loginAndPassword;
- }
+ }
+ }
+ }
+ return loginAndPassword;
+ }
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/servlets/ExistDBInitServlet.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/servlets/ExistDBInitServlet.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/servlets/ExistDBInitServlet.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -22,74 +22,68 @@
@SuppressWarnings("serial")
public abstract class ExistDBInitServlet extends AuthServlet {
- private Logger logger =
LoggerFactory.getLogger(ExistDBInitServlet.class);
+ private Logger logger =
LoggerFactory.getLogger(ExistDBInitServlet.class);
- /**
- *
- * upload file to eXistDatabase
- *
- * @param fileName
- * - name of the file which contains content of the
database
- * element
- * @param filePath
- * - path to file
- * @param collection
- * - collection where new database element will be added in
- * @throws XMLDBException
- */
- protected void uploadFile(String fileName, String filePath,
- Collection collection) throws XMLDBException {
+ /**
+ *
+ * upload file to eXistDatabase
+ *
+ * @param fileName
+ * - name of the file which contains content of the database
+ * element
+ * @param filePath
+ * - path to file
+ * @param collection
+ * - collection where new database element will be added in
+ * @throws XMLDBException
+ */
+ protected void uploadFile(String fileName, String filePath, Collection
collection) throws XMLDBException {
- XMLResource document = (XMLResource)
collection.createResource(
- fileName, "XMLResource");
- File f = new File(filePath + File.separator + fileName);
- document.setContent(f);
- collection.storeResource(document);
- }
+ XMLResource document = (XMLResource)
collection.createResource(fileName, "XMLResource");
+ File f = new File(filePath + File.separator + fileName);
+ document.setContent(f);
+ collection.storeResource(document);
+ }
- protected Collection getMainCollection(String dbUrl) {
- try {
- @SuppressWarnings("rawtypes")
- Class cl =
Class.forName("org.exist.xmldb.DatabaseImpl");
- Database database = (Database) cl.newInstance();
- // The following is needed in case of embedded DB
-// database.setProperty("create-database", "true");
- logger.debug("••• Connecting to eXist DB as \"" +
getUsername() + "\" •••");
- DatabaseManager.registerDatabase(database);
- Collection collection =
DatabaseManager.getCollection(dbUrl, getUsername(), getPassword());
- if (collection == null) {
- logger.warn("Something went wrong in
getMainCollection!");
- }
- return collection;
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } catch (InstantiationException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (XMLDBException e) {
- e.printStackTrace();
- }
- return null;
- }
+ protected Collection getMainCollection(String dbUrl) {
+ try {
+ @SuppressWarnings("rawtypes")
+ Class cl = Class.forName("org.exist.xmldb.DatabaseImpl");
+ Database database = (Database) cl.newInstance();
+ // The following is needed in case of embedded DB
+ // database.setProperty("create-database", "true");
+ logger.debug("••• Connecting to eXist DB as \"" + getUsername()
+ "\" •••");
+ DatabaseManager.registerDatabase(database);
+ Collection collection = DatabaseManager.getCollection(dbUrl,
getUsername(), getPassword());
+ if (collection == null) {
+ logger.warn("Something went wrong in getMainCollection!");
+ }
+ return collection;
+ } catch (ClassNotFoundException e) {
+ e.printStackTrace();
+ } catch (InstantiationException e) {
+ e.printStackTrace();
+ } catch (IllegalAccessException e) {
+ e.printStackTrace();
+ } catch (XMLDBException e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
- protected UserManagementService getUserManagmentService(
- Collection collection) throws XMLDBException {
- return (UserManagementService) collection.getService(
- "UserManagementService", "1.0");
- }
+ protected UserManagementService getUserManagmentService(Collection
collection) throws XMLDBException {
+ return (UserManagementService)
collection.getService("UserManagementService", "1.0");
+ }
- protected CollectionManagementService getCollectionManagmentService(
- Collection collection) throws XMLDBException {
- return (CollectionManagementService) collection.getService(
- "CollectionManagementService", "1.0");
- }
-
- protected User createUser(String username,String password,String
group){
- User user = new User(username,password);
- user.addGroup(group);
-
- return user;
- }
+ protected CollectionManagementService
getCollectionManagmentService(Collection collection) throws XMLDBException {
+ return (CollectionManagementService)
collection.getService("CollectionManagementService", "1.0");
+ }
+ protected User createUser(String username, String password, String
group) {
+ User user = new User(username, password);
+ user.addGroup(group);
+
+ return user;
+ }
+
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/AXIOMCreator.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/AXIOMCreator.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/AXIOMCreator.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -14,56 +14,56 @@
* Creates OMElement object from Element
*
* @author Maciej Glowiak
- *
+ *
*/
public class AXIOMCreator {
-
+
private OMFactory fac = OMAbstractFactory.getOMFactory();
-
/**
* Creates OMElement object from Element e
*/
- public OMElement getElement(Element e)
- throws XMLStreamException {
-
+ public OMElement getElement(Element e) throws XMLStreamException {
+
String nsPrefix = e.getNamespacePrefix();
OMNamespace omNs = null;
- if (nsPrefix!=null)
+ if (nsPrefix != null) {
omNs = fac.createOMNamespace(e.getNamespaceUri(), nsPrefix);
- else
- omNs = fac.createOMNamespace("","");
+ } else {
+ omNs = fac.createOMNamespace("", "");
+ }
- //start elemenet
- OMElement omElement = fac.createOMElement(e.getName(), omNs);
-
- //attributes
+ // start elemenet
+ OMElement omElement = fac.createOMElement(e.getName(), omNs);
+
+ // attributes
boolean isId = false;
for (Map.Entry<String, String> attr : e.getAttributes().entrySet()) {
String name = attr.getKey();
String value = attr.getValue();
OMAttribute omAttribute = fac.createOMAttribute(name, null,
value);
omElement.addAttribute(omAttribute);
- if (name.equals("id")) isId = true;
+ if (name.equals("id")) {
+ isId = true;
+ }
}
-
- //id - only if it's no present and doGenerateId is true
+
+ // id - only if it's no present and doGenerateId is true
if (!isId && e.isDoGenerateId()) {
OMAttribute omAttribute = fac.createOMAttribute("id", null,
e.getId());
omElement.addAttribute(omAttribute);
}
-
- //characters
+
+ // characters
omElement.addChild(fac.createOMText(omElement, e.getText()));
-
-
- //children
+
+ // children
for (Element ch : e.getChildren()) {
omElement.addChild(getElement(ch));
}
-
+
return omElement;
-
+
}
-} //AXIOMCreator
+} // AXIOMCreator
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/ConfigurationStaxParser.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/ConfigurationStaxParser.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/ConfigurationStaxParser.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -6,55 +6,51 @@
import org.perfsonar.base2.service.exceptions.PerfSONARException;
/**
- * StaxParser basing on perfSONAR base Configuration
- * It takes element mappings from configuration file (using
ConfiguratioManager)
+ * StaxParser basing on perfSONAR base Configuration It takes element
mappings
+ * from configuration file (using ConfiguratioManager)
+ *
* @author Maciej Glowiak
- *
+ *
*/
public class ConfigurationStaxParser extends StaxParser {
// ----------------------------------------------------- Instance
variables
-
- String serviceName = null;
- ProtocolMappings elementMapping = null;
-
+
+ private String serviceName = null;
+ private ProtocolMappings elementMapping = null;
+
// -----------------------------------------------------------
constructors
-
-
+
public ConfigurationStaxParser() {
}
-
public ConfigurationStaxParser(String serviceName) {
this.serviceName = serviceName;
}
-
-
+
// -------------------------------------------------------- Public
elements
-
public String getMappingForElement(String element) {
String className = null;
try {
- if (elementMapping == null) setElementMapping();
+ if (elementMapping == null) {
+ setElementMapping();
+ }
className = elementMapping.getElement(element).getMapping();
} catch (Exception e) {
- //do nothing just return null!
+ // do nothing just return null!
}
return className;
-
-
+
}
-
+
protected void setElementMapping() throws PerfSONARException {
Configuration conf =
ConfigurationManager.getInstance().getConfiguration();
if (serviceName == null) {
- elementMapping = (ProtocolMappings)
-
(conf.getService().getEntry(Configuration.PROTOCOL_MAPPINGS));
+ elementMapping = (ProtocolMappings)
(conf.getService().getEntry(Configuration.PROTOCOL_MAPPINGS));
} else {
- elementMapping = (ProtocolMappings)
-
(conf.getService(serviceName).getEntry(Configuration.PROTOCOL_MAPPINGS));
+ elementMapping = (ProtocolMappings)
(conf.getService(serviceName).getEntry(Configuration.PROTOCOL_MAPPINGS));
}
}
-
-} //ConfigurationStaxParser
+
+} // ConfigurationStaxParser
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/Element.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/Element.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/Element.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -41,17 +41,14 @@
// indicate whether to generate id if there is no id attribute
protected boolean doGenerateId = false;
-
// ------------------------------------------------------------
Constructor
-
public Element() {
-
- //just do nothing...
+ // just do nothing...
+
}
-
public Element(String name, String namespacePrefix, String namespaceUri)
{
super();
@@ -60,29 +57,24 @@
this.namespaceUri = namespaceUri;
}
-
// --------------------------------------------------------- Public
methods
-
public String getName() {
return name;
}
-
public void setName(String name) {
- //System.out.println(" --" + name);
+ // System.out.println(" --" + name);
this.name = name;
}
-
public String getNamespaceUri() {
return namespaceUri;
}
-
public String getNamespacePrefix() {
// return namespaceContext.getPrefix(namespaceUri);
@@ -90,55 +82,48 @@
}
-
public void setNamespaceUri(String namespace) {
this.namespaceUri = namespace;
}
-
public void setNamespacePrefix(String namespace) {
this.namespacePrefix = namespace;
}
-
public void setNamespaceContext(NamespaceContext namespaceContext) {
this.namespaceContext = namespaceContext;
}
-
public NamespaceContext getNamespaceContext() {
return namespaceContext;
}
-
public void addChild(Element e) {
children.add(e);
}
-
public void addAttribute(String name, String value) {
- if (name.equals("id"))
+ if (name.equals("id")) {
id = value;
+ }
attributes.put(name, value);
}
-
public void setId(String value) {
addAttribute("id", value);
}
-
public String getAttribute(String name) {
return attributes.get(name);
@@ -149,120 +134,116 @@
try {
String param = getAttribute(name);
return Integer.parseInt(param);
- } catch (RuntimeException e) { return -1; }
+ } catch (RuntimeException e) {
+ return -1;
+ }
}
-
public void removeAttribute(String name) {
- if (name.equals("id"))
+ if (name.equals("id")) {
id = null;
+ }
attributes.remove(name);
}
-
public boolean removeChild(Element child) {
return children.remove(child);
}
-
/**
* Get full list of children (in order)
+ *
* @return
*/
public Collection<Element> getChildren() {
return children;
-
+
}
/**
* Get list of elements having specified name (in order)
+ *
* @param elementName
* @return
*/
public Collection<Element> getChildren(String elementName) {
-
+
return getChildren(elementName, null);
-
+
}
- /**
- * Get list of elements having specified name (in order)
- * and having either namespace prefix (e.g. "nmwg") or
- * full prefix ("http://ggf.org/ns/nmwg/base/2.0/")
+ /**
+ * Get list of elements having specified name (in order) and having
either
+ * namespace prefix (e.g. "nmwg") or full prefix
+ * ("http://ggf.org/ns/nmwg/base/2.0/")
*/
public Collection<Element> getChildren(String elementName, String ns) {
ArrayList<Element> chld = null;
-
+
for (Element e : children) {
if (e.getName().equals(elementName)) {
- if (
- (ns==null) || //if no
namespace given
- (ns.equals(e.getNamespacePrefix())) || //or if prefix
the same
- (ns.equals(e.getNamespaceUri())) //or full URI
the same
- ) {
- if (chld==null) chld = new ArrayList<Element>();
- chld.add(e);
- }
+ if ((ns == null) || // if no namespace given
+ (ns.equals(e.getNamespacePrefix())) || // or if
prefix
+ // the same
+ (ns.equals(e.getNamespaceUri())) // or full URI the
same
+ ) {
+ if (chld == null) {
+ chld = new ArrayList<Element>();
+ }
+ chld.add(e);
+ }
}
- } //end for
+ } // end for
return chld;
-
- }
- public Map<String,String> getAttributes() {
+ }
+ public Map<String, String> getAttributes() {
+
return attributes;
}
-
public void setText(String s) {
text = s;
}
-
public String getText() {
return text;
}
-
public boolean isDoGenerateId() {
return doGenerateId;
}
-
public void setDoGenerateId(boolean doGenerateId) {
this.doGenerateId = doGenerateId;
}
-
public String getId() {
return id;
}
-
@Override
- public String toString()
- {
+ public String toString() {
StringBuilder sb = new StringBuilder();
getDeeper(this, sb, "");
sb.append("\n");
return sb.toString();
}
- private StringBuilder getDeeper(Element parent, StringBuilder sb, String
indent)
- {
+ private StringBuilder getDeeper(Element parent, StringBuilder sb, String
indent) {
sb.append("\n").append(indent).append("name=").append(parent.getName());
sb.append("\n").append(indent).append("class=").append(parent.getClass());
sb.append("\n").append(indent).append("nsContext=").append(parent.getNamespaceUri());
@@ -279,14 +260,13 @@
sb.append("\n").append(indent).append("-----------");
indent += " ";
- for (Element _ch : parent.getChildren()) {
- getDeeper(_ch, sb, indent);
+ for (Element myCh : parent.getChildren()) {
+ getDeeper(myCh, sb, indent);
}
-
- return sb;
+
+ return sb;
}
-
-
+
/**
* Gets a copy of Element object. It determines the actual class of
Element
* and created dynamically class of the same type.
@@ -308,7 +288,6 @@
}
-
/**
* Generic copy of Element. This method should be re-implemented in
* descendant class if the class defines more fields or data to be
copied.
@@ -336,62 +315,70 @@
return out;
}
-
+
/**
- * Returns any (first) element having specified name
- * or null if not present
+ * Returns any (first) element having specified name or null if not
present
+ *
* @param name
* @return
*/
public Element getFirstChild(String name) {
- Collection<Element> children = getChildren(name);
- if (children == null) return null;
- for (Element ch : children) {
+ Collection<Element> myChildren = getChildren(name);
+ if (myChildren == null) {
+ return null;
+ }
+ for (Element ch : myChildren) {
return ch;
}
return null;
}
-
/**
* Checks whether element has specified name (and optionally namespace)
- * @param namespace namespace given as prefix OR url OR null value if
not to be checked
- * @param name The name of the element
+ *
+ * @param namespace
+ * namespace given as prefix OR url OR null value if not to be
+ * checked
+ * @param name
+ * The name of the element
* @return boolean value
*/
public boolean hasName(String namespace, String name) {
-
- if (namespace==null) {
- return this.name.equals(name); //if namespace==null
- } else {
- if ( (namespace.equals(namespacePrefix)) ||
(namespace.equals(namespaceUri)) )
- return this.name.equals(name);
- else return false; //neither namespace nor name the same
+
+ if (namespace == null) {
+ return this.name.equals(name); // if namespace==null
+ } else {
+ if ((namespace.equals(namespacePrefix)) ||
(namespace.equals(namespaceUri))) {
+ return this.name.equals(name);
+ } else {
+ return false; // neither namespace nor name the same
+ }
}
}
/**
- * Checks whether element has specified name. Namespace is not checked
at all
- * @param name The name of the element
+ * Checks whether element has specified name. Namespace is not checked at
+ * all
+ *
+ * @param name
+ * The name of the element
* @return boolean value
*/
public boolean hasName(String name) {
return hasName(null, name);
}
-
+
// ------------------------------------------------------------------
Static
- static private long currentId = 0;
+ private static long currentId = 0;
-
/**
* Generates random unique URI for new Element.
*
*/
public static String generateNextId() {
- String id = "uri:ps-element-id:" + System.currentTimeMillis() + ":"
- + Element.currentId;
+ String id = "uri:ps-element-id:" + System.currentTimeMillis() + ":"
+ Element.currentId;
Element.currentId++;
return id;
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/ElementSerializer.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/ElementSerializer.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/ElementSerializer.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -13,144 +13,152 @@
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
-
/**
* Serializer for Element objects.
*
* @author Maciej Glowiak
- *
+ *
*/
public class ElementSerializer {
-
-
- //TODO: parameters should be added (indentation, character encoding, etc)
-// private boolean isIndent = false;
-// private int indent = 2;
+ // TODO: parameters should be added (indentation, character encoding,
etc)
- private boolean isStartingDocumentDeclaration = false; // <?xml
version='1.0' encoding='ISO-8859-1'?>
-
-
+ // private boolean isIndent = false;
+ // private int indent = 2;
+
+ private boolean isStartingDocumentDeclaration = false; // <?xml
+ // version='1.0'
+ //
encoding='ISO-8859-1'?>
+
/**
- * Serialize single Element e to XMLStreamWriter. All children elements
- * will be serialized as well
- * @param writer XMLStreamWriter
- * @param e Element to serialize
- * @param ns set of namespaces already used (definitions printed out)
+ * Serialize single Element e to XMLStreamWriter. All children elements
will
+ * be serialized as well
+ *
+ * @param writer
+ * XMLStreamWriter
+ * @param e
+ * Element to serialize
+ * @param ns
+ * set of namespaces already used (definitions printed out)
* @throws XMLStreamException
*/
- protected void writeElement(
- XMLStreamWriter writer, Element e, Set<String> ns)
- throws XMLStreamException {
+ protected void writeElement(XMLStreamWriter writer, Element e,
Set<String> ns) throws XMLStreamException {
String nsPrefix = e.getNamespacePrefix();
- //start elemenet
+ // start elemenet
if (nsPrefix == null) {
writer.writeStartElement(e.getName());
} else {
- writer.writeStartElement(nsPrefix , e.getName(),
e.getNamespaceUri());
+ writer.writeStartElement(nsPrefix, e.getName(),
e.getNamespaceUri());
}
-
+
boolean nsPrefixExists = false;
- if (nsPrefix!=null) {
+ if (nsPrefix != null) {
nsPrefixExists = ns.contains(nsPrefix);
-
+
if (!nsPrefixExists) {
writer.writeNamespace(nsPrefix, e.getNamespaceUri());
ns.add(nsPrefix);
}
}
-
- //attributes
+
+ // attributes
boolean isId = false;
for (Map.Entry<String, String> attr : e.getAttributes().entrySet()) {
String name = attr.getKey();
String value = attr.getValue();
writer.writeAttribute(name, value);
- if (name.equals("id")) isId = true;
+ if (name.equals("id")) {
+ isId = true;
+ }
}
-
- //id - only if it's no present and doGenerateId is true
- if (!isId && e.isDoGenerateId())
+
+ // id - only if it's no present and doGenerateId is true
+ if (!isId && e.isDoGenerateId()) {
writer.writeAttribute("id", e.getId());
-
- //characters
- writer.writeCharacters(e.getText());
+ }
- //children
+ // characters
+ writer.writeCharacters(e.getText());
+
+ // children
for (Element ch : e.getChildren()) {
writeElement(writer, ch, ns);
}
-
- //remove prefix from the set - in case of siblings elements (in
recursion)
- if ((nsPrefix!=null) && (!nsPrefixExists)) {
+
+ // remove prefix from the set - in case of siblings elements (in
+ // recursion)
+ if ((nsPrefix != null) && (!nsPrefixExists)) {
ns.remove(nsPrefix);
}
-
+
writer.writeEndElement();
-
+
}
-
-
+
/**
* Serializes element e to output stream out
- * @param out any OutputStream
- * @param e Element instance to be serialized
+ *
+ * @param out
+ * any OutputStream
+ * @param e
+ * Element instance to be serialized
* @throws XMLStreamException
* @throws IOException
*/
public void write(OutputStream out, Element e) throws
XMLStreamException, IOException {
-
+
XMLOutputFactory factory = XMLOutputFactory.newInstance();
XMLStreamWriter writer = factory.createXMLStreamWriter(out);
- if (isStartingDocumentDeclaration)
writer.writeStartDocument("ISO-8859-1", "1.0");
-
+ if (isStartingDocumentDeclaration) {
+ writer.writeStartDocument("ISO-8859-1", "1.0");
+ }
+
writeElement(writer, e, new HashSet<String>());
writer.writeEndDocument();
writer.flush();
writer.close();
out.close();
-
+
}
/**
*
* Serializes Element and write it to file
*
- * @param file - dest file with serialized Element
- * @param e - element to serialize
+ * @param file
+ * - dest file with serialized Element
+ * @param e
+ * - element to serialize
*/
- public void write(String file,Element e){
-
- try {
- File f=new File(file);
- FileOutputStream fos=new FileOutputStream(f);
- try {
- write(fos,e);
- } catch (XMLStreamException e1) {
- e1.printStackTrace();
- } catch (IOException e1) {
- e1.printStackTrace();
- }
- } catch (FileNotFoundException e1) {
- e1.printStackTrace();
- }
+ public void write(String file, Element e) {
+
+ try {
+ File f = new File(file);
+ FileOutputStream fos = new FileOutputStream(f);
+ try {
+ write(fos, e);
+ } catch (XMLStreamException e1) {
+ e1.printStackTrace();
+ } catch (IOException e1) {
+ e1.printStackTrace();
+ }
+ } catch (FileNotFoundException e1) {
+ e1.printStackTrace();
+ }
}
-
public boolean isStartingDocumentDeclaration() {
-
+
return isStartingDocumentDeclaration;
}
+ public void setStartingDocumentDeclaration(boolean isDocumentStarted) {
-
- public void setStartingDocumentDeclaration(boolean isDocumentStarted) {
-
this.isStartingDocumentDeclaration = isDocumentStarted;
}
-} //ElementSerializer
+} // ElementSerializer
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/ParserSource.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/ParserSource.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/ParserSource.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -12,36 +12,36 @@
* Class for getting InputStream from various sources
*
* @author Maciej Glowiak
- *
+ *
*/
public class ParserSource {
- static public InputStream getInputStreamFromFile(File f) throws
FileNotFoundException {
- InputStream in = new FileInputStream(f);
+ public static InputStream getInputStreamFromFile(File f) throws
FileNotFoundException {
+ InputStream in = new FileInputStream(f);
return in;
}
-
- static public InputStream getInputStreamFromFile(String fn) throws
FileNotFoundException {
- InputStream in = new FileInputStream(fn);
+
+ public static InputStream getInputStreamFromFile(String fn) throws
FileNotFoundException {
+ InputStream in = new FileInputStream(fn);
return in;
}
-
- static public InputStream getInputStreamFromString(String xml) {
-
+
+ public static InputStream getInputStreamFromString(String xml) {
+
ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes());
return bais;
-
+
}
-
- static public InputStream getInputStreamFromURL(URL url) throws
IOException {
+
+ public static InputStream getInputStreamFromURL(URL url) throws
IOException {
InputStream in = url.openStream();
return in;
}
-
- static public InputStream getInputStreamFromURL(String url) throws
IOException {
+
+ public static InputStream getInputStreamFromURL(String url) throws
IOException {
URL u = new URL(url);
InputStream in = u.openStream();
return in;
- }
-
+ }
+
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/StaxParser.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/StaxParser.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/StaxParser.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -18,219 +18,219 @@
*/
public class StaxParser {
- private static final String DEFAULT_ELEMENT_CLASSNAME =
"org.perfsonar.base2.xml.Element";
- private static final String ANY_ELEMENT = "*";
+ private static final String DEFAULT_ELEMENT_CLASSNAME =
"org.perfsonar.base2.xml.Element";
+ private static final String ANY_ELEMENT = "*";
- HashMap<String, String> objectMappings = new HashMap<String,
String>();
+ private HashMap<String, String> objectMappings = new HashMap<String,
String>();
- // -----------------------------------------------------------
constructor
+ // -----------------------------------------------------------
constructor
- public StaxParser() {
+ public StaxParser() {
- objectMappings.put(ANY_ELEMENT, DEFAULT_ELEMENT_CLASSNAME);
// default
- // one
+ objectMappings.put(ANY_ELEMENT, DEFAULT_ELEMENT_CLASSNAME); //
default
+ // one
- }
+ }
- public StaxParser(HashMap<String, String> objectMapping) {
+ public StaxParser(HashMap<String, String> objectMapping) {
- setObjectMappings(objectMapping);
+ setObjectMappings(objectMapping);
- }
+ }
- // -------------------------------------------------------- public
methods
+ // -------------------------------------------------------- public
methods
- /**
- * StAX Parser for InputStream, creates XMLStreamReader and runs
parser
- *
- * @param fis
- * @return
- * @throws XMLStreamException
- */
- public Element parse(InputStream istream) throws XMLStreamException {
+ /**
+ * StAX Parser for InputStream, creates XMLStreamReader and runs parser
+ *
+ * @param fis
+ * @return
+ * @throws XMLStreamException
+ */
+ public Element parse(InputStream istream) throws XMLStreamException {
- // create STAX reader from inputstream
- XMLInputFactory factory = XMLInputFactory
- .newInstance();
- XMLStreamReader staxXmlReader = factory
- .createXMLStreamReader(istream);
- return parse(staxXmlReader);
+ // create STAX reader from inputstream
+ XMLInputFactory factory = XMLInputFactory.newInstance();
+ XMLStreamReader staxXmlReader =
factory.createXMLStreamReader(istream);
+ return parse(staxXmlReader);
- }
+ }
- /**
- * StAX Parser for XMLStreamReader
- *
- * @param fis
- * @return
- * @throws XMLStreamException
- */
- public Element parse(XMLStreamReader staxXmlReader)
- throws XMLStreamException {
+ /**
+ * StAX Parser for XMLStreamReader
+ *
+ * @param fis
+ * @return
+ * @throws XMLStreamException
+ */
+ public Element parse(XMLStreamReader staxXmlReader) throws
XMLStreamException {
- Element topElement = null;
- Stack<Element> parents = new Stack<Element>();
+ Element topElement = null;
+ Stack<Element> parents = new Stack<Element>();
- // current element reference
- Element currentElement = null;
+ // current element reference
+ Element currentElement = null;
- String textNodeName=null;
- boolean textNodeFound = false;
- StringBuilder sb = new StringBuilder();
- String localName;
+ String textNodeName = null;
+ boolean textNodeFound = false;
+ StringBuilder sb = new StringBuilder();
+ String localName;
- // Parse for all STAX events
- for (int event = staxXmlReader.next(); event !=
XMLStreamConstants.END_DOCUMENT; event = staxXmlReader
- .next()) {
+ // Parse for all STAX events
+ for (int event = staxXmlReader.next(); event !=
XMLStreamConstants.END_DOCUMENT; event = staxXmlReader.next()) {
- if (textNodeFound) {
- if (event ==
XMLStreamConstants.START_ELEMENT) {
- localName =
staxXmlReader.getLocalName();
- sb.append("<");
- sb.append(localName);
- sb.append(">");
+ if (textNodeFound) {
+ if (event == XMLStreamConstants.START_ELEMENT) {
+ localName = staxXmlReader.getLocalName();
+ sb.append("<");
+ sb.append(localName);
+ sb.append(">");
- } else if (event ==
XMLStreamConstants.END_ELEMENT) {
- localName =
staxXmlReader.getLocalName();
- if (localName.equals(textNodeName)) {
- textNodeFound = false;
-
currentElement.setText(sb.toString().trim());
- if (parents.size() > 1)
- currentElement =
parents.pop();
- } else {
- sb.append("</");
- sb.append(localName);
- sb.append(">");
- }
+ } else if (event == XMLStreamConstants.END_ELEMENT) {
+ localName = staxXmlReader.getLocalName();
+ if (localName.equals(textNodeName)) {
+ textNodeFound = false;
+ currentElement.setText(sb.toString().trim());
+ if (parents.size() > 1) {
+ currentElement = parents.pop();
+ }
+ } else {
+ sb.append("</");
+ sb.append(localName);
+ sb.append(">");
+ }
- } else if (event ==
XMLStreamConstants.CHARACTERS) {
- sb.append(staxXmlReader.getText());
- }
- } else {
- if (event ==
XMLStreamConstants.START_ELEMENT) {
+ } else if (event == XMLStreamConstants.CHARACTERS) {
+ sb.append(staxXmlReader.getText());
+ }
+ } else {
+ if (event == XMLStreamConstants.START_ELEMENT) {
- // log("== BEGIN:
"+staxXmlReader.getLocalName());
+ // log("== BEGIN: "+staxXmlReader.getLocalName());
- localName =
staxXmlReader.getLocalName();
- String namespaceUri =
staxXmlReader.getNamespaceURI();
+ localName = staxXmlReader.getLocalName();
+ String namespaceUri = staxXmlReader.getNamespaceURI();
- // get mapping for element
{namespace}name
+ // get mapping for element {namespace}name
- String key = "{" + namespaceUri + "}"
+ localName;
- String classname =
getMappingForElement(key);
+ String key = "{" + namespaceUri + "}" + localName;
+ String classname = getMappingForElement(key);
- // if there is no mapping for
specific {namespace}element
- // try general mapping for such
elements {*}element
- if (classname == null)
- classname =
getMappingForElement("{*}" + localName);
+ // if there is no mapping for specific {namespace}element
+ // try general mapping for such elements {*}element
+ if (classname == null) {
+ classname = getMappingForElement("{*}" + localName);
+ }
- // if there is no general mapping get
defualt class
- if (classname == null)
- classname =
getMappingForElement(ANY_ELEMENT);
+ // if there is no general mapping get defualt class
+ if (classname == null) {
+ classname = getMappingForElement(ANY_ELEMENT);
+ }
- // create element class basing on
mapping
- Element e = createElement(classname);
+ // create element class basing on mapping
+ Element e = createElement(classname);
- // if current node is TextElement
then in next iteration
- // concatanate content of this node
- if (e instanceof TextElement) {
- textNodeFound = true;
- textNodeName = localName;
- }
+ // if current node is TextElement then in next iteration
+ // concatanate content of this node
+ if (e instanceof TextElement) {
+ textNodeFound = true;
+ textNodeName = localName;
+ }
- if (e == null)
- e = new Element();
+ if (e == null) {
+ e = new Element();
+ }
- // set name and namespace of element
- e.setName(localName);
+ // set name and namespace of element
+ e.setName(localName);
- // if there is a namespace,set it
- if (namespaceUri != null) {
-
e.setNamespaceContext(staxXmlReader
-
.getNamespaceContext());
-
e.setNamespacePrefix(staxXmlReader
-
.getNamespaceContext().getPrefix(namespaceUri));
-
e.setNamespaceUri(namespaceUri);
- }
+ // if there is a namespace,set it
+ if (namespaceUri != null) {
+
e.setNamespaceContext(staxXmlReader.getNamespaceContext());
+
e.setNamespacePrefix(staxXmlReader.getNamespaceContext().getPrefix(namespaceUri));
+ e.setNamespaceUri(namespaceUri);
+ }
- // set current element
+ // set current element
- currentElement = e;
+ currentElement = e;
- // set attributes
- for (int i = 0, n =
staxXmlReader.getAttributeCount(); i < n; ++i) {
- // no namespace handling
- QName qname =
staxXmlReader.getAttributeName(i);
- String value =
staxXmlReader.getAttributeValue(i);
-
e.addAttribute(qname.getLocalPart(), value);
- }
+ // set attributes
+ for (int i = 0, n = staxXmlReader.getAttributeCount(); i
< n; ++i) {
+ // no namespace handling
+ QName qname = staxXmlReader.getAttributeName(i);
+ String value = staxXmlReader.getAttributeValue(i);
+ e.addAttribute(qname.getLocalPart(), value);
+ }
- // if Node - add to stack, set top
element
+ // if Node - add to stack, set top element
- if (topElement != null) {
+ if (topElement != null) {
- Element parent =
parents.lastElement();
- parent.addChild(e);
- parents.push(e);
+ Element parent = parents.lastElement();
+ parent.addChild(e);
+ parents.push(e);
- } else {
- topElement = e;
- parents.push(e);
- }
+ } else {
+ topElement = e;
+ parents.push(e);
+ }
- } // end START_ELEMENT
+ // end START_ELEMENT
- else if (event ==
XMLStreamConstants.END_ELEMENT) {
- localName =
staxXmlReader.getLocalName();
+ } else if (event == XMLStreamConstants.END_ELEMENT) {
+ localName = staxXmlReader.getLocalName();
- // pop next parent from stack
- if (parents.size() > 1)
- currentElement =
parents.pop();
+ // pop next parent from stack
+ if (parents.size() > 1) {
+ currentElement = parents.pop();
+ }
- } // end END_ELEMENT
+ // end END_ELEMENT
- else if (event ==
XMLStreamConstants.CHARACTERS) {
+ } else if (event == XMLStreamConstants.CHARACTERS) {
- // set text
- String textContent =
staxXmlReader.getText().trim();
- if
("".equals(currentElement.getText()))
-
currentElement.setText(textContent);
+ // set text
+ String textContent = staxXmlReader.getText().trim();
+ if ("".equals(currentElement.getText())) {
+ currentElement.setText(textContent);
+ }
- } // end CHARACTERS
+ } // end CHARACTERS
- }
+ }
- } // end for
+ } // end for
- return topElement;
- }
+ return topElement;
+ }
- /**
- * Creates new element object upon classname
- */
- private Element createElement(String classname) {
- try {
- Element e = (Element)
Class.forName(classname).newInstance();
- return e;
- } catch (Exception e) {
- return null;
- }
- }
+ /**
+ * Creates new element object upon classname
+ */
+ private Element createElement(String classname) {
+ try {
+ Element e = (Element) Class.forName(classname).newInstance();
+ return e;
+ } catch (Exception e) {
+ return null;
+ }
+ }
- public HashMap<String, String> getObjectMappings() {
- return objectMappings;
- }
+ public HashMap<String, String> getObjectMappings() {
+ return objectMappings;
+ }
- public void setObjectMappings(HashMap<String, String> objectMapping) {
- this.objectMappings = objectMapping;
- }
+ public void setObjectMappings(HashMap<String, String> objectMapping) {
+ this.objectMappings = objectMapping;
+ }
- public void addMapping(String element, String classname) {
- objectMappings.put(element, classname);
- }
+ public void addMapping(String element, String classname) {
+ objectMappings.put(element, classname);
+ }
- public String getMappingForElement(String element) {
- return objectMappings.get(element);
- }
+ public String getMappingForElement(String element) {
+ return objectMappings.get(element);
+ }
} // StaxParser
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/StringBufferOutputStream.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/StringBufferOutputStream.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/StringBufferOutputStream.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -5,48 +5,51 @@
/**
* StringBuffer OutputStream. Writes to given StringBuffer
+ *
* @author Maciej Glowiak
*/
public class StringBufferOutputStream extends OutputStream {
-
/**
* Local StringBuffer
*/
private StringBuffer sb;
-
-
+
/**
* Constructor, needs to specify StringBuffer destination
+ *
* @param sb
*/
public StringBufferOutputStream(StringBuffer sb) {
-
- if (sb==null) this.sb = new StringBuffer();
- else this.sb = sb;
-
+
+ if (sb == null) {
+ this.sb = new StringBuffer();
+ } else {
+ this.sb = sb;
+ }
+
}
-
+
public StringBufferOutputStream() {
this(null);
- }
+ }
public void write(int b) throws IOException {
- sb.append((char)b);
-
- }
-
- public StringBuffer getStringBuffer() {
- return sb;
+ sb.append((char) b);
+
}
-
- public String getString() {
- return sb.toString();
+
+ public StringBuffer getStringBuffer() {
+ return sb;
}
-
+
+ public String getString() {
+ return sb.toString();
+ }
+
public void reset() {
sb = new StringBuffer();
}
-
-} //StringBufferOutputStream
+
+} // StringBufferOutputStream
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/TextElement.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/TextElement.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/TextElement.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -2,12 +2,12 @@
public class TextElement extends Element {
- public TextElement() {
- super();
- }
+ public TextElement() {
+ super();
+ }
- public TextElement(String name, String namespacePrefix, String
namespaceUri) {
- super(name, namespacePrefix, namespaceUri);
- }
+ public TextElement(String name, String namespacePrefix, String
namespaceUri) {
+ super(name, namespacePrefix, namespaceUri);
+ }
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/nmwg/Data.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/nmwg/Data.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/nmwg/Data.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -2,20 +2,15 @@
import org.perfsonar.base2.xml.Element;
-
public class Data extends Element {
+ // ----------------------------------------------------- instance
variables
- // ----------------------------------------------------- instance
variables
+ protected Key key = null;
+ protected Datum datum = null;
-
- protected Key key = null;
- protected Datum datum = null;
-
-
// -----------------------------------------------------------
Constructors
-
public Data() {
super("data", "nmwg", NMWGNamespaceFactory.getNamespace("nmwg"));
@@ -31,17 +26,14 @@
}
-
// --------------------------------------------------------- Public
methods
-
public void setMetadataIdRef(String idRef) {
addAttribute("metadataIdRef", idRef);
}
-
public String getMetadataIdRef() {
return getAttribute("metadataIdRef");
@@ -71,32 +63,33 @@
@Override
public void addChild(Element e) {
- if (e instanceof Key)
+ if (e instanceof Key) {
key = (Key) e;
- else if (e instanceof Datum)
+ } else if (e instanceof Datum) {
datum = (Datum) e;
+ }
super.addChild(e);
}
public boolean removeKey(Key key) {
- return removeChild(key);
+ return removeChild(key);
}
public boolean removeDatum(Datum datum) {
- return removeChild(datum);
+ return removeChild(datum);
}
@Override
public boolean removeChild(Element e) {
- if (e instanceof Key)
+ if (e instanceof Key) {
key = null;
- else if (e instanceof Datum)
+ } else if (e instanceof Datum) {
datum = null;
+ }
return super.removeChild(e);
}
-
-} //Data
+} // Data
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/nmwg/Key.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/nmwg/Key.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/nmwg/Key.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -2,26 +2,20 @@
//import org.perfsonar.base2.xml.Element;
-
public class Key extends ParametersContainer {
-
// ----------------------------------------------------- instance
variables
-
protected Parameters parameters = null;
-
-
+
// -----------------------------------------------------------
Constructors
-
-
+
public Key() {
super("key", "nmwg", NMWGNamespaceFactory.getNamespace("nmwg"));
}
public Key(String prefix) {
- super("key", prefix, NMWGNamespaceFactory.getNamespace(prefix));
+ super("key", prefix, NMWGNamespaceFactory.getNamespace(prefix));
}
-
-
-} //Key
+
+} // Key
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/nmwg/Metadata.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/nmwg/Metadata.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/nmwg/Metadata.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -1,46 +1,37 @@
package org.perfsonar.base2.xml.nmwg;
-
import java.util.ArrayList;
import org.perfsonar.base2.xml.Element;
-
public class Metadata extends ParametersContainer {
-
// ----------------------------------------------------- instance
variables
-
protected Subject subject = null;
protected ArrayList<EventType> eventTypes = null;
-
- //protected Parameters parameters = null;
- //protected HashMap<String, Parameters> parametersMap = new
HashMap<String, Parameters>();
-
- protected Key key = null;
- public static String nmwgUri = "http://ggf.org/ns/nmwg/base/2.0/";
+ // protected Parameters parameters = null;
+ // protected HashMap<String, Parameters> parametersMap = new
HashMap<String,
+ // Parameters>();
-
+ protected Key key = null;
+
// -----------------------------------------------------------
Constructors
-
public Metadata() {
this(Element.generateNextId(), "nmwg");
-
+
}
-
public Metadata(String id, String prefix) {
super("metadata", prefix, NMWGNamespaceFactory.getNamespace(prefix));
setId(id);
}
-
// --------------------------------------------------------- Public
methods
public void setMetadataIdRef(String idRef) {
@@ -48,39 +39,37 @@
addAttribute("metadataIdRef", idRef);
}
-
public String getMetadataIdRef() {
return getAttribute("metadataIdRef");
}
-
public EventType getFirstEventType() {
- if (eventTypes != null)
- if (!eventTypes.isEmpty())
- for (EventType e : eventTypes) return e;
+ if (eventTypes != null) {
+ if (!eventTypes.isEmpty()) {
+ for (EventType e : eventTypes) {
+ return e;
+ }
+ }
+ }
return null;
}
-
public void setEventType(EventType eventType) {
addChild(eventType);
}
-
public Subject getSubject() {
return subject;
}
-
public void setSubject(Subject subject) {
addChild(subject);
}
-
public Key getKey() {
return key;
@@ -92,51 +81,52 @@
}
/**
- * Adds eventType, when necessary creates the collection
(ArrayList<EventType>)
+ * Adds eventType, when necessary creates the collection
+ * (ArrayList<EventType>)
+ *
* @param e
*/
protected void addEventType(EventType e) {
- if (eventTypes==null)
+ if (eventTypes == null) {
eventTypes = new ArrayList<EventType>();
+ }
eventTypes.add(e);
}
-
+
@Override
public void addChild(Element e) {
- if (e instanceof Subject)
+ if (e instanceof Subject) {
subject = (Subject) e;
- else if (e instanceof EventType)
- addEventType((EventType)e);
- else if (e instanceof Key)
- key = (Key) e;
+ } else if (e instanceof EventType) {
+ addEventType((EventType) e);
+ } else if (e instanceof Key) {
+ key = (Key) e;
+ }
super.addChild(e);
}
-
@Override
public boolean removeChild(Element e) {
- if (e instanceof Subject)
+ if (e instanceof Subject) {
subject = null;
- else if (e instanceof EventType)
+ } else if (e instanceof EventType) {
eventTypes.remove(e);
- else if (e instanceof Key)
- key = null;
+ } else if (e instanceof Key) {
+ key = null;
+ }
return super.removeChild(e);
}
-
-
public ArrayList<EventType> getEventTypes() {
-
+
return eventTypes;
}
public void setEventTypes(ArrayList<EventType> eventTypes) {
-
+
this.eventTypes = eventTypes;
}
-
-} //Metadata
+} // Metadata
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/nmwg/NMWGNamespaceFactory.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/nmwg/NMWGNamespaceFactory.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/nmwg/NMWGNamespaceFactory.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -4,26 +4,25 @@
import org.perfsonar.base2.xml.Element;
-
public class NMWGNamespaceFactory {
- static HashMap<String,String> namespaces = new HashMap<String,String>();
-
+ private static HashMap<String, String> namespaces = new HashMap<String,
String>();
+
static {
- //TODO: to be loaded from file ?
+ // TODO: to be loaded from file ?
namespaces.put("nmwg", "http://ggf.org/ns/nmwg/base/2.0/");
namespaces.put("perfsonar",
"http://ggf.org/ns/nmwg/tools/org/perfsonar/1.0/");
namespaces.put("psservice",
"http://ggf.org/ns/nmwg/tools/org/perfsonar/service/1.0/");
namespaces.put("xquery",
"http://ggf.org/ns/nmwg/tools/org/perfsonar/service/lookup/xquery/1.0/");
namespaces.put("nmwgr", "http://ggf.org/ns/nmwg/result/2.0/");
- //..........
+ // ..........
}
-
+
public static String getNamespace(String prefix) {
return namespaces.get(prefix);
}
-
+
public static Element getElement(String name, String prefix) {
return new Element(name, prefix, getNamespace(prefix));
- }
+ }
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/nmwg/Parameter.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/nmwg/Parameter.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/nmwg/Parameter.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -2,50 +2,51 @@
import org.perfsonar.base2.xml.Element;
-
public class Parameter extends Element {
-
// -----------------------------------------------------------
Constructors
-
-
+
public Parameter() {
super("parameter", "nmwg",
NMWGNamespaceFactory.getNamespace("nmwg"));
}
public Parameter(String prefix) {
- super("parameter", prefix,
NMWGNamespaceFactory.getNamespace(prefix));
+ super("parameter", prefix,
NMWGNamespaceFactory.getNamespace(prefix));
}
-
// --------------------------------------------------------- Public
methods
-
-
+
public void setParameter(String name, String value) {
-
- addAttribute(name, value);
-
+
+ addAttribute(name, value);
+
}
/**
- * Returns value. Selects between text value (content) and value
attribute
([@value])
+ * Returns value. Selects between text value (content) and value
attribute
+ *
([@value])
+ *
* @return
*/
public String getValue() {
String val1 = getAttribute("value");
String val2 = getText();
- if (val1 != null) return val1;
- else return val2;
+ if (val1 != null) {
+ return val1;
+ } else {
+ return val2;
+ }
}
-
+
/**
* Returns parameter name attribute
+ *
* @return
*/
public String getParameterName() {
String val1 = getAttribute("name");
return val1;
- }
-
-} //Parameter
+ }
+
+} // Parameter
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/nmwg/Parameters.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/nmwg/Parameters.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/nmwg/Parameters.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -5,24 +5,20 @@
import org.perfsonar.base2.xml.Element;
-
public class Parameters extends Element {
+ // ----------------------------------------------------- instance
variables
- //----------------------------------------------------- instance
variables
-
-
public Parameters() {
super("parameters", "nmwg",
NMWGNamespaceFactory.getNamespace("nmwg"));
}
public Parameters(String prefix) {
- super("parameters", prefix,
NMWGNamespaceFactory.getNamespace(prefix));
+ super("parameters", prefix,
NMWGNamespaceFactory.getNamespace(prefix));
}
-
-
+
// --------------------------------------------------------- Public
methods
-
+
/**
* Adds parameter
*/
@@ -30,91 +26,99 @@
addChild(parameter);
}
-
- /**
- * Get list of elements having specified name (in order)
- * and having either namespace prefix (e.g. "nmwg") or
- * full prefix ("http://ggf.org/ns/nmwg/base/2.0/")
+ /**
+ * Get list of elements having specified name (in order) and having
either
+ * namespace prefix (e.g. "nmwg") or full prefix
+ * ("http://ggf.org/ns/nmwg/base/2.0/")
*/
public Collection<Parameter> getParameters(String paramName) {
ArrayList<Parameter> params = null;
for (Element e : getChildren("parameter")) {
if (e instanceof Parameter) {
- Parameter p = (Parameter)e;
+ Parameter p = (Parameter) e;
if (paramName.equals(p.getParameterName())) {
- if (params==null) params=new ArrayList<Parameter>();
+ if (params == null) {
+ params = new ArrayList<Parameter>();
+ }
params.add(p);
}
}
}
return params;
}
-
+
/**
* Returns any Parameter having specified name
+ *
* @param paramName
* @return
*/
public Parameter getFirstParameter(String paramName) {
- //get all elements "paremeter"
+ // get all elements "paremeter"
for (Element e : getChildren("parameter")) {
- //when instance of Parameter class
+ // when instance of Parameter class
if (e instanceof Parameter) {
- //convert it
- Parameter p = (Parameter)e;
- //return parameter if name equal
- if (paramName.equals(p.getParameterName())) return p;
+ // convert it
+ Parameter p = (Parameter) e;
+ // return parameter if name equal
+ if (paramName.equals(p.getParameterName())) {
+ return p;
+ }
}
}
return null;
}
-
/**
* Returns any Parameter value having specified name
+ *
* @param paramName
* @return
*/
public String getFirstParameterValue(String paramName) {
- //get all elements "parameter"
+ // get all elements "parameter"
for (Element e : getChildren("parameter")) {
- //when instance of Parameter class
+ // when instance of Parameter class
if (e instanceof Parameter) {
- //convert to Parameter
- Parameter p = (Parameter)e;
- //return value if name equal
- if (paramName.equals(p.getParameterName())) return
p.getValue();
+ // convert to Parameter
+ Parameter p = (Parameter) e;
+ // return value if name equal
+ if (paramName.equals(p.getParameterName())) {
+ return p.getValue();
+ }
}
}
return null;
- }
-
+ }
+
/**
* return parameters values (text value of element) or null if not
present
+ *
* @param name
* @return
*/
public Collection<String> getParameterValues(String paramName) {
ArrayList<String> params = null;
- //get all elements "parameter"
+ // get all elements "parameter"
for (Element e : getChildren("parameter")) {
- //when instance of Parameter class
+ // when instance of Parameter class
if (e instanceof Parameter) {
- //convert
- Parameter p = (Parameter)e;
- //check if name is equal
+ // convert
+ Parameter p = (Parameter) e;
+ // check if name is equal
if (paramName.equals(p.getParameterName())) {
- //create params if necessary
- if (params==null) params=new ArrayList<String>();
- //add parameter value
+ // create params if necessary
+ if (params == null) {
+ params = new ArrayList<String>();
+ }
+ // add parameter value
params.add(p.getValue());
}
}
}
return params;
}
-
-} //Parameters
+} // Parameters
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/nmwg/ParametersContainer.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/nmwg/ParametersContainer.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/base2/xml/nmwg/ParametersContainer.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -1,35 +1,27 @@
package org.perfsonar.base2.xml.nmwg;
-
import org.perfsonar.base2.xml.Element;
import java.util.Map;
import java.util.HashMap;
-
public abstract class ParametersContainer extends Element {
-
// ----------------------------------------------------- instance
variables
-
- protected HashMap<String, Parameters> parametersMap = new
HashMap<String, Parameters>();
-
- public static String nmwgUri = "http://ggf.org/ns/nmwg/base/2.0/";
-
-
+ protected HashMap<String, Parameters> parametersMap = new
HashMap<String, Parameters>();
+
+ public static final String NMWG_URI = "http://ggf.org/ns/nmwg/base/2.0/";
+
// ------------------------------------------------------------
Constructor
-
-
+
public ParametersContainer(String name, String namespacePrefix, String
namespaceUri) {
super(name, namespacePrefix, namespaceUri);
}
-
// --------------------------------------------------------- Public
methods
-
-
+
public void setParameters(Parameters parameters) {
addChild(parameters);
@@ -37,51 +29,52 @@
public Parameters getParameters() {
- return parametersMap.get(nmwgUri);
+ return parametersMap.get(NMWG_URI);
}
public Parameters getParameters(String namespaceUri) {
return parametersMap.get(namespaceUri);
}
-
+
public Map<String, Parameters> getParametersMap() {
return parametersMap;
}
-
+
public void clearParametersMap() {
parametersMap.clear();
}
-
+
public void addParameter(String name, String value) {
-
- Parameter parameter = new Parameter();
- parameter.setParameter(name, value);
- Parameters parameters = getParameters();
- if (parameters == null) {
- parameters = new Parameters();
- addChild(parameters);
- }
- parameters.addParameter(parameter);
+
+ Parameter parameter = new Parameter();
+ parameter.setParameter(name, value);
+ Parameters parameters = getParameters();
+ if (parameters == null) {
+ parameters = new Parameters();
+ addChild(parameters);
+ }
+ parameters.addParameter(parameter);
}
-
+
@Override
public void addChild(Element e) {
- if (e instanceof Parameters)
- parametersMap.put(e.getNamespaceUri(), (Parameters) e);
+ if (e instanceof Parameters) {
+ parametersMap.put(e.getNamespaceUri(), (Parameters) e);
+ }
super.addChild(e);
}
@Override
public boolean removeChild(Element e) {
- if (e instanceof Parameters)
- parametersMap.remove(e.getNamespaceUri());
+ if (e instanceof Parameters) {
+ parametersMap.remove(e.getNamespaceUri());
+ }
return super.removeChild(e);
}
-
-
-} //ParametersContainer
+
+} // ParametersContainer
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/contrib/HTTPServer.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/contrib/HTTPServer.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/contrib/HTTPServer.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -1,19 +1,25 @@
package org.perfsonar.contrib;
+import java.io.BufferedReader;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.net.ServerSocket;
+import java.net.Socket;
+
//***************************************
//HTTP Server
//***************************************
-import java.net.*;
-import java.io.*;
-
public class HTTPServer {
- public static void main(String args[]) {
+ public static void main(String[] args) {
System.out.println("[ ] Simple HTTP Service");
int port;
- ServerSocket server_socket;
+ ServerSocket serverSocket;
String responseFilename = null;
try {
@@ -24,28 +30,26 @@
try {
responseFilename = args[0];
- System.out.println(" Response file is: "+responseFilename);
+ System.out.println(" Response file is: " + responseFilename);
} catch (Exception ex) {
System.out.println(" ERROR - no filename");
return;
}
-
+
try {
// print out the port number for user
- server_socket = new ServerSocket(port);
- System.out.println(" HTTP Server running on port: "
- + server_socket.getLocalPort());
+ serverSocket = new ServerSocket(port);
+ System.out.println(" HTTP Server running on port: " +
serverSocket.getLocalPort());
// server infinite loop
while (true) {
- Socket socket = server_socket.accept();
- System.out.println("New connection accepted "
- + socket.getInetAddress() + ":" + socket.getPort());
+ Socket socket = serverSocket.accept();
+ System.out.println("New connection accepted " +
socket.getInetAddress() + ":" + socket.getPort());
// Construct handler to process the HTTP request message.
try {
- httpRequestHandler request = new
httpRequestHandler(socket, responseFilename);
+ HTTPRequestHandler request = new
HTTPRequestHandler(socket, responseFilename);
// Create a new thread to process the request.
Thread thread = new Thread(request);
@@ -55,42 +59,34 @@
System.out.println(e);
}
}
- }
-
- catch (IOException e) {
+ } catch (IOException e) {
System.out.println(e);
}
}
}
+class HTTPRequestHandler implements Runnable {
-class httpRequestHandler implements Runnable {
+ static final String CRLF = "\r\n";
- final static String CRLF = "\r\n";
+ private String filename;
- String filename;
-
- Socket socket;
+ private Socket socket;
- InputStream input;
+ private OutputStream output;
- OutputStream output;
+ private BufferedReader br;
- BufferedReader br;
-
-
// Constructor
- public httpRequestHandler(Socket socket, String filename) throws
Exception {
+ public HTTPRequestHandler(Socket socket, String filename) throws
Exception {
this.socket = socket;
this.filename = filename;
- this.input = socket.getInputStream();
+ socket.getInputStream();
this.output = socket.getOutputStream();
- this.br = new BufferedReader(new InputStreamReader(socket
- .getInputStream()));
+ this.br = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
}
-
// Implement the run() method of the Runnable interface.
public void run() {
@@ -107,66 +103,51 @@
String headerLine = br.readLine();
System.out.println(headerLine);
- if (headerLine.equals(CRLF) || headerLine.equals(""))
+ if (headerLine.equals(CRLF) || headerLine.equals("")) {
break;
+ }
- {
-
- // Open the requested file.
- FileInputStream fis = null;
- boolean fileExists = true;
- try {
- fis = new FileInputStream(filename);
- } catch (FileNotFoundException e) {
- fileExists = false;
- }
-
- // Construct the response message.
- String serverLine = "Server: fpont simple java httpServer";
- String statusLine = null;
- String contentTypeLine = null;
- String entityBody = null;
- String contentLengthLine = "error";
- if (fileExists) {
- statusLine = "HTTP/1.0 200 OK" + CRLF;
- contentTypeLine = "Content-type: " +
contentType(filename)
- + CRLF;
- contentLengthLine = "Content-Length: "
- + (new Integer(fis.available())).toString() +
CRLF;
- } else {
- statusLine = "HTTP/1.0 404 Not Found" + CRLF;
- contentTypeLine = "text/html";
- entityBody = "<HTML>"
- + "<HEAD><TITLE>404 Not Found</TITLE></HEAD>"
- + "<BODY>404 Not Found"
- + "<br>usage:http://www.snaip.com:4444/"
- + "fileName.html</BODY></HTML>";
- }
-
- // Send the status line.
- output.write(statusLine.getBytes());
-
- // Send the server line.
- output.write(serverLine.getBytes());
-
- // Send the content type line.
- output.write(contentTypeLine.getBytes());
-
- // Send the Content-Length
- output.write(contentLengthLine.getBytes());
-
- // Send a blank line to indicate the end of the header lines.
- output.write(CRLF.getBytes());
-
- // Send the entity body.
- if (fileExists) {
- sendBytes(fis, output);
- fis.close();
- } else {
- output.write(entityBody.getBytes());
- }
-
+ // Open the requested file.
+ FileInputStream fis = null;
+ boolean fileExists = true;
+ try {
+ fis = new FileInputStream(filename);
+ } catch (FileNotFoundException e) {
+ fileExists = false;
}
+ // Construct the response message.
+ String serverLine = "Server: fpont simple java httpServer";
+ String statusLine = null;
+ String contentTypeLine = null;
+ String entityBody = null;
+ String contentLengthLine = "error";
+ if (fileExists) {
+ statusLine = "HTTP/1.0 200 OK" + CRLF;
+ contentTypeLine = "Content-type: " + contentType(filename) +
CRLF;
+ contentLengthLine = "Content-Length: " + (new
Integer(fis.available())).toString() + CRLF;
+ } else {
+ statusLine = "HTTP/1.0 404 Not Found" + CRLF;
+ contentTypeLine = "text/html";
+ entityBody = "<HTML>" + "<HEAD><TITLE>404 Not
Found</TITLE></HEAD>" + "<BODY>404 Not Found"
+ + "<br>usage:http://www.snaip.com:4444/" +
"fileName.html</BODY></HTML>";
+ }
+ // Send the status line.
+ output.write(statusLine.getBytes());
+ // Send the server line.
+ output.write(serverLine.getBytes());
+ // Send the content type line.
+ output.write(contentTypeLine.getBytes());
+ // Send the Content-Length
+ output.write(contentLengthLine.getBytes());
+ // Send a blank line to indicate the end of the header lines.
+ output.write(CRLF.getBytes());
+ // Send the entity body.
+ if (fileExists) {
+ sendBytes(fis, output);
+ fis.close();
+ } else {
+ output.write(entityBody.getBytes());
+ }
}
try {
@@ -177,10 +158,8 @@
}
}
+ private static void sendBytes(FileInputStream fis, OutputStream os)
throws Exception {
- private static void sendBytes(FileInputStream fis, OutputStream os)
- throws Exception {
-
// Construct a 1K buffer to hold bytes on their way to the socket.
byte[] buffer = new byte[1024];
int bytes = 0;
@@ -191,7 +170,6 @@
}
}
-
private static String contentType(String fileName) {
if (fileName.endsWith(".htm") || fileName.endsWith(".html")) {
@@ -202,4 +180,4 @@
}
-}
\ No newline at end of file
+}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/service/simpleservice/SimpleServiceServiceEngine.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/service/simpleservice/SimpleServiceServiceEngine.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/service/simpleservice/SimpleServiceServiceEngine.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -1,6 +1,5 @@
package org.perfsonar.service.simpleservice;
-
import org.perfsonar.base2.service.exceptions.PerfSONARException;
import org.perfsonar.base2.service.requesthandler.ServiceEngine;
import org.perfsonar.base2.service.requesthandler.ServiceMessage;
@@ -9,24 +8,21 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-
/**
* $Id: SimpleServiceServiceEngine.java 4684 2008-11-03 13:07:33Z roman $
*/
public class SimpleServiceServiceEngine implements ServiceEngine {
+ private static final Logger LOGGER =
LoggerFactory.getLogger(SimpleServiceServiceEngine.class);
- private static final Logger logger =
LoggerFactory.getLogger(SimpleServiceServiceEngine.class);
+ public void takeAction(ServiceMessage serviceRequest, ServiceMessage
serviceResponse) throws PerfSONARException {
+ LOGGER.info("Simple-Service ServiceEngine started, do echo...");
- public void takeAction(ServiceMessage serviceRequest, ServiceMessage
serviceResponse)
- throws PerfSONARException {
-
- logger.info("Simple-Service ServiceEngine started, do echo...");
-
Message request = serviceRequest.getMessageElement();
- //get a copy of Element tree, in order to avoid cross references
problems
- Message response = (Message)request.getCopy();
+ // get a copy of Element tree, in order to avoid cross references
+ // problems
+ Message response = (Message) request.getCopy();
response.setId("SimpleService-response-for-" +
request.getAttribute("type"));
response.addAttribute("type", "EchoResponse");
@@ -34,5 +30,4 @@
}
-
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/test/ElementToJavaGenerator.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/test/ElementToJavaGenerator.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/test/ElementToJavaGenerator.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -10,77 +10,71 @@
import org.perfsonar.base2.xml.Element;
import org.perfsonar.base2.xml.StaxParser;
-
public class ElementToJavaGenerator {
- public static void main(String args[]) throws FileNotFoundException,
XMLStreamException {
+ public static void main(String[] args) throws FileNotFoundException,
XMLStreamException {
StaxParser sp = new StaxParser();
- Element e = sp.parse(new FileInputStream(
- "/tmp/b.xml"));
+ Element e = sp.parse(new FileInputStream("/tmp/b.xml"));
ElementToJavaGenerator gen = new ElementToJavaGenerator();
-
-
+
gen.writeElement(e, null);
-
+
}
-
- private HashMap<String,Integer> nums = new HashMap<String,Integer>();
-
-
- protected void writeElement(Element e, String parentName) {
- if (parentName == null)
- System.out.println("public Element generateRequest() {");
-
-
- String elementName = e.getName();
- if (nums.get(elementName)==null) nums.put(elementName, 1);
- else {
- int num = nums.get(elementName);
- elementName = elementName + num;
- nums.put(elementName, num+1);
- }
-
- System.out.println();
- System.out.println(" Element "+elementName+" = new Element();");
- System.out.println("
"+elementName+".setName(\""+e.getName()+"\");");
-
-
- //start elemenet
- if (e.getNamespacePrefix() != null) {
- System.out.println("
"+elementName+".setNamespacePrefix(\""+e.getNamespacePrefix()+"\");");
- System.out.println("
"+elementName+".setNamespaceUri(\""+e.getNamespaceUri()+"\");");
- }
-
- //attributes
- for (Map.Entry<String, String> attr : e.getAttributes().entrySet()) {
- String name = attr.getKey();
- String value = attr.getValue();
- System.out.println(" " + elementName + ".addAttribute(\"" +
name + "\", \"" + value + "\");");
- }
-
- //characters
- if (e.getText() != null)
- if (!("".equals(e.getText()))) {
- System.out.println("
"+elementName+".setText(\""+e.getText()+"\");");
- }
+ private HashMap<String, Integer> nums = new HashMap<String, Integer>();
- if (parentName!=null)
- System.out.println("
"+parentName+".addChild("+elementName+");");
+ protected void writeElement(Element e, String parentName) {
+ if (parentName == null) {
+ System.out.println("public Element generateRequest() {");
+ }
- //children
- for (Element ch : e.getChildren()) {
- writeElement(ch, elementName);
- }
-
- if (parentName == null) {
- System.out.println("\n return "+elementName+";");
- System.out.println("\n}\n");
- }
-
+ String elementName = e.getName();
+ if (nums.get(elementName) == null) {
+ nums.put(elementName, 1);
+ } else {
+ int num = nums.get(elementName);
+ elementName = elementName + num;
+ nums.put(elementName, num + 1);
+ }
- }
+ System.out.println();
+ System.out.println(" Element " + elementName + " = new
Element();");
+ System.out.println(" " + elementName + ".setName(\"" +
e.getName() + "\");");
-
-
+ // start elemenet
+ if (e.getNamespacePrefix() != null) {
+ System.out.println(" " + elementName +
".setNamespacePrefix(\"" + e.getNamespacePrefix() + "\");");
+ System.out.println(" " + elementName + ".setNamespaceUri(\""
+ e.getNamespaceUri() + "\");");
+ }
+
+ // attributes
+ for (Map.Entry<String, String> attr : e.getAttributes().entrySet()) {
+ String name = attr.getKey();
+ String value = attr.getValue();
+ System.out.println(" " + elementName + ".addAttribute(\"" +
name + "\", \"" + value + "\");");
+ }
+
+ // characters
+ if (e.getText() != null) {
+ if (!("".equals(e.getText()))) {
+ System.out.println(" " + elementName + ".setText(\"" +
e.getText() + "\");");
+ }
+ }
+
+ if (parentName != null) {
+ System.out.println(" " + parentName + ".addChild(" +
elementName + ");");
+ }
+
+ // children
+ for (Element ch : e.getChildren()) {
+ writeElement(ch, elementName);
+ }
+
+ if (parentName == null) {
+ System.out.println("\n return " + elementName + ";");
+ System.out.println("\n}\n");
+ }
+
+ }
+
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/test/StaxParserSimple.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/test/StaxParserSimple.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/test/StaxParserSimple.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -20,97 +20,98 @@
*/
public class StaxParserSimple {
- private final Logger logger =
LoggerFactory.getLogger(StaxParserSimple.class);
+ private final Logger logger =
LoggerFactory.getLogger(StaxParserSimple.class);
- private static final String DEFAULT_ELEMENT_CLASSNAME =
"org.perfsonar.base2.xml.Element";
- private static final String ANY_ELEMENT = "*";
+ private static final String DEFAULT_ELEMENT_CLASSNAME =
"org.perfsonar.base2.xml.Element";
+ private static final String ANY_ELEMENT = "*";
- HashMap<String, String> objectMappings = new HashMap<String,
String>();
+ private HashMap<String, String> objectMappings = new HashMap<String,
String>();
- // -----------------------------------------------------------
constructor
+ // -----------------------------------------------------------
constructor
- public StaxParserSimple() {
- objectMappings.put(ANY_ELEMENT, DEFAULT_ELEMENT_CLASSNAME);
// default
-
// one
- }
+ public StaxParserSimple() {
+ objectMappings.put(ANY_ELEMENT, DEFAULT_ELEMENT_CLASSNAME); //
default
+ // one
+ }
- // -------------------------------------------------------- public
methods
+ // -------------------------------------------------------- public
methods
- /**
- * StAX Parser for InputStream
- *
- * @param fis
- * @return
- * @throws XMLStreamException
- */
- public Element parse(InputStream istream) throws XMLStreamException {
- // create STAX reader from inputstream
- XMLInputFactory factory = XMLInputFactory.newInstance();
- XMLStreamReader staxXmlReader =
factory.createXMLStreamReader(istream);
- return parse(staxXmlReader);
- }
+ /**
+ * StAX Parser for InputStream
+ *
+ * @param fis
+ * @return
+ * @throws XMLStreamException
+ */
+ public Element parse(InputStream istream) throws XMLStreamException {
+ // create STAX reader from inputstream
+ XMLInputFactory factory = XMLInputFactory.newInstance();
+ XMLStreamReader staxXmlReader =
factory.createXMLStreamReader(istream);
+ return parse(staxXmlReader);
+ }
- /**
- * StAX Parser for XMLStreamReader
- *
- * @param fis
- * @return
- * @throws XMLStreamException
- */
- public Element parse(XMLStreamReader staxXmlReader) throws
XMLStreamException {
+ /**
+ * StAX Parser for XMLStreamReader
+ *
+ * @param fis
+ * @return
+ * @throws XMLStreamException
+ */
+ public Element parse(XMLStreamReader staxXmlReader) throws
XMLStreamException {
- Element topElement = null;
+ Element topElement = null;
- // initialize settings
+ // initialize settings
- // for textual elements
- int begin = 0;
- String elementName = "";
- boolean rememberIndex = false;
- @SuppressWarnings("unused")
- int lastIndex = 0;
+ // for textual elements
+ int begin = 0;
+ String elementName = "";
+ boolean rememberIndex = false;
+ @SuppressWarnings("unused")
+ int lastIndex = 0;
- // Parse for all STAX events
- for (int event = staxXmlReader.next(); event !=
XMLStreamConstants.END_DOCUMENT; event = staxXmlReader.next()) {
+ // Parse for all STAX events
+ for (int event = staxXmlReader.next(); event !=
XMLStreamConstants.END_DOCUMENT; event = staxXmlReader.next()) {
- if (event == XMLStreamConstants.START_ELEMENT) {
- logger.debug("\n== BEGIN: " +
staxXmlReader.getLocalName());
- try {
- log("* [" + staxXmlReader.getText() +
"]");
- } catch (Exception ex) {
- }
- elementName = staxXmlReader.getLocalName();
- rememberIndex = true;
+ if (event == XMLStreamConstants.START_ELEMENT) {
+ logger.debug("\n== BEGIN: " + staxXmlReader.getLocalName());
+ try {
+ log("* [" + staxXmlReader.getText() + "]");
+ } catch (Exception ex) {
+ }
+ elementName = staxXmlReader.getLocalName();
+ rememberIndex = true;
- } // end START_ELEMENT
+ // end START_ELEMENT
- else if (event == XMLStreamConstants.END_ELEMENT) {
- logger.debug("\n == END: " +
staxXmlReader.getLocalName());
+ } else if (event == XMLStreamConstants.END_ELEMENT) {
+ logger.debug("\n == END: " + staxXmlReader.getLocalName());
- } // end END_ELEMENT
+ // end END_ELEMENT
- else if (event == XMLStreamConstants.CHARACTERS) {
+ } else if (event == XMLStreamConstants.CHARACTERS) {
-
logger.debug("-----------------------------------------------------------------------\n");
- logger.debug("\n== CHARACTERS <" +
elementName + ">:");
+
logger.debug("-----------------------------------------------------------------------\n");
+ logger.debug("\n== CHARACTERS <" + elementName + ">:");
- if (rememberIndex) {
- rememberIndex = false;
- lastIndex = begin;
- }
+ if (rememberIndex) {
+ rememberIndex = false;
+ lastIndex = begin;
+ }
- if (staxXmlReader.getTextStart() > begin)
- begin = staxXmlReader.getTextStart();
+ if (staxXmlReader.getTextStart() > begin) {
+ begin = staxXmlReader.getTextStart();
+ }
- } // end CHARACTERS
+ } // end CHARACTERS
- } // end for
+ } // end for
- return topElement;
- }
+ return topElement;
+ }
- private void log(String s) {
- System.out.println(s);
- }
+ private void log(String s) {
+ System.out.println(s);
+ }
} // StaxParser
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/test/TestParser.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/test/TestParser.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/test/TestParser.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -18,14 +18,15 @@
/**
* @param args
- * @throws XMLStreamException
- * @throws IOException
+ * @throws XMLStreamException
+ * @throws IOException
*/
public static void main(String[] args) throws XMLStreamException,
IOException {
StaxParser parser = new StaxParser();
- //StaxParser parser = new StaxParser();
- //parser.addMapping("{http://ggf.org/ns/nmwg/base/2.0/}metadata",
"org.perfsonar.base2.xml.TextElement");
+ // StaxParser parser = new StaxParser();
+ // parser.addMapping("{http://ggf.org/ns/nmwg/base/2.0/}metadata",
+ // "org.perfsonar.base2.xml.TextElement");
parser.addMapping("{http://ggf.org/ns/nmwg/base/2.0/}message",
"org.perfsonar.base2.xml.nmwg.Message");
parser.addMapping("{http://ggf.org/ns/nmwg/base/2.0/}metadata",
"org.perfsonar.base2.xml.nmwg.Metadata");
parser.addMapping("{http://ggf.org/ns/nmwg/base/2.0/}data",
"org.perfsonar.base2.xml.nmwg.Data");
@@ -34,34 +35,32 @@
parser.addMapping("{http://ggf.org/ns/nmwg/base/2.0/}parameter",
"org.perfsonar.base2.xml.nmwg.Parameter");
FileInputStream fis = new
FileInputStream("/home/mac/projects/simple-service-branch/test.xml");
-
+
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLStreamReader r = factory.createXMLStreamReader(fis);
- Element e= parser.parse(r);
-
-
-// Element e = parser.parse(ParserSource.getInputStreamFromFile(
-//
"/home/mac/projects/perfsonar/simple-service/samples/requests/EchoRequest.xml"));
-// System.out.println("\n\n\n");
-// for (Element e1 : e.getChildren("metadata")) {
-//
//System.out.println("----"+e1.getName()+":\n["+e1.getText()+"]\n"/*+e1.toString()*/);
-// //serializer.write(System.out, e1);
-// }
+ Element e = parser.parse(r);
+ // Element e = parser.parse(ParserSource.getInputStreamFromFile(
+ //
"/home/mac/projects/perfsonar/simple-service/samples/requests/EchoRequest.xml"));
+ // System.out.println("\n\n\n");
+ // for (Element e1 : e.getChildren("metadata")) {
+ //
//System.out.println("----"+e1.getName()+":\n["+e1.getText()+"]\n"/*+e1.toString()*/);
+ // //serializer.write(System.out, e1);
+ // }
- Message m = ((Message)e);
+ Message m = ((Message) e);
for (Metadata meta : m.getMetadataCollection()) {
- System.out.println("meta: "+meta.getId());
+ System.out.println("meta: " + meta.getId());
Parameters params = meta.getParameters();
- System.out.println(" --
"+params.getFirstParameter("eventType").getValue());
- System.out.println(" --
"+params.getFirstParameterValue("eventType"));
+ System.out.println(" -- " +
params.getFirstParameter("eventType").getValue());
+ System.out.println(" -- " +
params.getFirstParameterValue("eventType"));
for (Parameter p : params.getParameters("zupa")) {
- System.out.println(" + "+p.getValue());
+ System.out.println(" + " + p.getValue());
}
}
-// ElementSerializer serializer = new ElementSerializer();
-// serializer.write(System.out, e);
-
+ // ElementSerializer serializer = new ElementSerializer();
+ // serializer.write(System.out, e);
+
}
}
Modified:
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/test/ThreadTask.java
===================================================================
---
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/test/ThreadTask.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/java/org/perfsonar/test/ThreadTask.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -10,20 +10,20 @@
/**
* @param args
- * @throws InterruptedException
+ * @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
ExecutorService pool;
- pool = Executors.newFixedThreadPool(2);
+ pool = Executors.newFixedThreadPool(2);
- Future<String> future1 = pool.submit(new ThreadTask(1000));
+ Future<String> future1 = pool.submit(new ThreadTask(1000));
Thread.sleep(350);
- Future<String> future2 = pool.submit(new ThreadTask(2000));
+ Future<String> future2 = pool.submit(new ThreadTask(2000));
Thread.sleep(350);
-
- Future<String> future3 = pool.submit(new ThreadTask(3000));
+
+ Future<String> future3 = pool.submit(new ThreadTask(3000));
Thread.sleep(350);
try {
System.out.println(future1.get());
@@ -33,51 +33,45 @@
// TODO Auto-generated catch block
e.printStackTrace();
}
-// for (int i=0; i<10; i++) {
-// System.out.println("--> "+future1.isDone()+",
"+future2.isDone()+", "+future3.isDone()+". ");
-// Thread.sleep(1600);
-// }
-
- //pool.execute(new ThreadTask(4000));
-
+
pool.shutdown();
}
-//-----------------------------------------------------------------------
-
+ //
-----------------------------------------------------------------------
+
private int id = 0;
- public ThreadTask(int i) { id = i; }
-
+ public ThreadTask(int i) {
+ id = i;
+ }
+
public void run() {
- for (int i=1; i<5; i++) {
-
- System.out.println(((id>3999)?"*** ":"")+"Thread [#"+id+"] run
for ["+i+"] time");
+ for (int i = 1; i < 5; i++) {
+
+ System.out.println(((id > 3999) ? "*** " : "") + "Thread [#" +
id + "] run for [" + i + "] time");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
- System.out.println("Thread [#"+id+"] finished.");
-
+ System.out.println("Thread [#" + id + "] finished.");
+
}
public String call() throws Exception {
- for (int i=1; i<5; i++) {
-
- System.out.println(((id>3999)?"*** ":"")+"Thread [#"+id+"] run
for ["+i+"] time");
+ for (int i = 1; i < 5; i++) {
+
+ System.out.println(((id > 3999) ? "*** " : "") + "Thread [#" +
id + "] run for [" + i + "] time");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
- System.out.println("Thread [#"+id+"] finished.");
- return ("ID is "+id);
+ System.out.println("Thread [#" + id + "] finished.");
+ return ("ID is " + id);
}
-
-
}
Modified:
trunk/perfsonar-java-base2/src/main/resources/perfsonar/conf/configuration-rules.xml
===================================================================
---
trunk/perfsonar-java-base2/src/main/resources/perfsonar/conf/configuration-rules.xml
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/main/resources/perfsonar/conf/configuration-rules.xml
2013-04-30 13:14:31 UTC (rev 6294)
@@ -120,16 +120,16 @@
<pattern
value="configuration/service/auxiliaryComponents/component/actions">
<object-create-rule
classname="org.perfsonar.base2.service.configuration.Actions" />
- <set-next-rule methodname="addActions" />
+ <set-next-rule methodname="addActions" />
</pattern>
<pattern
value="configuration/service/auxiliaryComponents/component/actions/action">
- <object-create-rule attrname="className"/>
+ <object-create-rule attrname="className"/>
<set-properties-rule>
<alias attr-name="name" prop-name="name"/>
</set-properties-rule>
- <set-next-rule methodname="addAction" />
+ <set-next-rule methodname="addAction" />
</pattern>
Modified:
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/AllTests.java
===================================================================
---
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/AllTests.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/AllTests.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -11,13 +11,13 @@
*/
public class AllTests {
- public static Test suite() {
- TestSuite suite = new TestSuite("All test cases");
- //$JUnit-BEGIN$
- suite.addTest(AllMigrationTests.suite());
- suite.addTestSuite(JREVersionTest.class);
- //$JUnit-END$
- return suite;
- }
+ public static Test suite() {
+ TestSuite suite = new TestSuite("All test cases");
+ // $JUnit-BEGIN$
+ suite.addTest(AllMigrationTests.suite());
+ suite.addTestSuite(JREVersionTest.class);
+ // $JUnit-END$
+ return suite;
+ }
}
Modified:
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/AllMigrationTests.java
===================================================================
---
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/AllMigrationTests.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/AllMigrationTests.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -10,16 +10,15 @@
*/
public class AllMigrationTests {
- public static Test suite() {
- TestSuite suite = new TestSuite(
- "Migration tool from base-1 to base-2 test cases");
- //$JUnit-BEGIN$
- suite.addTest(AllGrammarTests.suite());
- suite.addTestSuite(SimpleTemplateEngineTest.class);
- suite.addTestSuite(ConfigFilesCollectionTest.class);
- suite.addTestSuite(MigratorComponentTest.class);
- //$JUnit-END$
- return suite;
- }
+ public static Test suite() {
+ TestSuite suite = new TestSuite("Migration tool from base-1 to
base-2 test cases");
+ // $JUnit-BEGIN$
+ suite.addTest(AllGrammarTests.suite());
+ suite.addTestSuite(SimpleTemplateEngineTest.class);
+ suite.addTestSuite(ConfigFilesCollectionTest.class);
+ suite.addTestSuite(MigratorComponentTest.class);
+ // $JUnit-END$
+ return suite;
+ }
}
Modified:
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/ConfigFilesCollectionTest.java
===================================================================
---
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/ConfigFilesCollectionTest.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/ConfigFilesCollectionTest.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -11,82 +11,87 @@
* @author <a
href="mailto:">Blazej
Pietrzak</a>
*/
public class ConfigFilesCollectionTest extends TestCase {
-
- private ConfigFilesCollection configCollection;
- private static final String CONFIG_PATH =
"src/test/java/org/perfsonar/base2/service/configuration/migration";
-
- protected void setUp() throws Exception {
- super.setUp();
- configCollection = new ConfigFilesCollection(new
File(CONFIG_PATH));
- }
-
- protected void tearDown() throws Exception {
- super.tearDown();
- }
+ private ConfigFilesCollection configCollection;
+ private static final String CONFIG_PATH =
"src/test/java/org/perfsonar/base2/service/configuration/migration";
- public void testMatches2() {
- assertTrue(configCollection.matchesFileName(".properties"));
- }
+ protected void setUp() throws Exception {
+ super.setUp();
- public void testGetFiles() throws Exception {
-
assertCollectionEquals(createExpectedConfigFiles(".properties"),
configCollection.getFiles());
- }
+ configCollection = new ConfigFilesCollection(new File(CONFIG_PATH));
+ }
- public void testGetFilesDirectoryDoesNotExist() throws IOException {
- configCollection = new ConfigFilesCollection(new
File(CONFIG_PATH + File.separator + "does_not_exist"));
- assertEquals(0, configCollection.getFiles().size());
- }
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
- public void testGetFilesFilePath() throws IOException {
- configCollection = new ConfigFilesCollection(new
File(CONFIG_PATH + File.separator + "ConfigurationMigratorTest.class"));
- assertEquals(0, configCollection.getFiles().size());
- }
+ public void testMatches2() {
+ assertTrue(configCollection.matchesFileName(".properties"));
+ }
- public void testRemoveFiles() throws IOException {
- configCollection.removeFiles();
- for (File file :
createExpectedConfigFiles(".properties.remove")) {
- assertTrue(file.exists());
- final String name = file.getName().substring(0,
file.getName().length() - ".remove".length());
- assertTrue(file.renameTo(new File(CONFIG_PATH +
File.separator + name)));
- }
- }
+ public void testGetFiles() throws Exception {
+ assertCollectionEquals(createExpectedConfigFiles(".properties"),
configCollection.getFiles());
+ }
- public void testRemoveFilesWhereTheFileExists() throws IOException {
- assertTrue(new File(CONFIG_PATH + File.separator +
"wizard.properties.remove").createNewFile());
- try {
- configCollection.removeFiles();
- fail("IOException should be thrown.");
- } catch (IOException ex) { }
- assertTrue(new File(CONFIG_PATH + File.separator +
"wizard.properties.remove").delete());
- for (File file :
createExpectedConfigFiles(".properties.remove")) {
- if (file.getName().equals("wizard.properties.remove"))
- continue;
- if (file.exists()) {
- final String name =
file.getName().substring(0, file.getName().length() - ".remove".length());
- assertTrue(file.renameTo(new File(CONFIG_PATH
+ File.separator + name)));
- }
- }
- }
+ public void testGetFilesDirectoryDoesNotExist() throws IOException {
+ configCollection = new ConfigFilesCollection(new File(CONFIG_PATH +
File.separator + "does_not_exist"));
+ assertEquals(0, configCollection.getFiles().size());
+ }
- private Collection<File> createExpectedConfigFiles(String suffix) {
- final Collection<File> expected = new ArrayList<File>();
- expected.add(new File(CONFIG_PATH + File.separator +
"components" + suffix));
- expected.add(new File(CONFIG_PATH + File.separator + "log4j"
+ suffix));
- expected.add(new File(CONFIG_PATH + File.separator +
"service" + suffix));
- expected.add(new File(CONFIG_PATH + File.separator +
"servlet" + suffix));
- expected.add(new File(CONFIG_PATH + File.separator + "wizard"
+ suffix));
- return expected;
- }
-
- private void assertCollectionEquals(Collection<File> expected,
Collection<File> actual) {
- final Collection<File> result = new ArrayList<File>();
- for (File obj : expected) {
- if (!actual.contains(obj))
- result.add(obj);
- }
-
- if (result.size() != 0)
- fail("The following are missing in the collection: "
+ result.toString());
- }
+ public void testGetFilesFilePath() throws IOException {
+ configCollection = new ConfigFilesCollection(new File(CONFIG_PATH +
File.separator
+ + "ConfigurationMigratorTest.class"));
+ assertEquals(0, configCollection.getFiles().size());
+ }
+
+ public void testRemoveFiles() throws IOException {
+ configCollection.removeFiles();
+ for (File file : createExpectedConfigFiles(".properties.remove")) {
+ assertTrue(file.exists());
+ final String name = file.getName().substring(0,
file.getName().length() - ".remove".length());
+ assertTrue(file.renameTo(new File(CONFIG_PATH + File.separator +
name)));
+ }
+ }
+
+ public void testRemoveFilesWhereTheFileExists() throws IOException {
+ assertTrue(new File(CONFIG_PATH + File.separator +
"wizard.properties.remove").createNewFile());
+ try {
+ configCollection.removeFiles();
+ fail("IOException should be thrown.");
+ } catch (IOException ex) {
+ }
+ assertTrue(new File(CONFIG_PATH + File.separator +
"wizard.properties.remove").delete());
+ for (File file : createExpectedConfigFiles(".properties.remove")) {
+ if (file.getName().equals("wizard.properties.remove")) {
+ continue;
+ }
+ if (file.exists()) {
+ final String name = file.getName().substring(0,
file.getName().length() - ".remove".length());
+ assertTrue(file.renameTo(new File(CONFIG_PATH +
File.separator + name)));
+ }
+ }
+ }
+
+ private Collection<File> createExpectedConfigFiles(String suffix) {
+ final Collection<File> expected = new ArrayList<File>();
+ expected.add(new File(CONFIG_PATH + File.separator + "components" +
suffix));
+ expected.add(new File(CONFIG_PATH + File.separator + "log4j" +
suffix));
+ expected.add(new File(CONFIG_PATH + File.separator + "service" +
suffix));
+ expected.add(new File(CONFIG_PATH + File.separator + "servlet" +
suffix));
+ expected.add(new File(CONFIG_PATH + File.separator + "wizard" +
suffix));
+ return expected;
+ }
+
+ private void assertCollectionEquals(Collection<File> expected,
Collection<File> actual) {
+ final Collection<File> result = new ArrayList<File>();
+ for (File obj : expected) {
+ if (!actual.contains(obj)) {
+ result.add(obj);
+ }
+ }
+
+ if (result.size() != 0) {
+ fail("The following are missing in the collection: " +
result.toString());
+ }
+ }
}
Modified:
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/FileNamePatternTest.java
===================================================================
---
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/FileNamePatternTest.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/FileNamePatternTest.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -15,34 +15,33 @@
*/
@RunWith(Parameterized.class)
public class FileNamePatternTest {
- @Parameters
- public static Collection<Object[]> getData() {
- final Collection<Object[]> result = new ArrayList<Object[]>();
- result.add(new Object[] { "abcdef.properties", true });
- result.add(new Object[] { "abcdef.properties.rpmsave", true
});
- result.add(new Object[] { "abcdef.properties.rpmorig", true
});
- result.add(new Object[] { ".properties", true });
- result.add(new Object[] { "abcdef.properties.rpmnew", true });
- result.add(new Object[] { "abcdef.properties.remove", false
});
- result.add(new Object[] { "abcdef.properties.old", false });
- result.add(new Object[] { "configurationproperties", false });
- result.add(new Object[] { "properties.rpmsave", false });
- return result;
- }
-
- private final String path;
- private final boolean expected;
- private final ConfigFilesCollection config = new
ConfigFilesCollection();
-
- public FileNamePatternTest(String path, boolean value) {
- this.path = path;
- this.expected = value;
- }
-
- @Test
- public void checkIfPathPointsToConfigurationFile() {
- assertTrue(path + " " + (expected ? "should" : "shouldn't")
- + " match configuration pattern.",
- config.matchesFileName(path) == expected);
- }
+ @Parameters
+ public static Collection<Object[]> getData() {
+ final Collection<Object[]> result = new ArrayList<Object[]>();
+ result.add(new Object[] {"abcdef.properties", true });
+ result.add(new Object[] {"abcdef.properties.rpmsave", true });
+ result.add(new Object[] {"abcdef.properties.rpmorig", true });
+ result.add(new Object[] {".properties", true });
+ result.add(new Object[] {"abcdef.properties.rpmnew", true });
+ result.add(new Object[] {"abcdef.properties.remove", false });
+ result.add(new Object[] {"abcdef.properties.old", false });
+ result.add(new Object[] {"configurationproperties", false });
+ result.add(new Object[] {"properties.rpmsave", false });
+ return result;
+ }
+
+ private final String path;
+ private final boolean expected;
+ private final ConfigFilesCollection config = new ConfigFilesCollection();
+
+ public FileNamePatternTest(String path, boolean value) {
+ this.path = path;
+ this.expected = value;
+ }
+
+ @Test
+ public void checkIfPathPointsToConfigurationFile() {
+ assertTrue(path + " " + (expected ? "should" : "shouldn't") + "
match configuration pattern.",
+ config.matchesFileName(path) == expected);
+ }
}
Modified:
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/MigratorComponentTest.java
===================================================================
---
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/MigratorComponentTest.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/MigratorComponentTest.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -13,49 +13,51 @@
*/
public class MigratorComponentTest extends TestCase {
- private MigratorComponent migrator;
- protected void setUp() throws Exception {
- super.setUp();
- migrator = new MigratorComponent();
- }
+ private MigratorComponent migrator;
- protected void tearDown() throws Exception {
- super.tearDown();
- }
+ protected void setUp() throws Exception {
+ super.setUp();
+ migrator = new MigratorComponent();
+ }
- public void testInitWithConfigDirectoryNotSet() {
- assertNull(migrator.getConfigDirectory());
- }
-
- public void testInitWithConfigDirectorySet() {
- setConfigDirectory(getCurrentDirectory());
- assertEquals(getCurrentDirectory(),
migrator.getConfigDirectory().getAbsolutePath());
- }
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
- private void setConfigDirectory(String path) {
- migrator.addOption(new Option("config-directory", path));
- }
+ public void testInitWithConfigDirectoryNotSet() {
+ assertNull(migrator.getConfigDirectory());
+ }
- private String getCurrentDirectory() {
- return new File(".").getAbsolutePath();
- }
+ public void testInitWithConfigDirectorySet() {
+ setConfigDirectory(getCurrentDirectory());
+ assertEquals(getCurrentDirectory(),
migrator.getConfigDirectory().getAbsolutePath());
+ }
- public void testRunWithEmptyConfigDirectory() throws
PerfSONARException {
- setConfigDirectory(getAbsolutePath("emptydir"));
- migrator.init();
- migrator.setTemplateEngine(new TemplateEngine() {
- @Override
- public File createFileFromTemplate(File template,
String newFileName)
- throws IOException {
- fail("There are no configuration files, so
new File should not be created.");
- return null;
- }
- });
- migrator.run();
- }
+ private void setConfigDirectory(String path) {
+ migrator.addOption(new Option("config-directory", path));
+ }
- private String getAbsolutePath(String path) {
- return "src" + File.separator + "test" + File.separator +
"java" + File.separator +
MigratorComponentTest.class.getPackage().getName().replace(".",
File.separator) + File.separator + path;
- }
+ private String getCurrentDirectory() {
+ return new File(".").getAbsolutePath();
+ }
+ public void testRunWithEmptyConfigDirectory() throws PerfSONARException {
+ setConfigDirectory(getAbsolutePath("emptydir"));
+ migrator.init();
+ migrator.setTemplateEngine(new TemplateEngine() {
+ @Override
+ public File createFileFromTemplate(File template, String
newFileName) throws IOException {
+ fail("There are no configuration files, so new File should
not be created.");
+ return null;
+ }
+ });
+ migrator.run();
+ }
+
+ private String getAbsolutePath(String path) {
+ return "src" + File.separator + "test" + File.separator + "java" +
File.separator
+ +
MigratorComponentTest.class.getPackage().getName().replace(".",
File.separator) + File.separator
+ + path;
+ }
+
}
Modified:
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/SimpleTemplateEngineTest.java
===================================================================
---
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/SimpleTemplateEngineTest.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/SimpleTemplateEngineTest.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -6,8 +6,6 @@
import java.io.FileReader;
import java.io.IOException;
-import
org.perfsonar.base2.service.configuration.migration.ConfigFilesCollection;
-import
org.perfsonar.base2.service.configuration.migration.SimpleTemplateEngine;
import
org.perfsonar.base2.service.configuration.migration.grammar.function.IndexerFunction;
import junit.framework.TestCase;
@@ -17,63 +15,75 @@
*/
public class SimpleTemplateEngineTest extends TestCase {
- TemplateEngine engine;
-
- protected void setUp() throws Exception {
- super.setUp();
- engine = new SimpleTemplateEngine(new
ConfigFilesCollection(new File(getConfigPath())).loadProperties());
- }
+ private TemplateEngine engine;
- private String getConfigPath() {
- return "src" + File.separator + "test" + File.separator +
"java" + File.separator +
SimpleTemplateEngine.class.getPackage().getName().replace(".",
File.separator);
- }
-
- public void testCreateFromTemplateWhereTemplateIsaDirectory() {
- try {
- engine.createFileFromTemplate(new
File(getConfigPath()), "configuration.xml");
- fail("IOException not thrown.");
- } catch (IOException ex) { }
- }
- public void testCreateFromTemplateWhereTemplateDoesNotExist() throws
IOException {
- try {
- engine.createFileFromTemplate(new
File(getConfigPath() + File.separator + "does_not_exist"),
"configuration.xml");
- fail("FileNotFoundException not thrown.");
- } catch (FileNotFoundException ex) { }
- }
- public void testCreateFromTemplateWhereFileIsaDirectory() {
- try {
- engine.createFileFromTemplate(new
File(getConfigPath() + File.separator + "configuration.xml.template"),
getConfigPath());
- fail("IOException not thrown.");
- } catch (IOException ex) { }
- }
- public void testCreateFromTemplate() throws IOException {
- new IndexerFunction().reset();
- assertEquals(new File(getConfigPath() + File.separator +
"expected.xml"), engine.createFileFromTemplate(new File(getConfigPath() +
File.separator + "configuration.xml.template"), getConfigPath() +
File.separator + "configuration.xml"));
- assertTrue(new File(getConfigPath() + File.separator +
"configuration.xml").delete());
- }
-
- private void assertEquals(File expected, File actual) throws
IOException {
- assertEquals(toString(expected), toString(actual));
- }
+ protected void setUp() throws Exception {
+ super.setUp();
+ engine = new SimpleTemplateEngine(new ConfigFilesCollection(new
File(getConfigPath())).loadProperties());
+ }
- private String toString(File file) throws IOException {
- final BufferedReader reader = new BufferedReader(new
FileReader(file));
- final StringBuilder result = new StringBuilder();
- boolean first = true;
- for (String line = reader.readLine(); line != null; line =
reader.readLine()) {
- if (first == false)
- result.append("\n");
- else
- first = false;
- result.append(line);
- }
- reader.close();
-
- return result.toString();
- }
-
- protected void tearDown() throws Exception {
- super.tearDown();
- }
+ private String getConfigPath() {
+ return "src" + File.separator + "test" + File.separator + "java" +
File.separator
+ +
SimpleTemplateEngine.class.getPackage().getName().replace(".",
File.separator);
+ }
+ public void testCreateFromTemplateWhereTemplateIsaDirectory() {
+ try {
+ engine.createFileFromTemplate(new File(getConfigPath()),
"configuration.xml");
+ fail("IOException not thrown.");
+ } catch (IOException ex) {
+ }
+ }
+
+ public void testCreateFromTemplateWhereTemplateDoesNotExist() throws
IOException {
+ try {
+ engine.createFileFromTemplate(new File(getConfigPath() +
File.separator + "does_not_exist"),
+ "configuration.xml");
+ fail("FileNotFoundException not thrown.");
+ } catch (FileNotFoundException ex) {
+ }
+ }
+
+ public void testCreateFromTemplateWhereFileIsaDirectory() {
+ try {
+ engine.createFileFromTemplate(new File(getConfigPath() +
File.separator + "configuration.xml.template"),
+ getConfigPath());
+ fail("IOException not thrown.");
+ } catch (IOException ex) {
+ }
+ }
+
+ public void testCreateFromTemplate() throws IOException {
+ new IndexerFunction().reset();
+ assertEquals(new File(getConfigPath() + File.separator +
"expected.xml"), engine.createFileFromTemplate(
+ new File(getConfigPath() + File.separator +
"configuration.xml.template"), getConfigPath()
+ + File.separator + "configuration.xml"));
+ assertTrue(new File(getConfigPath() + File.separator +
"configuration.xml").delete());
+ }
+
+ private void assertEquals(File expected, File actual) throws IOException
{
+ assertEquals(toString(expected), toString(actual));
+ }
+
+ private String toString(File file) throws IOException {
+ final BufferedReader reader = new BufferedReader(new
FileReader(file));
+ final StringBuilder result = new StringBuilder();
+ boolean first = true;
+ for (String line = reader.readLine(); line != null; line =
reader.readLine()) {
+ if (!first) {
+ result.append("\n");
+ } else {
+ first = false;
+ }
+ result.append(line);
+ }
+ reader.close();
+
+ return result.toString();
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+
}
Modified:
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/configuration.xml.template
===================================================================
---
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/configuration.xml.template
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/configuration.xml.template
2013-04-30 13:14:31 UTC (rev 6294)
@@ -52,8 +52,8 @@
<!-- auth configuration -->
<component name="auth"
className="org.perfsonar.base2.service.authn.component.wssec.WSSecAuthNComponent">
- <option name="as_endpoint" value="${service.as.point}"/>
- <option name="comp_id" value="urn:compId"/>
+ <option name="as_endpoint" value="${service.as.point}"/>
+ <option name="comp_id" value="urn:compId"/>
</component>
<!-- Scheduler -->
Modified:
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/expected.xml
===================================================================
---
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/expected.xml
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/expected.xml
2013-04-30 13:14:31 UTC (rev 6294)
@@ -52,8 +52,8 @@
<!-- auth configuration -->
<component name="auth"
className="org.perfsonar.base2.service.authn.component.wssec.WSSecAuthNComponent">
- <option name="as_endpoint"
value="http://homer.rediris.es:8080/perfSONAR-AS/services/AuthService"/>
- <option name="comp_id" value="urn:compId"/>
+ <option name="as_endpoint"
value="http://homer.rediris.es:8080/perfSONAR-AS/services/AuthService"/>
+ <option name="comp_id" value="urn:compId"/>
</component>
<!-- Scheduler -->
Modified:
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/grammar/AllGrammarTests.java
===================================================================
---
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/grammar/AllGrammarTests.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/grammar/AllGrammarTests.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -10,15 +10,15 @@
*/
public class AllGrammarTests {
- public static Test suite() {
- TestSuite suite = new TestSuite("Grammar test cases");
- //$JUnit-BEGIN$
- suite.addTest(AllFunctionTests.suite());
- suite.addTestSuite(PropertyExpressionTest.class);
- suite.addTestSuite(LoopExpressionTest.class);
- suite.addTestSuite(LoopTest.class);
- //$JUnit-END$
- return suite;
- }
+ public static Test suite() {
+ TestSuite suite = new TestSuite("Grammar test cases");
+ // $JUnit-BEGIN$
+ suite.addTest(AllFunctionTests.suite());
+ suite.addTestSuite(PropertyExpressionTest.class);
+ suite.addTestSuite(LoopExpressionTest.class);
+ suite.addTestSuite(LoopTest.class);
+ // $JUnit-END$
+ return suite;
+ }
}
Modified:
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/grammar/LoopExpressionTest.java
===================================================================
---
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/grammar/LoopExpressionTest.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/grammar/LoopExpressionTest.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -4,8 +4,6 @@
import java.io.StringWriter;
import java.util.Properties;
-import
org.perfsonar.base2.service.configuration.migration.grammar.LoopExpression;
-
import junit.framework.TestCase;
/**
@@ -13,69 +11,64 @@
*/
public class LoopExpressionTest extends TestCase {
- private LoopExpression stmt;
- protected void setUp() throws Exception {
- super.setUp();
- Properties props = new Properties();
- props.setProperty("abc", "def");
- stmt = new LoopExpression(props);
- }
+ private LoopExpression stmt;
- protected void tearDown() throws Exception {
- super.tearDown();
- }
+ protected void setUp() throws Exception {
+ super.setUp();
+ Properties props = new Properties();
+ props.setProperty("abc", "def");
+ stmt = new LoopExpression(props);
+ }
- public void testFilterNormalString() throws IOException {
- final StringWriter writer = new StringWriter();
- stmt.interpret(writer, "Ala ma kota i psa Asa.");
- assertEquals("Ala ma kota i psa Asa.", writer.toString());
- }
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
- public void testFilterForString() throws IOException {
- final StringWriter writer = new StringWriter();
- stmt.interpret(writer, "value=\"#for(var temp string \"Ala ma
kota\" split \" \") ${temp}_#end()\"");
- writer.flush();
- assertEquals("value=\" Ala_ ma_ kota_\"", writer.toString());
- }
-
- public void testFilterForStringMultiline1() throws IOException {
- final StringWriter writer = new StringWriter();
- stmt.interpret(writer, "value=\"#for(var temp string \"Ala ma
kota\" split \" \")bak");
- stmt.interpret(writer, "${temp}_#end()\"");
- writer.flush();
- assertEquals("value=\"bak"+ newLine()
- + "Ala_bak" + newLine()
- + "ma_bak" + newLine()
- + "kota_\"", writer.toString());
- }
-
- public void testFilterForStringMultiline2() throws IOException {
- final StringWriter writer = new StringWriter();
- stmt.interpret(writer, "value=\"#for(var temp string \"Ala ma
kota\" split \" \")bak");
- stmt.interpret(writer, "${temp}_${abc}");
- stmt.interpret(writer, "#end()\"");
- writer.flush();
- assertEquals("value=\"bak"+ newLine()
- + "Ala_defbak" + newLine()
- + "ma_defbak" + newLine()
- + "kota_def\"", writer.toString());
- }
-
- public void testFilterForStringMultiline3() throws IOException {
- final StringWriter writer = new StringWriter();
- stmt.interpret(writer, "<!-- Lookup Services -->#for(var
lsAddress string \"http://somewhere,https://somehow\" split \",\")");
- stmt.interpret(writer, "<option name=\"lsAddress-1\"
value=\"${lsAddress}\" />#end()");
- writer.flush();
- assertEquals("<!-- Lookup Services -->"+ newLine()
- + "<option name=\"lsAddress-1\"
value=\"http://somewhere\" />" + newLine()
- + "<option name=\"lsAddress-1\"
value=\"https://somehow\" />",
- writer.toString());
-
-
-
- }
-
- private String newLine() {
- return System.getProperty("line.separator");
- }
+ public void testFilterNormalString() throws IOException {
+ final StringWriter writer = new StringWriter();
+ stmt.interpret(writer, "Ala ma kota i psa Asa.");
+ assertEquals("Ala ma kota i psa Asa.", writer.toString());
+ }
+
+ public void testFilterForString() throws IOException {
+ final StringWriter writer = new StringWriter();
+ stmt.interpret(writer, "value=\"#for(var temp string \"Ala ma kota\"
split \" \") ${temp}_#end()\"");
+ writer.flush();
+ assertEquals("value=\" Ala_ ma_ kota_\"", writer.toString());
+ }
+
+ public void testFilterForStringMultiline1() throws IOException {
+ final StringWriter writer = new StringWriter();
+ stmt.interpret(writer, "value=\"#for(var temp string \"Ala ma kota\"
split \" \")bak");
+ stmt.interpret(writer, "${temp}_#end()\"");
+ writer.flush();
+ assertEquals("value=\"bak" + newLine() + "Ala_bak" + newLine() +
"ma_bak" + newLine() + "kota_\"",
+ writer.toString());
+ }
+
+ public void testFilterForStringMultiline2() throws IOException {
+ final StringWriter writer = new StringWriter();
+ stmt.interpret(writer, "value=\"#for(var temp string \"Ala ma kota\"
split \" \")bak");
+ stmt.interpret(writer, "${temp}_${abc}");
+ stmt.interpret(writer, "#end()\"");
+ writer.flush();
+ assertEquals("value=\"bak" + newLine() + "Ala_defbak" + newLine() +
"ma_defbak" + newLine() + "kota_def\"",
+ writer.toString());
+ }
+
+ public void testFilterForStringMultiline3() throws IOException {
+ final StringWriter writer = new StringWriter();
+ stmt.interpret(writer,
+ "<!-- Lookup Services -->#for(var lsAddress string
\"http://somewhere,https://somehow\" split \",\")");
+ stmt.interpret(writer, "<option name=\"lsAddress-1\"
value=\"${lsAddress}\" />#end()");
+ writer.flush();
+ assertEquals("<!-- Lookup Services -->" + newLine()
+ + "<option name=\"lsAddress-1\" value=\"http://somewhere\"
/>" + newLine()
+ + "<option name=\"lsAddress-1\" value=\"https://somehow\"
/>", writer.toString());
+
+ }
+
+ private String newLine() {
+ return System.getProperty("line.separator");
+ }
}
Modified:
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/grammar/LoopTest.java
===================================================================
---
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/grammar/LoopTest.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/grammar/LoopTest.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -3,9 +3,6 @@
import java.util.Properties;
import java.util.regex.Matcher;
-import org.perfsonar.base2.service.configuration.migration.grammar.Loop;
-import
org.perfsonar.base2.service.configuration.migration.grammar.LoopExpression;
-
import junit.framework.TestCase;
/**
@@ -13,55 +10,57 @@
*/
public class LoopTest extends TestCase {
- private Loop expr;
+ private Loop expr;
- public void testPatternFor() {
- expr = createForLoop("value=\"#for(var temp string \"Ala ma
kota\" split \" \") asdasd");
- assertFalse(expr.isEndStatement());
- assertTrue(expr.isForStatement());
- assertEquals("temp", expr.getVariableName());
- assertEquals("Ala ma kota", expr.getString());
- assertEquals(" ", expr.getSplitRegexp());
- }
+ public void testPatternFor() {
+ expr = createForLoop("value=\"#for(var temp string \"Ala ma kota\"
split \" \") asdasd");
+ assertFalse(expr.isEndStatement());
+ assertTrue(expr.isForStatement());
+ assertEquals("temp", expr.getVariableName());
+ assertEquals("Ala ma kota", expr.getString());
+ assertEquals(" ", expr.getSplitRegexp());
+ }
- public void testPatternEnd() {
- expr = new Loop(createMatcher("value=\"#end()\""));
- assertTrue(expr.isEndStatement());
- assertFalse(expr.isForStatement());
- }
-
- public void testForEnd() {
- expr = createForLoop("value=\"#for(var temp string \"Ala ma
kota\" split \" \")${var}_\"#end()\"\"");
- assertFalse(expr.isEndStatement());
- assertTrue(expr.isForStatement());
- assertEquals("temp", expr.getVariableName());
- assertEquals("Ala ma kota", expr.getString());
- assertEquals(" ", expr.getSplitRegexp());
- }
-
- public void testSplit() {
- expr = createForLoop("value=\"#for(var temp string \"Ala ma
kota\" split \" \")");
- String[] expected = new String[3];
- expected[0] = "Ala";
- expected[1] = "ma";
- expected[2] = "kota";
- assertEqualTables(expected, expr.split());
- }
-
- private void assertEqualTables(String[] expected, String[] actual) {
- if (expected.length != actual.length)
- fail("Expected table with size=" + expected.length +
" but was " + actual.length);
- for (int i = 0; i < actual.length; i++)
- assertEquals(expected[i], actual[i]);
- }
+ public void testPatternEnd() {
+ expr = new Loop(createMatcher("value=\"#end()\""));
+ assertTrue(expr.isEndStatement());
+ assertFalse(expr.isForStatement());
+ }
- private Matcher createMatcher(String string) {
- final Matcher result = new LoopExpression(new
Properties()).getPattern().matcher(string);
- assertTrue(result.find());
- return result;
- }
-
- private Loop createForLoop(String line) {
- return new Loop(createMatcher(line));
- }
+ public void testForEnd() {
+ expr = createForLoop("value=\"#for(var temp string \"Ala ma kota\"
split \" \")${var}_\"#end()\"\"");
+ assertFalse(expr.isEndStatement());
+ assertTrue(expr.isForStatement());
+ assertEquals("temp", expr.getVariableName());
+ assertEquals("Ala ma kota", expr.getString());
+ assertEquals(" ", expr.getSplitRegexp());
+ }
+
+ public void testSplit() {
+ expr = createForLoop("value=\"#for(var temp string \"Ala ma kota\"
split \" \")");
+ String[] expected = new String[3];
+ expected[0] = "Ala";
+ expected[1] = "ma";
+ expected[2] = "kota";
+ assertEqualTables(expected, expr.split());
+ }
+
+ private void assertEqualTables(String[] expected, String[] actual) {
+ if (expected.length != actual.length) {
+ fail("Expected table with size=" + expected.length + " but was "
+ actual.length);
+ }
+ for (int i = 0; i < actual.length; i++) {
+ assertEquals(expected[i], actual[i]);
+ }
+ }
+
+ private Matcher createMatcher(String string) {
+ final Matcher result = new LoopExpression(new
Properties()).getPattern().matcher(string);
+ assertTrue(result.find());
+ return result;
+ }
+
+ private Loop createForLoop(String line) {
+ return new Loop(createMatcher(line));
+ }
}
Modified:
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/grammar/PropertyExpressionTest.java
===================================================================
---
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/grammar/PropertyExpressionTest.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/grammar/PropertyExpressionTest.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -4,8 +4,6 @@
import java.util.Properties;
import java.util.regex.Matcher;
-import
org.perfsonar.base2.service.configuration.migration.grammar.PropertyExpression;
-
import junit.framework.TestCase;
/**
@@ -13,46 +11,50 @@
*/
public class PropertyExpressionTest extends TestCase {
- private PropertyExpression filter;
- protected void setUp() throws Exception {
- super.setUp();
-
- filter = new PropertyExpression(new Properties());
- }
+ private PropertyExpression filter;
- protected void tearDown() throws Exception {
- super.tearDown();
- }
+ protected void setUp() throws Exception {
+ super.setUp();
- public void testPropertyPatternLineWithProperty() {
- final Matcher m = filter.getPattern().matcher("property
${prop.name}=${prop.value}.");
- assertTrue(m.find());
- assertEquals("prop.name", m.group(1));
- assertTrue(m.find());
- assertEquals("prop.value", m.group(1));
- assertFalse(m.find());
- }
-
- public void testPropertyPatternLineWithoutProperty() {
-
assertFalse(filter.getPattern().matcher("property={prop.value}.").matches());
- }
-
- public void testFilter() throws IOException {
- final Properties props = new Properties();
- props.setProperty("name1", "interval");
- props.setProperty("value1", "6000");
- props.setProperty("name2", "enabled");
- props.setProperty("value2", "yes");
- filter = new PropertyExpression(props);
- assertEquals("property interval=6000; enabled=yes",
filter.interpret("property ${name1}=${value1}; ${name2}=${value2}"));
- }
- public void testFilterPropertyDoesNotExist() throws IOException {
- final Properties props = new Properties();
- props.setProperty("name1", "interval");
- props.setProperty("value1", "6000");
- props.setProperty("value2", "yes");
- filter = new PropertyExpression(props);
- assertEquals("property interval=6000; ${name2}=yes",
filter.interpret("property ${name1}=${value1}; ${name2}=${value2}"));
- }
-
+ filter = new PropertyExpression(new Properties());
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+
+ public void testPropertyPatternLineWithProperty() {
+ final Matcher m = filter.getPattern().matcher("property
${prop.name}=${prop.value}.");
+ assertTrue(m.find());
+ assertEquals("prop.name", m.group(1));
+ assertTrue(m.find());
+ assertEquals("prop.value", m.group(1));
+ assertFalse(m.find());
+ }
+
+ public void testPropertyPatternLineWithoutProperty() {
+
assertFalse(filter.getPattern().matcher("property={prop.value}.").matches());
+ }
+
+ public void testFilter() throws IOException {
+ final Properties props = new Properties();
+ props.setProperty("name1", "interval");
+ props.setProperty("value1", "6000");
+ props.setProperty("name2", "enabled");
+ props.setProperty("value2", "yes");
+ filter = new PropertyExpression(props);
+ assertEquals("property interval=6000; enabled=yes",
+ filter.interpret("property ${name1}=${value1};
${name2}=${value2}"));
+ }
+
+ public void testFilterPropertyDoesNotExist() throws IOException {
+ final Properties props = new Properties();
+ props.setProperty("name1", "interval");
+ props.setProperty("value1", "6000");
+ props.setProperty("value2", "yes");
+ filter = new PropertyExpression(props);
+ assertEquals("property interval=6000; ${name2}=yes",
+ filter.interpret("property ${name1}=${value1};
${name2}=${value2}"));
+ }
+
}
Modified:
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/grammar/function/AllFunctionTests.java
===================================================================
---
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/grammar/function/AllFunctionTests.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/grammar/function/AllFunctionTests.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -1,6 +1,5 @@
package org.perfsonar.base2.service.configuration.migration.grammar.function;
-
import junit.framework.Test;
import junit.framework.TestSuite;
@@ -9,14 +8,14 @@
*/
public class AllFunctionTests {
- public static Test suite() {
- TestSuite suite = new TestSuite("Function expressions test
cases");
- //$JUnit-BEGIN$
- suite.addTestSuite(ReplaceFunctionTest.class);
- suite.addTestSuite(IndexerFunctionTest.class);
- suite.addTestSuite(FunctionExpressionTest.class);
- //$JUnit-END$
- return suite;
- }
+ public static Test suite() {
+ TestSuite suite = new TestSuite("Function expressions test cases");
+ // $JUnit-BEGIN$
+ suite.addTestSuite(ReplaceFunctionTest.class);
+ suite.addTestSuite(IndexerFunctionTest.class);
+ suite.addTestSuite(FunctionExpressionTest.class);
+ // $JUnit-END$
+ return suite;
+ }
}
Modified:
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/grammar/function/FunctionExpressionTest.java
===================================================================
---
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/grammar/function/FunctionExpressionTest.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/grammar/function/FunctionExpressionTest.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -2,35 +2,36 @@
import java.io.IOException;
-import
org.perfsonar.base2.service.configuration.migration.grammar.function.FunctionExpression;
-
import junit.framework.TestCase;
/**
* @author <a
href="mailto:">Blazej
Pietrzak</a>
*/
public class FunctionExpressionTest extends TestCase {
- private FunctionExpression filter;
-
- protected void setUp() throws Exception {
- super.setUp();
-
- filter = new FunctionExpression();
- }
-
- public void testPatternLineWithFunction() {
-
assertTrue(filter.getPattern().matcher("value=\"#replace(string
\"${component.mp.xmldb.db_uri}\" regexp \"\" with \"\")\"").find());
- }
-
- public void testPatternLineWithoutFunction() {
-
assertFalse(filter.getPattern().matcher("property={prop.value}.").find());
- }
-
- public void testFilterReplace() throws IOException {
- assertEquals("value=\"bas ${component.mp.xmldb.db_uri}
bbas\"", filter.interpret("value=\"#replace(string \"as
${component.mp.xmldb.db_uri} bas\" regexp \"as\" with \"bas\")\""));
- }
-
- public void testFilterFunctionNotImplemented() throws IOException {
- assertEquals("value=\"#notImplemented()\"",
filter.interpret("value=\"#notImplemented()\""));
- }
+ private FunctionExpression filter;
+
+ protected void setUp() throws Exception {
+ super.setUp();
+
+ filter = new FunctionExpression();
+ }
+
+ public void testPatternLineWithFunction() {
+ assertTrue(filter.getPattern()
+ .matcher("value=\"#replace(string
\"${component.mp.xmldb.db_uri}\" regexp \"\" with \"\")\"").find());
+ }
+
+ public void testPatternLineWithoutFunction() {
+
assertFalse(filter.getPattern().matcher("property={prop.value}.").find());
+ }
+
+ public void testFilterReplace() throws IOException {
+ assertEquals(
+ "value=\"bas ${component.mp.xmldb.db_uri} bbas\"",
+ filter.interpret("value=\"#replace(string \"as
${component.mp.xmldb.db_uri} bas\" regexp \"as\" with \"bas\")\""));
+ }
+
+ public void testFilterFunctionNotImplemented() throws IOException {
+ assertEquals("value=\"#notImplemented()\"",
filter.interpret("value=\"#notImplemented()\""));
+ }
}
Modified:
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/grammar/function/FunctionTestCase.java
===================================================================
---
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/grammar/function/FunctionTestCase.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/grammar/function/FunctionTestCase.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -2,9 +2,6 @@
import java.util.regex.Matcher;
-import
org.perfsonar.base2.service.configuration.migration.grammar.function.Function;
-import
org.perfsonar.base2.service.configuration.migration.grammar.function.FunctionExpression;
-
import junit.framework.TestCase;
/**
@@ -12,23 +9,24 @@
*/
public abstract class FunctionTestCase extends TestCase {
- protected FunctionExpression filter = new FunctionExpression();
- protected Function function;
+ protected FunctionExpression filter = new FunctionExpression();
+ protected Function function;
- protected void setUp() throws Exception {
- super.setUp();
- final Matcher temp = getFunctionMatcher(getLine());
- assertTrue(temp.find());
- function = new Function(temp);
- function.reset();
- }
+ protected void setUp() throws Exception {
+ super.setUp();
+ final Matcher temp = getFunctionMatcher(getLine());
+ assertTrue(temp.find());
+ function = new Function(temp);
+ function.reset();
+ }
- private Matcher getFunctionMatcher(String line) {
- return filter.getPattern().matcher(line);
- }
+ private Matcher getFunctionMatcher(String line) {
+ return filter.getPattern().matcher(line);
+ }
- protected abstract String getLine();
-
- public abstract void testGetName();
- public abstract void testGetArguments();
+ protected abstract String getLine();
+
+ public abstract void testGetName();
+
+ public abstract void testGetArguments();
}
Modified:
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/grammar/function/IndexerFunctionTest.java
===================================================================
---
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/grammar/function/IndexerFunctionTest.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/grammar/function/IndexerFunctionTest.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -4,21 +4,21 @@
* @author <a
href="mailto:">Blazej
Pietrzak</a>
*/
public class IndexerFunctionTest extends FunctionTestCase {
-
- protected String getLine() {
- return "<option name=\"lsAddress-#indexer()\"
value=\"${lsAddress}\" />";
- }
- public void testGetName() {
- assertEquals("indexer", function.getName());
- }
+ protected String getLine() {
+ return "<option name=\"lsAddress-#indexer()\" value=\"${lsAddress}\"
/>";
+ }
- public void testGetArguments() {
- assertEquals(0, function.getArguments().size());
- }
-
- public void testExecute() {
- assertEquals("1", function.execute());
- assertEquals("2", function.execute());
- }
+ public void testGetName() {
+ assertEquals("indexer", function.getName());
+ }
+
+ public void testGetArguments() {
+ assertEquals(0, function.getArguments().size());
+ }
+
+ public void testExecute() {
+ assertEquals("1", function.execute());
+ assertEquals("2", function.execute());
+ }
}
Modified:
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/grammar/function/ReplaceFunctionTest.java
===================================================================
---
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/grammar/function/ReplaceFunctionTest.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/grammar/function/ReplaceFunctionTest.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -7,20 +7,21 @@
* @author <a
href="mailto:">Blazej
Pietrzak</a>
*/
public class ReplaceFunctionTest extends FunctionTestCase {
- protected String getLine() {
- return "<option name=\"url\" value=\"#replace(string
\"http://localhost:8180/exist/rest/db/ls\" regexp
\"http://(.+)/exist/rest/db/(.*)\" with
\"xmldb:exist://$1/exist/xmlrpc/db/$2\")\" />";
- }
+ protected String getLine() {
+ return "<option name=\"url\" value=\"#replace(string
\"http://localhost:8180/exist/rest/db/ls\" "
+ + " regexp \"http://(.+)/exist/rest/db/(.*)\" with
\"xmldb:exist://$1/exist/xmlrpc/db/$2\")\" />";
+ }
- public void testGetName() {
- assertEquals("replace", function.getName());
- }
+ public void testGetName() {
+ assertEquals("replace", function.getName());
+ }
- public void testGetArguments() {
- Map<String, String> expected = new Hashtable<String,
String>();
- expected.put("string",
"http://localhost:8180/exist/rest/db/ls");
- expected.put("regexp", "http://(.+)/exist/rest/db/(.*)");
- expected.put("with", "xmldb:exist://$1/exist/xmlrpc/db/$2");
- assertEquals(expected, function.getArguments());
- }
+ public void testGetArguments() {
+ Map<String, String> expected = new Hashtable<String, String>();
+ expected.put("string", "http://localhost:8180/exist/rest/db/ls");
+ expected.put("regexp", "http://(.+)/exist/rest/db/(.*)");
+ expected.put("with", "xmldb:exist://$1/exist/xmlrpc/db/$2");
+ assertEquals(expected, function.getArguments());
+ }
}
Modified:
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/wizard.properties
===================================================================
---
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/wizard.properties
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/configuration/migration/wizard.properties
2013-04-30 13:14:31 UTC (rev 6294)
@@ -7,12 +7,12 @@
<!ELEMENT entry (#PCDATA) >
<!ATTLIST entry
key CDATA #REQUIRED
- password (true|false) #IMPLIED
- required (true|false) #IMPLIED >
+ password (true|false) #IMPLIED
+ required (true|false) #IMPLIED >
<!ELEMENT Comment (#PCDATA) >
<!ELEMENT ProposedValue (#PCDATA) >
<!ELEMENT Group (#PCDATA) >
-<!ATTLIST Group
+<!ATTLIST Group
order CDATA #REQUIRED
check (true|false) #IMPLIED
dependsOn CDATA #IMPLIED
Modified:
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/validation/JREVersionTest.java
===================================================================
---
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/validation/JREVersionTest.java
2013-04-30 09:50:21 UTC (rev 6293)
+++
trunk/perfsonar-java-base2/src/test/java/org/perfsonar/base2/service/validation/JREVersionTest.java
2013-04-30 13:14:31 UTC (rev 6294)
@@ -7,35 +7,36 @@
*/
public class JREVersionTest extends TestCase {
- private JREVersion jreVersion;
- protected void setUp() throws Exception {
- super.setUp();
- jreVersion = new JREVersion();
- jreVersion.setJREVersion("1.6.0");
- }
+ private JREVersion jreVersion;
- protected void tearDown() throws Exception {
- super.tearDown();
- jreVersion = null;
- }
+ protected void setUp() throws Exception {
+ super.setUp();
+ jreVersion = new JREVersion();
+ jreVersion.setJREVersion("1.6.0");
+ }
- public void testIsJRECompatibleWithEqualMajorLowerMinor() {
- assertFalse(jreVersion.isJRECompatibleWith(1, 5));
- }
-
- public void testIsJRECompatibleWithEqualMajorEqualMinor() {
- assertTrue(jreVersion.isJRECompatibleWith(1, 6));
- }
-
- public void testIsJRECompatibleWithEqualMajorGreaterMinor() {
- assertTrue(jreVersion.isJRECompatibleWith(1, 7));
- }
-
- public void testIsJRECompatibleWithGreaterMajorLowerMinor() {
- assertTrue(jreVersion.isJRECompatibleWith(2, 0));
- }
-
- public void testIsJRECompatibleWithGreaterMajorGreaterMinor() {
- assertTrue(jreVersion.isJRECompatibleWith(2, 7));
- }
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ jreVersion = null;
+ }
+
+ public void testIsJRECompatibleWithEqualMajorLowerMinor() {
+ assertFalse(jreVersion.isJRECompatibleWith(1, 5));
+ }
+
+ public void testIsJRECompatibleWithEqualMajorEqualMinor() {
+ assertTrue(jreVersion.isJRECompatibleWith(1, 6));
+ }
+
+ public void testIsJRECompatibleWithEqualMajorGreaterMinor() {
+ assertTrue(jreVersion.isJRECompatibleWith(1, 7));
+ }
+
+ public void testIsJRECompatibleWithGreaterMajorLowerMinor() {
+ assertTrue(jreVersion.isJRECompatibleWith(2, 0));
+ }
+
+ public void testIsJRECompatibleWithGreaterMajorGreaterMinor() {
+ assertTrue(jreVersion.isJRECompatibleWith(2, 7));
+ }
}
- [pS-dev] [GEANT/SA2/ps-java-services] r6294 - in trunk: parent perfsonar-java-base2 perfsonar-java-bas e2/src perfsonar-java-base2/src/checkstyle perfsonar-java- base2/src/main/java/org/perfsonar/base2/client perfsonar-j ava-base2/src/main/java/org/perfsonar/base2/client/authn p erfsonar-java-base2/src/main/java/org/perfsonar/base2/clie nt/authn/edugain perfsonar-java-base2/src/main/java/org/pe rfsonar/base2/service/authn perfsonar-java-base2/src/main/ java/org/perfsonar/base2/service/authn/component perfsonar -java-base2/src/main/java/org/perfsonar/base2/service/auth n/component/wssec perfsonar-java-base2/src/main/java/org/p erfsonar/base2/service/authn/tokens perfsonar-java-base2/s rc/main/java/org/perfsonar/base2/service/axis2interface pe rfsonar-java-base2/src/main/java/org/perfsonar/base2/servi ce/configuration perfsonar-java-base2/src/main/java/org/pe rfsonar/base2/service/configuration/migration perfsonar-ja va-base2/src/main/java/org/perfsonar/base2/service/configu ration/migration/g rammar perfsonar-java-base2/src/main/ja va/org/perfsonar/base2/service/configuration/migration/gra mmar/function perfsonar-java-base2/src/main/java/org/perfs onar/base2/service/exceptions perfsonar-java-base2/src/mai n/java/org/perfsonar/base2/service/messages perfsonar-java -base2/src/main/java/org/perfsonar/base2/service/registrat ion perfsonar-java-base2/src/main/java/org/perfsonar/base2 /service/requesthandler perfsonar-java-base2/src/main/java /org/perfsonar/base2/service/requesthandler/axis2 perfsona r-java-base2/src/main/java/org/perfsonar/base2/service/req uesthandler/file perfsonar-java-base2/src/main/java/org/pe rfsonar/base2/service/scheduler perfsonar-java-base2/src/m ain/java/org/perfsonar/base2/service/scheduler/singleThrea d perfsonar-java-base2/src/main/java/org/perfsonar/base2/s ervice/storage/xml perfsonar-java-base2/src/main/java/org/ perfsonar/base2/service/storage/xml/exist perfsonar-java-b ase2/src/main/java/org/perfsonar/base2/service/util perfso nar-java-base2/src/mai n/java/org/perfsonar/base2/service/ validation perfsonar-java-base2/src/main/java/org/perfsona r/base2/servlets perfsonar-java-base2/src/main/java/org/pe rfsonar/base2/xml perfsonar-java-base2/src/main/java/org/p erfsonar/base2/xml/nmwg perfsonar-java-base2/src/main/java /org/perfsonar/contrib perfsonar-java-base2/src/main/java/ org/perfsonar/service/simpleservice perfsonar-java-base2/s rc/main/java/org/perfsonar/test perfsonar-java-base2/src/m ain/resources/perfsonar/conf perfsonar-java-base2/src/test /java/org/perfsonar/base2/service perfsonar-java-base2/src /test/java/org/perfsonar/base2/service/configuration/migra tion perfsonar-java-base2/src/test/java/org/perfsonar/base 2/service/configuration/migration/grammar perfsonar-java-b ase2/src/test/java/org/perfsonar/base2/service/configurati on/migration/grammar/function perfsonar-java-base2/src/tes t/java/org/perfsonar/base2/service/validation, svn-noreply, 04/30/2013
Archive powered by MHonArc 2.6.16.