Skip to Content.
Sympa Menu

perfsonar-dev - [pS-dev] [GEANT/SA2/ps-java-services] r6371 - in trunk: nmwg-sql-converter/src/main/java/org/perfsonar /nmwg/converter nmwg-sql-converter/src/test/java/org/perfs onar/nmwg/converter parent parent/checkstyle perfsonar-bas e/annotations perfsonar-base/annotations/src/main/java/net /geant/perfsonar/annotations perfsonar-base/annotations/sr c/main/java/net/geant/perfsonar/annotations/request perfso nar-base/annotations/src/main/java/net/geant/perfsonar/ann otations/selftest perfsonar-base/apt perfsonar-base/apt/du mmyservice/net/geant/perfsonar/dummyservice perfsonar-base /apt/dummyservice/net/geant/perfsonar/dummyservice/selftes t perfsonar-base/apt/dummyservice/net/geant/perfsonar/dumm yservice/xpath perfsonar-base/apt/src/main/java/net/geant/ perfsonar/annotations perfsonar-base/apt/src/main/java/net /geant/perfsonar/annotations/ls perfsonar-base/apt/src/mai n/java/net/geant/perfsonar/annotations/request perfsonar-b ase/apt/src/main/java/net/geant/perfsonar/annotations/self test perfsonar-bas e/apt/src/main/java/net/geant/perfsonar /annotations/xpath perfsonar-base/apt/src/test/java/net/ge ant/perfsonar/annotations perfsonar-base/apt/src/test/java /net/geant/perfsonar/annotations/selftest perfsonar-base/a pt/src/test/java/net/geant/perfsonar/annotations/selftest/ compiler perfsonar-base/base perfsonar-base/base/src/main/ java/net/geant/perfsonar perfsonar-base/base/src/main/java /net/geant/perfsonar/base perfsonar-base/base/src/main/jav a/net/geant/perfsonar/response perfsonar-base/base/src/mai n/java/net/geant/perfsonar/selftest perfsonar-base/base/sr c/main/resources/net/geant/perfsonar/response perfsonar-ba se/base/src/test/java/net/geant/perfsonar perfsonar-base/b ase/src/test/java/net/geant/perfsonar/configuration perfso nar-base/base/src/test/java/net/geant/perfsonar/helpers pe rfsonar-base/base/src/test/java/net/geant/perfsonar/mp/ssh telnet perfsonar-base/ls perfsonar-base/ls/src/main/java/n et/geant/perfsonar/ls perfsonar-base/ls/src/test/java/net/ geant/perfsonar/ls per fsonar-base/ls/src/test/resources/n et/geant/perfsonar/mp/sshtelnet perfsonar-base/messaging p erfsonar-base/messaging/src/main/java/net/geant/perfsonar/ messaging perfsonar-base/messaging/src/main/java/net/geant /perfsonar/templates perfsonar-base/messaging/src/test/gro ovy/net/geant/perfsonar/templates perfsonar-base/messaging /src/test/java/net/geant/perfsonar/messaging perfsonar-bas e/messaging/src/test/java/net/geant/perfsonar/mp/sshtelnet perfsonar-base/messaging/src/test/java/net/geant/perfsona r/templates perfsonar-base/messaging-test-data perfsonar-b ase/messaging-test-data/src/main/java/net/geant/perfsonar/ messaging/data perfsonar-base/sample-service perfsonar-bas e/sample-service/src/main/java/net/geant/perfsonar/mp/ssht elnet perfsonar-base/sample-service/src/main/resources per fsonar-base/sample-service/src/main/resources/net/geant/pe rfsonar/mp/sshtelnet perfsonar-base/sample-service/src/tes t/java/net/geant/perfsonar/mp/sshtelnet perfsonar-java-rrd -ma-SQL_backend/src/main/j ava/org/perfsonar/service/tem p perfsonar-java-rrd-ma-SQL_backend/src/main/resources/p erfsonar/conf perfsonar-java-rrd-ma-base3 perfsonar-java-r rd-ma-base3/src/main perfsonar-java-rrd-ma-base3/src/test/ java/net/geant/perfsonar/ma/rrd perfsonar-java-web-admin p erfsonar-java-web-admin/perfsonar-java-web-admin-component perfsonar-java-web-admin/perfsonar-java-web-admin-compone nt/src/main/java/org/perfsonar/webadmin/config perfsonar-j ava-web-admin/perfsonar-java-web-admin-component/src/main/ java/org/perfsonar/webadmin/filters perfsonar-java-web-adm in/perfsonar-java-web-admin-component/src/main/java/org/pe rfsonar/webadmin/servlet perfsonar-java-web-admin/perfsona r-java-web-admin-component/src/main/java/org/perfsonar/web admin/servlet/util perfsonar-java-web-admin/perfsonar-java -web-admin-component/src/main/java/org/perfsonar/webadmin/ test perfsonar-java-web-admin/perfsonar-java-web-admin-com ponent/src/main/java/org/perfsonar/webadmin/util perfsonar -java-web-admin/perfsonar-java-web -admin-component/src/ma in/resources perfsonar-java-web-admin/perfsonar-java-web-a dmin-component/src/main/webapp/wa/scripts perfsonar-java-w eb-admin/perfsonar-java-web-admin-component/src/test/resou rces perfsonar-java-web-admin/perfsonar-java-web-admin-exa mpleservice

Subject: perfsonar development work

List archive

[pS-dev] [GEANT/SA2/ps-java-services] r6371 - in trunk: nmwg-sql-converter/src/main/java/org/perfsonar /nmwg/converter nmwg-sql-converter/src/test/java/org/perfs onar/nmwg/converter parent parent/checkstyle perfsonar-bas e/annotations perfsonar-base/annotations/src/main/java/net /geant/perfsonar/annotations perfsonar-base/annotations/sr c/main/java/net/geant/perfsonar/annotations/request perfso nar-base/annotations/src/main/java/net/geant/perfsonar/ann otations/selftest perfsonar-base/apt perfsonar-base/apt/du mmyservice/net/geant/perfsonar/dummyservice perfsonar-base /apt/dummyservice/net/geant/perfsonar/dummyservice/selftes t perfsonar-base/apt/dummyservice/net/geant/perfsonar/dumm yservice/xpath perfsonar-base/apt/src/main/java/net/geant/ perfsonar/annotations perfsonar-base/apt/src/main/java/net /geant/perfsonar/annotations/ls perfsonar-base/apt/src/mai n/java/net/geant/perfsonar/annotations/request perfsonar-b ase/apt/src/main/java/net/geant/perfsonar/annotations/self test perfsonar-bas e/apt/src/main/java/net/geant/perfsonar /annotations/xpath perfsonar-base/apt/src/test/java/net/ge ant/perfsonar/annotations perfsonar-base/apt/src/test/java /net/geant/perfsonar/annotations/selftest perfsonar-base/a pt/src/test/java/net/geant/perfsonar/annotations/selftest/ compiler perfsonar-base/base perfsonar-base/base/src/main/ java/net/geant/perfsonar perfsonar-base/base/src/main/java /net/geant/perfsonar/base perfsonar-base/base/src/main/jav a/net/geant/perfsonar/response perfsonar-base/base/src/mai n/java/net/geant/perfsonar/selftest perfsonar-base/base/sr c/main/resources/net/geant/perfsonar/response perfsonar-ba se/base/src/test/java/net/geant/perfsonar perfsonar-base/b ase/src/test/java/net/geant/perfsonar/configuration perfso nar-base/base/src/test/java/net/geant/perfsonar/helpers pe rfsonar-base/base/src/test/java/net/geant/perfsonar/mp/ssh telnet perfsonar-base/ls perfsonar-base/ls/src/main/java/n et/geant/perfsonar/ls perfsonar-base/ls/src/test/java/net/ geant/perfsonar/ls per fsonar-base/ls/src/test/resources/n et/geant/perfsonar/mp/sshtelnet perfsonar-base/messaging p erfsonar-base/messaging/src/main/java/net/geant/perfsonar/ messaging perfsonar-base/messaging/src/main/java/net/geant /perfsonar/templates perfsonar-base/messaging/src/test/gro ovy/net/geant/perfsonar/templates perfsonar-base/messaging /src/test/java/net/geant/perfsonar/messaging perfsonar-bas e/messaging/src/test/java/net/geant/perfsonar/mp/sshtelnet perfsonar-base/messaging/src/test/java/net/geant/perfsona r/templates perfsonar-base/messaging-test-data perfsonar-b ase/messaging-test-data/src/main/java/net/geant/perfsonar/ messaging/data perfsonar-base/sample-service perfsonar-bas e/sample-service/src/main/java/net/geant/perfsonar/mp/ssht elnet perfsonar-base/sample-service/src/main/resources per fsonar-base/sample-service/src/main/resources/net/geant/pe rfsonar/mp/sshtelnet perfsonar-base/sample-service/src/tes t/java/net/geant/perfsonar/mp/sshtelnet perfsonar-java-rrd -ma-SQL_backend/src/main/j ava/org/perfsonar/service/tem p perfsonar-java-rrd-ma-SQL_backend/src/main/resources/p erfsonar/conf perfsonar-java-rrd-ma-base3 perfsonar-java-r rd-ma-base3/src/main perfsonar-java-rrd-ma-base3/src/test/ java/net/geant/perfsonar/ma/rrd perfsonar-java-web-admin p erfsonar-java-web-admin/perfsonar-java-web-admin-component perfsonar-java-web-admin/perfsonar-java-web-admin-compone nt/src/main/java/org/perfsonar/webadmin/config perfsonar-j ava-web-admin/perfsonar-java-web-admin-component/src/main/ java/org/perfsonar/webadmin/filters perfsonar-java-web-adm in/perfsonar-java-web-admin-component/src/main/java/org/pe rfsonar/webadmin/servlet perfsonar-java-web-admin/perfsona r-java-web-admin-component/src/main/java/org/perfsonar/web admin/servlet/util perfsonar-java-web-admin/perfsonar-java -web-admin-component/src/main/java/org/perfsonar/webadmin/ test perfsonar-java-web-admin/perfsonar-java-web-admin-com ponent/src/main/java/org/perfsonar/webadmin/util perfsonar -java-web-admin/perfsonar-java-web -admin-component/src/ma in/resources perfsonar-java-web-admin/perfsonar-java-web-a dmin-component/src/main/webapp/wa/scripts perfsonar-java-w eb-admin/perfsonar-java-web-admin-component/src/test/resou rces perfsonar-java-web-admin/perfsonar-java-web-admin-exa mpleservice


Chronological Thread 
  • From:
  • To:
  • Subject: [pS-dev] [GEANT/SA2/ps-java-services] r6371 - in trunk: nmwg-sql-converter/src/main/java/org/perfsonar /nmwg/converter nmwg-sql-converter/src/test/java/org/perfs onar/nmwg/converter parent parent/checkstyle perfsonar-bas e/annotations perfsonar-base/annotations/src/main/java/net /geant/perfsonar/annotations perfsonar-base/annotations/sr c/main/java/net/geant/perfsonar/annotations/request perfso nar-base/annotations/src/main/java/net/geant/perfsonar/ann otations/selftest perfsonar-base/apt perfsonar-base/apt/du mmyservice/net/geant/perfsonar/dummyservice perfsonar-base /apt/dummyservice/net/geant/perfsonar/dummyservice/selftes t perfsonar-base/apt/dummyservice/net/geant/perfsonar/dumm yservice/xpath perfsonar-base/apt/src/main/java/net/geant/ perfsonar/annotations perfsonar-base/apt/src/main/java/net /geant/perfsonar/annotations/ls perfsonar-base/apt/src/mai n/java/net/geant/perfsonar/annotations/request perfsonar-b ase/apt/src/main/java/net/geant/perfsonar/annotations/self test perfsonar-bas e/apt/src/main/java/net/geant/perfsonar /annotations/xpath perfsonar-base/apt/src/test/java/net/ge ant/perfsonar/annotations perfsonar-base/apt/src/test/java /net/geant/perfsonar/annotations/selftest perfsonar-base/a pt/src/test/java/net/geant/perfsonar/annotations/selftest/ compiler perfsonar-base/base perfsonar-base/base/src/main/ java/net/geant/perfsonar perfsonar-base/base/src/main/java /net/geant/perfsonar/base perfsonar-base/base/src/main/jav a/net/geant/perfsonar/response perfsonar-base/base/src/mai n/java/net/geant/perfsonar/selftest perfsonar-base/base/sr c/main/resources/net/geant/perfsonar/response perfsonar-ba se/base/src/test/java/net/geant/perfsonar perfsonar-base/b ase/src/test/java/net/geant/perfsonar/configuration perfso nar-base/base/src/test/java/net/geant/perfsonar/helpers pe rfsonar-base/base/src/test/java/net/geant/perfsonar/mp/ssh telnet perfsonar-base/ls perfsonar-base/ls/src/main/java/n et/geant/perfsonar/ls perfsonar-base/ls/src/test/java/net/ geant/perfsonar/ls per fsonar-base/ls/src/test/resources/n et/geant/perfsonar/mp/sshtelnet perfsonar-base/messaging p erfsonar-base/messaging/src/main/java/net/geant/perfsonar/ messaging perfsonar-base/messaging/src/main/java/net/geant /perfsonar/templates perfsonar-base/messaging/src/test/gro ovy/net/geant/perfsonar/templates perfsonar-base/messaging /src/test/java/net/geant/perfsonar/messaging perfsonar-bas e/messaging/src/test/java/net/geant/perfsonar/mp/sshtelnet perfsonar-base/messaging/src/test/java/net/geant/perfsona r/templates perfsonar-base/messaging-test-data perfsonar-b ase/messaging-test-data/src/main/java/net/geant/perfsonar/ messaging/data perfsonar-base/sample-service perfsonar-bas e/sample-service/src/main/java/net/geant/perfsonar/mp/ssht elnet perfsonar-base/sample-service/src/main/resources per fsonar-base/sample-service/src/main/resources/net/geant/pe rfsonar/mp/sshtelnet perfsonar-base/sample-service/src/tes t/java/net/geant/perfsonar/mp/sshtelnet perfsonar-java-rrd -ma-SQL_backend/src/main/j ava/org/perfsonar/service/tem p perfsonar-java-rrd-ma-SQL_backend/src/main/resources/p erfsonar/conf perfsonar-java-rrd-ma-base3 perfsonar-java-r rd-ma-base3/src/main perfsonar-java-rrd-ma-base3/src/test/ java/net/geant/perfsonar/ma/rrd perfsonar-java-web-admin p erfsonar-java-web-admin/perfsonar-java-web-admin-component perfsonar-java-web-admin/perfsonar-java-web-admin-compone nt/src/main/java/org/perfsonar/webadmin/config perfsonar-j ava-web-admin/perfsonar-java-web-admin-component/src/main/ java/org/perfsonar/webadmin/filters perfsonar-java-web-adm in/perfsonar-java-web-admin-component/src/main/java/org/pe rfsonar/webadmin/servlet perfsonar-java-web-admin/perfsona r-java-web-admin-component/src/main/java/org/perfsonar/web admin/servlet/util perfsonar-java-web-admin/perfsonar-java -web-admin-component/src/main/java/org/perfsonar/webadmin/ test perfsonar-java-web-admin/perfsonar-java-web-admin-com ponent/src/main/java/org/perfsonar/webadmin/util perfsonar -java-web-admin/perfsonar-java-web -admin-component/src/ma in/resources perfsonar-java-web-admin/perfsonar-java-web-a dmin-component/src/main/webapp/wa/scripts perfsonar-java-w eb-admin/perfsonar-java-web-admin-component/src/test/resou rces perfsonar-java-web-admin/perfsonar-java-web-admin-exa mpleservice
  • Date: Wed, 8 May 2013 21:41:45 +0100 (BST)
  • Authentication-results: sfpop-ironport04.merit.edu; dkim=neutral (message not signed) header.i=none

Author: dante.delvaux
Date: 2013-05-08 21:41:45 +0100 (Wed, 08 May 2013)
New Revision: 6371

Added:
trunk/perfsonar-base/sample-service/logs/
trunk/perfsonar-java-rrd-ma-base3/src/main/webapp/
Modified:

trunk/nmwg-sql-converter/src/main/java/org/perfsonar/nmwg/converter/Main.java

trunk/nmwg-sql-converter/src/test/java/org/perfsonar/nmwg/converter/OnePairConverterTest.java

trunk/nmwg-sql-converter/src/test/java/org/perfsonar/nmwg/converter/TwoPairsConverterTest.java
trunk/parent/checkstyle/checkstyle.xml
trunk/parent/pom.xml
trunk/perfsonar-base/annotations/
trunk/perfsonar-base/annotations/pom.xml

trunk/perfsonar-base/annotations/src/main/java/net/geant/perfsonar/annotations/Namespace.java

trunk/perfsonar-base/annotations/src/main/java/net/geant/perfsonar/annotations/XPath.java

trunk/perfsonar-base/annotations/src/main/java/net/geant/perfsonar/annotations/XPaths.java

trunk/perfsonar-base/annotations/src/main/java/net/geant/perfsonar/annotations/package-info.java

trunk/perfsonar-base/annotations/src/main/java/net/geant/perfsonar/annotations/request/package-info.java

trunk/perfsonar-base/annotations/src/main/java/net/geant/perfsonar/annotations/selftest/SelfTest.java

trunk/perfsonar-base/annotations/src/main/java/net/geant/perfsonar/annotations/selftest/SelfTestData.java

trunk/perfsonar-base/annotations/src/main/java/net/geant/perfsonar/annotations/selftest/package-info.java
trunk/perfsonar-base/apt/

trunk/perfsonar-base/apt/dummyservice/net/geant/perfsonar/dummyservice/ServiceController.java

trunk/perfsonar-base/apt/dummyservice/net/geant/perfsonar/dummyservice/selftest/InvalidSelfTests.java

trunk/perfsonar-base/apt/dummyservice/net/geant/perfsonar/dummyservice/selftest/ValidSelfTests.java

trunk/perfsonar-base/apt/dummyservice/net/geant/perfsonar/dummyservice/xpath/InvalidXPaths.java
trunk/perfsonar-base/apt/pom.xml

trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/XPath.java

trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/XPaths.java

trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/ls/LookupServiceRegisterProcessor.java

trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/ls/TemplateEngine.java

trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/request/RequestProcessor.java

trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/request/TemplateEngine.java

trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/selftest/AbstractClassChecker.java

trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/selftest/BaseElementVisitor.java

trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/selftest/BaseMethodElementVisitor.java

trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/selftest/ReturnTypeVisitor.java

trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/selftest/SelfTestCollector.java

trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/selftest/SelfTestDataCollector.java

trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/selftest/SelfTestProcessor.java

trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/selftest/SelfTestProcessorListener.java

trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/selftest/SelfTestProcessorListenerImpl.java

trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/selftest/TemplateEngine.java

trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/xpath/EnvelopedXPath.java

trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/xpath/IdentifierValidator.java

trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/xpath/TemplateEngine.java

trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/xpath/XPathProcessor.java

trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/xpath/XPathValidator.java

trunk/perfsonar-base/apt/src/test/java/net/geant/perfsonar/annotations/LookupServiceRegisterProcessorTest.java

trunk/perfsonar-base/apt/src/test/java/net/geant/perfsonar/annotations/RequestProcessorTest.java

trunk/perfsonar-base/apt/src/test/java/net/geant/perfsonar/annotations/XPathProcessorTest.java

trunk/perfsonar-base/apt/src/test/java/net/geant/perfsonar/annotations/selftest/SelfTestLoggerHelper.java

trunk/perfsonar-base/apt/src/test/java/net/geant/perfsonar/annotations/selftest/SelfTestProcessorTest.java

trunk/perfsonar-base/apt/src/test/java/net/geant/perfsonar/annotations/selftest/compiler/BinaryClassLoader.java

trunk/perfsonar-base/apt/src/test/java/net/geant/perfsonar/annotations/selftest/compiler/CompilerHelper.java

trunk/perfsonar-base/apt/src/test/java/net/geant/perfsonar/annotations/selftest/compiler/DiagnosticImpl.java

trunk/perfsonar-base/apt/src/test/java/net/geant/perfsonar/annotations/selftest/compiler/Diagnostics.java
trunk/perfsonar-base/base/

trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/Configuration.java

trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/HandlerConfiguration.java
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/Logger.java

trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/NMWGMessage.java
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/PerfSONAR.java

trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/ServiceType.java

trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/base/Scheduler.java

trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/response/EchoRequestHandler.java

trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/response/EchoResponse.java

trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/response/SelfTestLoggerImpl.java

trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/response/SelfTestResponse.java

trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/selftest/ParameterizedSelfTestTask.java

trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/selftest/SelfTest.java

trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/selftest/SelfTestListener.java

trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/selftest/SelfTestLogger.java

trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/selftest/SelfTestRunner.java

trunk/perfsonar-base/base/src/main/resources/net/geant/perfsonar/response/EchoResponse.template

trunk/perfsonar-base/base/src/main/resources/net/geant/perfsonar/response/SelfTest_footer.template
trunk/perfsonar-base/base/src/test/java/net/geant/perfsonar/Handlers.java

trunk/perfsonar-base/base/src/test/java/net/geant/perfsonar/PerfSONARTest.java

trunk/perfsonar-base/base/src/test/java/net/geant/perfsonar/SchedulerTest.java

trunk/perfsonar-base/base/src/test/java/net/geant/perfsonar/configuration/ConfigurationTest.java

trunk/perfsonar-base/base/src/test/java/net/geant/perfsonar/configuration/SampleTests.java

trunk/perfsonar-base/base/src/test/java/net/geant/perfsonar/configuration/SelfTestsTest.java

trunk/perfsonar-base/base/src/test/java/net/geant/perfsonar/helpers/PerfSONARClient.java

trunk/perfsonar-base/base/src/test/java/net/geant/perfsonar/helpers/PerfSONARServiceClient.java

trunk/perfsonar-base/base/src/test/java/net/geant/perfsonar/helpers/Response.java

trunk/perfsonar-base/base/src/test/java/net/geant/perfsonar/mp/sshtelnet/ServiceController.java
trunk/perfsonar-base/ls/

trunk/perfsonar-base/ls/src/main/java/net/geant/perfsonar/ls/LSRegistrationTask.java

trunk/perfsonar-base/ls/src/test/java/net/geant/perfsonar/ls/LSEnabledService.java

trunk/perfsonar-base/ls/src/test/java/net/geant/perfsonar/ls/LSRegisterTest.java

trunk/perfsonar-base/ls/src/test/java/net/geant/perfsonar/ls/LSRegisterTestBase.java

trunk/perfsonar-base/ls/src/test/java/net/geant/perfsonar/ls/MockLSService.java

trunk/perfsonar-base/ls/src/test/resources/net/geant/perfsonar/mp/sshtelnet/LSRegister.template
trunk/perfsonar-base/messaging-test-data/
trunk/perfsonar-base/messaging-test-data/pom.xml

trunk/perfsonar-base/messaging-test-data/src/main/java/net/geant/perfsonar/messaging/data/Dummy.java
trunk/perfsonar-base/messaging/

trunk/perfsonar-base/messaging/src/main/java/net/geant/perfsonar/messaging/DeserializationException.java

trunk/perfsonar-base/messaging/src/main/java/net/geant/perfsonar/messaging/Helper.java

trunk/perfsonar-base/messaging/src/main/java/net/geant/perfsonar/messaging/InMemoryInstancesListener.java

trunk/perfsonar-base/messaging/src/main/java/net/geant/perfsonar/messaging/Method.java

trunk/perfsonar-base/messaging/src/main/java/net/geant/perfsonar/messaging/ReferenceInterceptor.java

trunk/perfsonar-base/messaging/src/main/java/net/geant/perfsonar/messaging/SelfTestResult.java

trunk/perfsonar-base/messaging/src/main/java/net/geant/perfsonar/messaging/XPathConfiguration.java

trunk/perfsonar-base/messaging/src/main/java/net/geant/perfsonar/messaging/XPathDeserializer.java

trunk/perfsonar-base/messaging/src/main/java/net/geant/perfsonar/templates/TemplateEngine.java

trunk/perfsonar-base/messaging/src/test/groovy/net/geant/perfsonar/templates/NMWG.groovy

trunk/perfsonar-base/messaging/src/test/java/net/geant/perfsonar/messaging/InvalidXPathsTest.java

trunk/perfsonar-base/messaging/src/test/java/net/geant/perfsonar/messaging/MethodOnObjectTest.java

trunk/perfsonar-base/messaging/src/test/java/net/geant/perfsonar/messaging/MethodTest.java

trunk/perfsonar-base/messaging/src/test/java/net/geant/perfsonar/messaging/StaticMethodTest.java

trunk/perfsonar-base/messaging/src/test/java/net/geant/perfsonar/messaging/XMLDogTest.java

trunk/perfsonar-base/messaging/src/test/java/net/geant/perfsonar/messaging/XPathDeserializerTest.java

trunk/perfsonar-base/messaging/src/test/java/net/geant/perfsonar/mp/sshtelnet/Command.java

trunk/perfsonar-base/messaging/src/test/java/net/geant/perfsonar/mp/sshtelnet/Router.java

trunk/perfsonar-base/messaging/src/test/java/net/geant/perfsonar/mp/sshtelnet/RouterReference.java

trunk/perfsonar-base/messaging/src/test/java/net/geant/perfsonar/templates/TemplateEngineTest.java
trunk/perfsonar-base/sample-service/

trunk/perfsonar-base/sample-service/src/main/java/net/geant/perfsonar/mp/sshtelnet/Command.java

trunk/perfsonar-base/sample-service/src/main/java/net/geant/perfsonar/mp/sshtelnet/ConfigurationFileChecker.java

trunk/perfsonar-base/sample-service/src/main/java/net/geant/perfsonar/mp/sshtelnet/Router.java

trunk/perfsonar-base/sample-service/src/main/java/net/geant/perfsonar/mp/sshtelnet/RouterReference.java

trunk/perfsonar-base/sample-service/src/main/java/net/geant/perfsonar/mp/sshtelnet/SSHTelnetMPService.java

trunk/perfsonar-base/sample-service/src/main/java/net/geant/perfsonar/mp/sshtelnet/ServiceController.java
trunk/perfsonar-base/sample-service/src/main/resources/configuration.xml

trunk/perfsonar-base/sample-service/src/main/resources/net/geant/perfsonar/mp/sshtelnet/LSRegister.template

trunk/perfsonar-base/sample-service/src/main/resources/net/geant/perfsonar/mp/sshtelnet/MetadataKeyResponse.template

trunk/perfsonar-base/sample-service/src/main/resources/net/geant/perfsonar/mp/sshtelnet/SetupDataResponse.template

trunk/perfsonar-base/sample-service/src/test/java/net/geant/perfsonar/mp/sshtelnet/ConfigurationFileCheckerTest.java

trunk/perfsonar-base/sample-service/src/test/java/net/geant/perfsonar/mp/sshtelnet/LSRegisterTest.java

trunk/perfsonar-base/sample-service/src/test/java/net/geant/perfsonar/mp/sshtelnet/SSHTelnetMPTest.java

trunk/perfsonar-java-rrd-ma-SQL_backend/src/main/java/org/perfsonar/service/temp/FetchData.java

trunk/perfsonar-java-rrd-ma-SQL_backend/src/main/resources/perfsonar/conf/rrdma_db.sql

trunk/perfsonar-java-rrd-ma-SQL_backend/src/main/resources/perfsonar/conf/test_rrdma_db.sql
trunk/perfsonar-java-rrd-ma-base3/
trunk/perfsonar-java-rrd-ma-base3/pom.xml

trunk/perfsonar-java-rrd-ma-base3/src/test/java/net/geant/perfsonar/ma/rrd/RRDMATest.java
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/

trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/config/HTMLGenerator.java

trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/config/ObjectMap.java

trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/filters/AuthFilter.java

trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/servlet/BasicServlet.java

trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/servlet/ConfigurationServlet.java

trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/servlet/LoginServlet.java

trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/servlet/SelfTestServlet.java

trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/servlet/util/ConfigurationServletHelper.java

trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/test/SOAPClient.java

trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/test/SOAPClientException.java

trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/util/HTMLUtil.java

trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/util/NSContext.java

trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/util/Tuple.java

trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/util/WAXMLReader.java

trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/util/WAXMLWriter.java

trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/util/XMLUtil.java

trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/resources/wa.xsd

trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/webapp/wa/scripts/Service_Admin.js

trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/webapp/wa/scripts/wz_tooltip.js

trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/test/resources/soapResponse1.xml

trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/test/resources/soapResponse2.xml
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-exampleservice/
trunk/perfsonar-java-web-admin/pom.xml
Log:


Modified:
trunk/nmwg-sql-converter/src/main/java/org/perfsonar/nmwg/converter/Main.java
===================================================================
---
trunk/nmwg-sql-converter/src/main/java/org/perfsonar/nmwg/converter/Main.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/nmwg-sql-converter/src/main/java/org/perfsonar/nmwg/converter/Main.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -1,16 +1,7 @@
package org.perfsonar.nmwg.converter;

import java.io.File;
-import java.util.Iterator;
-import java.util.List;

-import javax.xml.transform.TransformerConfigurationException;
-import javax.xml.transform.TransformerException;
-
-import org.perfsonar.nmwg.converter.helper.Interfaces;
-import org.perfsonar.nmwg.converter.parser.DataParser;
-import org.perfsonar.nmwg.converter.parser.MetadataParser;
-
public class Main {

static public void main(String[] arg) {

Modified:
trunk/nmwg-sql-converter/src/test/java/org/perfsonar/nmwg/converter/OnePairConverterTest.java
===================================================================
---
trunk/nmwg-sql-converter/src/test/java/org/perfsonar/nmwg/converter/OnePairConverterTest.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/nmwg-sql-converter/src/test/java/org/perfsonar/nmwg/converter/OnePairConverterTest.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -156,10 +156,7 @@

@Test
public void shouldIgnoreDataWithWrongMetadataIdRef(){
- //given
- InterfacesHelper ih = new InterfacesHelper();
- Interfaces intf = ih.createInterfce("meta1", "data1");
-
+ //parse a file with wrong MetadataIdRef
URL url = getClass().getClassLoader().getResource(TEST2_FILE);
Converter converter = new Converter();


Modified:
trunk/nmwg-sql-converter/src/test/java/org/perfsonar/nmwg/converter/TwoPairsConverterTest.java
===================================================================
---
trunk/nmwg-sql-converter/src/test/java/org/perfsonar/nmwg/converter/TwoPairsConverterTest.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/nmwg-sql-converter/src/test/java/org/perfsonar/nmwg/converter/TwoPairsConverterTest.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -7,7 +7,6 @@
import java.util.List;

import org.junit.Test;
-import static org.junit.Assert.assertEquals;

import org.perfsonar.nmwg.converter.helper.Interfaces;
import org.perfsonar.nmwg.converter.helper.InterfacesHelper;

Modified: trunk/parent/checkstyle/checkstyle.xml
===================================================================
--- trunk/parent/checkstyle/checkstyle.xml 2013-05-07 14:18:22 UTC (rev
6370)
+++ trunk/parent/checkstyle/checkstyle.xml 2013-05-08 20:41:45 UTC (rev
6371)
@@ -1,186 +1,94 @@
-<?xml version="1.0"?>
-<!DOCTYPE module PUBLIC
- "-//Puppy Crawl//DTD Check Configuration 1.3//EN"
- "http://www.puppycrawl.com/dtds/configuration_1_3.dtd";>
+<?xml version="1.0" encoding="UTF-8"?>
+<!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.
+ This configuration file was written by the eclipse-cs plugin
configuration editor
-->
-
<!--
-
- 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.
-
+ Checkstyle-Configuration: perfSONAR checkstyle config
+ Description:
+Global perfSONAR checkstyle configuration.
-->
-
<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 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"/>
-
- <!-- 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."/>
+ <property name="severity" value="warning"/>
+ <module name="TreeWalker">
+ <module name="JavadocStyle">
+ <property name="checkFirstSentence" value="false"/>
</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"/>
-
-
- <!-- Checks for Size Violations. -->
- <!-- See http://checkstyle.sf.net/config_sizes.html -->
- <module name="LineLength">
- <!-- 80 is waaaayyyyy too short on current screens standards, HD
you know? -->
- <property name="max" value="150"/>
- </module>
- <module name="MethodLength"/>
- <module name="ParameterNumber"/>
-
-
- <!-- 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"/>
- <!-- I'm not interested in defining constants for every other
number that appears in my code -->
- <!--<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="FinalClass"/>
- <module name="HideUtilityClassConstructor"/>
- <module name="InterfaceIsType"/>
- <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="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"/>
+ <module name="AvoidStarImport"/>
+ <module name="IllegalImport"/>
+ <module name="RedundantImport"/>
+ <module name="UnusedImports"/>
+ <module name="LineLength">
+ <property name="max" value="150"/>
</module>
-
+ <module name="MethodLength"/>
+ <module name="ParameterNumber"/>
+ <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"/>
+ <module name="ModifierOrder"/>
+ <module name="RedundantModifier"/>
+ <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"/>
+ <module name="EmptyStatement"/>
+ <module name="EqualsHashCode"/>
+ <module name="HiddenField">
+ <property name="tokens" value="VARIABLE_DEF"/>
+ </module>
+ <module name="IllegalInstantiation"/>
+ <module name="InnerAssignment"/>
+ <module name="MissingSwitchDefault"/>
+ <module name="RedundantThrows">
+ <property name="suppressLoadErrors" value="true"/>
+ </module>
+ <module name="SimplifyBooleanExpression"/>
+ <module name="SimplifyBooleanReturn"/>
+ <module name="FinalClass"/>
+ <module name="HideUtilityClassConstructor"/>
+ <module name="InterfaceIsType"/>
+ <module name="VisibilityModifier">
+ <property name="protectedAllowed" value="true"/>
+ </module>
+ <module name="ArrayTypeStyle"/>
+ <module name="UpperEll"/>
+ <module name="IllegalCatch"/>
+ <module name="IllegalThrows"/>
+ <module name="ModifiedControlVariable"/>
+ <module name="PackageDeclaration"/>
+ <module name="ParameterAssignment"/>
+ <module name="StringLiteralEquality"/>
+ <module name="SuperClone"/>
+ <module name="SuperFinalize"/>
+ <module name="UnnecessaryParentheses"/>
+ <module name="LeftCurly"/>
+ </module>
+ <module name="NewlineAtEndOfFile"/>
+ <module name="Translation"/>
+ <module name="FileLength"/>
+ <module name="FileTabCharacter"/>
+ <module name="RegexpSingleline">
+ <property name="format" value="[^[:space:]\*]+\s+$"/>
+ <property name="message" value="Line has trailing spaces."/>
+ </module>
</module>

Modified: trunk/parent/pom.xml
===================================================================
--- trunk/parent/pom.xml 2013-05-07 14:18:22 UTC (rev 6370)
+++ trunk/parent/pom.xml 2013-05-08 20:41:45 UTC (rev 6371)
@@ -19,6 +19,15 @@

<name>perfSONAR Java Services parent POM</name>
<url>http://perfsonar.geant.net/</url>
+ <description>This is the parent POM of all perfSONAR artifacts, all
should inherit of its settings.
+
+To run a complete build with tests and packaging, you may need to increase
the mvn allocated memory with something similar to:
+ MAVEN_OPTS=&quot;-XX:MaxPermSize=256m&quot;
+ export MAVEN_OPTS
+
+See the BUILDING.txt and RELEASES.txt files for more details.
+ </description>
+
<licenses>
<license>
<name>GÉANT Standard Open Source Software Outward License</name>
@@ -159,6 +168,54 @@
<generateBackupPoms>false</generateBackupPoms>
</configuration>
</plugin>
+
+ <!-- QA plugins that must be active for all submodules -->
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <version>2.10</version>
+ <executions>
+ <execution>
+ <id>check-style</id>
+ <goals>
+ <goal>check</goal>
+ </goals>
+ <phase>validate</phase>
+ <configuration>
+ <consoleOutput>true</consoleOutput>
+
<logViolationsToConsole>true</logViolationsToConsole>
+ <failsOnError>true</failsOnError>
+ <failOnViolation>true</failOnViolation>
+
<configLocation>${user.dir}/parent/checkstyle/checkstyle.xml</configLocation>
+
<includeTestSourceDirectory>true</includeTestSourceDirectory>
+
<excludes>${basedir}/target/generated-sources/**/*.java</excludes>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-pmd-plugin</artifactId>
+ <version>3.0.1</version>
+ <executions>
+ <execution>
+ <id>check-pmd</id>
+ <goals>
+ <goal>check</goal>
+ </goals>
+ <phase>validate</phase>
+ <configuration>
+ <linkXRef>false</linkXRef>
+
<sourceEncoding>${project.build.sourceEncoding}</sourceEncoding>
+ <minimumTokens>100</minimumTokens>
+
<targetJdk>${maven-compiler-plugin.source}</targetJdk>
+ <rulesets>java-basic java-imports
java-unusedcode</rulesets>
+ <verbose>true</verbose>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
</plugins>

<pluginManagement>
@@ -319,50 +376,6 @@
<!-- QA and reporting plugins -->
<!-- TODO: Most of these plugins should be moved to the
build section to be active in all submodules -->
<plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-checkstyle-plugin</artifactId>
- <version>2.10</version>
- <executions>
- <execution>
- <id>check-style</id>
- <goals>
- <goal>check</goal>
- </goals>
- <phase>validate</phase>
- <configuration>
- <consoleOutput>true</consoleOutput>
-
<logViolationsToConsole>true</logViolationsToConsole>
- <failsOnError>true</failsOnError>
- <failOnViolation>true</failOnViolation>
-
<configLocation>${basedir}/../parent/checkstyle/checkstyle.xml</configLocation>
- </configuration>
- </execution>
- </executions>
- </plugin>
-
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-pmd-plugin</artifactId>
- <version>3.0.1</version>
- <executions>
- <execution>
- <id>check-pmd</id>
- <goals>
- <goal>check</goal>
- </goals>
- <phase>validate</phase>
- <configuration>
- <linkXRef>false</linkXRef>
-
<sourceEncoding>${project.build.sourceEncoding}</sourceEncoding>
- <minimumTokens>100</minimumTokens>
-
<targetJdk>${maven-compiler-plugin.source}</targetJdk>
- <rulesets>java-basic java-imports
java-unusedcode</rulesets>
- </configuration>
- </execution>
- </executions>
- </plugin>
-
- <plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>findbugs-maven-plugin</artifactId>
<version>2.5.2</version>


Property changes on: trunk/perfsonar-base/annotations
___________________________________________________________________
Modified: svn:ignore
- .settings
.classpath
.project

target

+ .settings
.classpath
.project

target

.pmd

.pmdruleset


Modified: trunk/perfsonar-base/annotations/pom.xml
===================================================================
--- trunk/perfsonar-base/annotations/pom.xml 2013-05-07 14:18:22 UTC (rev
6370)
+++ trunk/perfsonar-base/annotations/pom.xml 2013-05-08 20:41:45 UTC (rev
6371)
@@ -6,7 +6,7 @@
<parent>
<groupId>net.geant.perfsonar</groupId>
<artifactId>parent</artifactId>
- <version>1.0.2</version>
+ <version>1.0.3-SNAPSHOT</version>
<relativePath>../../parent/</relativePath>
</parent>


Modified:
trunk/perfsonar-base/annotations/src/main/java/net/geant/perfsonar/annotations/Namespace.java
===================================================================
---
trunk/perfsonar-base/annotations/src/main/java/net/geant/perfsonar/annotations/Namespace.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/annotations/src/main/java/net/geant/perfsonar/annotations/Namespace.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -10,7 +10,7 @@
*
* @author <a
href="mailto:">Blazej
Pietrzak</a>
*/
-@Target({ElementType.FIELD,
ElementType.TYPE})
+@Target({ElementType.FIELD,
ElementType.TYPE })
@Retention(RetentionPolicy.SOURCE)
public @interface Namespace {
String prefix() default "";

Modified:
trunk/perfsonar-base/annotations/src/main/java/net/geant/perfsonar/annotations/XPath.java
===================================================================
---
trunk/perfsonar-base/annotations/src/main/java/net/geant/perfsonar/annotations/XPath.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/annotations/src/main/java/net/geant/perfsonar/annotations/XPath.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -18,5 +18,5 @@
@Retention(RetentionPolicy.SOURCE)
public @interface XPath {
String xpath();
- Namespace[] namespaces() default {};
+ Namespace[] namespaces() default { };
}

Modified:
trunk/perfsonar-base/annotations/src/main/java/net/geant/perfsonar/annotations/XPaths.java
===================================================================
---
trunk/perfsonar-base/annotations/src/main/java/net/geant/perfsonar/annotations/XPaths.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/annotations/src/main/java/net/geant/perfsonar/annotations/XPaths.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -7,12 +7,12 @@

/**
* Aggregates multiple xpaths for the given method.
- *
+ *
* @author <a
href="mailto:">Blazej
Pietrzak</a>
- *
+ *
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface XPaths {
- XPath[] value();
+ XPath[] value();
}

Modified:
trunk/perfsonar-base/annotations/src/main/java/net/geant/perfsonar/annotations/package-info.java
===================================================================
---
trunk/perfsonar-base/annotations/src/main/java/net/geant/perfsonar/annotations/package-info.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/annotations/src/main/java/net/geant/perfsonar/annotations/package-info.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -2,4 +2,4 @@
* This package contains annotations used for deserialization
* of the object model and for MetadataKey, SetupData messages.
*/
-package net.geant.perfsonar.annotations;
\ No newline at end of file
+package net.geant.perfsonar.annotations;

Modified:
trunk/perfsonar-base/annotations/src/main/java/net/geant/perfsonar/annotations/request/package-info.java
===================================================================
---
trunk/perfsonar-base/annotations/src/main/java/net/geant/perfsonar/annotations/request/package-info.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/annotations/src/main/java/net/geant/perfsonar/annotations/request/package-info.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -1,4 +1,4 @@
/**
* This package contains annotations used for denoting methods that handle
requests from users.
*/
-package net.geant.perfsonar.annotations.request;
\ No newline at end of file
+package net.geant.perfsonar.annotations.request;

Modified:
trunk/perfsonar-base/annotations/src/main/java/net/geant/perfsonar/annotations/selftest/SelfTest.java
===================================================================
---
trunk/perfsonar-base/annotations/src/main/java/net/geant/perfsonar/annotations/selftest/SelfTest.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/annotations/src/main/java/net/geant/perfsonar/annotations/selftest/SelfTest.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -6,63 +6,62 @@
import java.lang.annotation.Target;

/**
- * Annotates methods that process Self Test requests.
- * Self test is described with the unique name, success message, and failure
message.
- * Success message is used in the response when the test passed, while
failure is
- * used for latter case. Name and success message are explictly declared as
annotation
+ * Annotates methods that process Self Test requests. Self test is described
+ * with the unique name, success message, and failure message. Success
message
+ * is used in the response when the test passed, while failure is used for
+ * latter case. Name and success message are explicitly declared as
annotation
* properties, while the failure message is taken from the exception's
message.
*
* For instance a method that checks whether database is running could look
like
- * the following snippet:
- * <code>
+ * the following snippet: <code>
* %SelfTest(name="database", successMessage = "Database is present.")<br/>
- * public List<Dictionary> listDictionaries() {<br/>
- * return Dictionary.listDictionaries(factory);<br/>
- * }<br/>
+ * public List<Dictionary> listDictionaries() {<br/>
+ * return Dictionary.listDictionaries(factory);<br/>
+ * }<br/>
* </code>
*
- * The database test is identified with the unique name "database". When it
passes
- * "Database is present" message is provided in the response. When it fails
- * exception's message will be returned in the response.
+ * The database test is identified with the unique name "database". When it
+ * passes "Database is present" message is provided in the response. When it
+ * fails exception's message will be returned in the response.
*
- * Self test methods may be optionally parameterized. It is necessary
- * when the number of tests depends on dynamic behavior of the system e.g.
- * the result of the query, or service configuration.
- * Parameterized self-tests are methods with argument as a parameter.
- * There must be self-test-data method present that provides parameter
values.
- * It must be of type java.util.List<T>, where T is the type of the argument.
- *
- * perfSONAR base provides two builtin properties:
- * ${index} - unique identifier of the self-test run (integer from 0..*)
- * ${arg} - argument of the parameterized self-test
+ * Self test methods may be optionally parameterised. It is necessary when
the
+ * number of tests depends on dynamic behaviour of the system e.g. the
result of
+ * the query, or service configuration. Parameterised self-tests are methods
+ * with argument as a parameter. There must be self-test-data method present
+ * that provides parameter values. It must be of type java.util.List<T>,
where T
+ * is the type of the argument.
*
- * The following example shows the parameterized self test.
- * There is a parameter of Dictionary type as the test parameter.
- * <code><br/>
- * %SelfTest(</br>
- * name="translation${index}",<br/>
- * successMessage = "${arg} dictionary works correctly.")<br/>
- * public void checkTranslation(Dictionary dictionary) throws Exception
{<br/>
- * if (!dictionary.translate(word,
factory).equals(translated))<br/>
- * throw new Exception("Invalid translation.");<br/>
- * }<br/>
+ * perfSONAR base provides two built in properties: ${index} - unique
identifier
+ * of the self-test run (integer from 0..*) ${arg} - argument of the
+ * Parameterised self-test
+ *
+ * The following example shows the parameterised self test. There is a
parameter
+ * of Dictionary type as the test parameter. <code><br/>
+ * %SelfTest(<br/>
+ * name="translation${index}",<br/>
+ * successMessage = "${arg} dictionary works correctly.")<br/>
+ * public void checkTranslation(Dictionary dictionary) throws Exception
{<br/>
+ * if (!dictionary.translate(word, factory).equals(translated))<br/>
+ * throw new Exception("Invalid translation.");<br/>
+ * }<br/>
* <br/>
* %SelfTestData<br/>
- * public List<Dictionary> listDictionaries() {<br/>
- * return Dictionary.listDictionaries(factory);<br/>
- * }<br/>
+ * public List<Dictionary> listDictionaries() {<br/>
+ * return Dictionary.listDictionaries(factory);<br/>
+ * }<br/>
* </code>
- *
- * The method listDictionaries provides test data for checkTranslation
method.
- * checkTranslation method accepts the arguments of type Dictionary, so
listDictionaries
- * must return the type java.util.List<Dictionary>.
*
+ * The method listDictionaries provides test data for checkTranslation
method.
+ * checkTranslation method accepts the arguments of type Dictionary, so
+ * listDictionaries must return the type java.util.List<Dictionary>.
+ *
* @author <a
href="mailto:">Blazej
Pietrzak</a>
- *
+ *
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface SelfTest {
- String name();
- String successMessage();
+ String name();
+
+ String successMessage();
}

Modified:
trunk/perfsonar-base/annotations/src/main/java/net/geant/perfsonar/annotations/selftest/SelfTestData.java
===================================================================
---
trunk/perfsonar-base/annotations/src/main/java/net/geant/perfsonar/annotations/selftest/SelfTestData.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/annotations/src/main/java/net/geant/perfsonar/annotations/selftest/SelfTestData.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -8,15 +8,15 @@
/**
* Annotates a method as a self test data provider.
*
- * Self test methods may be optionally parameterized. It is necessary
- * when the number of tests depends on dynamic behavior of the system e.g.
- * the result of the query, or service configuration.
- * Parameterized self-tests are methods with argument as a parameter.
- * There must be self-test-data method present that provides parameter
values.
- * It must be of type java.util.List<T>, where T is the type of the self
test argument.
+ * Self test methods may be optionally parameterized. It is necessary when
the
+ * number of tests depends on dynamic behavior of the system e.g. the result
of
+ * the query, or service configuration. Parameterized self-tests are methods
+ * with argument as a parameter. There must be self-test-data method present
+ * that provides parameter values. It must be of type java.util.List<T>,
where T
+ * is the type of the self test argument.
*
* @author <a
href="mailto:">Blazej
Pietrzak</a>
- *
+ *
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)

Modified:
trunk/perfsonar-base/annotations/src/main/java/net/geant/perfsonar/annotations/selftest/package-info.java
===================================================================
---
trunk/perfsonar-base/annotations/src/main/java/net/geant/perfsonar/annotations/selftest/package-info.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/annotations/src/main/java/net/geant/perfsonar/annotations/selftest/package-info.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -1,4 +1,4 @@
/**
* This package contains annotations used for selftest messaging
functionality.
*/
-package net.geant.perfsonar.annotations.selftest;
\ No newline at end of file
+package net.geant.perfsonar.annotations.selftest;


Property changes on: trunk/perfsonar-base/apt
___________________________________________________________________
Modified: svn:ignore
- target

.settings

.classpath

.project

+ target

.settings

.classpath

.project

.pmd

.pmdruleset

.checkstyle


Modified:
trunk/perfsonar-base/apt/dummyservice/net/geant/perfsonar/dummyservice/ServiceController.java
===================================================================
---
trunk/perfsonar-base/apt/dummyservice/net/geant/perfsonar/dummyservice/ServiceController.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/apt/dummyservice/net/geant/perfsonar/dummyservice/ServiceController.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -1,7 +1,6 @@
package net.geant.perfsonar.dummyservice;

import java.io.IOException;
-import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.List;

Modified:
trunk/perfsonar-base/apt/dummyservice/net/geant/perfsonar/dummyservice/selftest/InvalidSelfTests.java
===================================================================
---
trunk/perfsonar-base/apt/dummyservice/net/geant/perfsonar/dummyservice/selftest/InvalidSelfTests.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/apt/dummyservice/net/geant/perfsonar/dummyservice/selftest/InvalidSelfTests.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -23,7 +23,7 @@

@SelfTest(name = "private static",
successMessage = "Only public non-static methods
are allowed.")
- private static void error() {
+ private static void error() { //NOPMD
System.err.println("Second selftest.");
}


Modified:
trunk/perfsonar-base/apt/dummyservice/net/geant/perfsonar/dummyservice/selftest/ValidSelfTests.java
===================================================================
---
trunk/perfsonar-base/apt/dummyservice/net/geant/perfsonar/dummyservice/selftest/ValidSelfTests.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/apt/dummyservice/net/geant/perfsonar/dummyservice/selftest/ValidSelfTests.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -3,7 +3,6 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
-import java.util.List;

import net.geant.perfsonar.annotations.selftest.*;


Modified:
trunk/perfsonar-base/apt/dummyservice/net/geant/perfsonar/dummyservice/xpath/InvalidXPaths.java
===================================================================
---
trunk/perfsonar-base/apt/dummyservice/net/geant/perfsonar/dummyservice/xpath/InvalidXPaths.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/apt/dummyservice/net/geant/perfsonar/dummyservice/xpath/InvalidXPaths.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -1,26 +1,10 @@
package net.geant.perfsonar.dummyservice.selftest;
-import static net.geant.perfsonar.messaging.XPathDeserializer.any;
-import static net.geant.perfsonar.messaging.XPathDeserializer.whenXPath;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.fail;

-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.List;
-
-import javax.xml.xpath.XPathException;
-
-import org.junit.Test;
-import org.xml.sax.InputSource;
-
import net.geant.perfsonar.annotations.Namespace;
import net.geant.perfsonar.annotations.XPath;
import net.geant.perfsonar.annotations.selftest.*;
-import net.geant.perfsonar.messaging.DeserializationException;

public abstract class InvalidXPaths {
- private String id;

@XPath(xpath="nmwg:message/@id",

namespaces=@Namespace(prefix="nmwg",
uri="http://ggf.org/ns/nmwg/base/2.0/";))
@@ -33,6 +17,6 @@

@XPath(xpath="nmwg:message/@id",

namespaces=@Namespace(prefix="nmwg",
uri="http://ggf.org/ns/nmwg/base/2.0/";))
- private static void publicNonStaticAreAllowed(String arg) {
+ private static void publicNonStaticAreAllowed(String arg) { //NOPMD
}
}

Modified: trunk/perfsonar-base/apt/pom.xml
===================================================================
--- trunk/perfsonar-base/apt/pom.xml 2013-05-07 14:18:22 UTC (rev 6370)
+++ trunk/perfsonar-base/apt/pom.xml 2013-05-08 20:41:45 UTC (rev 6371)
@@ -42,6 +42,14 @@
<version>1.8.5</version>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-log4j12</artifactId>
+ </dependency>
<dependency>
<groupId>net.geant.perfsonar.base</groupId>
<artifactId>annotations</artifactId>

Modified:
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/XPath.java
===================================================================
---
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/XPath.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/XPath.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -3,5 +3,5 @@

public @interface XPath {
String xpath();
- Namespace[] namespaces() default {};
+ Namespace[] namespaces() default { };
}

Modified:
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/XPaths.java
===================================================================
---
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/XPaths.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/XPaths.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -7,12 +7,12 @@

/**
* Aggregates multiple xpaths for the given method.
- *
+ *
* @author <a
href="mailto:">Blazej
Pietrzak</a>
- *
+ *
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface XPaths {
- XPath[] value();
+ XPath[] value();
}

Modified:
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/ls/LookupServiceRegisterProcessor.java
===================================================================
---
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/ls/LookupServiceRegisterProcessor.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/ls/LookupServiceRegisterProcessor.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -24,90 +24,89 @@

@SupportedAnnotationTypes("net.geant.perfsonar.annotations.LookupServiceRegister")
@SupportedSourceVersion(SourceVersion.RELEASE_6)
public class LookupServiceRegisterProcessor extends AbstractProcessor {
- @Override
- public boolean process(Set<? extends TypeElement> annotations,
- RoundEnvironment roundEnv) {
+ @Override
+ public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {

- if (annotations.size() <= 0)
- return false;
+ if (annotations.size() <= 0) {
+ return false;
+ }

- final SelfTestProcessorListener reporter = new
SelfTestProcessorListenerImpl(processingEnv.getMessager());
- ExecutableElement handler = null;
+ final SelfTestProcessorListener reporter = new
SelfTestProcessorListenerImpl(processingEnv.getMessager());
+ ExecutableElement handler = null;

- for (Element method :
roundEnv.getElementsAnnotatedWith(LookupServiceRegister.class)) {
- if (isDeclarationViolated((ExecutableElement) method,
reporter))
- continue;
-
- if (handler != null) {
- reporter.error("Only one handler for Lookup
Service registration is allowed.", method);
- continue;
- }
-
- handler = (ExecutableElement) method;
- }
+ for (Element method :
roundEnv.getElementsAnnotatedWith(LookupServiceRegister.class)) {
+ if (isDeclarationViolated((ExecutableElement) method, reporter))
{
+ continue;
+ }

- Writer writer = null;
- try {
- writer = openWriter(roundEnv.getRootElements());
- new TemplateEngine().writeHandler(writer, handler);
- } catch (IOException ex) {
- reporter.error(ex.toString());
- } finally {
- if (writer != null)
- try {
- writer.close();
- } catch (IOException ex) {
- reporter.error(ex.toString());
- }
- }
+ if (handler != null) {
+ reporter.error("Only one handler for Lookup Service
registration is allowed.", method);
+ continue;
+ }

- return false;
- }
+ handler = (ExecutableElement) method;
+ }

- protected boolean isDeclarationViolated(ExecutableElement elem,
- SelfTestProcessorListener listener) {
- int errorsCount = 0;
+ Writer writer = null;
+ try {
+ writer = openWriter(roundEnv.getRootElements());
+ new TemplateEngine().writeHandler(writer, handler);
+ } catch (IOException ex) {
+ reporter.error(ex.toString());
+ } finally {
+ if (writer != null) {
+ try {
+ writer.close();
+ } catch (IOException ex) {
+ reporter.error(ex.toString());
+ }
+ }
+ }

- if (elem.getModifiers().contains(Modifier.ABSTRACT)) {
- listener.error("The method cannot be abstract", elem);
- errorsCount++;
- }
+ return false;
+ }

- if (!elem.getModifiers().contains(Modifier.PUBLIC)) {
- listener.error("The method must be public.", elem);
- errorsCount++;
- }
+ protected boolean isDeclarationViolated(ExecutableElement elem,
SelfTestProcessorListener listener) {
+ int errorsCount = 0;

- if (elem.getModifiers().contains(Modifier.STATIC)) {
- listener.error("The method cannot be static.", elem);
- errorsCount++;
- }
+ if (elem.getModifiers().contains(Modifier.ABSTRACT)) {
+ listener.error("The method cannot be abstract", elem);
+ errorsCount++;
+ }

- if (elem.getReturnType().getKind() == TypeKind.VOID) {
- listener.error("Type of the method cannot be void.",
elem);
- errorsCount++;
- }
+ if (!elem.getModifiers().contains(Modifier.PUBLIC)) {
+ listener.error("The method must be public.", elem);
+ errorsCount++;
+ }

- if (elem.getModifiers().contains(Modifier.FINAL)) {
- listener.error("The method cannot be final.", elem);
- errorsCount++;
- }
+ if (elem.getModifiers().contains(Modifier.STATIC)) {
+ listener.error("The method cannot be static.", elem);
+ errorsCount++;
+ }

- if (elem.isVarArgs() || (elem.getParameters().size() > 0)) {
- listener.error("The method cannot have any
parameters.", elem);
- errorsCount++;
- }
+ if (elem.getReturnType().getKind() == TypeKind.VOID) {
+ listener.error("Type of the method cannot be void.", elem);
+ errorsCount++;
+ }

- return (errorsCount > 0);
- }
+ if (elem.getModifiers().contains(Modifier.FINAL)) {
+ listener.error("The method cannot be final.", elem);
+ errorsCount++;
+ }

- private Writer openWriter(Set<? extends Element> elements)
- throws IOException {
- final Filer filer = processingEnv.getFiler();
- final FileObject out = filer.createSourceFile(
- "net.geant.perfsonar.LookupServiceRegister",
- elements.toArray(new Element[0]));
- return out.openWriter();
- }
+ if (elem.isVarArgs() || elem.getParameters().size() > 0) {
+ listener.error("The method cannot have any parameters.", elem);
+ errorsCount++;
+ }

+ return errorsCount > 0;
+ }
+
+ private Writer openWriter(Set<? extends Element> elements) throws
IOException {
+ final Filer filer = processingEnv.getFiler();
+ final FileObject out =
filer.createSourceFile("net.geant.perfsonar.LookupServiceRegister",
+ elements.toArray(new Element[0]));
+ return out.openWriter();
+ }
+
}

Modified:
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/ls/TemplateEngine.java
===================================================================
---
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/ls/TemplateEngine.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/ls/TemplateEngine.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -6,38 +6,40 @@
import javax.lang.model.element.ExecutableElement;

public class TemplateEngine {
- private Writer writer;
-
- private void write(String text) throws IOException {
- writer.write(text);
- }
-
- public void writeHandler(Writer writer, ExecutableElement handler)
throws IOException {
- this.writer = writer;
-
- write("package net.geant.perfsonar;\n\n");
-
- write("import static
net.geant.perfsonar.ls.LSRegistrationTask.*;\n");
- write("import static net.geant.perfsonar.Configuration.*;\n");
- write("import javax.annotation.Generated;\n");
- write("\n");
- write("@Generated(\"" + getClass().getName() + "\")\n");
- write("public class LookupServiceRegister {\n");
- write("\n");
- write(" public LookupServiceRegister() {\n");
- write(" try {\n");
- writeHandlerInvocation(handler);
- write(" } catch (Exception ex) { }\n");
- write(" }\n");
- write("}\n");
- }
+ private Writer writer;

- private void writeHandlerInvocation(ExecutableElement method) throws
IOException {
- write(" ");
- write("configure(registerToLookupService(");
- write(method.getEnclosingElement().asType().toString());
- write(".class).");
- write(method.getSimpleName().toString());
- write("());\n");
- }
+ private void write(String text) throws IOException {
+ writer.write(text);
+ }
+
+ public void writeHandler(Writer writer, ExecutableElement handler)
throws IOException {
+ this.writer = writer;
+
+ write("package net.geant.perfsonar;\n\n");
+
+ write("import static
net.geant.perfsonar.ls.LSRegistrationTask.*;\n");
+ write("import static net.geant.perfsonar.Configuration.*;\n");
+ write("import javax.annotation.Generated;\n");
+ write("\n");
+ write("@Generated(\"" + getClass().getName() + "\")\n");
+ write("public class LookupServiceRegister {\n");
+ write("\n");
+ write(" public LookupServiceRegister() {\n");
+ write(" try {\n");
+ writeHandlerInvocation(handler);
+ write(" } catch (Exception ex) { // NOPMD\n");
+ // TODO: we should add proper exception handling
+ write(" }\n");
+ write(" }\n");
+ write("}\n");
+ }
+
+ private void writeHandlerInvocation(ExecutableElement method) throws
IOException {
+ write(" ");
+ write("configure(registerToLookupService(");
+ write(method.getEnclosingElement().asType().toString());
+ write(".class).");
+ write(method.getSimpleName().toString());
+ write("());\n");
+ }
}

Modified:
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/request/RequestProcessor.java
===================================================================
---
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/request/RequestProcessor.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/request/RequestProcessor.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -26,103 +26,94 @@
@SupportedAnnotationTypes(RequestProcessor.ANNOTATION_PREFIX + ".*")
@SupportedSourceVersion(SourceVersion.RELEASE_6)
public class RequestProcessor extends AbstractProcessor {
- static final String ANNOTATION_PREFIX =
"net.geant.perfsonar.annotations.request";
+ static final String ANNOTATION_PREFIX =
"net.geant.perfsonar.annotations.request";

- @Override
- public boolean process(Set<? extends TypeElement> annotations,
- RoundEnvironment roundEnv) {
+ @Override
+ public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {

- if (annotations.size() <= 0)
- return false;
+ if (annotations.size() <= 0) {
+ return false;
+ }

- final SelfTestProcessorListener reporter = new
SelfTestProcessorListenerImpl(
- processingEnv.getMessager());
- final Map<String, ExecutableElement> handlers = new
Hashtable<String, ExecutableElement>();
+ final SelfTestProcessorListener reporter = new
SelfTestProcessorListenerImpl(processingEnv.getMessager());
+ final Map<String, ExecutableElement> handlers = new
Hashtable<String, ExecutableElement>();

- for (Element root : roundEnv.getRootElements()) {
- for (Element method : root.getEnclosedElements()) {
- for (AnnotationMirror annotation : method
- .getAnnotationMirrors())
- if (getName(annotation).startsWith(
-
RequestProcessor.ANNOTATION_PREFIX)) {
- if
(isDeclarationViolated((ExecutableElement) method,
- reporter))
- continue;
- handlers.put(
-
getName(annotation).substring(
-
RequestProcessor.ANNOTATION_PREFIX
-
.length() + 1)
-
+ "Request", (ExecutableElement) method);
- }
- }
- }
+ for (Element root : roundEnv.getRootElements()) {
+ for (Element method : root.getEnclosedElements()) {
+ for (AnnotationMirror annotation :
method.getAnnotationMirrors()) {
+ if
(getName(annotation).startsWith(RequestProcessor.ANNOTATION_PREFIX)) {
+ if (isDeclarationViolated((ExecutableElement)
method, reporter)) {
+ continue;
+ }
+
handlers.put(getName(annotation).substring(RequestProcessor.ANNOTATION_PREFIX.length()
+ 1)
+ + "Request", (ExecutableElement) method);
+ }
+ }
+ }
+ }

- Writer writer = null;
- try {
- writer = openWriter(roundEnv.getRootElements());
- new TemplateEngine().writeHandlers(writer, handlers);
- } catch (IOException ex) {
- reporter.error(ex.toString());
- } finally {
- if (writer != null)
- try {
- writer.close();
- } catch (IOException ex) {
- reporter.error(ex.toString());
- }
- }
+ Writer writer = null;
+ try {
+ writer = openWriter(roundEnv.getRootElements());
+ new TemplateEngine().writeHandlers(writer, handlers);
+ } catch (IOException ex) {
+ reporter.error(ex.toString());
+ } finally {
+ if (writer != null) {
+ try {
+ writer.close();
+ } catch (IOException ex) {
+ reporter.error(ex.toString());
+ }
+ }
+ }

- return false;
- }
+ return false;
+ }

- private String getName(AnnotationMirror annotation) {
- return annotation.getAnnotationType().toString();
- }
+ private String getName(AnnotationMirror annotation) {
+ return annotation.getAnnotationType().toString();
+ }

- protected boolean isDeclarationViolated(ExecutableElement elem,
- SelfTestProcessorListener listener) {
- int errorsCount = 0;
+ protected boolean isDeclarationViolated(ExecutableElement elem,
SelfTestProcessorListener listener) {
+ int errorsCount = 0;

- if (elem.getModifiers().contains(Modifier.ABSTRACT)) {
- listener.error("The method cannot be abstract", elem);
- errorsCount++;
- }
+ if (elem.getModifiers().contains(Modifier.ABSTRACT)) {
+ listener.error("The method cannot be abstract", elem);
+ errorsCount++;
+ }

- if (!elem.getModifiers().contains(Modifier.PUBLIC)) {
- listener.error("The method must be public.", elem);
- errorsCount++;
- }
+ if (!elem.getModifiers().contains(Modifier.PUBLIC)) {
+ listener.error("The method must be public.", elem);
+ errorsCount++;
+ }

- if (elem.getModifiers().contains(Modifier.STATIC)) {
- listener.error("The method cannot be static.", elem);
- errorsCount++;
- }
+ if (elem.getModifiers().contains(Modifier.STATIC)) {
+ listener.error("The method cannot be static.", elem);
+ errorsCount++;
+ }

- if (elem.getReturnType().getKind() == TypeKind.VOID) {
- listener.error("Type of the method cannot be void.",
elem);
- errorsCount++;
- }
+ if (elem.getReturnType().getKind() == TypeKind.VOID) {
+ listener.error("Type of the method cannot be void.", elem);
+ errorsCount++;
+ }

- if (elem.getModifiers().contains(Modifier.FINAL)) {
- listener.error("The method cannot be final.", elem);
- errorsCount++;
- }
+ if (elem.getModifiers().contains(Modifier.FINAL)) {
+ listener.error("The method cannot be final.", elem);
+ errorsCount++;
+ }

- if (elem.isVarArgs() || (elem.getParameters().size() > 1)) {
- listener.error("The method cannot have more than one
parameter.",
- elem);
- errorsCount++;
- }
+ if (elem.isVarArgs() || elem.getParameters().size() > 1) {
+ listener.error("The method cannot have more than one
parameter.", elem);
+ errorsCount++;
+ }

- return (errorsCount > 0);
- }
+ return errorsCount > 0;
+ }

- private Writer openWriter(Set<? extends Element> elements)
- throws IOException {
- final Filer filer = processingEnv.getFiler();
- final FileObject out = filer.createSourceFile(
- "net.geant.perfsonar.Handlers",
- elements.toArray(new Element[0]));
- return out.openWriter();
- }
+ private Writer openWriter(Set<? extends Element> elements) throws
IOException {
+ final Filer filer = processingEnv.getFiler();
+ final FileObject out =
filer.createSourceFile("net.geant.perfsonar.Handlers", elements.toArray(new
Element[0]));
+ return out.openWriter();
+ }
}

Modified:
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/request/TemplateEngine.java
===================================================================
---
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/request/TemplateEngine.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/request/TemplateEngine.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -7,49 +7,51 @@
import javax.lang.model.element.ExecutableElement;

public class TemplateEngine {
- private Writer writer;
-
- private void write(String text) throws IOException {
- writer.write(text);
- }
-
- public void writeHandlers(Writer writer, Map<String,
ExecutableElement> handlers) throws IOException {
- this.writer = writer;
-
- write("package net.geant.perfsonar;\n\n");
-
- write("import static net.geant.perfsonar.Configuration.*;\n");
- write("import javax.annotation.Generated;\n");
- write("\n");
- write("@Generated(\"" + getClass().getName() + "\")\n");
- write("public class Handlers {\n");
- write("\n");
- write(" public Handlers() {\n");
- write(" try {\n");
- writeHandlerInvocations(handlers);
- write(" } catch (Exception ex) { }\n");
- write(" }\n");
- write("}\n");
- }
+ private Writer writer;

- private void writeHandlerInvocations(Map<String, ExecutableElement>
handlers) throws IOException {
- for (String request : handlers.keySet()) {
- final ExecutableElement method =
handlers.get(request);
-
- write(" ");
- write("configure(when(\"");
- write(request);
- write("\").then(");
-
write(method.getEnclosingElement().asType().toString());
- write(".class).");
- write(method.getSimpleName().toString());
- if (method.getParameters().size() <= 0)
- write("());\n");
- else {
- write("(any(");
-
write(method.getParameters().get(0).asType().toString());
- write(".class)));\n");
- }
- }
- }
+ private void write(String text) throws IOException {
+ writer.write(text);
+ }
+
+ public void writeHandlers(Writer writer, Map<String, ExecutableElement>
handlers) throws IOException {
+ this.writer = writer;
+
+ write("package net.geant.perfsonar;\n\n");
+
+ write("import static net.geant.perfsonar.Configuration.*;\n");
+ write("import javax.annotation.Generated;\n");
+ write("\n");
+ write("@Generated(\"" + getClass().getName() + "\")\n");
+ write("public class Handlers {\n");
+ write("\n");
+ write(" public Handlers() {\n");
+ write(" try {\n");
+ writeHandlerInvocations(handlers);
+ write(" } catch (Exception ex) { // NOPMD\n");
+ // TODO: we should add proper exception handling
+ write(" }\n");
+ write(" }\n");
+ write("}\n");
+ }
+
+ private void writeHandlerInvocations(Map<String, ExecutableElement>
handlers) throws IOException {
+ for (String request : handlers.keySet()) {
+ final ExecutableElement method = handlers.get(request);
+
+ write(" ");
+ write("configure(when(\"");
+ write(request);
+ write("\").then(");
+ write(method.getEnclosingElement().asType().toString());
+ write(".class).");
+ write(method.getSimpleName().toString());
+ if (method.getParameters().size() <= 0) {
+ write("());\n");
+ } else {
+ write("(any(");
+ write(method.getParameters().get(0).asType().toString());
+ write(".class)));\n");
+ }
+ }
+ }
}

Modified:
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/selftest/AbstractClassChecker.java
===================================================================
---
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/selftest/AbstractClassChecker.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/selftest/AbstractClassChecker.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -5,18 +5,19 @@
import javax.lang.model.element.TypeElement;

public class AbstractClassChecker extends BaseElementVisitor<Boolean,
Object> {
- private TypeElement type = null;
- @Override
- public Boolean visitType(TypeElement type, Object ignored) {
- this.type = type;
- return type.getModifiers().contains(Modifier.ABSTRACT);
- }
-
- public boolean isEnclosingClassAbstract(ExecutableElement method) {
- return method.getEnclosingElement().accept(this, null);
- }
-
- public TypeElement getEnclosingType(ExecutableElement method) {
- return type;
- }
+ private TypeElement type = null;
+
+ @Override
+ public Boolean visitType(TypeElement type, Object ignored) {
+ this.type = type;
+ return type.getModifiers().contains(Modifier.ABSTRACT);
+ }
+
+ public boolean isEnclosingClassAbstract(ExecutableElement method) {
+ return method.getEnclosingElement().accept(this, null);
+ }
+
+ public TypeElement getEnclosingType(ExecutableElement method) {
+ return type;
+ }
}

Modified:
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/selftest/BaseElementVisitor.java
===================================================================
---
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/selftest/BaseElementVisitor.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/selftest/BaseElementVisitor.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -8,33 +8,33 @@
import javax.lang.model.util.AbstractElementVisitor6;

public class BaseElementVisitor<R, P> extends AbstractElementVisitor6<R, P> {
- @Override
- public R visitExecutable(ExecutableElement arg0, P arg1) {
- // TODO Auto-generated method stub
- return null;
- }
+ @Override
+ public R visitExecutable(ExecutableElement arg0, P arg1) {
+ // TODO Auto-generated method stub
+ return null;
+ }

- @Override
- public R visitPackage(PackageElement arg0, P arg1) {
- // TODO Auto-generated method stub
- return null;
- }
+ @Override
+ public R visitPackage(PackageElement arg0, P arg1) {
+ // TODO Auto-generated method stub
+ return null;
+ }

- @Override
- public R visitType(TypeElement arg0, P arg1) {
- // TODO Auto-generated method stub
- return null;
- }
+ @Override
+ public R visitType(TypeElement arg0, P arg1) {
+ // TODO Auto-generated method stub
+ return null;
+ }

- @Override
- public R visitTypeParameter(TypeParameterElement arg0, P arg1) {
- // TODO Auto-generated method stub
- return null;
- }
+ @Override
+ public R visitTypeParameter(TypeParameterElement arg0, P arg1) {
+ // TODO Auto-generated method stub
+ return null;
+ }

- @Override
- public R visitVariable(VariableElement arg0, P arg1) {
- // TODO Auto-generated method stub
- return null;
- }
+ @Override
+ public R visitVariable(VariableElement arg0, P arg1) {
+ // TODO Auto-generated method stub
+ return null;
+ }
}

Modified:
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/selftest/BaseMethodElementVisitor.java
===================================================================
---
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/selftest/BaseMethodElementVisitor.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/selftest/BaseMethodElementVisitor.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -1,29 +1,28 @@
package net.geant.perfsonar.annotations.selftest;

-import javax.lang.model.element.ExecutableElement;
+import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;

public class BaseMethodElementVisitor<R, P> extends BaseElementVisitor<R, P>
{
-
- protected boolean isDeclarationViolated(ExecutableElement elem,
- SelfTestProcessorListener processor) {
- int errorsCount = 0;
-
- if (elem.getModifiers().contains(Modifier.ABSTRACT)) {
- processor.error("The method cannot be abstract",
elem);
- errorsCount++;
- }
-
- if (!elem.getModifiers().contains(Modifier.PUBLIC)) {
- processor.error("The method must be public.", elem);
- errorsCount++;
- }
-
- if (elem.getModifiers().contains(Modifier.STATIC)) {
- processor.error("The method cannot be static.", elem);
- errorsCount++;
- }
-
- return (errorsCount > 0);
- }
+
+ protected boolean isDeclarationViolated(ExecutableElement elem,
SelfTestProcessorListener processor) {
+ int errorsCount = 0;
+
+ if (elem.getModifiers().contains(Modifier.ABSTRACT)) {
+ processor.error("The method cannot be abstract", elem);
+ errorsCount++;
+ }
+
+ if (!elem.getModifiers().contains(Modifier.PUBLIC)) {
+ processor.error("The method must be public.", elem);
+ errorsCount++;
+ }
+
+ if (elem.getModifiers().contains(Modifier.STATIC)) {
+ processor.error("The method cannot be static.", elem);
+ errorsCount++;
+ }
+
+ return errorsCount > 0;
+ }
}

Modified:
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/selftest/ReturnTypeVisitor.java
===================================================================
---
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/selftest/ReturnTypeVisitor.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/selftest/ReturnTypeVisitor.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -14,48 +14,48 @@

public class ReturnTypeVisitor extends AbstractTypeVisitor6<TypeMirror,
SelfTestProcessorListener> {

- @Override
- public TypeMirror visitArray(ArrayType arg0,
SelfTestProcessorListener arg1) {
- return null;
- }
+ @Override
+ public TypeMirror visitArray(ArrayType arg0, SelfTestProcessorListener
arg1) {
+ return null;
+ }

- @Override
- public TypeMirror visitDeclared(DeclaredType type,
SelfTestProcessorListener processor) {
- return type;
- }
+ @Override
+ public TypeMirror visitDeclared(DeclaredType type,
SelfTestProcessorListener processor) {
+ return type;
+ }

- @Override
- public TypeMirror visitError(ErrorType arg0,
SelfTestProcessorListener arg1) {
- return null;
- }
+ @Override
+ public TypeMirror visitError(ErrorType arg0, SelfTestProcessorListener
arg1) {
+ return null;
+ }

- @Override
- public TypeMirror visitExecutable(ExecutableType arg0,
SelfTestProcessorListener arg1) {
- return null;
- }
+ @Override
+ public TypeMirror visitExecutable(ExecutableType arg0,
SelfTestProcessorListener arg1) {
+ return null;
+ }

- @Override
- public TypeMirror visitNoType(NoType arg0, SelfTestProcessorListener
arg1) {
- return null;
- }
+ @Override
+ public TypeMirror visitNoType(NoType arg0, SelfTestProcessorListener
arg1) {
+ return null;
+ }

- @Override
- public TypeMirror visitNull(NullType arg0, SelfTestProcessorListener
arg1) {
- return null;
- }
+ @Override
+ public TypeMirror visitNull(NullType arg0, SelfTestProcessorListener
arg1) {
+ return null;
+ }

- @Override
- public TypeMirror visitPrimitive(PrimitiveType arg0,
SelfTestProcessorListener arg1) {
- return null;
- }
+ @Override
+ public TypeMirror visitPrimitive(PrimitiveType arg0,
SelfTestProcessorListener arg1) {
+ return null;
+ }

- @Override
- public TypeMirror visitTypeVariable(TypeVariable arg0,
SelfTestProcessorListener arg1) {
- return null;
- }
+ @Override
+ public TypeMirror visitTypeVariable(TypeVariable arg0,
SelfTestProcessorListener arg1) {
+ return null;
+ }

- @Override
- public TypeMirror visitWildcard(WildcardType arg0,
SelfTestProcessorListener arg1) {
- return null;
- }
+ @Override
+ public TypeMirror visitWildcard(WildcardType arg0,
SelfTestProcessorListener arg1) {
+ return null;
+ }
}

Modified:
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/selftest/SelfTestCollector.java
===================================================================
---
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/selftest/SelfTestCollector.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/selftest/SelfTestCollector.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -6,60 +6,60 @@
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.type.TypeMirror;

-public class SelfTestCollector extends BaseMethodElementVisitor<Map<String,
ExecutableElement>, SelfTestProcessorListener> {
-
- private final Map<String, ExecutableElement> selfTests
- = new Hashtable<String, ExecutableElement>();
-
- private final Map<TypeMirror, ExecutableElement> selfTestData
- = new Hashtable<TypeMirror, ExecutableElement>();
-
- protected SelfTestCollector(Map<String, ExecutableElement> selfTests,
- Map<TypeMirror, ExecutableElement> selfTestData) {
-
- this.selfTests.putAll(selfTests);
- this.selfTestData.putAll(selfTestData);
- }
+public class SelfTestCollector extends
+ BaseMethodElementVisitor<Map<String, ExecutableElement>,
SelfTestProcessorListener> {

- @Override
- public Map<String, ExecutableElement>
visitExecutable(ExecutableElement elem, SelfTestProcessorListener listener) {
- if(isDeclarationViolated(elem, listener))
- return selfTests;
-
- if (selfTests.get(elem.getAnnotation(SelfTest.class).name())
!= null) {
- listener.error("Duplicated name of the self test.",
elem);
- return selfTests;
- }
-
- selfTests.put(elem.getAnnotation(SelfTest.class).name(),
elem);
-
- return selfTests;
- }
+ private final Map<String, ExecutableElement> selfTests = new
Hashtable<String, ExecutableElement>();

- protected boolean isDeclarationViolated(ExecutableElement elem,
- SelfTestProcessorListener listener) {
- int errorsCount = 0;
-
- if (super.isDeclarationViolated(elem, listener))
- errorsCount++;
-
-// if (elem.getReturnType().getKind() != TypeKind.VOID) {
-// listener.error("Type of the method must be void.",
elem);
-// errorsCount++;
-// }
-
- if (elem.isVarArgs() || (elem.getParameters().size() > 1)) {
- listener.error("The method cannot have more than one
parameter.", elem);
- errorsCount++;
- }
-
- if (elem.getParameters().size() == 1) {
- if
(selfTestData.get(elem.getParameters().get(0).asType()) == null) {
- listener.error("There are no self test data
provided. Add a public method annotatated with @SelfTestData of return type
java.util.List<" + elem.getParameters().get(0).asType() + ">", elem);
- errorsCount++;
- }
- }
-
- return (errorsCount > 0);
- }
+ private final Map<TypeMirror, ExecutableElement> selfTestData = new
Hashtable<TypeMirror, ExecutableElement>();
+
+ protected SelfTestCollector(Map<String, ExecutableElement> selfTests,
+ Map<TypeMirror, ExecutableElement> selfTestData) {
+
+ this.selfTests.putAll(selfTests);
+ this.selfTestData.putAll(selfTestData);
+ }
+
+ @Override
+ public Map<String, ExecutableElement> visitExecutable(ExecutableElement
elem, SelfTestProcessorListener listener) {
+ if (isDeclarationViolated(elem, listener)) {
+ return selfTests;
+ }
+
+ if (selfTests.get(elem.getAnnotation(SelfTest.class).name()) !=
null) {
+ listener.error("Duplicated name of the self test.", elem);
+ return selfTests;
+ }
+
+ selfTests.put(elem.getAnnotation(SelfTest.class).name(), elem);
+
+ return selfTests;
+ }
+
+ protected boolean isDeclarationViolated(ExecutableElement elem,
SelfTestProcessorListener listener) {
+ int errorsCount = 0;
+
+ if (super.isDeclarationViolated(elem, listener)) {
+ errorsCount++;
+ }
+
+ // if (elem.getReturnType().getKind() != TypeKind.VOID) {
+ // listener.error("Type of the method must be void.", elem);
+ // errorsCount++;
+ // }
+
+ if (elem.isVarArgs() || elem.getParameters().size() > 1) {
+ listener.error("The method cannot have more than one
parameter.", elem);
+ errorsCount++;
+ }
+
+ if (elem.getParameters().size() == 1 &&
selfTestData.get(elem.getParameters().get(0).asType()) == null) {
+ listener.error(
+ "There are no self test data provided. Add a public
method annotatated with @SelfTestData of return type java.util.List<"
+ + elem.getParameters().get(0).asType() + ">",
elem);
+ errorsCount++;
+ }
+
+ return errorsCount > 0;
+ }
}

Modified:
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/selftest/SelfTestDataCollector.java
===================================================================
---
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/selftest/SelfTestDataCollector.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/selftest/SelfTestDataCollector.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -7,53 +7,57 @@
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeMirror;

-public class SelfTestDataCollector extends
BaseMethodElementVisitor<Map<TypeMirror, ExecutableElement>,
SelfTestProcessorListener> {
-
- private final Map<TypeMirror, ExecutableElement> selfTestData
- = new Hashtable<TypeMirror, ExecutableElement>();
-
- protected SelfTestDataCollector(Map<TypeMirror, ExecutableElement>
selfTestData) {
- this.selfTestData.putAll(selfTestData);
- }
-
- @Override
- public Map<TypeMirror, ExecutableElement>
visitExecutable(ExecutableElement method, SelfTestProcessorListener listener)
{
- int errorCount = 0;
- if(isDeclarationViolated(method, listener))
- errorCount++;
-
- final DeclaredType returnType =
getType(method.getReturnType());
-
- if (!returnType.toString().startsWith("java.util.List<")) {
- listener.error("The return type of the method must be
of type java.util.List<E>", method);
- return selfTestData;
- }
-
- if (errorCount > 0)
- return selfTestData;
-
- selfTestData.put(returnType.getTypeArguments().get(0),
method);
- //processor.addSelfTestData(elem,
returnType.getTypeArguments().get(0));
-
- return selfTestData;
- }
+public class SelfTestDataCollector extends
+ BaseMethodElementVisitor<Map<TypeMirror, ExecutableElement>,
SelfTestProcessorListener> {

- private DeclaredType getType(TypeMirror returnType) {
- return (DeclaredType) returnType.accept(new
ReturnTypeVisitor(), null);
- }
+ private final Map<TypeMirror, ExecutableElement> selfTestData = new
Hashtable<TypeMirror, ExecutableElement>();

- protected boolean isDeclarationViolated(ExecutableElement elem,
- SelfTestProcessorListener listener) {
- int errorsCount = 0;
-
- if (super.isDeclarationViolated(elem, listener))
- errorsCount++;
-
- if (elem.isVarArgs() || (elem.getParameters().size() > 0)) {
- listener.error("The method cannot have parameters.",
elem);
- errorsCount++;
- }
-
- return (errorsCount > 0);
- }
+ protected SelfTestDataCollector(Map<TypeMirror, ExecutableElement>
selfTestData) {
+ this.selfTestData.putAll(selfTestData);
+ }
+
+ @Override
+ public Map<TypeMirror, ExecutableElement>
visitExecutable(ExecutableElement method,
+ SelfTestProcessorListener listener) {
+ int errorCount = 0;
+ if (isDeclarationViolated(method, listener)) {
+ errorCount++;
+ }
+
+ final DeclaredType returnType = getType(method.getReturnType());
+
+ if (!returnType.toString().startsWith("java.util.List<")) {
+ listener.error("The return type of the method must be of type
java.util.List<E>", method);
+ return selfTestData;
+ }
+
+ if (errorCount > 0) {
+ return selfTestData;
+ }
+
+ selfTestData.put(returnType.getTypeArguments().get(0), method);
+ // processor.addSelfTestData(elem,
+ // returnType.getTypeArguments().get(0));
+
+ return selfTestData;
+ }
+
+ private DeclaredType getType(TypeMirror returnType) {
+ return (DeclaredType) returnType.accept(new ReturnTypeVisitor(),
null);
+ }
+
+ protected boolean isDeclarationViolated(ExecutableElement elem,
SelfTestProcessorListener listener) {
+ int errorsCount = 0;
+
+ if (super.isDeclarationViolated(elem, listener)) {
+ errorsCount++;
+ }
+
+ if (elem.isVarArgs() || elem.getParameters().size() > 0) {
+ listener.error("The method cannot have parameters.", elem);
+ errorsCount++;
+ }
+
+ return errorsCount > 0;
+ }
}

Modified:
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/selftest/SelfTestProcessor.java
===================================================================
---
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/selftest/SelfTestProcessor.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/selftest/SelfTestProcessor.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -23,89 +23,93 @@
@SupportedAnnotationTypes("net.geant.perfsonar.annotations.selftest.*")
@SupportedSourceVersion(SourceVersion.RELEASE_6)
public class SelfTestProcessor extends AbstractProcessor {
- @Override
- public boolean process(Set<? extends TypeElement> annotations,
- RoundEnvironment roundEnv) {
-
- if (annotations.size() <= 0)
- return false;
-
- final SelfTestProcessorListener reporter = new
SelfTestProcessorListenerImpl(processingEnv.getMessager());
-
- final Map<TypeMirror, ExecutableElement> selfTestData
- = new Hashtable<TypeMirror, ExecutableElement>();
-
- for (Element elem : getSelfTestData(roundEnv))
- selfTestData.putAll(elem.accept(new
SelfTestDataCollector(selfTestData), reporter));
-
- final Map<String, ExecutableElement> selfTests
- = new Hashtable<String, ExecutableElement>();
-
- for (Element method : getSelfTests(roundEnv))
- selfTests.putAll(method.accept(new
SelfTestCollector(selfTests, selfTestData), reporter));
-
- Writer writer = null;
- try {
- writer = openWriter(getSelfTests(roundEnv));
- new TemplateEngine().writeSelfTestRunnerClass(writer,
sortByName(createSelfTestDependencyGraph(filter(selfTests, reporter))),
selfTestData);
- } catch (IOException ex) {
- reporter.error(ex.toString());
- } finally {
- if (writer != null)
- try {
- writer.close();
- } catch (IOException ex) {
- reporter.error(ex.toString());
- }
- }
-
- return false;
- }
+ @Override
+ public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {

- private Writer openWriter(Set<? extends Element> elements) throws
IOException {
- final Filer filer = processingEnv.getFiler();
- final FileObject out =
filer.createSourceFile("net.geant.perfsonar.SelfTestsConfiguration",
- elements.toArray(new Element[0]));
- return out.openWriter();
- }
-
- private Set<? extends Element> getSelfTestData(RoundEnvironment
roundEnv) {
- return roundEnv.getElementsAnnotatedWith(SelfTestData.class);
- }
+ if (annotations.size() <= 0) {
+ return false;
+ }

- private Set<? extends Element> getSelfTests(RoundEnvironment
roundEnv) {
- return roundEnv.getElementsAnnotatedWith(SelfTest.class);
- }
-
- private Map<String, ExecutableElement> filter(Map<String,
ExecutableElement> selfTests, SelfTestProcessorListener reporter) {
- final Map<String, ExecutableElement> result = new
Hashtable<String, ExecutableElement>();
- final AbstractClassChecker checker = new
AbstractClassChecker();
- for (String name : selfTests.keySet()) {
- final ExecutableElement method = selfTests.get(name);
- if (!checker.isEnclosingClassAbstract(method))
- result.put(name, method);
- else
- reporter.error("The class cannot be
abstract.", checker.getEnclosingType(method));
- }
-
- return result;
- }
-
- //FIXME add sorting
- private List<List<ExecutableElement>>
sortByName(List<List<ExecutableElement>> graph) {
- return graph;
- }
+ final SelfTestProcessorListener reporter = new
SelfTestProcessorListenerImpl(processingEnv.getMessager());

- //FIXME add dependency
- private List<List<ExecutableElement>>
createSelfTestDependencyGraph(Map<String, ExecutableElement> selfTests) {
- final List<List<ExecutableElement>> result = new
ArrayList<List<ExecutableElement>>();
-
- for (ExecutableElement method : selfTests.values()) {
- final List<ExecutableElement> temp = new
ArrayList<ExecutableElement>();
- temp.add(method);
- result.add(temp);
- }
-
- return result;
- }
+ final Map<TypeMirror, ExecutableElement> selfTestData = new
Hashtable<TypeMirror, ExecutableElement>();
+
+ for (Element elem : getSelfTestData(roundEnv)) {
+ selfTestData.putAll(elem.accept(new
SelfTestDataCollector(selfTestData), reporter));
+ }
+
+ final Map<String, ExecutableElement> selfTests = new
Hashtable<String, ExecutableElement>();
+
+ for (Element method : getSelfTests(roundEnv)) {
+ selfTests.putAll(method.accept(new SelfTestCollector(selfTests,
selfTestData), reporter));
+ }
+
+ Writer writer = null;
+ try {
+ writer = openWriter(getSelfTests(roundEnv));
+ new TemplateEngine().writeSelfTestRunnerClass(writer,
+
sortByName(createSelfTestDependencyGraph(filter(selfTests, reporter))),
selfTestData);
+ } catch (IOException ex) {
+ reporter.error(ex.toString());
+ } finally {
+ if (writer != null) {
+ try {
+ writer.close();
+ } catch (IOException ex) {
+ reporter.error(ex.toString());
+ }
+ }
+ }
+
+ return false;
+ }
+
+ private Writer openWriter(Set<? extends Element> elements) throws
IOException {
+ final Filer filer = processingEnv.getFiler();
+ final FileObject out =
filer.createSourceFile("net.geant.perfsonar.SelfTestsConfiguration",
+ elements.toArray(new Element[0]));
+ return out.openWriter();
+ }
+
+ private Set<? extends Element> getSelfTestData(RoundEnvironment
roundEnv) {
+ return roundEnv.getElementsAnnotatedWith(SelfTestData.class);
+ }
+
+ private Set<? extends Element> getSelfTests(RoundEnvironment roundEnv) {
+ return roundEnv.getElementsAnnotatedWith(SelfTest.class);
+ }
+
+ private Map<String, ExecutableElement> filter(Map<String,
ExecutableElement> selfTests,
+ SelfTestProcessorListener reporter) {
+ final Map<String, ExecutableElement> result = new Hashtable<String,
ExecutableElement>();
+ final AbstractClassChecker checker = new AbstractClassChecker();
+ for (String name : selfTests.keySet()) {
+ final ExecutableElement method = selfTests.get(name);
+ if (!checker.isEnclosingClassAbstract(method)) {
+ result.put(name, method);
+ } else {
+ reporter.error("The class cannot be abstract.",
checker.getEnclosingType(method));
+ }
+ }
+
+ return result;
+ }
+
+ // FIXME add sorting
+ private List<List<ExecutableElement>>
sortByName(List<List<ExecutableElement>> graph) {
+ return graph;
+ }
+
+ // FIXME add dependency
+ private List<List<ExecutableElement>>
createSelfTestDependencyGraph(Map<String, ExecutableElement> selfTests) {
+ final List<List<ExecutableElement>> result = new
ArrayList<List<ExecutableElement>>();
+
+ for (ExecutableElement method : selfTests.values()) {
+ final List<ExecutableElement> temp = new
ArrayList<ExecutableElement>();
+ temp.add(method);
+ result.add(temp);
+ }
+
+ return result;
+ }
}

Modified:
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/selftest/SelfTestProcessorListener.java
===================================================================
---
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/selftest/SelfTestProcessorListener.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/selftest/SelfTestProcessorListener.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -3,6 +3,7 @@
import javax.lang.model.element.Element;

public interface SelfTestProcessorListener {
- void error(String message);
- void error(String message, Element element);
+ void error(String message);
+
+ void error(String message, Element element);
}

Modified:
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/selftest/SelfTestProcessorListenerImpl.java
===================================================================
---
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/selftest/SelfTestProcessorListenerImpl.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/selftest/SelfTestProcessorListenerImpl.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -5,20 +5,20 @@
import javax.tools.Diagnostic.Kind;

public class SelfTestProcessorListenerImpl implements
SelfTestProcessorListener {
-
- private Messager messager;
-
- public SelfTestProcessorListenerImpl(Messager messager) {
- this.messager = messager;
- }
-
- @Override
- public void error(String message) {
- messager.printMessage(Kind.ERROR, message);
- }

- @Override
- public void error(String message, Element element) {
- messager.printMessage(Kind.ERROR, message, element);
- }
+ private Messager messager;
+
+ public SelfTestProcessorListenerImpl(Messager messager) {
+ this.messager = messager;
+ }
+
+ @Override
+ public void error(String message) {
+ messager.printMessage(Kind.ERROR, message);
+ }
+
+ @Override
+ public void error(String message, Element element) {
+ messager.printMessage(Kind.ERROR, message, element);
+ }
}

Modified:
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/selftest/TemplateEngine.java
===================================================================
---
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/selftest/TemplateEngine.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/selftest/TemplateEngine.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -9,47 +9,56 @@
import javax.lang.model.type.TypeMirror;

public class TemplateEngine {
- private Writer writer;
-
- private void write(String text) throws IOException {
- writer.write(text);
- }
-
- public void writeSelfTestRunnerClass(Writer writer,
List<List<ExecutableElement>> selftestsDG, Map<TypeMirror, ExecutableElement>
selfTestData) throws IOException {
- this.writer = writer;
-
- write("package net.geant.perfsonar;\n\n");
- write("import static
net.geant.perfsonar.selftest.SelfTestRunner.addSelfTest;\n");
+ private Writer writer;
+
+ private void write(String text) throws IOException {
+ writer.write(text);
+ }
+
+ public void writeSelfTestRunnerClass(Writer writer,
List<List<ExecutableElement>> selftestsDG,
+ Map<TypeMirror, ExecutableElement> selfTestData) throws
IOException {
+ this.writer = writer;
+
+ write("package net.geant.perfsonar;\n\n");
+ write("import static
net.geant.perfsonar.selftest.SelfTestRunner.addSelfTest;\n");
write("import static
net.geant.perfsonar.selftest.SelfTestRunner.any;\n");
write("import static
net.geant.perfsonar.selftest.SelfTestRunner.configureForType;\n");
write("import static
net.geant.perfsonar.selftest.SelfTestRunner.selfTestData;\n");
- write("import javax.annotation.Generated;\n");
- write("\n");
- write("@Generated(\"" + getClass().getName() + "\")\n");
- write("public class SelfTestsConfiguration {\n");
- write(" public SelfTestsConfiguration() {\n");
- write(" try {\n");
-
- writeTestsInvocations(selftestsDG, selfTestData);
-
- write(" } catch (Exception ex) { }\n");
- write(" }\n");
- write("}\n");
- }
+ write("import javax.annotation.Generated;\n");
+ write("\n");
+ write("@Generated(\"" + getClass().getName() + "\")\n");
+ write("public class SelfTestsConfiguration {\n");
+ write(" public SelfTestsConfiguration() {\n");
+ write(" try {\n");

- private void writeTestsInvocations(List<List<ExecutableElement>>
selftestsDG,
- Map<TypeMirror, ExecutableElement> selfTestData)
throws IOException {
-
- for (List<ExecutableElement> methods : selftestsDG)
- for (ExecutableElement method : methods) {
- write(" addSelfTest(\"" +
method.getAnnotation(SelfTest.class).name() + "\", \"" +
method.getAnnotation(SelfTest.class).successMessage() + "\", " +
method.getEnclosingElement() + ".class)." + method.getSimpleName() + "(");
-
- if (method.getParameters().size() == 1) {
- TypeMirror type =
method.getParameters().get(0).asType();
- write("any(" + type.toString() +
".class));\n");
- write(" configureForType("
+ type.toString() + ".class, selfTestData(" + method.getEnclosingElement() +
".class)." + selfTestData.get(type).getSimpleName() + "());\n");
- } else
- write(");\n");
- }
- }
+ writeTestsInvocations(selftestsDG, selfTestData);
+
+ write(" } catch (Exception ex) { // NOPMD\n");
+ // TODO: we should add proper exception handling
+ write(" }\n");
+ write(" }\n");
+ write("}\n");
+ }
+
+ private void writeTestsInvocations(List<List<ExecutableElement>>
selftestsDG,
+ Map<TypeMirror, ExecutableElement> selfTestData) throws
IOException {
+
+ for (List<ExecutableElement> methods : selftestsDG) {
+ for (ExecutableElement method : methods) {
+ write(" addSelfTest(\"" +
method.getAnnotation(SelfTest.class).name() + "\", \""
+ +
method.getAnnotation(SelfTest.class).successMessage() + "\", " +
method.getEnclosingElement()
+ + ".class)." + method.getSimpleName() + "(");
+
+ if (method.getParameters().size() == 1) {
+ TypeMirror type = method.getParameters().get(0).asType();
+ write("any(" + type.toString() + ".class));\n");
+ write(" configureForType(" + type.toString()
+ ".class, selfTestData("
+ + method.getEnclosingElement() + ".class)." +
selfTestData.get(type).getSimpleName()
+ + "());\n");
+ } else {
+ write(");\n");
+ }
+ }
+ }
+ }
}

Modified:
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/xpath/EnvelopedXPath.java
===================================================================
---
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/xpath/EnvelopedXPath.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/xpath/EnvelopedXPath.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -4,39 +4,43 @@

public class EnvelopedXPath {

- private XPath annotation;
+ private XPath annotation;

- protected EnvelopedXPath(XPath annotation) {
- this.annotation = annotation;
- }
+ protected EnvelopedXPath(XPath annotation) {
+ this.annotation = annotation;
+ }

- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result
- + ((annotation == null) ? 0 :
annotation.hashCode());
- return result;
- }
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((annotation == null) ? 0 :
annotation.hashCode());
+ return result;
+ }

- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- EnvelopedXPath other = (EnvelopedXPath) obj;
- if (annotation == null) {
- if (other.annotation != null)
- return false;
- } else if
(!annotation.xpath().equals(other.annotation.xpath()))
- return false;
- return true;
- }
-
- public XPath getAnnotation() {
- return annotation;
- }
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null) {
+ return false;
+ }
+ if (getClass() != obj.getClass()) {
+ return false;
+ }
+ EnvelopedXPath other = (EnvelopedXPath) obj;
+ if (annotation == null) {
+ if (other.annotation != null) {
+ return false;
+ }
+ } else if (!annotation.xpath().equals(other.annotation.xpath())) {
+ return false;
+ }
+ return true;
+ }
+
+ public XPath getAnnotation() {
+ return annotation;
+ }
}

Modified:
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/xpath/IdentifierValidator.java
===================================================================
---
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/xpath/IdentifierValidator.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/xpath/IdentifierValidator.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -14,70 +14,71 @@
/**
* Checks whether methods annotated with Identifier are valid.
*
- * <p>Valid methods are:
+ * <p>
+ * Valid methods are:
* <ul>
- * <li>with exactly zero arguments</li>
- * <li>public</li>
- * <li>non static</li>
- * <li>cannot be abstract</li>
- * <li>cannot be final</li>
- * <li>the enclosing class cannot be abstract</li>
- * </ul></p>
+ * <li>with exactly zero arguments</li>
+ * <li>public</li>
+ * <li>non static</li>
+ * <li>cannot be abstract</li>
+ * <li>cannot be final</li>
+ * <li>the enclosing class cannot be abstract</li>
+ * </ul>
+ * </p>
*
* @author <a
href="mailto:">Blazej
Pietrzak</a>
- *
+ *
*/
public class IdentifierValidator extends
BaseMethodElementVisitor<List<ExecutableElement>, SelfTestProcessorListener> {

- final AbstractClassChecker checker = new AbstractClassChecker();
- final List<TypeElement> abstractClasses = new
ArrayList<TypeElement>();
-
- private final List<ExecutableElement> ids = new
ArrayList<ExecutableElement>();
-
- protected IdentifierValidator(List<ExecutableElement> ids) {
- this.ids.addAll(ids);
- }
+ private final AbstractClassChecker checker = new AbstractClassChecker();
+ private final List<TypeElement> abstractClasses = new
ArrayList<TypeElement>();

- @Override
- public List<ExecutableElement> visitExecutable(ExecutableElement
elem, SelfTestProcessorListener listener) {
- if(isDeclarationViolated(elem, listener))
- return ids;
-
- ids.add(elem);
-
- return ids;
- }
+ private final List<ExecutableElement> ids = new
ArrayList<ExecutableElement>();

- protected boolean isDeclarationViolated(ExecutableElement elem,
- SelfTestProcessorListener listener) {
- int errorsCount = 0;
-
- if (super.isDeclarationViolated(elem, listener))
- errorsCount++;
-
- if (elem.getModifiers().contains(Modifier.FINAL)) {
- listener.error("The method cannot be final.", elem);
- errorsCount++;
- }
-
- if (elem.getModifiers().contains(Modifier.STATIC)) {
- listener.error("The method cannot be static.", elem);
- errorsCount++;
- }
-
- if (elem.isVarArgs() || (elem.getParameters().size() > 0)) {
- listener.error("The method must have zero
parameters.", elem);
- errorsCount++;
- }
-
- if (checker.isEnclosingClassAbstract(elem)) {
- if
(!abstractClasses.contains(checker.getEnclosingType(elem))) {
-
abstractClasses.add(checker.getEnclosingType(elem));
- listener.error("The class cannot be
abstract.", checker.getEnclosingType(elem));
- errorsCount++;
- }
- }
-
- return (errorsCount > 0);
- }
+ protected IdentifierValidator(List<ExecutableElement> ids) {
+ this.ids.addAll(ids);
+ }
+
+ @Override
+ public List<ExecutableElement> visitExecutable(ExecutableElement elem,
SelfTestProcessorListener listener) {
+ if (isDeclarationViolated(elem, listener)) {
+ return ids;
+ }
+
+ ids.add(elem);
+
+ return ids;
+ }
+
+ protected boolean isDeclarationViolated(ExecutableElement elem,
SelfTestProcessorListener listener) {
+ int errorsCount = 0;
+
+ if (super.isDeclarationViolated(elem, listener)) {
+ errorsCount++;
+ }
+
+ if (elem.getModifiers().contains(Modifier.FINAL)) {
+ listener.error("The method cannot be final.", elem);
+ errorsCount++;
+ }
+
+ if (elem.getModifiers().contains(Modifier.STATIC)) {
+ listener.error("The method cannot be static.", elem);
+ errorsCount++;
+ }
+
+ if (elem.isVarArgs() || elem.getParameters().size() > 0) {
+ listener.error("The method must have zero parameters.", elem);
+ errorsCount++;
+ }
+
+ if (checker.isEnclosingClassAbstract(elem) &&
!abstractClasses.contains(checker.getEnclosingType(elem))) {
+ abstractClasses.add(checker.getEnclosingType(elem));
+ listener.error("The class cannot be abstract.",
checker.getEnclosingType(elem));
+ errorsCount++;
+ }
+
+ return errorsCount > 0;
+ }
}

Modified:
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/xpath/TemplateEngine.java
===================================================================
---
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/xpath/TemplateEngine.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/xpath/TemplateEngine.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -8,75 +8,80 @@

import javax.lang.model.element.ExecutableElement;

+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
import net.geant.perfsonar.annotations.Namespace;

public class TemplateEngine {
- private Writer writer;
-
- private void write(String text) throws IOException {
- writer.write(text);
- }
-
- public void writeXPaths(Writer writer, Map<EnvelopedXPath,
ExecutableElement> xpaths, List<ExecutableElement> ids) throws IOException {
- this.writer = writer;
-
- write("package net.geant.perfsonar;\n\n");
- write("import static
net.geant.perfsonar.messaging.XPathDeserializer.any;\n");
- write("import static
net.geant.perfsonar.messaging.XPathDeserializer.declarePrefix;\n");
- write("import static
net.geant.perfsonar.messaging.XPathDeserializer.identifier;\n");
- write("import static
net.geant.perfsonar.messaging.XPathDeserializer.whenXPath;\n");
- write("import javax.annotation.Generated;\n");
- write("\n");
- write("@Generated(\"" + getClass().getName() + "\")\n");
- write("public class XPaths {\n");
- write("\n");
- write(" public XPaths() {\n");
- write(" try {\n");
- writeIdentiferInvocations(ids);
- writeXPathInvocations(xpaths);
- write(" } catch (Exception ex) {\n");
- write(" ex.printStackTrace();\n");
- write(" }\n");
- write(" }\n");
- write("}\n");
- }
+ protected Logger logger = LoggerFactory.getLogger(getClass());
+ private Writer writer;

- private void writeIdentiferInvocations(List<ExecutableElement> ids)
throws IOException {
- for (ExecutableElement method : ids) {
- write("identifier(");
-
write(method.getEnclosingElement().asType().toString());
- write(".class).");
- write(method.getSimpleName().toString());
- write("();\n");
- }
-
- }
+ private void write(String text) throws IOException {
+ writer.write(text);
+ }

- private void writeXPathInvocations(Map<EnvelopedXPath,
ExecutableElement> xpaths) throws IOException {
- for (EnvelopedXPath xpath : xpaths.keySet()) {
- final ExecutableElement method = xpaths.get(xpath);
-
- try {
- for (Namespace namespace :
xpath.getAnnotation().namespaces()) {
- write(" ");
- write("declarePrefix(\"");
- write(namespace.prefix());
- write("\", \"");
- write(namespace.uri());
- write("\");\n");
- }
- } catch (IncompleteAnnotationException ex) {
- //do nothing when namespaces attribute is not
defined in XPath annotation
- }
-
- write(" ");
- write("whenXPath(\"");
- write(xpath.getAnnotation().xpath());
- write("\").then(");
-
write(method.getEnclosingElement().asType().toString());
- write(".class).");
- write(method.getSimpleName().toString());
- write("(any(" +
method.getParameters().get(0).asType().toString() + ".class));\n");
- }
- }
+ public void writeXPaths(Writer writer, Map<EnvelopedXPath,
ExecutableElement> xpaths, List<ExecutableElement> ids)
+ throws IOException {
+ this.writer = writer;
+
+ write("package net.geant.perfsonar;\n\n");
+ write("import static
net.geant.perfsonar.messaging.XPathDeserializer.any; // NOPMD\n");
+ write("import static
net.geant.perfsonar.messaging.XPathDeserializer.declarePrefix; // NOPMD\n");
+ write("import static
net.geant.perfsonar.messaging.XPathDeserializer.identifier; // NOPMD\n");
+ write("import static
net.geant.perfsonar.messaging.XPathDeserializer.whenXPath; // NOPMD\n");
+ write("import javax.annotation.Generated;\n");
+ write("\n");
+ write("@Generated(\"" + getClass().getName() + "\")\n");
+ write("public class XPaths {\n");
+ write("\n");
+ write(" public XPaths() {\n");
+ write(" try {\n");
+ writeIdentiferInvocations(ids);
+ writeXPathInvocations(xpaths);
+ write(" } catch (Exception ex) {\n");
+ write(" ex.printStackTrace();\n");
+ write(" }\n");
+ write(" }\n");
+ write("}\n");
+ }
+
+ private void writeIdentiferInvocations(List<ExecutableElement> ids)
throws IOException {
+ for (ExecutableElement method : ids) {
+ write("identifier(");
+ write(method.getEnclosingElement().asType().toString());
+ write(".class).");
+ write(method.getSimpleName().toString());
+ write("();\n");
+ }
+
+ }
+
+ private void writeXPathInvocations(Map<EnvelopedXPath,
ExecutableElement> xpaths) throws IOException {
+ for (EnvelopedXPath xpath : xpaths.keySet()) {
+ final ExecutableElement method = xpaths.get(xpath);
+
+ try {
+ for (Namespace namespace :
xpath.getAnnotation().namespaces()) {
+ write(" ");
+ write("declarePrefix(\"");
+ write(namespace.prefix());
+ write("\", \"");
+ write(namespace.uri());
+ write("\");\n");
+ }
+ } catch (IncompleteAnnotationException ex) {
+ logger.debug("Namespace attribute is not defined in XPath
annotation: {}", xpath.getAnnotation());
+ }
+
+ write(" ");
+ write("whenXPath(\"");
+ write(xpath.getAnnotation().xpath());
+ write("\").then(");
+ write(method.getEnclosingElement().asType().toString());
+ write(".class).");
+ write(method.getSimpleName().toString());
+ write("(any(" +
method.getParameters().get(0).asType().toString() + ".class));\n");
+ }
+ }
}

Modified:
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/xpath/XPathProcessor.java
===================================================================
---
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/xpath/XPathProcessor.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/xpath/XPathProcessor.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -28,81 +28,85 @@
/**
* Processes methods annotated with XPath annotation.
*
- * <p>Valid methods are:
+ * <p>
+ * Valid methods are:
* <ul>
- * <li>with exactly one argument</li>
- * <li>public</li>
- * <li>non static</li>
- * <li>cannot be abstract</li>
- * <li>cannot be final</li>
- * <li>the enclosing class cannot be abstract</li>
- * </ul></p>
+ * <li>with exactly one argument</li>
+ * <li>public</li>
+ * <li>non static</li>
+ * <li>cannot be abstract</li>
+ * <li>cannot be final</li>
+ * <li>the enclosing class cannot be abstract</li>
+ * </ul>
+ * </p>
*
* @author <a
href="mailto:">Blazej
Pietrzak</a>
*/
-@SupportedAnnotationTypes({"net.geant.perfsonar.annotations.XPath",
"net.geant.perfsonar.annotations.XPaths",
"net.geant.perfsonar.annotations.Identifier"})
+@SupportedAnnotationTypes({
"net.geant.perfsonar.annotations.XPath",
"net.geant.perfsonar.annotations.XPaths",
+ "net.geant.perfsonar.annotations.Identifier" })
@SupportedSourceVersion(SourceVersion.RELEASE_6)
public class XPathProcessor extends AbstractProcessor {
- @Override
- public boolean process(Set<? extends TypeElement> annotations,
- RoundEnvironment roundEnv) {
-
- if (annotations.size() <= 0)
- return false;
-
- final SelfTestProcessorListener reporter = new
SelfTestProcessorListenerImpl(processingEnv.getMessager());
- final Map<EnvelopedXPath, ExecutableElement> xpaths = new
Hashtable<EnvelopedXPath, ExecutableElement>();
- final List<ExecutableElement> ids = new
ArrayList<ExecutableElement>();
- final XPathValidator xpathValidator = new XPathValidator();
- final IdentifierValidator idValidator = new
IdentifierValidator(ids);
-
- xpathValidator.setAggregator();
- for (Element method :
getMethodsAnnotatedWithXPaths(roundEnv)) {
- xpaths.putAll(method.accept(xpathValidator,
reporter));
- }
-
- xpathValidator.unsetAggregator();
- for (Element method : getMethodsAnnotatedWithXPath(roundEnv))
{
- xpaths.putAll(method.accept(xpathValidator,
reporter));
- }
-
- for (Element method :
getMethodsAnnotatedWithIdentifier(roundEnv)) {
- ids.addAll(method.accept(idValidator, reporter));
- }
-
- Writer writer = null;
- try {
- writer =
openWriter(getMethodsAnnotatedWithXPath(roundEnv));
- new TemplateEngine().writeXPaths(writer, xpaths, ids);
- } catch (IOException ex) {
- reporter.error(ex.toString());
- } finally {
- if (writer != null)
- try {
- writer.close();
- } catch (IOException ex) {
- reporter.error(ex.toString());
- }
- }
-
- return false;
- }
+ @Override
+ public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {

- private Writer openWriter(Set<? extends Element> elements) throws
IOException {
- final Filer filer = processingEnv.getFiler();
- final FileObject out =
filer.createSourceFile("net.geant.perfsonar.XPaths", elements.toArray(new
Element[0]));
- return out.openWriter();
- }
-
- private Set<? extends Element>
getMethodsAnnotatedWithXPath(RoundEnvironment roundEnv) {
- return roundEnv.getElementsAnnotatedWith(XPath.class);
- }
-
- private Set<? extends Element>
getMethodsAnnotatedWithXPaths(RoundEnvironment roundEnv) {
- return roundEnv.getElementsAnnotatedWith(XPaths.class);
- }
-
- private Set<? extends Element>
getMethodsAnnotatedWithIdentifier(RoundEnvironment roundEnv) {
- return roundEnv.getElementsAnnotatedWith(Identifier.class);
- }
+ if (annotations.size() <= 0) {
+ return false;
+ }
+
+ final SelfTestProcessorListener reporter = new
SelfTestProcessorListenerImpl(processingEnv.getMessager());
+ final Map<EnvelopedXPath, ExecutableElement> xpaths = new
Hashtable<EnvelopedXPath, ExecutableElement>();
+ final List<ExecutableElement> ids = new
ArrayList<ExecutableElement>();
+ final XPathValidator xpathValidator = new XPathValidator();
+ final IdentifierValidator idValidator = new IdentifierValidator(ids);
+
+ xpathValidator.setAggregator();
+ for (Element method : getMethodsAnnotatedWithXPaths(roundEnv)) {
+ xpaths.putAll(method.accept(xpathValidator, reporter));
+ }
+
+ xpathValidator.unsetAggregator();
+ for (Element method : getMethodsAnnotatedWithXPath(roundEnv)) {
+ xpaths.putAll(method.accept(xpathValidator, reporter));
+ }
+
+ for (Element method : getMethodsAnnotatedWithIdentifier(roundEnv)) {
+ ids.addAll(method.accept(idValidator, reporter));
+ }
+
+ Writer writer = null;
+ try {
+ writer = openWriter(getMethodsAnnotatedWithXPath(roundEnv));
+ new TemplateEngine().writeXPaths(writer, xpaths, ids);
+ } catch (IOException ex) {
+ reporter.error(ex.toString());
+ } finally {
+ if (writer != null) {
+ try {
+ writer.close();
+ } catch (IOException ex) {
+ reporter.error(ex.toString());
+ }
+ }
+ }
+
+ return false;
+ }
+
+ private Writer openWriter(Set<? extends Element> elements) throws
IOException {
+ final Filer filer = processingEnv.getFiler();
+ final FileObject out =
filer.createSourceFile("net.geant.perfsonar.XPaths", elements.toArray(new
Element[0]));
+ return out.openWriter();
+ }
+
+ private Set<? extends Element>
getMethodsAnnotatedWithXPath(RoundEnvironment roundEnv) {
+ return roundEnv.getElementsAnnotatedWith(XPath.class);
+ }
+
+ private Set<? extends Element>
getMethodsAnnotatedWithXPaths(RoundEnvironment roundEnv) {
+ return roundEnv.getElementsAnnotatedWith(XPaths.class);
+ }
+
+ private Set<? extends Element>
getMethodsAnnotatedWithIdentifier(RoundEnvironment roundEnv) {
+ return roundEnv.getElementsAnnotatedWith(Identifier.class);
+ }
}

Modified:
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/xpath/XPathValidator.java
===================================================================
---
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/xpath/XPathValidator.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/apt/src/main/java/net/geant/perfsonar/annotations/xpath/XPathValidator.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -18,80 +18,84 @@
/**
* Checks whether methods annotated with XPath are valid.
*
- * <p>Valid methods are:
+ * <p>
+ * Valid methods are:
* <ul>
- * <li>with exactly one argument</li>
- * <li>public</li>
- * <li>non static</li>
- * <li>cannot be abstract</li>
- * <li>cannot be final</li>
- * <li>the enclosing class cannot be abstract</li>
- * </ul></p>
+ * <li>with exactly one argument</li>
+ * <li>public</li>
+ * <li>non static</li>
+ * <li>cannot be abstract</li>
+ * <li>cannot be final</li>
+ * <li>the enclosing class cannot be abstract</li>
+ * </ul>
+ * </p>
*
* @author <a
href="mailto:">Blazej
Pietrzak</a>
- *
+ *
*/
-public class XPathValidator extends
BaseMethodElementVisitor<Map<EnvelopedXPath, ExecutableElement>,
SelfTestProcessorListener> {
+public class XPathValidator extends
+ BaseMethodElementVisitor<Map<EnvelopedXPath, ExecutableElement>,
SelfTestProcessorListener> {

- final AbstractClassChecker checker = new AbstractClassChecker();
- final List<TypeElement> abstractClasses = new
ArrayList<TypeElement>();
-
- private final Map<EnvelopedXPath, ExecutableElement> xpaths
- = new Hashtable<EnvelopedXPath, ExecutableElement>();
- private boolean aggregator;
-
- public void setAggregator() {
- aggregator = true;
- }
-
- public void unsetAggregator() {
- aggregator = false;
- }
+ private final AbstractClassChecker checker = new AbstractClassChecker();
+ private final List<TypeElement> abstractClasses = new
ArrayList<TypeElement>();

- @Override
- public Map<EnvelopedXPath, ExecutableElement>
visitExecutable(ExecutableElement elem, SelfTestProcessorListener listener) {
- if(isDeclarationViolated(elem, listener))
- return xpaths;
-
- if (!aggregator)
- xpaths.put(new
EnvelopedXPath(elem.getAnnotation(XPath.class)), elem);
- else
- for (XPath xpath :
elem.getAnnotation(XPaths.class).value())
- xpaths.put(new EnvelopedXPath(xpath), elem);
-
- return xpaths;
- }
+ private final Map<EnvelopedXPath, ExecutableElement> xpaths = new
Hashtable<EnvelopedXPath, ExecutableElement>();
+ private boolean aggregator;

- protected boolean isDeclarationViolated(ExecutableElement elem,
- SelfTestProcessorListener listener) {
- int errorsCount = 0;
-
- if (super.isDeclarationViolated(elem, listener))
- errorsCount++;
-
- if (elem.getModifiers().contains(Modifier.FINAL)) {
- listener.error("The method cannot be final.", elem);
- errorsCount++;
- }
-
- if (elem.getModifiers().contains(Modifier.STATIC)) {
- listener.error("The method cannot be static.", elem);
- errorsCount++;
- }
-
- if (elem.isVarArgs() || (elem.getParameters().size() > 1)) {
- listener.error("The method cannot have more than one
parameter.", elem);
- errorsCount++;
- }
-
- if (checker.isEnclosingClassAbstract(elem)) {
- if
(!abstractClasses.contains(checker.getEnclosingType(elem))) {
-
abstractClasses.add(checker.getEnclosingType(elem));
- listener.error("The class cannot be
abstract.", checker.getEnclosingType(elem));
- errorsCount++;
- }
- }
-
- return (errorsCount > 0);
- }
+ public void setAggregator() {
+ aggregator = true;
+ }
+
+ public void unsetAggregator() {
+ aggregator = false;
+ }
+
+ @Override
+ public Map<EnvelopedXPath, ExecutableElement>
visitExecutable(ExecutableElement elem,
+ SelfTestProcessorListener listener) {
+ if (isDeclarationViolated(elem, listener)) {
+ return xpaths;
+ }
+
+ if (!aggregator) {
+ xpaths.put(new EnvelopedXPath(elem.getAnnotation(XPath.class)),
elem);
+ } else {
+ for (XPath xpath : elem.getAnnotation(XPaths.class).value()) {
+ xpaths.put(new EnvelopedXPath(xpath), elem);
+ }
+ }
+
+ return xpaths;
+ }
+
+ protected boolean isDeclarationViolated(ExecutableElement elem,
SelfTestProcessorListener listener) {
+ int errorsCount = 0;
+
+ if (super.isDeclarationViolated(elem, listener)) {
+ errorsCount++;
+ }
+
+ if (elem.getModifiers().contains(Modifier.FINAL)) {
+ listener.error("The method cannot be final.", elem);
+ errorsCount++;
+ }
+
+ if (elem.getModifiers().contains(Modifier.STATIC)) {
+ listener.error("The method cannot be static.", elem);
+ errorsCount++;
+ }
+
+ if (elem.isVarArgs() || elem.getParameters().size() > 1) {
+ listener.error("The method cannot have more than one
parameter.", elem);
+ errorsCount++;
+ }
+
+ if (checker.isEnclosingClassAbstract(elem) &&
!abstractClasses.contains(checker.getEnclosingType(elem))) {
+ abstractClasses.add(checker.getEnclosingType(elem));
+ listener.error("The class cannot be abstract.",
checker.getEnclosingType(elem));
+ errorsCount++;
+ }
+
+ return errorsCount > 0;
+ }
}

Modified:
trunk/perfsonar-base/apt/src/test/java/net/geant/perfsonar/annotations/LookupServiceRegisterProcessorTest.java
===================================================================
---
trunk/perfsonar-base/apt/src/test/java/net/geant/perfsonar/annotations/LookupServiceRegisterProcessorTest.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/apt/src/test/java/net/geant/perfsonar/annotations/LookupServiceRegisterProcessorTest.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -19,43 +19,42 @@
import org.junit.Test;

public class LookupServiceRegisterProcessorTest {
- private static final String SAMPLES_PATH = "dummyservice";
- final BinaryClassLoader classLoader = new
BinaryClassLoader(getClassPath());
- private CompilerHelper compiler;
-
- private static String[] getClassPath() {
- final List<String> result = new ArrayList<String>();
- for (String path :
System.getProperty("java.class.path").split(File.pathSeparator)) {
- result.add(path);
- }
-
- result.add(CompilerHelper.ANNOTATED_SOURCE_OUTPUT);
- result.add(SAMPLES_PATH);
-
- return result.toArray(new String[0]);
- }
-
- @Before
- public void givenCompiler() throws Exception {
- compiler = new CompilerHelper(SAMPLES_PATH, new
LookupServiceRegisterProcessor());
- }
+ private static final String SAMPLES_PATH = "dummyservice";
+ private final BinaryClassLoader classLoader = new
BinaryClassLoader(getClassPath());
+ private CompilerHelper compiler;

- @After
- public void finalizeCompiler() throws IOException {
- compiler.close();
- compiler = null;
- }
-
- @Test
- public void shouldCompileController() {
- assertEquals(Diagnostics.EMPTY,
-
compiler.compile("/net/geant/perfsonar/dummyservice/ServiceController.java"));
- }
+ private static String[] getClassPath() {
+ final List<String> result = new ArrayList<String>();
+ for (String path :
System.getProperty("java.class.path").split(File.pathSeparator)) {
+ result.add(path);
+ }

- @Test
- public void shouldConfigureLookupServiceHandler() throws Exception {
-
compiler.compile("/net/geant/perfsonar/dummyservice/ServiceController.java");
-
classLoader.loadClass("net.geant.perfsonar.LookupServiceRegister").newInstance();
- assertNotNull(Configuration.getHandler("LSRegister"));
- }
+ result.add(CompilerHelper.ANNOTATED_SOURCE_OUTPUT);
+ result.add(SAMPLES_PATH);
+
+ return result.toArray(new String[0]);
+ }
+
+ @Before
+ public void givenCompiler() throws Exception {
+ compiler = new CompilerHelper(SAMPLES_PATH, new
LookupServiceRegisterProcessor());
+ }
+
+ @After
+ public void finalizeCompiler() throws IOException {
+ compiler.close();
+ compiler = null;
+ }
+
+ @Test
+ public void shouldCompileController() {
+ assertEquals(Diagnostics.EMPTY,
compiler.compile("/net/geant/perfsonar/dummyservice/ServiceController.java"));
+ }
+
+ @Test
+ public void shouldConfigureLookupServiceHandler() throws Exception {
+
compiler.compile("/net/geant/perfsonar/dummyservice/ServiceController.java");
+
classLoader.loadClass("net.geant.perfsonar.LookupServiceRegister").newInstance();
+ assertNotNull(Configuration.getHandler("LSRegister"));
+ }
}

Modified:
trunk/perfsonar-base/apt/src/test/java/net/geant/perfsonar/annotations/RequestProcessorTest.java
===================================================================
---
trunk/perfsonar-base/apt/src/test/java/net/geant/perfsonar/annotations/RequestProcessorTest.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/apt/src/test/java/net/geant/perfsonar/annotations/RequestProcessorTest.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -19,51 +19,50 @@
import org.junit.Test;

public class RequestProcessorTest {
- private static final String SAMPLES_PATH = "dummyservice";
- final BinaryClassLoader classLoader = new
BinaryClassLoader(getClassPath());
- private CompilerHelper compiler;
-
- private static String[] getClassPath() {
- final List<String> result = new ArrayList<String>();
- for (String path :
System.getProperty("java.class.path").split(File.pathSeparator)) {
- result.add(path);
- }
-
- result.add(CompilerHelper.ANNOTATED_SOURCE_OUTPUT);
- result.add(SAMPLES_PATH);
-
- return result.toArray(new String[0]);
- }
-
- @Before
- public void givenCompiler() throws Exception {
- compiler = new CompilerHelper(SAMPLES_PATH, new
RequestProcessor());
- }
+ private static final String SAMPLES_PATH = "dummyservice";
+ private final BinaryClassLoader classLoader = new
BinaryClassLoader(getClassPath());
+ private CompilerHelper compiler;

- @After
- public void finalizeCompiler() throws IOException {
- compiler.close();
- compiler = null;
- }
-
- @Test
- public void shouldCompileController() {
- assertEquals(Diagnostics.EMPTY,
-
compiler.compile("/net/geant/perfsonar/dummyservice/ServiceController.java"));
- }
+ private static String[] getClassPath() {
+ final List<String> result = new ArrayList<String>();
+ for (String path :
System.getProperty("java.class.path").split(File.pathSeparator)) {
+ result.add(path);
+ }

- @Test
- public void shouldConfigureSetupData() throws Exception {
-
compiler.compile("/net/geant/perfsonar/dummyservice/ServiceController.java");
-
classLoader.loadClass("net.geant.perfsonar.Handlers").newInstance();
- assertNotNull(Configuration.getHandler("SetupDataRequest"));
- }
-
- @Test
- public void shouldConfigureMetadataKey() throws Exception {
-
compiler.compile("/net/geant/perfsonar/dummyservice/ServiceController.java");
-
classLoader.loadClass("net.geant.perfsonar.Handlers").newInstance();
- assertNotNull(Configuration.getHandler("MetadataKeyRequest"));
- }
+ result.add(CompilerHelper.ANNOTATED_SOURCE_OUTPUT);
+ result.add(SAMPLES_PATH);

+ return result.toArray(new String[0]);
+ }
+
+ @Before
+ public void givenCompiler() throws Exception {
+ compiler = new CompilerHelper(SAMPLES_PATH, new RequestProcessor());
+ }
+
+ @After
+ public void finalizeCompiler() throws IOException {
+ compiler.close();
+ compiler = null;
+ }
+
+ @Test
+ public void shouldCompileController() {
+ assertEquals(Diagnostics.EMPTY,
compiler.compile("/net/geant/perfsonar/dummyservice/ServiceController.java"));
+ }
+
+ @Test
+ public void shouldConfigureSetupData() throws Exception {
+
compiler.compile("/net/geant/perfsonar/dummyservice/ServiceController.java");
+ classLoader.loadClass("net.geant.perfsonar.Handlers").newInstance();
+ assertNotNull(Configuration.getHandler("SetupDataRequest"));
+ }
+
+ @Test
+ public void shouldConfigureMetadataKey() throws Exception {
+
compiler.compile("/net/geant/perfsonar/dummyservice/ServiceController.java");
+ classLoader.loadClass("net.geant.perfsonar.Handlers").newInstance();
+ assertNotNull(Configuration.getHandler("MetadataKeyRequest"));
+ }
+
}

Modified:
trunk/perfsonar-base/apt/src/test/java/net/geant/perfsonar/annotations/XPathProcessorTest.java
===================================================================
---
trunk/perfsonar-base/apt/src/test/java/net/geant/perfsonar/annotations/XPathProcessorTest.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/apt/src/test/java/net/geant/perfsonar/annotations/XPathProcessorTest.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -10,7 +10,6 @@
import java.util.ArrayList;
import java.util.List;

-import net.geant.perfsonar.annotations.selftest.SelfTestLoggerHelper;
import net.geant.perfsonar.annotations.selftest.compiler.BinaryClassLoader;
import net.geant.perfsonar.annotations.selftest.compiler.CompilerHelper;
import net.geant.perfsonar.annotations.selftest.compiler.Diagnostics;
@@ -23,108 +22,99 @@
import org.xml.sax.InputSource;

public class XPathProcessorTest {
- private static final String SAMPLES_PATH = "dummyservice";
- final BinaryClassLoader classLoader = new
BinaryClassLoader(getClassPath());
- private CompilerHelper compiler;
-
- final SelfTestLoggerHelper logger = new SelfTestLoggerHelper();
-
- private static String[] getClassPath() {
- final List<String> result = new ArrayList<String>();
- for (String path :
System.getProperty("java.class.path").split(File.pathSeparator)) {
- result.add(path);
- }
-
- result.add(CompilerHelper.ANNOTATED_SOURCE_OUTPUT);
- result.add(SAMPLES_PATH);
-
- return result.toArray(new String[0]);
- }
+ private static final String SAMPLES_PATH = "dummyservice";
+ private final BinaryClassLoader classLoader = new
BinaryClassLoader(getClassPath());
+ private CompilerHelper compiler;

- @Before
- public void givenCompiler() throws Exception {
- compiler = new CompilerHelper(SAMPLES_PATH, new
XPathProcessor());
- }
+ private static String[] getClassPath() {
+ final List<String> result = new ArrayList<String>();
+ for (String path :
System.getProperty("java.class.path").split(File.pathSeparator)) {
+ result.add(path);
+ }

- @After
- public void finalizeCompiler() throws IOException {
- compiler.close();
- compiler = null;
- }
+ result.add(CompilerHelper.ANNOTATED_SOURCE_OUTPUT);
+ result.add(SAMPLES_PATH);

- @Test
- public void shouldCompileValidXPaths() {
- assertEquals(Diagnostics.EMPTY,
-
compiler.compile("/net/geant/perfsonar/dummyservice/xpath/NMWGMessage.java"));
- }
-
- @Test
- public void shouldNotCompileAbstractClass() {
- assertEquals(
- new Diagnostics()
- .addAbstractClassViolationAtLine(6),
-
-
compiler.compile("/net/geant/perfsonar/dummyservice/xpath/InvalidXPathsAbstractClass.java"));
- }
-
- @Test
- public void shouldNotCompileInvalidXPaths() {
- assertEquals(
- new Diagnostics()
- .addAbstractClassViolationAtLine(22)
- .addAbstractMethodViolationAtLine(27)
- .addNumberOfParametersViolationAtLine(31)
- .addStaticMethodViolationAtLine(36)
- .addStaticMethodViolationAtLine(36)
- .addRangeViolationAtLine(36),
-
compiler.compile("/net/geant/perfsonar/dummyservice/xpath/InvalidXPaths.java"));
- }
-
- @SuppressWarnings("unchecked")
- @Test
- public void shouldDeserializeNMWGMessage() throws Exception {
- compiler.compile(
-
"/net/geant/perfsonar/dummyservice/xpath/NMWGMessage.java",
-
"/net/geant/perfsonar/dummyservice/xpath/EchoMessage.java");
-
-
classLoader.loadClass("net.geant.perfsonar.XPaths").newInstance();
-
- final Class<?> nmwgClass =
classLoader.loadClass("net.geant.perfsonar.dummyservice.xpath.NMWGMessage");
- final Class<?> echoClass =
classLoader.loadClass("net.geant.perfsonar.dummyservice.xpath.EchoMessage");
-
- final XPathDeserializer deserializer = new
XPathDeserializer();
- final List<Object> objects = (List<Object>)
deserializer.deserialize(new InputSource(toEchoRequest("request1")));
- Object msg = getObjects(nmwgClass, objects).get(0);
- Object echo = getObjects(echoClass, objects).get(0);
-
- assertEquals("request1",
msg.getClass().getMethod("getId").invoke(msg));
- assertEquals("EchoRequest",
msg.getClass().getMethod("getType").invoke(msg));
-
assertEquals("http://schemas.perfsonar.net/tools/admin/echo/2.0";,
echo.getClass().getMethod("getEventType").invoke(echo));
- assertEquals(nmwgClass.getMethod("getId"),
XPathDeserializer.findIdentifier(nmwgClass));
- }
+ return result.toArray(new String[0]);
+ }

- @SuppressWarnings("unchecked")
- private <T> List<T> getObjects(Class<T> type, List<Object> objects) {
- final List<T> result = new ArrayList<T>();
- for (Object obj : objects) {
- if (obj.getClass().equals(type)) {
- result.add((T) obj);
- }
- }
- return result;
- }
-
- private Reader toEchoRequest(String id) {
- final StringWriter writer = new StringWriter();
- writer.write("<?xml version='1.0' encoding='UTF-8'?>");
- writer.write("<nmwg:message
xmlns:nmwg='http://ggf.org/ns/nmwg/base/2.0/' id='");
- writer.write(id);
- writer.write("' type='EchoRequest'>");
- writer.write("<nmwg:metadata id='meta'>");
-
writer.write("<nmwg:eventType>http://schemas.perfsonar.net/tools/admin/echo/2.0</nmwg:eventType>");
- writer.write("</nmwg:metadata>");
- writer.write("<nmwg:data id='data' metadataIdRef='meta' />");
- writer.write("</nmwg:message>");
- return new StringReader(writer.toString());
- }
+ @Before
+ public void givenCompiler() throws Exception {
+ compiler = new CompilerHelper(SAMPLES_PATH, new XPathProcessor());
+ }
+
+ @After
+ public void finalizeCompiler() throws IOException {
+ compiler.close();
+ compiler = null;
+ }
+
+ @Test
+ public void shouldCompileValidXPaths() {
+ assertEquals(Diagnostics.EMPTY,
compiler.compile("/net/geant/perfsonar/dummyservice/xpath/NMWGMessage.java"));
+ }
+
+ @Test
+ public void shouldNotCompileAbstractClass() {
+ assertEquals(new Diagnostics().addAbstractClassViolationAtLine(6),
+
+
compiler.compile("/net/geant/perfsonar/dummyservice/xpath/InvalidXPathsAbstractClass.java"));
+ }
+
+ @Test
+ public void shouldNotCompileInvalidXPaths() {
+ assertEquals(new
Diagnostics().addAbstractClassViolationAtLine(7).addAbstractMethodViolationAtLine(11)
+
.addNumberOfParametersViolationAtLine(15).addStaticMethodViolationAtLine(20)
+
.addStaticMethodViolationAtLine(20).addRangeViolationAtLine(20),
+
compiler.compile("/net/geant/perfsonar/dummyservice/xpath/InvalidXPaths.java"));
+ }
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public void shouldDeserializeNMWGMessage() throws Exception {
+
compiler.compile("/net/geant/perfsonar/dummyservice/xpath/NMWGMessage.java",
+ "/net/geant/perfsonar/dummyservice/xpath/EchoMessage.java");
+
+ classLoader.loadClass("net.geant.perfsonar.XPaths").newInstance();
+
+ final Class<?> nmwgClass =
classLoader.loadClass("net.geant.perfsonar.dummyservice.xpath.NMWGMessage");
+ final Class<?> echoClass =
classLoader.loadClass("net.geant.perfsonar.dummyservice.xpath.EchoMessage");
+
+ final XPathDeserializer deserializer = new XPathDeserializer();
+ final List<Object> objects = (List<Object>) deserializer
+ .deserialize(new InputSource(toEchoRequest("request1")));
+ Object msg = getObjects(nmwgClass, objects).get(0);
+ Object echo = getObjects(echoClass, objects).get(0);
+
+ assertEquals("request1",
msg.getClass().getMethod("getId").invoke(msg));
+ assertEquals("EchoRequest",
msg.getClass().getMethod("getType").invoke(msg));
+ assertEquals("http://schemas.perfsonar.net/tools/admin/echo/2.0";,
echo.getClass().getMethod("getEventType")
+ .invoke(echo));
+ assertEquals(nmwgClass.getMethod("getId"),
XPathDeserializer.findIdentifier(nmwgClass));
+ }
+
+ @SuppressWarnings("unchecked")
+ private <T> List<T> getObjects(Class<T> type, List<Object> objects) {
+ final List<T> result = new ArrayList<T>();
+ for (Object obj : objects) {
+ if (obj.getClass().equals(type)) {
+ result.add((T) obj);
+ }
+ }
+ return result;
+ }
+
+ private Reader toEchoRequest(String id) {
+ final StringWriter writer = new StringWriter();
+ writer.write("<?xml version='1.0' encoding='UTF-8'?>");
+ writer.write("<nmwg:message
xmlns:nmwg='http://ggf.org/ns/nmwg/base/2.0/' id='");
+ writer.write(id);
+ writer.write("' type='EchoRequest'>");
+ writer.write("<nmwg:metadata id='meta'>");
+
writer.write("<nmwg:eventType>http://schemas.perfsonar.net/tools/admin/echo/2.0</nmwg:eventType>");
+ writer.write("</nmwg:metadata>");
+ writer.write("<nmwg:data id='data' metadataIdRef='meta' />");
+ writer.write("</nmwg:message>");
+ return new StringReader(writer.toString());
+ }
}

Modified:
trunk/perfsonar-base/apt/src/test/java/net/geant/perfsonar/annotations/selftest/SelfTestLoggerHelper.java
===================================================================
---
trunk/perfsonar-base/apt/src/test/java/net/geant/perfsonar/annotations/selftest/SelfTestLoggerHelper.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/apt/src/test/java/net/geant/perfsonar/annotations/selftest/SelfTestLoggerHelper.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -7,19 +7,19 @@
import net.geant.perfsonar.selftest.SelfTestLogger;

public class SelfTestLoggerHelper implements SelfTestLogger {
- private final Map<String, String> result = new Hashtable<String,
String>();
+ private final Map<String, String> result = new Hashtable<String,
String>();

- @Override
- public void success(String name, String successMessage) {
- result.put(name, successMessage);
- }
+ @Override
+ public void success(String name, String successMessage) {
+ result.put(name, successMessage);
+ }

- @Override
- public void failure(String name, String message) {
- result.put(name, message);
- }
-
- public Map<String, String> toMap() {
- return Collections.unmodifiableMap(result);
- }
+ @Override
+ public void failure(String name, String message) {
+ result.put(name, message);
+ }
+
+ public Map<String, String> toMap() {
+ return Collections.unmodifiableMap(result);
+ }
}

Modified:
trunk/perfsonar-base/apt/src/test/java/net/geant/perfsonar/annotations/selftest/SelfTestProcessorTest.java
===================================================================
---
trunk/perfsonar-base/apt/src/test/java/net/geant/perfsonar/annotations/selftest/SelfTestProcessorTest.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/apt/src/test/java/net/geant/perfsonar/annotations/selftest/SelfTestProcessorTest.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -20,109 +20,102 @@
import org.junit.Test;

public class SelfTestProcessorTest {
- private static final String SAMPLES_PATH = "dummyservice";
- final BinaryClassLoader classLoader = new
BinaryClassLoader(getClassPath());
- private CompilerHelper compiler;
- private Scheduler scheduler = new Scheduler() {
- @Override
- public void runInParallel(Runnable runnable) {
- runnable.run();
- }
+ private static final String SAMPLES_PATH = "dummyservice";
+ private final BinaryClassLoader classLoader = new
BinaryClassLoader(getClassPath());
+ private CompilerHelper compiler;
+ private Scheduler scheduler = new Scheduler() {
+ @Override
+ public void runInParallel(Runnable runnable) {
+ runnable.run();
+ }

- @Override
- public void runEvery(int seconds, Runnable task) {
- }
+ @Override
+ public void runEvery(int seconds, Runnable task) {
+ }

- @Override
- public void stop(Runnable task) {
- }
+ @Override
+ public void stop(Runnable task) {
+ }

- @Override
- public void stopAll() {
- }
+ @Override
+ public void stopAll() {
+ }

- @Override
- public void waitToFinish(Runnable... tasks)
- throws InterruptedException,
ExecutionException {
- // TODO Auto-generated method stub
-
- }
- };
- final SelfTestLoggerHelper logger = new SelfTestLoggerHelper();
-
- private static String[] getClassPath() {
- final List<String> result = new ArrayList<String>();
- for (String path :
System.getProperty("java.class.path").split(File.pathSeparator)) {
- result.add(path);
- }
-
- result.add(CompilerHelper.ANNOTATED_SOURCE_OUTPUT);
- result.add(SAMPLES_PATH);
-
- return result.toArray(new String[0]);
- }
+ @Override
+ public void waitToFinish(Runnable... tasks) throws
InterruptedException, ExecutionException {
+ // TODO Auto-generated method stub

- @Before
- public void givenCompiler() throws Exception {
- compiler = new CompilerHelper(SAMPLES_PATH, new
SelfTestProcessor());
- }
+ }
+ };
+ private final SelfTestLoggerHelper logger = new SelfTestLoggerHelper();

- @After
- public void finalizeCompiler() throws IOException {
- compiler.close();
- compiler = null;
- }
+ private static String[] getClassPath() {
+ final List<String> result = new ArrayList<String>();
+ for (String path :
System.getProperty("java.class.path").split(File.pathSeparator)) {
+ result.add(path);
+ }

- @Test
- public void shouldCompileValidSelfTests() {
- assertEquals(Diagnostics.EMPTY,
-
compiler.compile("/net/geant/perfsonar/dummyservice/selftest/ValidSelfTests.java"));
- }
-
- @Test
- public void shouldNotCompileAbstractClass() {
- assertEquals(
- new Diagnostics()
- .addAbstractClassViolationAtLine(5),
-
-
compiler.compile("/net/geant/perfsonar/dummyservice/selftest/InvalidSelfTestsAbstractClass.java"));
- }
-
- @Test
- public void shouldNotCompileInvalidSelfTests() {
- assertEquals(
- new Diagnostics()
- .addAbstractClassViolationAtLine(7)
-// .addSelfTestReturnTypeViolation(10)
- .addAbstractMethodViolationAtLine(16)
- .addRangeViolationAtLine(16)
- .addNumberOfParametersViolationAtLine(20)
- .addStaticMethodViolationAtLine(26)
- .addRangeViolationAtLine(26)
- .addDuplicatedSelfTestNameViolationAtLine(36)
- .addNoSelfTestDataProvidedViolationAtLine(42)
- .addSelfTestDataReturnTypeViolationAtLine(52),
-
-
compiler.compile("/net/geant/perfsonar/dummyservice/selftest/InvalidSelfTests.java"));
- }
-
- @Test
- public void shouldRunValidSelfTests() throws Exception {
-
compiler.compile("/net/geant/perfsonar/dummyservice/selftest/ValidSelfTests.java");
- classLoader.newSelfTestRunner().runSuite(scheduler, logger);
-
- final Map<String, String> expected = new Hashtable<String,
String>();
- expected.put("constant", "Added constant.");
- expected.put("add string 0", "Added Parameter1.");
- expected.put("add string 1", "Added Parameter2.");
- expected.put("add string 2", "Added Parameter3.");
- expected.put("add integer 0", "Added 0 at 0.");
- expected.put("add integer 1", "Added 1 at 1.");
- expected.put("add integer 2", "Added 2 at 2.");
- expected.put("add integer 3", "Value must be greater or equal
to 0.");
- expected.put("add integer 4", "Added 3 at 4.");
- expected.put("checked exception", "Checked exception was
thrown successfully.");
- expected.put("independent", "Self tests are independent from
each other.");
- assertEquals(expected, logger.toMap());
- }
+ result.add(CompilerHelper.ANNOTATED_SOURCE_OUTPUT);
+ result.add(SAMPLES_PATH);
+
+ return result.toArray(new String[0]);
+ }
+
+ @Before
+ public void givenCompiler() throws Exception {
+ compiler = new CompilerHelper(SAMPLES_PATH, new SelfTestProcessor());
+ }
+
+ @After
+ public void finalizeCompiler() throws IOException {
+ compiler.close();
+ compiler = null;
+ }
+
+ @Test
+ public void shouldCompileValidSelfTests() {
+ assertEquals(Diagnostics.EMPTY,
+
compiler.compile("/net/geant/perfsonar/dummyservice/selftest/ValidSelfTests.java"));
+ }
+
+ @Test
+ public void shouldNotCompileAbstractClass() {
+ assertEquals(new Diagnostics().addAbstractClassViolationAtLine(5),
+
+
compiler.compile("/net/geant/perfsonar/dummyservice/selftest/InvalidSelfTestsAbstractClass.java"));
+ }
+
+ @Test
+ public void shouldNotCompileInvalidSelfTests() {
+ assertEquals(
+ new Diagnostics()
+ .addAbstractClassViolationAtLine(7)
+ // .addSelfTestReturnTypeViolation(10)
+
.addAbstractMethodViolationAtLine(16).addRangeViolationAtLine(16)
+
.addNumberOfParametersViolationAtLine(20).addStaticMethodViolationAtLine(26)
+
.addRangeViolationAtLine(26).addDuplicatedSelfTestNameViolationAtLine(36)
+
.addNoSelfTestDataProvidedViolationAtLine(42).addSelfTestDataReturnTypeViolationAtLine(52),
+
+
compiler.compile("/net/geant/perfsonar/dummyservice/selftest/InvalidSelfTests.java"));
+ }
+
+ @Test
+ public void shouldRunValidSelfTests() throws Exception {
+
compiler.compile("/net/geant/perfsonar/dummyservice/selftest/ValidSelfTests.java");
+ classLoader.newSelfTestRunner().runSuite(scheduler, logger);
+
+ final Map<String, String> expected = new Hashtable<String, String>();
+ expected.put("constant", "Added constant.");
+ expected.put("add string 0", "Added Parameter1.");
+ expected.put("add string 1", "Added Parameter2.");
+ expected.put("add string 2", "Added Parameter3.");
+ expected.put("add integer 0", "Added 0 at 0.");
+ expected.put("add integer 1", "Added 1 at 1.");
+ expected.put("add integer 2", "Added 2 at 2.");
+ expected.put("add integer 3", "Value must be greater or equal to
0.");
+ expected.put("add integer 4", "Added 3 at 4.");
+ expected.put("checked exception", "Checked exception was thrown
successfully.");
+ expected.put("independent", "Self tests are independent from each
other.");
+ assertEquals(expected, logger.toMap());
+ }
}

Modified:
trunk/perfsonar-base/apt/src/test/java/net/geant/perfsonar/annotations/selftest/compiler/BinaryClassLoader.java
===================================================================
---
trunk/perfsonar-base/apt/src/test/java/net/geant/perfsonar/annotations/selftest/compiler/BinaryClassLoader.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/apt/src/test/java/net/geant/perfsonar/annotations/selftest/compiler/BinaryClassLoader.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -10,57 +10,62 @@

public class BinaryClassLoader extends ClassLoader {

- private String[] paths;
+ private String[] paths;

- public BinaryClassLoader(String... paths) {
- super();
- this.paths = paths;
- }
-
- public SelfTestRunner newSelfTestRunner() throws
InstantiationException, IllegalAccessException, ClassNotFoundException {
-
loadClass("net.geant.perfsonar.SelfTestsConfiguration").newInstance();
- return new SelfTestRunner();
- }
-
- public Class<?> findClass(String name) throws ClassNotFoundException {
+ public BinaryClassLoader(String... paths) {
+ super();
+ this.paths = paths;
+ }
+
+ public SelfTestRunner newSelfTestRunner() throws InstantiationException,
IllegalAccessException,
+ ClassNotFoundException {
+
loadClass("net.geant.perfsonar.SelfTestsConfiguration").newInstance();
+ return new SelfTestRunner();
+ }
+
+ public Class<?> findClass(String name) throws ClassNotFoundException {
byte[] b;
- try {
- b = loadClassData(name);
- } catch (IOException e) {
- throw new ClassNotFoundException(e.getMessage());
- }
+ try {
+ b = loadClassData(name);
+ } catch (IOException e) {
+ throw new ClassNotFoundException(e.getMessage());
+ }
return defineClass(name, b, 0, b.length);
}

private byte[] loadClassData(String name) throws IOException {
final List<Byte> data = new ArrayList<Byte>();
-
+
FileInputStream in = null;
try {
- in = new FileInputStream(getFileName(name));
- for (int b = in.read(); b != -1; b = in.read())
- data.add((byte) b);
+ in = new FileInputStream(getFileName(name));
+ for (int b = in.read(); b != -1; b = in.read()) {
+ data.add((byte) b);
+ }
} finally {
- if (in != null)
- in.close();
+ if (in != null) {
+ in.close();
+ }
}
-
+
final byte[] result = new byte[data.size()];
int idx = 0;
- for (Byte b : data)
- result[idx++] = b;
-
+ for (Byte b : data) {
+ result[idx++] = b;
+ }
+
return result;
}
-
+
private String getFileName(String className) throws IOException {
- for (String path : paths) {
- final String temp = path + "/" + className.replaceAll("[.]",
"/") + ".class";
- if (new File(temp).exists())
- return temp;
- }
-
- throw new IOException("File for " + className + " class does not
exist.");
+ for (String path : paths) {
+ final String temp = path + "/" + className.replaceAll("[.]",
"/") + ".class";
+ if (new File(temp).exists()) {
+ return temp;
+ }
+ }
+
+ throw new IOException("File for " + className + " class does not
exist.");
}

}

Modified:
trunk/perfsonar-base/apt/src/test/java/net/geant/perfsonar/annotations/selftest/compiler/CompilerHelper.java
===================================================================
---
trunk/perfsonar-base/apt/src/test/java/net/geant/perfsonar/annotations/selftest/compiler/CompilerHelper.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/apt/src/test/java/net/geant/perfsonar/annotations/selftest/compiler/CompilerHelper.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -18,79 +18,76 @@
import javax.tools.ToolProvider;

public class CompilerHelper {
- public static final String ANNOTATED_SOURCE_OUTPUT = "annotated";
- private final JavaCompiler compiler;
- private final StandardJavaFileManager fileManager;
- private final DiagnosticCollector<JavaFileObject> diagnostics;
- private final String path;
- private Processor processor;
-
- public CompilerHelper(String path, Processor processor) throws
IOException {
- diagnostics = new DiagnosticCollector<JavaFileObject>();
- compiler = ToolProvider.getSystemJavaCompiler();
- fileManager = compiler.getStandardFileManager(diagnostics, null,
null);
- fileManager.setLocation(StandardLocation.SOURCE_OUTPUT,
Arrays.asList(new File(ANNOTATED_SOURCE_OUTPUT)));
- this.path = path;
- this.processor = processor;
- }
-
- //public List<Diagnostic<? extends JavaFileObject>> compile(Class<?>
clazz) {
- // return compile(clazz.getSimpleName() + ".java");
- //}
-
- public List<Diagnostic<? extends JavaFileObject>> compile(String...
fileNames) {
- final List<String> absoluteNames = new ArrayList<String>();
-
- for (String fileName : fileNames)
- absoluteNames.add(path + fileName);
-
- final Iterable<? extends JavaFileObject> compilationUnits =
- fileManager.getJavaFileObjectsFromStrings(absoluteNames);
+ public static final String ANNOTATED_SOURCE_OUTPUT = "annotated";
+ private final JavaCompiler compiler;
+ private final StandardJavaFileManager fileManager;
+ private final DiagnosticCollector<JavaFileObject> diagnostics;
+ private final String path;
+ private Processor processor;

- CompilationTask task =
- compiler.getTask(null, fileManager, diagnostics, null, null,
compilationUnits);
-
- task.setProcessors(Arrays.asList(processor));
-
- task.call();
- return sortByLineNumberAndMessage(diagnostics.getDiagnostics());
- }
-
- public void close() throws IOException {
- fileManager.close();
- }
-
- private List<Diagnostic<? extends JavaFileObject>>
sortByLineNumberAndMessage(
- List<Diagnostic<? extends JavaFileObject>> toSort) {
-
- final List<Diagnostic<? extends JavaFileObject>> result = new
ArrayList<Diagnostic<? extends JavaFileObject>>();
-
- for (Diagnostic<? extends JavaFileObject> d : toSort) {
- int idx = getIndex(d, result);
- if (idx == -1)
- result.add(d);
- else
- result.add(idx, d);
- }
-
- return result;
- }
+ public CompilerHelper(String path, Processor processor) throws
IOException {
+ diagnostics = new DiagnosticCollector<JavaFileObject>();
+ compiler = ToolProvider.getSystemJavaCompiler();
+ fileManager = compiler.getStandardFileManager(diagnostics, null,
null);
+ fileManager.setLocation(StandardLocation.SOURCE_OUTPUT,
Arrays.asList(new File(ANNOTATED_SOURCE_OUTPUT)));
+ this.path = path;
+ this.processor = processor;
+ }

- private int getIndex(Diagnostic<? extends JavaFileObject> d,
- List<Diagnostic<? extends JavaFileObject>> result) {
-
- int idx = 0;
- for (Diagnostic<? extends JavaFileObject> r : result) {
- if (d.getLineNumber() < r.getLineNumber()) {
- return idx;
- } else if (d.getLineNumber() == r.getLineNumber()) {
- if
(d.getMessage(Locale.getDefault()).compareTo(r.getMessage(Locale.getDefault()))
<= 0)
- return idx;
- }
-
- idx++;
- }
-
- return -1;
- }
+ public List<Diagnostic<? extends JavaFileObject>> compile(String...
fileNames) {
+ final List<String> absoluteNames = new ArrayList<String>();
+
+ for (String fileName : fileNames) {
+ absoluteNames.add(path + fileName);
+ }
+
+ final Iterable<? extends JavaFileObject> compilationUnits =
fileManager
+ .getJavaFileObjectsFromStrings(absoluteNames);
+
+ CompilationTask task = compiler.getTask(null, fileManager,
diagnostics, null, null, compilationUnits);
+
+ task.setProcessors(Arrays.asList(processor));
+
+ task.call();
+ return sortByLineNumberAndMessage(diagnostics.getDiagnostics());
+ }
+
+ public void close() throws IOException {
+ fileManager.close();
+ }
+
+ private List<Diagnostic<? extends JavaFileObject>>
sortByLineNumberAndMessage(
+ List<Diagnostic<? extends JavaFileObject>> toSort) {
+
+ final List<Diagnostic<? extends JavaFileObject>> result = new
ArrayList<Diagnostic<? extends JavaFileObject>>();
+
+ for (Diagnostic<? extends JavaFileObject> d : toSort) {
+ int idx = getIndex(d, result);
+ if (idx == -1) {
+ result.add(d);
+ } else {
+ result.add(idx, d);
+ }
+ }
+
+ return result;
+ }
+
+ private int getIndex(Diagnostic<? extends JavaFileObject> d,
List<Diagnostic<? extends JavaFileObject>> result) {
+
+ int idx = 0;
+ for (Diagnostic<? extends JavaFileObject> r : result) {
+ if (d.getLineNumber() < r.getLineNumber()) {
+ return idx;
+ } else if (d.getLineNumber() == r.getLineNumber()) {
+ if
(d.getMessage(Locale.getDefault()).compareTo(r.getMessage(Locale.getDefault()))
<= 0) {
+ return idx;
+ }
+ }
+
+ idx++;
+ }
+
+ return -1;
+ }
}

Modified:
trunk/perfsonar-base/apt/src/test/java/net/geant/perfsonar/annotations/selftest/compiler/DiagnosticImpl.java
===================================================================
---
trunk/perfsonar-base/apt/src/test/java/net/geant/perfsonar/annotations/selftest/compiler/DiagnosticImpl.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/apt/src/test/java/net/geant/perfsonar/annotations/selftest/compiler/DiagnosticImpl.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -6,91 +6,92 @@
import javax.tools.JavaFileObject;

class DiagnosticImpl implements Diagnostic<JavaFileObject> {
-
- private final long lineNumber;
- private final String message;

- public DiagnosticImpl(long lineNumber, String message) {
- this.lineNumber = lineNumber;
- this.message = message;
- }
-
- @Override
- public String toString() {
- return lineNumber + ": " + message;
- }
-
- @Override
- public boolean equals(Object object) {
- if (!(object instanceof Diagnostic<?>))
- return false;
-
- final Diagnostic<?> d = (Diagnostic<?>) object;
-
- return ((d.getLineNumber() == lineNumber) &&
- getMessage(d).equals(message));
- }
-
- private String getMessage(Diagnostic<?> d) {
- String msg = d.getMessage(Locale.getDefault());
- int idx = msg.indexOf(":");
- msg = msg.substring(idx + 1).trim();
-
- if (idx != -1)
- return msg.substring(msg.indexOf(":") + 1).trim();
-
- return msg;
- }
+ private final long lineNumber;
+ private final String message;

- @Override
- public javax.tools.Diagnostic.Kind getKind() {
- return Kind.ERROR;
- }
+ public DiagnosticImpl(long lineNumber, String message) {
+ this.lineNumber = lineNumber;
+ this.message = message;
+ }

- @Override
- public JavaFileObject getSource() {
- // TODO Auto-generated method stub
- return null;
- }
+ @Override
+ public String toString() {
+ return lineNumber + ": " + message;
+ }

- @Override
- public long getPosition() {
- // TODO Auto-generated method stub
- return 0;
- }
+ @Override
+ public boolean equals(Object object) {
+ if (!(object instanceof Diagnostic<?>)) {
+ return false;
+ }

- @Override
- public long getStartPosition() {
- // TODO Auto-generated method stub
- return 0;
- }
+ final Diagnostic<?> d = (Diagnostic<?>) object;

- @Override
- public long getEndPosition() {
- // TODO Auto-generated method stub
- return 0;
- }
+ return (d.getLineNumber() == lineNumber) &&
getMessage(d).equals(message);
+ }

- @Override
- public long getLineNumber() {
- return lineNumber;
- }
+ private String getMessage(Diagnostic<?> d) {
+ String msg = d.getMessage(Locale.getDefault());
+ int idx = msg.indexOf(":");
+ msg = msg.substring(idx + 1).trim();

- @Override
- public long getColumnNumber() {
- // TODO Auto-generated method stub
- return 0;
- }
+ if (idx != -1) {
+ return msg.substring(msg.indexOf(":") + 1).trim();
+ }

- @Override
- public String getCode() {
- // TODO Auto-generated method stub
- return null;
- }
+ return msg;
+ }

- @Override
- public String getMessage(Locale locale) {
- return message;
- }
+ @Override
+ public javax.tools.Diagnostic.Kind getKind() {
+ return Kind.ERROR;
+ }

+ @Override
+ public JavaFileObject getSource() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public long getPosition() {
+ // TODO Auto-generated method stub
+ return 0;
+ }
+
+ @Override
+ public long getStartPosition() {
+ // TODO Auto-generated method stub
+ return 0;
+ }
+
+ @Override
+ public long getEndPosition() {
+ // TODO Auto-generated method stub
+ return 0;
+ }
+
+ @Override
+ public long getLineNumber() {
+ return lineNumber;
+ }
+
+ @Override
+ public long getColumnNumber() {
+ // TODO Auto-generated method stub
+ return 0;
+ }
+
+ @Override
+ public String getCode() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public String getMessage(Locale locale) {
+ return message;
+ }
+
}

Modified:
trunk/perfsonar-base/apt/src/test/java/net/geant/perfsonar/annotations/selftest/compiler/Diagnostics.java
===================================================================
---
trunk/perfsonar-base/apt/src/test/java/net/geant/perfsonar/annotations/selftest/compiler/Diagnostics.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/apt/src/test/java/net/geant/perfsonar/annotations/selftest/compiler/Diagnostics.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -6,73 +6,76 @@
import javax.tools.Diagnostic;
import javax.tools.JavaFileObject;

-
public class Diagnostics {

- public static final Diagnostics EMPTY = new Diagnostics();
- final List<Diagnostic<? extends JavaFileObject>> diagnostics = new
ArrayList<Diagnostic<? extends JavaFileObject>>();
-
- public Diagnostics add(int lineNumber, String message) {
- diagnostics.add(new DiagnosticImpl(lineNumber, message));
- return this;
- }
+ public static final Diagnostics EMPTY = new Diagnostics();
+ private final List<Diagnostic<? extends JavaFileObject>> diagnostics =
new ArrayList<Diagnostic<? extends JavaFileObject>>();

- public boolean equals(Object obj) {
- if (!(obj instanceof List<?>))
- return false;
-
- return diagnostics.equals(obj);
- }
-
- public String toString() {
- return diagnostics.toString();
- }
+ public Diagnostics add(int lineNumber, String message) {
+ diagnostics.add(new DiagnosticImpl(lineNumber, message));
+ return this;
+ }

- public Diagnostics addAbstractClassViolationAtLine(int lineNumber) {
- return add(lineNumber, "The class cannot be abstract.");
- }
+ public boolean equals(Object obj) {
+ if (!(obj instanceof List<?>)) {
+ return false;
+ }

-// public Diagnostics addSelfTestReturnTypeViolation(int lineNumber) {
-// return add(lineNumber, "Type of the method must be void.");
-// }
+ return diagnostics.equals(obj);
+ }

- public Diagnostics addAbstractMethodViolationAtLine(int lineNumber) {
- return add(lineNumber, "The method cannot be abstract");
- }
+ public String toString() {
+ return diagnostics.toString();
+ }

- public Diagnostics addRangeViolationAtLine(int lineNumber) {
- return add(lineNumber, "The method must be public.");
- }
-
- public Diagnostics addSetterViolationAtLine(int lineNumber) {
- return add(lineNumber, "The method must have one parameter.");
- }
+ public Diagnostics addAbstractClassViolationAtLine(int lineNumber) {
+ return add(lineNumber, "The class cannot be abstract.");
+ }

- public Diagnostics addNumberOfParametersViolationAtLine(int
lineNumber) {
- return add(lineNumber, "The method cannot have more than one
parameter.");
- }
+ // public Diagnostics addSelfTestReturnTypeViolation(int lineNumber) {
+ // return add(lineNumber, "Type of the method must be void.");
+ // }

- public Diagnostics addStaticMethodViolationAtLine(int lineNumber) {
- return add(lineNumber, "The method cannot be static.");
- }
+ public Diagnostics addAbstractMethodViolationAtLine(int lineNumber) {
+ return add(lineNumber, "The method cannot be abstract");
+ }

- public Diagnostics addDuplicatedSelfTestNameViolationAtLine(int
lineNumber) {
- return add(lineNumber, "Duplicated name of the self test.");
- }
+ public Diagnostics addRangeViolationAtLine(int lineNumber) {
+ return add(lineNumber, "The method must be public.");
+ }

- public Diagnostics addNoSelfTestDataProvidedViolationAtLine(int
lineNumber) {
- return add(lineNumber, "There are no self test data provided.
Add a public method annotatated with @SelfTestData of return type
java.util.List<java.lang.Integer>");
- }
+ public Diagnostics addSetterViolationAtLine(int lineNumber) {
+ return add(lineNumber, "The method must have one parameter.");
+ }

- public Diagnostics addSelfTestDataReturnTypeViolationAtLine(int
lineNumber) {
- return add(lineNumber, "The return type of the method must be
of type java.util.List<E>");
- }
+ public Diagnostics addNumberOfParametersViolationAtLine(int lineNumber) {
+ return add(lineNumber, "The method cannot have more than one
parameter.");
+ }

-// public Diagnostics addSetterReturnTypeViolationAtLine(int lineNumber)
{
-// return add(lineNumber, "Type of the method must be void.");
-// }
-
- public Diagnostics addSetterArgumentTypeViolationAtLine(int
lineNumber) {
- return add(lineNumber, "The method must have exactly one
parameter.");
- }
+ public Diagnostics addStaticMethodViolationAtLine(int lineNumber) {
+ return add(lineNumber, "The method cannot be static.");
+ }
+
+ public Diagnostics addDuplicatedSelfTestNameViolationAtLine(int
lineNumber) {
+ return add(lineNumber, "Duplicated name of the self test.");
+ }
+
+ public Diagnostics addNoSelfTestDataProvidedViolationAtLine(int
lineNumber) {
+ return add(
+ lineNumber,
+ "There are no self test data provided. "
+ + "Add a public method annotatated with @SelfTestData of
return type java.util.List<java.lang.Integer>");
+ }
+
+ public Diagnostics addSelfTestDataReturnTypeViolationAtLine(int
lineNumber) {
+ return add(lineNumber, "The return type of the method must be of
type java.util.List<E>");
+ }
+
+ // public Diagnostics addSetterReturnTypeViolationAtLine(int lineNumber)
{
+ // return add(lineNumber, "Type of the method must be void.");
+ // }
+
+ public Diagnostics addSetterArgumentTypeViolationAtLine(int lineNumber) {
+ return add(lineNumber, "The method must have exactly one
parameter.");
+ }
}


Property changes on: trunk/perfsonar-base/base
___________________________________________________________________
Modified: svn:ignore
- target
velocity.log*
.settings
.project
.classpath

logs

+ target
velocity.log*
.settings
.project
.classpath

logs

.checkstyle

.pmd

.pmdruleset


Modified:
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/Configuration.java
===================================================================
---
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/Configuration.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/Configuration.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -7,74 +7,83 @@
/**
* Represents configuration necessary for handling requests.
*
- * It consists of a set of static methods to improve the readability of the
code.
- * Please static import all the methods from the class.
+ * It consists of a set of static methods to improve the readability of the
+ * code. Please static import all the methods from the class.
*
* In order to configure the handler for the given type of request the
following
* code snippet must be used:
*
<code>configure(when("SetupData").then(ServiceController.class).createUser(any(String.class)))</code>
*
- * Configuration records the method invocation and assigns it to the given
request type.
- * This way of configuring is developer friendly. It ensures that when the
code
- * will be refactored, configuration will refactor with code too.
- * Furthermore, it checks at compile time whether controller methods are not
void.
- * They must provide some results that are serialized as responses to
clients.
- * Method configure ensures on compilation phase that the controller method
will return type.
- * Method when describes the type of the request. In this example the type
is SetupDataRequest.
- * Method then starts recording method invocation. In order to compile the
code correctly
- * one must specify class of the controller method. Then the appropriate
method is invoked.
- * In this example it is createUser(String). Please note that no real
invocation takes place.
- * Controller methods may contain zero or one parameters. If they contain a
parameter then
- * in order to compile an argument must be passed. Method any provide
compiler friendly
- * implementation. As an argument one provide type of the argument.
+ * Configuration records the method invocation and assigns it to the given
+ * request type. This way of configuring is developer friendly. It ensures
that
+ * when the code will be refactored, configuration will refactor with code
too.
+ * Furthermore, it checks at compile time whether controller methods are not
+ * void. They must provide some results that are serialized as responses to
+ * clients. Method configure ensures on compilation phase that the controller
+ * method will return type. Method when describes the type of the request. In
+ * this example the type is SetupDataRequest. Method then starts recording
+ * method invocation. In order to compile the code correctly one must specify
+ * class of the controller method. Then the appropriate method is invoked. In
+ * this example it is createUser(String). Please note that no real invocation
+ * takes place. Controller methods may contain zero or one parameters. If
they
+ * contain a parameter then in order to compile an argument must be passed.
+ * Method any provide compiler friendly implementation. As an argument one
+ * provide type of the argument.
+ *
* @author <a
href="mailto:">Blazej
Pietrzak</a>
*/
-public class Configuration {
- private static Method method;
- private static String type;
- private static Map<String, Method> handlers = new Hashtable<String,
Method>();
+public final class Configuration {
+ private static Method method;
+ private static String type;
+ private static Map<String, Method> handlers = new Hashtable<String,
Method>();

- /**
- * Method used for configuration of handlers. It ensures on the
compile time phase
- * that handlers return types that are later on serialized as
responses.
- * Please note that the handler cannot be of type void.
- *
- * @param executeMethod
- */
- public static <T> void configure(T executeMethod) {
- handlers.put(type, method);
- }
+ private Configuration() {
+ // Utility class, we don't want to be instantiated directly, we're
private
+ super();
+ }

- /**
- *
- * @param messageType
- * @return
- */
- public static HandlerConfiguration when(String messageType) {
- return new HandlerConfiguration(messageType);
- }
+ /**
+ * Method used for configuration of handlers. It ensures on the compile
time
+ * phase that handlers return types that are later on serialized as
+ * responses. Please note that the handler cannot be of type void.
+ *
+ * @param executeMethod
+ */
+ public static <T> void configure(T executeMethod) {
+ handlers.put(type, method);
+ }

- public static <T> T any(Class<T> type) {
- return null;
- }
+ /**
+ *
+ * @param messageType
+ * @return
+ */
+ public static HandlerConfiguration when(String messageType) {
+ return new HandlerConfiguration(messageType);
+ }

- /**
- *
- * @param type request type
- * @return controller method that handles the request
- */
- public static Method getHandler(String type) {
- return handlers.get(type);
- }
+ public static <T> T any(Class<T> type) {
+ return null;
+ }

- public static void setTemp(String type, Method method) {
- Configuration.type = type;
- Configuration.method = method;
- }
+ /**
+ *
+ * @param type
+ * request type
+ * @return controller method that handles the request
+ */
+ public static Method getHandler(String type) {
+ return handlers.get(type);
+ }

- public static void clearConfiguration() {
- type = null;
- method = null;
- handlers.clear();
- }
+ public static void setTemp(String type, Method method) {
+ Configuration.type = type;
+ Configuration.method = method;
+ }
+
+ public static void clearConfiguration() {
+ type = null;
+ method = null;
+ handlers.clear();
+ }
}

Modified:
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/HandlerConfiguration.java
===================================================================
---
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/HandlerConfiguration.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/HandlerConfiguration.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -10,26 +10,25 @@

public class HandlerConfiguration implements MethodInterceptor {

- private String type;
- private List<String> restrictedMethods = Arrays.asList("equals",
"hashCode", "finalize", "toString");
-
- public HandlerConfiguration(String type) {
- this.type = type;
- }
-
- @SuppressWarnings("unchecked")
- public <T> T then(Class<T> controller) throws InstantiationException,
IllegalAccessException {
- return (T) Enhancer.create(controller, this);
- }
+ private String type;
+ private List<String> restrictedMethods = Arrays.asList("equals",
"hashCode", "finalize", "toString");

- public Object intercept(Object obj, Method method, Object[] args,
- MethodProxy proxy) throws Throwable {
-
- if (restrictedMethods.contains(method.getName())) {
- return proxy.invokeSuper(obj, args);
- }
-
- Configuration.setTemp(type, method);
- return null;
- }
+ public HandlerConfiguration(String type) {
+ this.type = type;
+ }
+
+ @SuppressWarnings("unchecked")
+ public <T> T then(Class<T> controller) throws InstantiationException,
IllegalAccessException {
+ return (T) Enhancer.create(controller, this);
+ }
+
+ public Object intercept(Object obj, Method method, Object[] args,
MethodProxy proxy) throws Throwable {
+
+ if (restrictedMethods.contains(method.getName())) {
+ return proxy.invokeSuper(obj, args);
+ }
+
+ Configuration.setTemp(type, method);
+ return null;
+ }
}

Modified:
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/Logger.java
===================================================================
--- trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/Logger.java
2013-05-07 14:18:22 UTC (rev 6370)
+++ trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/Logger.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -2,5 +2,5 @@

public interface Logger {

- void error(String message, Throwable ex);
+ void error(String message, Throwable ex);
}

Modified:
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/NMWGMessage.java
===================================================================
---
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/NMWGMessage.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/NMWGMessage.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -7,94 +7,106 @@
*/
public class NMWGMessage {
private String type;
- private String eventType;
- private String id;
- private String key;
- private String testName;
+ private String eventType;
+ private String id;
+ private String key;

- public NMWGMessage() {
- }
- public NMWGMessage(String requestId, String type) {
- this.id = requestId;
- this.type = type;
- }
- public String getType() {
- return type;
- }
- public void setType(String type) {
- this.type = type;
- }
+ public NMWGMessage() {
+ }

- public boolean isEchoRequest() {
- return type.equals("EchoRequest") &&
eventType.equals("http://schemas.perfsonar.net/tools/admin/echo/2.0";);
- }
- public boolean isSelfTestRequest() {
- return type.equals("EchoRequest") &&
eventType.startsWith("http://schemas.perfsonar.net/tools/admin/selftest/";);
- }
+ public NMWGMessage(String requestId, String type) {
+ this.id = requestId;
+ this.type = type;
+ }

- public String getId() {
- return id;
- }
- public void setId(String id) {
- this.id = id;
- }
-
- public String getEventType() {
- return eventType;
- }
- public void setEventType(String eventType) {
- this.eventType = eventType;
- }
- public String getKey() {
- return this.key;
- }
- public void setKey(String key) {
- this.key = key;
- }
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((id == null) ? 0 : id.hashCode());
- result = prime * result + ((type == null) ? 0 :
type.hashCode());
- return result;
- }
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- NMWGMessage other = (NMWGMessage) obj;
- if (id == null) {
- if (other.id != null)
- return false;
- } else if (!id.equals(other.id))
- return false;
- if (type == null) {
- if (other.type != null)
- return false;
- } else if (!type.equals(other.type))
- return false;
- return true;
- }
-
- public void setTestName(String name) {
- this.testName = name;
- }
-
- public String getTestName() {
- if (isRunSuite())
- return null;
-
- return
getEventType().substring(getEventType().lastIndexOf("/") + 1);
- }
-
- public boolean isRunSuite() {
- return getEventType().endsWith("/1.0") ||
getEventType().endsWith("/1.0/");
- }
-
-
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ public boolean isEchoRequest() {
+ return type.equals("EchoRequest") &&
eventType.equals("http://schemas.perfsonar.net/tools/admin/echo/2.0";);
+ }
+
+ public boolean isSelfTestRequest() {
+ return type.equals("EchoRequest") &&
eventType.startsWith("http://schemas.perfsonar.net/tools/admin/selftest/";);
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public String getEventType() {
+ return eventType;
+ }
+
+ public void setEventType(String eventType) {
+ this.eventType = eventType;
+ }
+
+ public String getKey() {
+ return this.key;
+ }
+
+ public void setKey(String key) {
+ this.key = key;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((id == null) ? 0 : id.hashCode());
+ result = prime * result + ((type == null) ? 0 : type.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null) {
+ return false;
+ }
+ if (getClass() != obj.getClass()) {
+ return false;
+ }
+ NMWGMessage other = (NMWGMessage) obj;
+ if (id == null) {
+ if (other.id != null) {
+ return false;
+ }
+ } else if (!id.equals(other.id)) {
+ return false;
+ }
+ if (type == null) {
+ if (other.type != null) {
+ return false;
+ }
+ } else if (!type.equals(other.type)) {
+ return false;
+ }
+ return true;
+ }
+
+ public String getTestName() {
+ if (isRunSuite()) {
+ return null;
+ }
+
+ return getEventType().substring(getEventType().lastIndexOf("/") + 1);
+ }
+
+ public boolean isRunSuite() {
+ return getEventType().endsWith("/1.0") ||
getEventType().endsWith("/1.0/");
+ }
+
}

Modified:
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/PerfSONAR.java
===================================================================
---
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/PerfSONAR.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/PerfSONAR.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -38,251 +38,251 @@
* @author <a
href="mailto:">Blazej
Pietrzak</a>
*/
public abstract class PerfSONAR implements Provider<StreamSource> {
- public static final Object ANY = null;
+ public static final Object ANY = null;

- private static int defaultThreadPoolSize = 10;
+ private static int defaultThreadPoolSize = 10;

- /*
- * FIXME: do we really need our own Logger? protected static final
- * net.geant.perfsonar.Logger logger = new
net.geant.perfsonar.Logger() {
- * public void error(String msg, Throwable ex) {
- * LoggerFactory.getLogger(PerfSONAR.class).error(msg, ex); } };
- */
- protected Logger logger = LoggerFactory.getLogger(getClass());
+ /*
+ * FIXME: do we really need our own Logger? protected static final
+ * net.geant.perfsonar.Logger logger = new net.geant.perfsonar.Logger() {
+ * public void error(String msg, Throwable ex) {
+ * LoggerFactory.getLogger(PerfSONAR.class).error(msg, ex); } };
+ */
+ protected Logger logger = LoggerFactory.getLogger(getClass());

- protected Scheduler scheduler = createThreadPool();
- protected boolean usingAPT = false;
+ protected Scheduler scheduler = createThreadPool();
+ protected boolean usingAPT = false;

- public PerfSONAR() {
- try {
- declarePrefix("nmwg",
"http://ggf.org/ns/nmwg/base/2.0/";);
- declarePrefix("nmwgr",
"http://ggf.org/ns/nmwg/result/2.0/";);
- declarePrefix("nmwgtopo",
"http://ggf.org/ns/nmwg/topology/2.0/";);
-
whenXPath("nmwg:message/@type").then(NMWGMessage.class).setType(
- any(String.class));
-
whenXPath("nmwg:message/@id").then(NMWGMessage.class).setId(
- any(String.class));
- whenXPath(
-
"nmwg:message/nmwg:metadata[@id='meta']/nmwg:eventType/text()")
-
.then(NMWGMessage.class).setEventType(any(String.class));
-
whenXPath("nmwg:message/nmwg:metadata/nmwg:key/text()").then(
-
NMWGMessage.class).setKey(any(String.class));
-
- Configuration.configure(when("EchoRequest")
-
.then(EchoRequestHandler.class).handleEcho(any(NMWGMessage.class)));
- } catch (Exception ex) {
- //No exception will be thrown. It is just for
compiling code.
- }
-
- loadConfiguration();
- EchoRequestHandler.setScheduler(scheduler);
- EchoRequestHandler.setServiceName(getServiceName());
- EchoRequestHandler.setServiceType((getServiceType() == null)
? null : getServiceType().toString());
- usingAPT =
- getXPathAnnotations() != null
- || getLookupServiceRegisterAnnotations() != null
- || getSelfTestsAnnotations() != null;
- }
+ public PerfSONAR() {
+ try {
+ declarePrefix("nmwg", "http://ggf.org/ns/nmwg/base/2.0/";);
+ declarePrefix("nmwgr", "http://ggf.org/ns/nmwg/result/2.0/";);
+ declarePrefix("nmwgtopo",
"http://ggf.org/ns/nmwg/topology/2.0/";);
+
whenXPath("nmwg:message/@type").then(NMWGMessage.class).setType(any(String.class));
+
whenXPath("nmwg:message/@id").then(NMWGMessage.class).setId(any(String.class));
+
whenXPath("nmwg:message/nmwg:metadata[@id='meta']/nmwg:eventType/text()").then(NMWGMessage.class)
+ .setEventType(any(String.class));
+
whenXPath("nmwg:message/nmwg:metadata/nmwg:key/text()").then(NMWGMessage.class).setKey(any(String.class));

- private void loadConfiguration() {
- try {
- configure(getXPathAnnotations());
- } catch (Exception ex) {
- // When @XPath annotations are not found do nothing
- }
- try {
- configure(getHandlerAnnotations());
- } catch (Exception ex) {
- // When handler annotations (@MetadataKey etc.) are
not found do
- // nothing
- }
- try {
- configure(getLookupServiceRegisterAnnotations());
- } catch (Exception ex) {
- // When @LookupServiceRegister annotations are not
found do nothing
- }
-
- try {
- configure(getSelfTestsAnnotations());
- } catch (Exception ex) {
- // When @LookupServiceRegister annotations are not
found do nothing
- }
- }
+
Configuration.configure(when("EchoRequest").then(EchoRequestHandler.class).handleEcho(
+ any(NMWGMessage.class)));
+ } catch (Exception ex) {
+ // No exception will be thrown. It is just for compiling code.
+ logger.debug("Exception caught when parsing service
configuration: {}", ex.getMessage());
+ }

- public Class<?> getSelfTestsAnnotations() {
- try {
- return
Class.forName("net.geant.perfsonar.SelfTestsConfiguration");
- } catch (ClassNotFoundException ex) {
- return null;
- }
- }
+ loadConfiguration();
+ EchoRequestHandler.setScheduler(scheduler);
+ EchoRequestHandler.setServiceName(getServiceName());
+ EchoRequestHandler.setServiceType((getServiceType() == null) ? null
: getServiceType().toString());
+ usingAPT = getXPathAnnotations() != null ||
getLookupServiceRegisterAnnotations() != null
+ || getSelfTestsAnnotations() != null;
+ }

- public Class<?> getLookupServiceRegisterAnnotations() {
- try {
- return
Class.forName("net.geant.perfsonar.LookupServiceRegister");
- } catch (ClassNotFoundException ex) {
- return null;
- }
- }
+ private void loadConfiguration() {
+ try {
+ configure(getXPathAnnotations());
+ } catch (Exception ex) {
+ logger.debug("No @XPath annotations found ({}): {}",
ex.getClass(), ex.getMessage());
+ }
+ try {
+ configure(getHandlerAnnotations());
+ } catch (Exception ex) {
+ logger.debug("No Handler (@MatadataKey) annotations found ({}):
{}", ex.getClass(), ex.getMessage());
+ }
+ try {
+ configure(getLookupServiceRegisterAnnotations());
+ } catch (Exception ex) {
+ logger.debug("No @LookupServiceRegister annotations found ({}):
{}", ex.getClass(), ex.getMessage());
+ }

- public Class<?> getHandlerAnnotations() {
- try {
- return Class.forName("net.geant.perfsonar.Handlers");
- } catch (ClassNotFoundException ex) {
- return null;
- }
- }
+ try {
+ configure(getSelfTestsAnnotations());
+ } catch (Exception ex) {
+ logger.debug("No SelfTest annotations found ({}): {}",
ex.getClass(), ex.getMessage());
+ }
+ }

- public Class<?> getXPathAnnotations() {
- try {
- return Class.forName("net.geant.perfsonar.XPaths");
- } catch (ClassNotFoundException ex) {
- return null;
- }
- }
+ public Class<?> getSelfTestsAnnotations() {
+ try {
+ return
Class.forName("net.geant.perfsonar.SelfTestsConfiguration");
+ } catch (ClassNotFoundException ex) {
+ logger.debug("SelfTestConfiguration class not found!");
+ return null;
+ }
+ }

- private void configure(Class<?> annotations) throws Exception {
- annotations.newInstance();
- usingAPT = true;
- }
+ public Class<?> getLookupServiceRegisterAnnotations() {
+ try {
+ return
Class.forName("net.geant.perfsonar.LookupServiceRegister");
+ } catch (ClassNotFoundException ex) {
+ logger.debug("LookupServiceRegister class not found!");
+ return null;
+ }
+ }

- private static Scheduler createThreadPool() {
- return new Scheduler() {
- private ScheduledExecutorService pool = Executors
-
.newScheduledThreadPool(defaultThreadPoolSize);
- private Map<Runnable, ScheduledFuture<?>> tasks = new
Hashtable<Runnable, ScheduledFuture<?>>();
+ public Class<?> getHandlerAnnotations() {
+ try {
+ return Class.forName("net.geant.perfsonar.Handlers");
+ } catch (ClassNotFoundException ex) {
+ logger.debug("Handlers class not found!");
+ return null;
+ }
+ }

- public void runInParallel(Runnable task) {
- pool.execute(task);
- }
+ public Class<?> getXPathAnnotations() {
+ try {
+ return Class.forName("net.geant.perfsonar.XPaths");
+ } catch (ClassNotFoundException ex) {
+ logger.debug("XPaths class not found!");
+ return null;
+ }
+ }

- public void runEvery(int seconds, final Runnable
task) {
- tasks.put(task,
pool.scheduleAtFixedRate(task, 0, seconds,
- TimeUnit.SECONDS));
- }
+ private void configure(Class<?> annotations) throws Exception {
+ annotations.newInstance();
+ usingAPT = true;
+ }

- public void stop(Runnable task) {
- if (tasks.get(task) == null)
- return;
- tasks.get(task).cancel(false);
- tasks.remove(task);
- }
+ private static Scheduler createThreadPool() {
+ return new Scheduler() {
+ private ScheduledExecutorService pool =
Executors.newScheduledThreadPool(defaultThreadPoolSize);
+ private Map<Runnable, ScheduledFuture<?>> tasks = new
Hashtable<Runnable, ScheduledFuture<?>>();

- public void stopAll() {
- for (ScheduledFuture<?> task :
tasks.values()) {
- task.cancel(false);
- }
- pool.shutdownNow();
- tasks.clear();
- }
+ public void runInParallel(Runnable task) {
+ pool.execute(task);
+ }

- @Override
- public void waitToFinish(Runnable... tasks) throws
InterruptedException, ExecutionException {
- for (Runnable task : tasks) {
- final ScheduledFuture<?> future =
this.tasks.get(task);
- if (future == null) continue;
- future.get();
- }
- }
- };
- }
+ public void runEvery(int seconds, final Runnable task) {
+ tasks.put(task, pool.scheduleAtFixedRate(task, 0, seconds,
TimeUnit.SECONDS));
+ }

- public abstract ServiceType getServiceType();
+ public void stop(Runnable task) {
+ if (tasks.get(task) == null) {
+ return;
+ }
+ tasks.get(task).cancel(false);
+ tasks.remove(task);
+ }

- public abstract String getServiceName();
+ public void stopAll() {
+ for (ScheduledFuture<?> task : tasks.values()) {
+ task.cancel(false);
+ }
+ pool.shutdownNow();
+ tasks.clear();
+ }

- /**
- * Processes the incoming xml message.
- *
- * @see javax.xml.ws.Provider#invoke(java.lang.Object)
- */
- @SuppressWarnings("unchecked")
- public StreamSource invoke(StreamSource request) {
- final XPathDeserializer deserializer = new
XPathDeserializer();
- final List<Object> objects;
- try {
- objects = (List<Object>) deserializer
-
.deserialize(toInputSource(request));// .getCharacterStream());
- } catch (DeserializationException ex) {
- throw new RuntimeException(ex.getMessage());
- } catch (Throwable ex) {
- throw new RuntimeException("Could not deserialize the
request.", ex);
- }
+ @Override
+ public void waitToFinish(Runnable... tasks) throws
InterruptedException, ExecutionException {
+ for (Runnable task : tasks) {
+ final ScheduledFuture<?> future = this.tasks.get(task);
+ if (future == null) {
+ continue;
+ }
+ future.get();
+ }
+ }
+ };
+ }

- if (deserializer.getObjects(NMWGMessage.class,
objects).size() <= 0)
- throw new RuntimeException(
- "NMWG message was not found in the
payload.");
+ public abstract ServiceType getServiceType();

- final NMWGMessage msg =
deserializer.getObjects(NMWGMessage.class, objects).get(0);
+ public abstract String getServiceName();

- String msgType = msg.getType();
+ /**
+ * Processes the incoming xml message.
+ *
+ * @see javax.xml.ws.Provider#invoke(java.lang.Object)
+ */
+ @SuppressWarnings("unchecked")
+ public StreamSource invoke(StreamSource request) {
+ final XPathDeserializer deserializer = new XPathDeserializer();
+ final List<Object> objects;
+ try {
+ objects = (List<Object>)
deserializer.deserialize(toInputSource(request));
+ } catch (DeserializationException ex) {
+ throw new RuntimeException(ex.getMessage());
+ } catch (Throwable ex) {
+ throw new RuntimeException("Could not deserialize the request.",
ex);
+ }
+
+ if (deserializer.getObjects(NMWGMessage.class, objects).size() <= 0)
{
+ throw new RuntimeException("NMWG message was not found in the
payload.");
+ }
+
+ final NMWGMessage msg = deserializer.getObjects(NMWGMessage.class,
objects).get(0);
+
+ String msgType = msg.getType();
logger.debug("Dispatching an incoming message: {}", msgType);
- final Method m = Configuration.getHandler(msgType);
- if (m == null)
- throw new RuntimeException("No handler defined for "
+ msgType);
- if (m.getParameterTypes().length > 1)
- throw new RuntimeException(m + ": Controller methods
must have zero or one argument.");
+ final Method m = Configuration.getHandler(msgType);
+ if (m == null) {
+ throw new RuntimeException("No handler defined for " + msgType);
+ }
+ if (m.getParameterTypes().length > 1) {
+ throw new RuntimeException(m + ": Controller methods must have
zero or one argument.");
+ }

- TemplateEngine.put("serviceType", getServiceType());
- TemplateEngine.put("serviceName", getServiceName());
- TemplateEngine.put("requestId", msg.getId());
+ TemplateEngine.put("serviceType", getServiceType());
+ TemplateEngine.put("serviceName", getServiceName());
+ TemplateEngine.put("requestId", msg.getId());

- try {
- if (m.getParameterTypes().length < 1) {
- TemplateEngine.put("result",
-
m.invoke(m.getDeclaringClass().newInstance()));
- } else {
- final List<Object> result = new
ArrayList<Object>();
- for (Object obj : deserializer.getObjects(
- m.getParameterTypes()[0],
objects)) {
-
result.add(m.invoke(m.getDeclaringClass().newInstance(), obj));
- }
- TemplateEngine.put("result", result);
- }
- } catch (Exception ex) {
- throw new RuntimeException("Could not process the
request.", ex);
- }
+ try {
+ if (m.getParameterTypes().length < 1) {
+ TemplateEngine.put("result",
m.invoke(m.getDeclaringClass().newInstance()));
+ } else {
+ final List<Object> result = new ArrayList<Object>();
+ for (Object obj :
deserializer.getObjects(m.getParameterTypes()[0], objects)) {
+ result.add(m.invoke(m.getDeclaringClass().newInstance(),
obj));
+ }
+ TemplateEngine.put("result", result);
+ }
+ } catch (Exception ex) {
+ throw new RuntimeException("Could not process the request.", ex);
+ }

- final StringWriter writer = new StringWriter();
- try {
- TemplateEngine.evaluate(writer,
m.getDeclaringClass(), msg.getType().replace("Request", "Response.template"));
- writer.flush();
- writer.close();
- } catch (Exception ex) {
- throw new RuntimeException("Could not serialize
response", ex);
- }
+ final StringWriter writer = new StringWriter();
+ try {
+ TemplateEngine.evaluate(writer, m.getDeclaringClass(),
msg.getType()
+ .replace("Request", "Response.template"));
+ writer.flush();
+ writer.close();
+ } catch (Exception ex) {
+ throw new RuntimeException("Could not serialize response", ex);
+ }

- return new StreamSource(new StringReader(writer.toString()));
- }
+ return new StreamSource(new StringReader(writer.toString()));
+ }

- private InputSource toInputSource(StreamSource request) {
- if (request.getInputStream() != null)
- return new InputSource(request.getInputStream());
- else
- return new InputSource(request.getReader());
- }
+ private InputSource toInputSource(StreamSource request) {
+ if (request.getInputStream() != null) {
+ return new InputSource(request.getInputStream());
+ } else {
+ return new InputSource(request.getReader());
+ }
+ }

- /**
- * @return scheduler that uses thread pool.
- */
- public Scheduler getScheduler() {
- return scheduler;
- }
+ /**
+ * @return scheduler that uses thread pool.
+ */
+ public Scheduler getScheduler() {
+ return scheduler;
+ }

- /**
- * Sets thread pool size used by scheduler.
- *
- * @param size
- */
- public void setThreadPoolSize(int size) {
- PerfSONAR.defaultThreadPoolSize = size;
- scheduler = createThreadPool();
- }
+ /**
+ * Sets thread pool size used by scheduler.
+ *
+ * @param size
+ */
+ public void setThreadPoolSize(int size) {
+ PerfSONAR.defaultThreadPoolSize = size;
+ scheduler = createThreadPool();
+ }

- public void stop() {
- scheduler.stopAll();
- Configuration.clearConfiguration();
- SelfTestRunner.clearConfiguration();
- XPathDeserializer.clearConfiguration();
- }
+ public void stop() {
+ scheduler.stopAll();
+ Configuration.clearConfiguration();
+ SelfTestRunner.clearConfiguration();
+ XPathDeserializer.clearConfiguration();
+ }
}

Modified:
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/ServiceType.java
===================================================================
---
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/ServiceType.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/ServiceType.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -8,64 +8,58 @@
*/
public enum ServiceType {

- /**
- * Measurement Point service.
- *
- * The Measurement Point (MP) service is in charge of providing
measurement
- * data; if the measurements are currently being stored in an
archive, it
- * retrieves them. If they are not already being collected, the MP
"creates"
- * the measurement data either by initiating active measurement tests
or
- * querying passive measurement devices. An MP is a standard interface
- * “wrapper” around one or more measurement tool/capabilities. An MP
is,
- * basically, a place where some data are being metered. It can be,
for
- * example, a piece of hardware located in the core of the network to
get
- * precise data and deterministic behaviour of the network, but also
can be
- * software installed at the edge of the network on the hosts to
perform
- * end-to-end measurements.
- */
- MP,
- OWAMP_MP,
- BWCTL_MP,
+ /**
+ * Measurement Point service.
+ *
+ * The Measurement Point (MP) service is in charge of providing
measurement
+ * data; if the measurements are currently being stored in an archive, it
+ * retrieves them. If they are not already being collected, the MP
"creates"
+ * the measurement data either by initiating active measurement tests or
+ * querying passive measurement devices. An MP is a standard interface
+ * “wrapper” around one or more measurement tool/capabilities. An MP is,
+ * basically, a place where some data are being metered. It can be, for
+ * example, a piece of hardware located in the core of the network to get
+ * precise data and deterministic behaviour of the network, but also can
be
+ * software installed at the edge of the network on the hosts to perform
+ * end-to-end measurements.
+ */
+ MP, OWAMP_MP, BWCTL_MP,

- /**
- * Measurement Archive service.
- *
- * A Measurement Archive (MA) service is used to publish historical
- * monitoring data which are stored in an archive. It acts as a
wrapper
- * around an existing data archive to provide data to the outside
world. The
- * archive can be, for example, a network’s Round Robin Database (RRD
MA),
- * relational database (SQL MA) or a proprietary database of a Network
- * Management System. Additionally, an MA can publish information
produced
- * by MP services. It does not create (generate new raw data) or
transform
- * (i.e. aggregate/correlate/filter) any data.
- */
- MA,
- HADES_MA,
- TRACEROUTE_MA,
- OWAMP_MA,
- BWCTL_MA,
+ /**
+ * Measurement Archive service.
+ *
+ * A Measurement Archive (MA) service is used to publish historical
+ * monitoring data which are stored in an archive. It acts as a wrapper
+ * around an existing data archive to provide data to the outside world.
The
+ * archive can be, for example, a network’s Round Robin Database (RRD
MA),
+ * relational database (SQL MA) or a proprietary database of a Network
+ * Management System. Additionally, an MA can publish information
produced
+ * by MP services. It does not create (generate new raw data) or
transform
+ * (i.e. aggregate/correlate/filter) any data.
+ */
+ MA, HADES_MA, TRACEROUTE_MA, OWAMP_MA, BWCTL_MA,

- /**
- * Lookup service.
- *
- * Currently, it is difficult to discover and cumbersome to use the
tests
- * and measurement capabilities of multiple networks, even if they
have been
- * made publicly available. The Lookup Service (LS) enables users to
- * discover other services (MP, MA, Authentication service, etc.)
and, in
- * particular, the tools, capabilities, or data offered by those
services.
- * The LS gives the requestor all the information required to find and
- * contact the necessary services. In essence, the LS acts as a
service
- * directory, where services can advertise themselves (provide their
lookup
- * information) and requestors are able to find any service they
need. Some
- * information about services can be hidden, but high-level
information
- * should be exposed, so unauthorized users can determine if it is
- * “interesting” (i.e. worth seeking authorization to access) or not.
The LS
- * is a key element of the perfSONAR measurement framework because it
allows
- * every independent service to be a visible part of the system. New
- * services identify themselves to the community by registering with
an LS
- * and tender their capabilities, subject to locally-determined
policies, or
- * are withdrawn from the community without disrupting the interaction
- * between other services.
- */
- LS
-}
\ No newline at end of file
+ /**
+ * Lookup service.
+ *
+ * Currently, it is difficult to discover and cumbersome to use the tests
+ * and measurement capabilities of multiple networks, even if they have
been
+ * made publicly available. The Lookup Service (LS) enables users to
+ * discover other services (MP, MA, Authentication service, etc.) and, in
+ * particular, the tools, capabilities, or data offered by those
services.
+ * The LS gives the requestor all the information required to find and
+ * contact the necessary services. In essence, the LS acts as a service
+ * directory, where services can advertise themselves (provide their
lookup
+ * information) and requestors are able to find any service they need.
Some
+ * information about services can be hidden, but high-level information
+ * should be exposed, so unauthorized users can determine if it is
+ * “interesting” (i.e. worth seeking authorization to access) or not.
The LS
+ * is a key element of the perfSONAR measurement framework because it
allows
+ * every independent service to be a visible part of the system. New
+ * services identify themselves to the community by registering with an
LS
+ * and tender their capabilities, subject to locally-determined
policies, or
+ * are withdrawn from the community without disrupting the interaction
+ * between other services.
+ */
+ LS
+}

Modified:
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/base/Scheduler.java
===================================================================
---
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/base/Scheduler.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/base/Scheduler.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -4,13 +4,13 @@

public interface Scheduler {

- void runInParallel(Runnable task);
+ void runInParallel(Runnable task);

- void runEvery(int seconds, Runnable task);
-
- void stop(Runnable task);
-
- void stopAll();
-
- void waitToFinish(Runnable... tasks) throws InterruptedException,
ExecutionException;
-}
\ No newline at end of file
+ void runEvery(int seconds, Runnable task);
+
+ void stop(Runnable task);
+
+ void stopAll();
+
+ void waitToFinish(Runnable... tasks) throws InterruptedException,
ExecutionException;
+}

Modified:
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/response/EchoRequestHandler.java
===================================================================
---
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/response/EchoRequestHandler.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/response/EchoRequestHandler.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -9,48 +9,49 @@
import net.geant.perfsonar.selftest.SelfTestRunner;

public class EchoRequestHandler {
- private static Scheduler scheduler;
- private static String serviceName;
- private static String serviceType;
-
- private SelfTestRunner runner = new SelfTestRunner();
-
- public List<SelfTestResult> handleEcho(final NMWGMessage msg) {
- if (msg.isEchoRequest())
- return new ArrayList<SelfTestResult>();
-
- final SelfTestLoggerImpl logger = createLogger();
-
- if (msg.isRunSuite()) {
- try {
- runner.runSuite(scheduler, logger);
- } catch (Exception ex) {
- throw new RuntimeException("Could not run
self tests.", ex);
- }
- } else {
- try {
- runner.runTest(msg.getTestName(), scheduler,
logger);
- } catch (Exception ex) {
- throw new RuntimeException("Could not run
self tests.", ex);
- }
- }
-
- return logger.getResults();
- }
-
- private SelfTestLoggerImpl createLogger() {
- return new SelfTestLoggerImpl(serviceName, serviceType);
- }
+ private static Scheduler scheduler;
+ private static String serviceName;
+ private static String serviceType;

- public static void setScheduler(Scheduler scheduler) {
- EchoRequestHandler.scheduler = scheduler;
- }
-
- public static void setServiceName(String serviceName) {
- EchoRequestHandler.serviceName = serviceName;
- }
-
- public static void setServiceType(String serviceType) {
- EchoRequestHandler.serviceType = serviceType;
- }
+ private SelfTestRunner runner = new SelfTestRunner();
+
+ public List<SelfTestResult> handleEcho(final NMWGMessage msg) {
+ if (msg.isEchoRequest()) {
+ return new ArrayList<SelfTestResult>();
+ }
+
+ final SelfTestLoggerImpl logger = createLogger();
+
+ if (msg.isRunSuite()) {
+ try {
+ runner.runSuite(scheduler, logger);
+ } catch (Exception ex) {
+ throw new RuntimeException("Could not run self tests.", ex);
+ }
+ } else {
+ try {
+ runner.runTest(msg.getTestName(), scheduler, logger);
+ } catch (Exception ex) {
+ throw new RuntimeException("Could not run self tests.", ex);
+ }
+ }
+
+ return logger.getResults();
+ }
+
+ private SelfTestLoggerImpl createLogger() {
+ return new SelfTestLoggerImpl(serviceName, serviceType);
+ }
+
+ public static void setScheduler(Scheduler scheduler) {
+ EchoRequestHandler.scheduler = scheduler;
+ }
+
+ public static void setServiceName(String serviceName) {
+ EchoRequestHandler.serviceName = serviceName;
+ }
+
+ public static void setServiceType(String serviceType) {
+ EchoRequestHandler.serviceType = serviceType;
+ }
}

Modified:
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/response/EchoResponse.java
===================================================================
---
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/response/EchoResponse.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/response/EchoResponse.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -6,13 +6,20 @@
import net.geant.perfsonar.templates.TemplateEngine;

/**
- * Writes Echo response to the stream.
+ * Writes Echo response to the stream.
*
* @author <a
href="">Blazej
Pietrzak</a>
*/
-public class EchoResponse {
- public static void writeEcho(Writer writer, String requestId) throws
IOException {
- TemplateEngine.put("requestId", requestId);
- TemplateEngine.evaluate(writer, EchoResponse.class,
"EchoResponse.template");
- }
+public final class EchoResponse {
+
+ private EchoResponse() {
+ // Utility class, we don't want to be instantiated directly, we're
private
+ super();
+ }
+
+ public static void writeEcho(Writer writer, String requestId) throws
IOException {
+ TemplateEngine.put("requestId", requestId);
+ TemplateEngine.evaluate(writer, EchoResponse.class,
"EchoResponse.template");
+ }
+
}

Modified:
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/response/SelfTestLoggerImpl.java
===================================================================
---
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/response/SelfTestLoggerImpl.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/response/SelfTestLoggerImpl.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -7,26 +7,26 @@
import net.geant.perfsonar.selftest.SelfTestLogger;

public class SelfTestLoggerImpl implements SelfTestLogger {
- private List<SelfTestResult> selfTestResults = new
ArrayList<SelfTestResult>();
- private String serviceName;
- private String serviceType;
-
- public SelfTestLoggerImpl(String serviceName, String serviceType) {
- this.serviceName = serviceName;
- this.serviceType = serviceType;
- }
-
- public List<SelfTestResult> getResults() {
- return selfTestResults;
- }
-
- @Override
- public void success(String name, String successMessage) {
- selfTestResults.add(SelfTestResult.success(name,
successMessage, serviceName, serviceType));
- }
+ private List<SelfTestResult> selfTestResults = new
ArrayList<SelfTestResult>();
+ private String serviceName;
+ private String serviceType;

- @Override
- public void failure(String name, String message) {
- selfTestResults.add(SelfTestResult.failure(name, message,
serviceName, serviceType));
- }
+ public SelfTestLoggerImpl(String serviceName, String serviceType) {
+ this.serviceName = serviceName;
+ this.serviceType = serviceType;
+ }
+
+ public List<SelfTestResult> getResults() {
+ return selfTestResults;
+ }
+
+ @Override
+ public void success(String name, String successMessage) {
+ selfTestResults.add(SelfTestResult.success(name, successMessage,
serviceName, serviceType));
+ }
+
+ @Override
+ public void failure(String name, String message) {
+ selfTestResults.add(SelfTestResult.failure(name, message,
serviceName, serviceType));
+ }
}

Modified:
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/response/SelfTestResponse.java
===================================================================
---
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/response/SelfTestResponse.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/response/SelfTestResponse.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -16,43 +16,43 @@
* @author <a
href="mailto:">Blazej
Pietrzak</a>
*/
public class SelfTestResponse implements SelfTestLogger {
- private static Logger logger =
LoggerFactory.getLogger(SelfTestResponse.class);
-
- private Writer writer;
-
- public SelfTestResponse(ServiceType serviceType, String serviceName)
throws Exception {
- TemplateEngine.put("serviceType", serviceType);
- TemplateEngine.put("serviceName", serviceName);
- }
-
- public void begin(Writer writer, String requestId) throws IOException
{
- this.writer = writer;
- TemplateEngine.put("requestId", requestId);
- TemplateEngine.evaluate(writer, SelfTestResponse.class,
"SelfTest_header.template");
- }
-
- public void end() throws IOException {
- TemplateEngine.evaluate(writer, SelfTestResponse.class,
"SelfTest_footer.template");
- writer = null;
- }
+ private static Logger logger =
LoggerFactory.getLogger(SelfTestResponse.class);

- public void success(String name, String successMessage) {
- TemplateEngine.put("name", name);
- TemplateEngine.put("message", successMessage);
- try {
- TemplateEngine.evaluate(writer,
SelfTestResponse.class, "SelfTest_success.template");
- } catch (IOException e) {
- logger.error("Could not fill in the template with
self test results.", e);
- }
- }
+ private Writer writer;

- public void failure(String name, String message) {
- TemplateEngine.put("name", name);
- TemplateEngine.put("message", message);
- try {
- TemplateEngine.evaluate(writer,
SelfTestResponse.class, "SelfTest_failure.template");
- } catch (IOException e) {
- logger.error("Could not fill in the template with
self test results.", e);
- }
- }
+ public SelfTestResponse(ServiceType serviceType, String serviceName)
throws Exception {
+ TemplateEngine.put("serviceType", serviceType);
+ TemplateEngine.put("serviceName", serviceName);
+ }
+
+ public void begin(Writer writer, String requestId) throws IOException {
+ this.writer = writer;
+ TemplateEngine.put("requestId", requestId);
+ TemplateEngine.evaluate(writer, SelfTestResponse.class,
"SelfTest_header.template");
+ }
+
+ public void end() throws IOException {
+ TemplateEngine.evaluate(writer, SelfTestResponse.class,
"SelfTest_footer.template");
+ writer = null;
+ }
+
+ public void success(String name, String successMessage) {
+ TemplateEngine.put("name", name);
+ TemplateEngine.put("message", successMessage);
+ try {
+ TemplateEngine.evaluate(writer, SelfTestResponse.class,
"SelfTest_success.template");
+ } catch (IOException e) {
+ logger.error("Could not fill in the template with self test
results.", e);
+ }
+ }
+
+ public void failure(String name, String message) {
+ TemplateEngine.put("name", name);
+ TemplateEngine.put("message", message);
+ try {
+ TemplateEngine.evaluate(writer, SelfTestResponse.class,
"SelfTest_failure.template");
+ } catch (IOException e) {
+ logger.error("Could not fill in the template with self test
results.", e);
+ }
+ }
}

Modified:
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/selftest/ParameterizedSelfTestTask.java
===================================================================
---
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/selftest/ParameterizedSelfTestTask.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/selftest/ParameterizedSelfTestTask.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -3,20 +3,20 @@
//TODO move to runtime bundle
public abstract class ParameterizedSelfTestTask<T> implements Runnable {
private T data;
- private int index;
+ private int index;

- public ParameterizedSelfTestTask(T data, int index) {
- this.data = data;
- this.index = index;
+ public ParameterizedSelfTestTask(T data, int index) {
+ this.data = data;
+ this.index = index;
}

- public T getData() {
- return data;
- }
+ public T getData() {
+ return data;
+ }

- public int getIndex() {
- return index;
- }
-
- public abstract void run();
+ public int getIndex() {
+ return index;
+ }
+
+ public abstract void run();
}

Modified:
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/selftest/SelfTest.java
===================================================================
---
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/selftest/SelfTest.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/selftest/SelfTest.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -7,68 +7,68 @@

public class SelfTest {

- private Method method;
- private String successMessage;
- private String name;
- private Object arg;
+ private Method method;
+ private String successMessage;
+ private String name;
+ private Object arg;

- public SelfTest(String name, String successMessage, Method method) {
- this.name = name;
- this.method = method;
- this.successMessage = successMessage;
- }
-
- public SelfTest(String name, String successMessage, Method method,
int index, Object arg) {
- this.name = fillInTemplate(name, index, arg);
- this.method = method;
- this.successMessage = fillInTemplate(successMessage, index,
arg);
- this.arg = arg;
- }
-
- public void run(SelfTestLogger logger) {
- try {
- final Object test = newInstance(method);
- if (isParameterized())
- method.invoke(test, arg);
- else
- method.invoke(test);
- logger.success(name, successMessage);
- } catch (InvocationTargetException ex) {
- logger.failure(name,
ex.getTargetException().getMessage());
- } catch (Exception ex) {
- logger.failure(name, ex.getMessage());
- }
- }
+ public SelfTest(String name, String successMessage, Method method) {
+ this.name = name;
+ this.method = method;
+ this.successMessage = successMessage;
+ }

- public boolean isParameterized() {
- return method.getParameterTypes().length == 1;
- }
+ public SelfTest(String name, String successMessage, Method method, int
index, Object arg) {
+ this.name = fillInTemplate(name, index, arg);
+ this.method = method;
+ this.successMessage = fillInTemplate(successMessage, index, arg);
+ this.arg = arg;
+ }

- public Class<?> getParameterType() {
- return method.getParameterTypes()[0];
- }
+ public void run(SelfTestLogger logger) {
+ try {
+ final Object test = newInstance(method);
+ if (isParameterized()) {
+ method.invoke(test, arg);
+ } else {
+ method.invoke(test);
+ }
+ logger.success(name, successMessage);
+ } catch (InvocationTargetException ex) {
+ logger.failure(name, ex.getTargetException().getMessage());
+ } catch (Exception ex) {
+ logger.failure(name, ex.getMessage());
+ }
+ }

- private String fillInTemplate(String template, int i, Object arg) {
- TemplateEngine.put("index", i);
- TemplateEngine.put("arg", arg);
- return TemplateEngine.evaluate(template);
- }
+ public boolean isParameterized() {
+ return method.getParameterTypes().length == 1;
+ }

- private Object newInstance(Method m) throws InstantiationException,
- IllegalAccessException {
-
- return m.getDeclaringClass().newInstance();
- }
+ public Class<?> getParameterType() {
+ return method.getParameterTypes()[0];
+ }

- public String getName() {
- return name;
- }
-
- public String getSuccessMessage() {
- return successMessage;
- }
+ private String fillInTemplate(String template, int i, Object arg) {
+ TemplateEngine.put("index", i);
+ TemplateEngine.put("arg", arg);
+ return TemplateEngine.evaluate(template);
+ }

- public Method getMethod() {
- return method;
- }
+ private Object newInstance(Method m) throws InstantiationException,
IllegalAccessException {
+
+ return m.getDeclaringClass().newInstance();
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getSuccessMessage() {
+ return successMessage;
+ }
+
+ public Method getMethod() {
+ return method;
+ }
}

Modified:
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/selftest/SelfTestListener.java
===================================================================
---
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/selftest/SelfTestListener.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/selftest/SelfTestListener.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -1,6 +1,7 @@
package net.geant.perfsonar.selftest;

public interface SelfTestListener {
- void success(String name, String message);
- void failure(String name, String message);
+ void success(String name, String message);
+
+ void failure(String name, String message);
}

Modified:
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/selftest/SelfTestLogger.java
===================================================================
---
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/selftest/SelfTestLogger.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/selftest/SelfTestLogger.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -2,8 +2,8 @@

public interface SelfTestLogger {

- void success(String name, String successMessage);
+ void success(String name, String successMessage);

- void failure(String name, String message);
+ void failure(String name, String message);

}

Modified:
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/selftest/SelfTestRunner.java
===================================================================
---
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/selftest/SelfTestRunner.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/base/src/main/java/net/geant/perfsonar/selftest/SelfTestRunner.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -14,133 +14,146 @@

public class SelfTestRunner implements MethodInterceptor {

- private static String name;
- private static Map<String, SelfTest> tests = new Hashtable<String,
SelfTest>();
- private static Map<String, SelfTest> parameterizedTests = new
Hashtable<String, SelfTest>();
- private static Map<Class<?>, Method> testData = new
Hashtable<Class<?>, Method>();
-
- private static String successMessage;
- private static Method testDataMethod;
+ private static String name;
+ private static Map<String, SelfTest> tests = new Hashtable<String,
SelfTest>();
+ private static Map<String, SelfTest> parameterizedTests = new
Hashtable<String, SelfTest>();
+ private static Map<Class<?>, Method> testData = new Hashtable<Class<?>,
Method>();

- public void runSuite(final Scheduler scheduler, final SelfTestLogger
logger) throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException, InstantiationException {
- proccessParameterizedTests();
- final List<Runnable> tasks = new ArrayList<Runnable>();
- for (final String testName : tests.keySet()) {
- final Runnable task = createTask(testName, logger);
- scheduler.runInParallel(task);
- tasks.add(task);
- }
+ private static String successMessage;
+ private static Method testDataMethod;
+
+ public void runSuite(final Scheduler scheduler, final SelfTestLogger
logger) throws
+ IllegalAccessException, InvocationTargetException,
InstantiationException {
+ proccessParameterizedTests();
+ final List<Runnable> tasks = new ArrayList<Runnable>();
+ for (final String testName : tests.keySet()) {
+ final Runnable task = createTask(testName, logger);
+ scheduler.runInParallel(task);
+ tasks.add(task);
+ }
try {
- scheduler.waitToFinish(tasks.toArray(new
Runnable[0]));
- } catch (Exception ex) {
- throw new RuntimeException("Cannot run self tests:",
ex);
- }
- }
-
- public void runTest(final String testName, final Scheduler scheduler,
final SelfTestLogger logger) throws IllegalArgumentException,
IllegalAccessException, InvocationTargetException, InstantiationException {
- proccessParameterizedTests();
- final Runnable task = createTask(testName, logger);
- scheduler.runInParallel(task);
- try {
- scheduler.waitToFinish(task);
- } catch (Exception ex) {
- logger.failure(testName, ex.getMessage());
- }
- }
+ scheduler.waitToFinish(tasks.toArray(new Runnable[0]));
+ } catch (Exception ex) {
+ throw new RuntimeException("Cannot run self tests:", ex);
+ }
+ }

- private Runnable createTask(final String testName, final
SelfTestLogger logger) {
- return new Runnable(){
- @Override
- public void run() {
- final SelfTest test = tests.get(testName);
- if (test == null)
- throw new RuntimeException("Cannot
find self test named: " + testName);
- test.run(logger);
- }
- };
- }
-
- private void proccessParameterizedTests() throws
IllegalArgumentException, IllegalAccessException, InvocationTargetException,
InstantiationException {
- for (SelfTest test : parameterizedTests.values()) {
- Method data = testData.get(test.getParameterType());
- if (data == null)
- throw new RuntimeException("Self test without
self test data: " + test.getName());
-
- int i = 0;
- for (Object arg : (List<?>)
data.invoke(newInstance(data))) {
- final SelfTest temp = new
SelfTest(test.getName(), test.getSuccessMessage(), test.getMethod(), i++,
arg);
- tests.put(temp.getName(), temp);
- }
- }
-
- parameterizedTests.clear();
- }
+ public void runTest(final String testName, final Scheduler scheduler,
final SelfTestLogger logger)
+ throws IllegalAccessException, InvocationTargetException,
InstantiationException {
+ proccessParameterizedTests();
+ final Runnable task = createTask(testName, logger);
+ scheduler.runInParallel(task);
+ try {
+ scheduler.waitToFinish(task);
+ } catch (Exception ex) {
+ logger.failure(testName, ex.getMessage());
+ }
+ }

- private Object newInstance(Method m) throws InstantiationException,
IllegalAccessException {
- return m.getDeclaringClass().newInstance();
- }
+ private Runnable createTask(final String testName, final SelfTestLogger
logger) {
+ return new Runnable() {
+ @Override
+ public void run() {
+ final SelfTest test = tests.get(testName);
+ if (test == null) {
+ throw new RuntimeException("Cannot find self test named:
" + testName);
+ }
+ test.run(logger);
+ }
+ };
+ }

- @SuppressWarnings("unchecked")
- public static <T> T addSelfTest(String name, String successMessage,
Class<T> test) {
- SelfTestRunner.name = name;
- SelfTestRunner.successMessage = successMessage;
- return (T) Enhancer.create(test, new SelfTestRunner());
- }
-
- @SuppressWarnings("unchecked")
- public static <T> T selfTestData(Class<T> testData) {
- SelfTestRunner.name = null;
- SelfTestRunner.successMessage = null;
- return (T) Enhancer.create(testData, new SelfTestRunner());
- }
-
- public static <T> void configureForType(Class<T> type, List<T>
methodInvocation) {
- SelfTestRunner.testData.put(type,
SelfTestRunner.testDataMethod);
- SelfTestRunner.testDataMethod = null;
- }
-
- public static <T> T any(Class<T> type) {
- return null;
- }
+ private void proccessParameterizedTests() throws IllegalAccessException,
+ InvocationTargetException, InstantiationException {
+ for (SelfTest test : parameterizedTests.values()) {
+ Method data = testData.get(test.getParameterType());
+ if (data == null) {
+ throw new RuntimeException("Self test without self test
data: " + test.getName());
+ }

- @SuppressWarnings("rawtypes")
- @Override
- public Object intercept(Object obj, Method method, Object[] args,
MethodProxy proxy) throws Throwable {
- if (method.getName().equals("toString") ||
method.getName().equals("hashCode")) {
- return proxy.invokeSuper(obj, args);
- }
-
- if (!method.getReturnType().equals(Void.TYPE) &&
!isSelfTestData())
- throw new RuntimeException(method.toString() + ":
Self test method should be of type void.");
- else if (isSelfTestData()) {
- if (!method.getReturnType().isInstance(new
ArrayList()))
- throw new RuntimeException(method.toString()
+ ": Self test data method must be of List<E> type where E is type of self
test's argument type.");
- if (method.getParameterTypes().length != 0)
- throw new RuntimeException(method.toString()
+ ": Self test data method cannot have any arguments.");
- SelfTestRunner.testDataMethod = method;
- return null;
- }
-
- if (method.getParameterTypes().length > 1)
- throw new RuntimeException(method.toString() + ";
Self test method can have zero or one arguments.");
-
- if (method.getParameterTypes().length == 1)
-
SelfTestRunner.parameterizedTests.put(SelfTestRunner.name, new
SelfTest(SelfTestRunner.name, SelfTestRunner.successMessage, method));
- else
- SelfTestRunner.tests.put(SelfTestRunner.name, new
SelfTest(SelfTestRunner.name, SelfTestRunner.successMessage, method));
- return null;
- }
+ int i = 0;
+ for (Object arg : (List<?>) data.invoke(newInstance(data))) {
+ final SelfTest temp = new SelfTest(test.getName(),
test.getSuccessMessage(), test.getMethod(), i++, arg);
+ tests.put(temp.getName(), temp);
+ }
+ }

- private boolean isSelfTestData() {
- return SelfTestRunner.name == null &&
SelfTestRunner.successMessage == null;
- }
+ parameterizedTests.clear();
+ }

- public static void clearConfiguration() {
- SelfTestRunner.parameterizedTests.clear();
- SelfTestRunner.name = null;
- SelfTestRunner.successMessage = null;
- SelfTestRunner.testData.clear();
- SelfTestRunner.testDataMethod = null;
- SelfTestRunner.tests.clear();
- }
+ private Object newInstance(Method m) throws InstantiationException,
IllegalAccessException {
+ return m.getDeclaringClass().newInstance();
+ }
+
+ @SuppressWarnings("unchecked")
+ public static <T> T addSelfTest(String name, String successMessage,
Class<T> test) {
+ SelfTestRunner.name = name;
+ SelfTestRunner.successMessage = successMessage;
+ return (T) Enhancer.create(test, new SelfTestRunner());
+ }
+
+ @SuppressWarnings("unchecked")
+ public static <T> T selfTestData(Class<T> testData) {
+ SelfTestRunner.name = null;
+ SelfTestRunner.successMessage = null;
+ return (T) Enhancer.create(testData, new SelfTestRunner());
+ }
+
+ public static <T> void configureForType(Class<T> type, List<T>
methodInvocation) {
+ SelfTestRunner.testData.put(type, SelfTestRunner.testDataMethod);
+ SelfTestRunner.testDataMethod = null;
+ }
+
+ public static <T> T any(Class<T> type) {
+ return null;
+ }
+
+ @SuppressWarnings("rawtypes")
+ @Override
+ public Object intercept(Object obj, Method method, Object[] args,
MethodProxy proxy) throws Throwable {
+ if (method.getName().equals("toString") ||
method.getName().equals("hashCode")) {
+ return proxy.invokeSuper(obj, args);
+ }
+
+ if (!method.getReturnType().equals(Void.TYPE) && !isSelfTestData()) {
+ throw new RuntimeException(method.toString() + ": Self test
method should be of type void.");
+ } else if (isSelfTestData()) {
+ if (!method.getReturnType().isInstance(new ArrayList())) {
+ throw new RuntimeException(
+ method.toString()
+ + ": Self test data method must be of
List<E> type where E is type of self test's argument type.");
+ }
+ if (method.getParameterTypes().length != 0) {
+ throw new RuntimeException(method.toString() + ": Self test
data method cannot have any arguments.");
+ }
+ SelfTestRunner.testDataMethod = method;
+ return null;
+ }
+
+ if (method.getParameterTypes().length > 1) {
+ throw new RuntimeException(method.toString() + "; Self test
method can have zero or one arguments.");
+ }
+
+ if (method.getParameterTypes().length == 1) {
+ SelfTestRunner.parameterizedTests.put(SelfTestRunner.name, new
SelfTest(SelfTestRunner.name,
+ SelfTestRunner.successMessage, method));
+ } else {
+ SelfTestRunner.tests.put(SelfTestRunner.name, new
SelfTest(SelfTestRunner.name,
+ SelfTestRunner.successMessage, method));
+ }
+ return null;
+ }
+
+ private boolean isSelfTestData() {
+ return SelfTestRunner.name == null && SelfTestRunner.successMessage
== null;
+ }
+
+ public static void clearConfiguration() {
+ SelfTestRunner.parameterizedTests.clear();
+ SelfTestRunner.name = null;
+ SelfTestRunner.successMessage = null;
+ SelfTestRunner.testData.clear();
+ SelfTestRunner.testDataMethod = null;
+ SelfTestRunner.tests.clear();
+ }
}

Modified:
trunk/perfsonar-base/base/src/main/resources/net/geant/perfsonar/response/EchoResponse.template
===================================================================
---
trunk/perfsonar-base/base/src/main/resources/net/geant/perfsonar/response/EchoResponse.template
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/base/src/main/resources/net/geant/perfsonar/response/EchoResponse.template
2013-05-08 20:41:45 UTC (rev 6371)
@@ -21,4 +21,4 @@
#end
#end
</nmwg:data>
-</nmwg:message>
\ No newline at end of file
+</nmwg:message>

Modified:
trunk/perfsonar-base/base/src/main/resources/net/geant/perfsonar/response/SelfTest_footer.template
===================================================================
---
trunk/perfsonar-base/base/src/main/resources/net/geant/perfsonar/response/SelfTest_footer.template
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/base/src/main/resources/net/geant/perfsonar/response/SelfTest_footer.template
2013-05-08 20:41:45 UTC (rev 6371)
@@ -1,2 +1,2 @@
</nmwg:data>
-</nmwg:message>
\ No newline at end of file
+</nmwg:message>

Modified:
trunk/perfsonar-base/base/src/test/java/net/geant/perfsonar/Handlers.java
===================================================================
--- trunk/perfsonar-base/base/src/test/java/net/geant/perfsonar/Handlers.java
2013-05-07 14:18:22 UTC (rev 6370)
+++ trunk/perfsonar-base/base/src/test/java/net/geant/perfsonar/Handlers.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -1,6 +1,7 @@
package net.geant.perfsonar;

-import static net.geant.perfsonar.Configuration.*;
+import static net.geant.perfsonar.Configuration.configure;
+import static net.geant.perfsonar.Configuration.when;

public class Handlers {


Modified:
trunk/perfsonar-base/base/src/test/java/net/geant/perfsonar/PerfSONARTest.java
===================================================================
---
trunk/perfsonar-base/base/src/test/java/net/geant/perfsonar/PerfSONARTest.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/base/src/test/java/net/geant/perfsonar/PerfSONARTest.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -29,59 +29,62 @@
public class PerfSONARTest {
protected Logger logger = LoggerFactory.getLogger(getClass());

- static final String REQUEST_ID = "request1";
+ static final String REQUEST_ID = "request1";
private PerfSONARClient client;
- private PerfSONAR service = new PerfSONAR() {
+ private PerfSONAR service = new PerfSONAR() {

- @Override
- public ServiceType getServiceType() {
- return ServiceType.MP;
- }
+ @Override
+ public ServiceType getServiceType() {
+ return ServiceType.MP;
+ }

- @Override
- public String getServiceName() {
- return "SSHTELNET";
- }
- };
+ @Override
+ public String getServiceName() {
+ return "SSHTELNET";
+ }
+ };

- @Before
- public void givenPerfSONARClient() {
- addSelfTest("constant", "Success Message.",
SampleTests.class).constantTest();
- addSelfTest("add test ${index}", "Added ${arg}.",
SampleTests.class).add(any(Integer.class));
- configureForType(Integer.class,
selfTestData(SampleTests.class).values());
-
- client = new PerfSONARClient(service);
- }
-
- @After
- public void tearDown() {
- SelfTestRunner.clearConfiguration();
- }
+ @Before
+ public void givenPerfSONARClient() {
+ addSelfTest("constant", "Success Message.",
SampleTests.class).constantTest();
+ addSelfTest("add test ${index}", "Added ${arg}.",
SampleTests.class).add(any(Integer.class));
+ configureForType(Integer.class,
selfTestData(SampleTests.class).values());

- @Test
- public void shouldLoadConfiguration() throws Exception {
- assertEquals(PerfSONARTest.class.getMethod("dummyMethod"),
Configuration.getHandler("TestRequest"));
- }
-
- public int dummyMethod() {
- return 0;
- }
-
- @Test
- public void checkEchoConfiguration() throws Exception {
- assertNotNull(Configuration.getHandler("EchoRequest"));
- }
+ client = new PerfSONARClient(service);
+ }

- @Test
- public void checkEcho() throws Exception {
- assertEquals(new Response(NMWG.toEchoResponse(REQUEST_ID)),
client.echo(REQUEST_ID));
- }
-
- /**
- * This test against the "Premature end of file error" when parsing a
stream twice
- * @throws Exception
- */
+ @After
+ public void tearDown() {
+ SelfTestRunner.clearConfiguration();
+ }
+
@Test
+ public void shouldLoadConfiguration() throws Exception {
+ assertEquals(PerfSONARTest.class.getMethod("dummyMethod"),
Configuration.getHandler("TestRequest"));
+ }
+
+ // Needed for above test
+ public int dummyMethod() {
+ return 0;
+ }
+
+ @Test
+ public void checkEchoConfiguration() throws Exception {
+ assertNotNull(Configuration.getHandler("EchoRequest"));
+ }
+
+ @Test
+ public void checkEcho() throws Exception {
+ assertEquals(new Response(NMWG.toEchoResponse(REQUEST_ID)),
client.echo(REQUEST_ID));
+ }
+
+ /**
+ * This test against the "Premature end of file error" when parsing a
stream
+ * twice
+ *
+ * @throws Exception
+ */
+ @Test
public void checkEchoLogging() throws Exception {
Response expectedResponse = new
Response(NMWG.toEchoResponse(REQUEST_ID));
Response generatedResponse = client.echo(REQUEST_ID);
@@ -89,34 +92,34 @@
logger.debug("Generated response: {}", generatedResponse);
assertEquals(expectedResponse, generatedResponse);
}
-
- @Test
- public void checkSelfTest() throws Throwable {
- SelfTestResult expectedResult = success("constant", "Success
Message.", service.getServiceName(), service.getServiceType().toString());
- SelfTestResult generatedResult = client.selfTest(REQUEST_ID,
"constant");
- logger.debug("Expected result: {}", expectedResult);
- logger.debug("Generated result: {}", generatedResult);
- assertEquals(expectedResult, generatedResult);
- }
-
- @Test
- public void checkAllSelfTests() throws Throwable {
- Thread.sleep(5 * 1000);
- assertEquals(
- asList(
- success("add test 0", "Added 1.",
service.getServiceName(), service.getServiceType().toString()),
- success("add test 1", "Added 2.",
service.getServiceName(), service.getServiceType().toString()),
- failure("add test 2", "Value must be >= 0",
service.getServiceName(), service.getServiceType().toString()),
- success("add test 3", "Added 4.",
service.getServiceName(), service.getServiceType().toString()),
- success("add test 4", "Added 5.",
service.getServiceName(), service.getServiceType().toString()),
- success("constant", "Success Message.",
service.getServiceName(), service.getServiceType().toString())),
- sort(client.selfTest(REQUEST_ID)));
- }
-
- @SuppressWarnings({ "unchecked" })
- private <T> List<T> sort(List<T> list) {
- final Object[] result = list.toArray();
- Arrays.sort(result);
- return (List<T>) asList(result);
- }
+
+ @Test
+ public void checkSelfTest() throws Throwable {
+ SelfTestResult expectedResult = success("constant", "Success
Message.", service.getServiceName(), service
+ .getServiceType().toString());
+ SelfTestResult generatedResult = client.selfTest(REQUEST_ID,
"constant");
+ logger.debug("Expected result: {}", expectedResult);
+ logger.debug("Generated result: {}", generatedResult);
+ assertEquals(expectedResult, generatedResult);
+ }
+
+ @Test
+ public void checkAllSelfTests() throws Throwable {
+ assertEquals(
+ asList(success("add test 0", "Added 1.",
service.getServiceName(), service.getServiceType().toString()),
+ success("add test 1", "Added 2.",
service.getServiceName(), service.getServiceType().toString()),
+ failure("add test 2", "Value must be >= 0",
service.getServiceName(), service.getServiceType()
+ .toString()),
+ success("add test 3", "Added 4.",
service.getServiceName(), service.getServiceType().toString()),
+ success("add test 4", "Added 5.",
service.getServiceName(), service.getServiceType().toString()),
+ success("constant", "Success Message.",
service.getServiceName(), service.getServiceType()
+ .toString())),
sort(client.selfTest(REQUEST_ID)));
+ }
+
+ @SuppressWarnings({ "unchecked" })
+ private <T> List<T> sort(List<T> list) {
+ final Object[] result = list.toArray();
+ Arrays.sort(result);
+ return (List<T>) asList(result);
+ }
}

Modified:
trunk/perfsonar-base/base/src/test/java/net/geant/perfsonar/SchedulerTest.java
===================================================================
---
trunk/perfsonar-base/base/src/test/java/net/geant/perfsonar/SchedulerTest.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/base/src/test/java/net/geant/perfsonar/SchedulerTest.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -8,71 +8,74 @@
import org.junit.Test;

public class SchedulerTest {
- private PerfSONAR service = new PerfSONAR() {
+ private PerfSONAR service = new PerfSONAR() {

- @Override
- public ServiceType getServiceType() {
- return ServiceType.MA;
- }
+ @Override
+ public ServiceType getServiceType() {
+ return ServiceType.MA;
+ }

- @Override
- public String getServiceName() {
- return "RRD";
- }
-
- };
- private boolean executed1 = false;
- private boolean executed2 = false;
- private Scheduler scheduler;
-
- @Before
- public void givenScheduler() {
- scheduler = service.getScheduler();
- }
-
- @Test
- public void shouldRunTwoTasksInParallel() throws InterruptedException
{
- scheduler.runInParallel(new Runnable() {
- public void run() {
- int i = 0;
- while (!executed1 || (i > 10)) {
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) { }
- i++;
- }
- executed2 = executed1;
- }
- });
-
- scheduler.runInParallel(new Runnable() {
- public void run() {
- executed1 = true;
- }
- });
- Thread.sleep(1000);
- assertTrue(executed1);
- assertTrue(executed2);
- }
-
- @Test
- public void shouldRunEveryOneSecond() throws InterruptedException {
- final CounterTask task = new CounterTask();
- scheduler.runEvery(1, task);
- Thread.sleep(3 * 1000);
- assertEquals(3, task.getCounter());
- }
+ @Override
+ public String getServiceName() {
+ return "RRD";
+ }

- class CounterTask implements Runnable {
- private int counter = 0;
-
- public void run() {
- if (counter == 3) return;
- counter++;
- }
-
- public int getCounter() {
- return counter;
- }
- }
+ };
+ private boolean executed1 = false;
+ private boolean executed2 = false;
+ private Scheduler scheduler;
+
+ @Before
+ public void givenScheduler() {
+ scheduler = service.getScheduler();
+ }
+
+ @Test
+ public void shouldRunTwoTasksInParallel() throws InterruptedException {
+ scheduler.runInParallel(new Runnable() {
+ public void run() {
+ int i = 0;
+ while (!executed1 || (i > 10)) {
+ try {
+ Thread.sleep(100);
+ } catch (InterruptedException e) {
+ }
+ i++;
+ }
+ executed2 = executed1;
+ }
+ });
+
+ scheduler.runInParallel(new Runnable() {
+ public void run() {
+ executed1 = true;
+ }
+ });
+ Thread.sleep(1000);
+ assertTrue(executed1);
+ assertTrue(executed2);
+ }
+
+ @Test
+ public void shouldRunEveryOneSecond() throws InterruptedException {
+ final CounterTask task = new CounterTask();
+ scheduler.runEvery(1, task);
+ Thread.sleep(3 * 1000);
+ assertEquals(3, task.getCounter());
+ }
+
+ class CounterTask implements Runnable {
+ private int counter = 0;
+
+ public void run() {
+ if (counter == 3) {
+ return;
+ }
+ counter++;
+ }
+
+ public int getCounter() {
+ return counter;
+ }
+ }
}

Modified:
trunk/perfsonar-base/base/src/test/java/net/geant/perfsonar/configuration/ConfigurationTest.java
===================================================================
---
trunk/perfsonar-base/base/src/test/java/net/geant/perfsonar/configuration/ConfigurationTest.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/base/src/test/java/net/geant/perfsonar/configuration/ConfigurationTest.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -1,6 +1,6 @@
package net.geant.perfsonar.configuration;

-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;

import net.geant.perfsonar.Configuration;
import net.geant.perfsonar.mp.sshtelnet.ServiceController;
@@ -14,28 +14,24 @@

public class ConfigurationTest {

- @Before
- public void setUp() throws Exception {
- Configuration.clearConfiguration();
- }
+ @Before
+ public void setUp() throws Exception {
+ Configuration.clearConfiguration();
+ }

- @Test
- public void shouldListAvailableCommands() throws Exception {
- configure(when("MetadataKeyRequest")
-
.then(ServiceController.class).listAvailableRoutersAndCommands());
-
- assertEquals(
-
ServiceController.class.getMethod("listAvailableRoutersAndCommands"),
-
Configuration.getHandler("MetadataKeyRequest"));
- }
-
- @Test
- public void shouldExecuteCommand() throws Exception {
-
configure(when("SetupDataRequest").then(ServiceController.class)
- .execute(any(String.class)));
-
- assertEquals(
- ServiceController.class.getMethod("execute",
String.class),
- Configuration.getHandler("SetupDataRequest"));
- }
+ @Test
+ public void shouldListAvailableCommands() throws Exception {
+
configure(when("MetadataKeyRequest").then(ServiceController.class).listAvailableRoutersAndCommands());
+
+
assertEquals(ServiceController.class.getMethod("listAvailableRoutersAndCommands"),
+ Configuration.getHandler("MetadataKeyRequest"));
+ }
+
+ @Test
+ public void shouldExecuteCommand() throws Exception {
+
configure(when("SetupDataRequest").then(ServiceController.class).execute(any(String.class)));
+
+ assertEquals(ServiceController.class.getMethod("execute",
String.class),
+ Configuration.getHandler("SetupDataRequest"));
+ }
}

Modified:
trunk/perfsonar-base/base/src/test/java/net/geant/perfsonar/configuration/SampleTests.java
===================================================================
---
trunk/perfsonar-base/base/src/test/java/net/geant/perfsonar/configuration/SampleTests.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/base/src/test/java/net/geant/perfsonar/configuration/SampleTests.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -5,29 +5,31 @@

public class SampleTests {

- public void constantTest() { }
+ public void constantTest() {
+ }

- public List<Integer> values() {
- return Arrays.asList(1, 2, -1, 4, 5);
- }
-
- public static int result = 0;
+ public List<Integer> values() {
+ return Arrays.asList(1, 2, -1, 4, 5);
+ }

- public void add(Integer value) {
- if (value < 0)
- throw new IllegalArgumentException("Value must be >=
0");
-
- result += value;
- }
-
- public int getResult() {
- return result;
- }
+ private static int result = 0;

- public void print(String text) {
- }
+ public void add(Integer value) {
+ if (value < 0) {
+ throw new IllegalArgumentException("Value must be >= 0");
+ }

- public List<String> strings() {
- return Arrays.asList("John", "Doe");
- }
+ result += value;
+ }
+
+ public int getResult() {
+ return result;
+ }
+
+ public void print(String text) {
+ }
+
+ public List<String> strings() {
+ return Arrays.asList("John", "Doe");
+ }
}

Modified:
trunk/perfsonar-base/base/src/test/java/net/geant/perfsonar/configuration/SelfTestsTest.java
===================================================================
---
trunk/perfsonar-base/base/src/test/java/net/geant/perfsonar/configuration/SelfTestsTest.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/base/src/test/java/net/geant/perfsonar/configuration/SelfTestsTest.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -25,83 +25,83 @@
import org.junit.Test;

public class SelfTestsTest {
- private Scheduler scheduler = new Scheduler() {
- @Override
- public void runInParallel(Runnable task) {
- task.run();
- }
+ private Scheduler scheduler = new Scheduler() {
+ @Override
+ public void runInParallel(Runnable task) {
+ task.run();
+ }

- @Override
- public void runEvery(int seconds, Runnable task) { }
+ @Override
+ public void runEvery(int seconds, Runnable task) {
+ }

- @Override
- public void stop(Runnable task) { }
+ @Override
+ public void stop(Runnable task) {
+ }

- @Override
- public void stopAll() { }
+ @Override
+ public void stopAll() {
+ }

- @Override
- public void waitToFinish(Runnable... tasks)
- throws InterruptedException,
ExecutionException {
- }
- };
-
-
- private SelfTestLogger logger = new SelfTestLogger() {
- @Override
- public void success(String name, String successMessage) {
- testResults.add(SelfTestResult.success(name,
successMessage, "name", "type"));
- }
+ @Override
+ public void waitToFinish(Runnable... tasks) throws
InterruptedException, ExecutionException {
+ }
+ };

- @Override
- public void failure(String name, String message) {
- testResults.add(SelfTestResult.failure(name, message,
"name", "type"));
- }
-
- };
-
- private List<SelfTestResult> testResults = new
ArrayList<SelfTestResult>();
-
- @Before
- public void givenSelfTests() {
- addSelfTest("constant", "Success Message",
SampleTests.class).constantTest();
- addSelfTest("add test ${index}", "Added ${arg}.",
SampleTests.class).add(any(Integer.class));
- configureForType(Integer.class,
selfTestData(SampleTests.class).values());
- addSelfTest("string test ${index}", "String ${arg}",
SampleTests.class).print(any(String.class));
- configureForType(String.class,
selfTestData(SampleTests.class).strings());
- }
-
- @After
- public void clearSelfTests() {
- SelfTestRunner.clearConfiguration();
- testResults.clear();
- }
-
- @Test
- public void shouldRunTest() throws IllegalArgumentException,
IllegalAccessException, InvocationTargetException, InstantiationException {
- new SelfTestRunner().runTest("add test 1", scheduler, logger);
- assertEquals(asList(success("add test 1", "Added 2.", "name",
"type")), testResults);
- }
-
- @Test
- public void shouldRunSuite() throws Exception {
- new SelfTestRunner().runSuite(scheduler, logger);
- assertEquals(Arrays.asList(
- success("add test 0", "Added 1.", "name", "type"),
- success("add test 1", "Added 2.", "name", "type"),
- failure("add test 2", "Value must be >= 0", "name",
"type"),
- success("add test 3", "Added 4.", "name", "type"),
- success("add test 4", "Added 5.", "name", "type"),
- success("constant", "Success Message", "name",
"type"),
- success("string test 0", "String John", "name",
"type"),
- success("string test 1", "String Doe", "name", "type")
- ), sort(testResults));
- }
-
- @SuppressWarnings({ "unchecked" })
- private <T> List<T> sort(List<T> list) {
- final Object[] result = list.toArray();
- Arrays.sort(result);
- return (List<T>) asList(result);
- }
+ private SelfTestLogger logger = new SelfTestLogger() {
+ @Override
+ public void success(String name, String successMessage) {
+ testResults.add(SelfTestResult.success(name, successMessage,
"name", "type"));
+ }
+
+ @Override
+ public void failure(String name, String message) {
+ testResults.add(SelfTestResult.failure(name, message, "name",
"type"));
+ }
+
+ };
+
+ private List<SelfTestResult> testResults = new
ArrayList<SelfTestResult>();
+
+ @Before
+ public void givenSelfTests() {
+ addSelfTest("constant", "Success Message",
SampleTests.class).constantTest();
+ addSelfTest("add test ${index}", "Added ${arg}.",
SampleTests.class).add(any(Integer.class));
+ configureForType(Integer.class,
selfTestData(SampleTests.class).values());
+ addSelfTest("string test ${index}", "String ${arg}",
SampleTests.class).print(any(String.class));
+ configureForType(String.class,
selfTestData(SampleTests.class).strings());
+ }
+
+ @After
+ public void clearSelfTests() {
+ SelfTestRunner.clearConfiguration();
+ testResults.clear();
+ }
+
+ @Test
+ public void shouldRunTest() throws IllegalAccessException,
InvocationTargetException, InstantiationException {
+ new SelfTestRunner().runTest("add test 1", scheduler, logger);
+ assertEquals(asList(success("add test 1", "Added 2.", "name",
"type")), testResults);
+ }
+
+ @Test
+ public void shouldRunSuite() throws Exception {
+ new SelfTestRunner().runSuite(scheduler, logger);
+ assertEquals(
+ Arrays.asList(success("add test 0", "Added 1.", "name",
"type"),
+ success("add test 1", "Added 2.", "name", "type"),
+ failure("add test 2", "Value must be >= 0", "name",
"type"),
+ success("add test 3", "Added 4.", "name", "type"),
+ success("add test 4", "Added 5.", "name", "type"),
+ success("constant", "Success Message", "name",
"type"),
+ success("string test 0", "String John", "name",
"type"),
+ success("string test 1", "String Doe", "name",
"type")), sort(testResults));
+ }
+
+ @SuppressWarnings({ "unchecked" })
+ private <T> List<T> sort(List<T> list) {
+ final Object[] result = list.toArray();
+ Arrays.sort(result);
+ return (List<T>) asList(result);
+ }
}

Modified:
trunk/perfsonar-base/base/src/test/java/net/geant/perfsonar/helpers/PerfSONARClient.java
===================================================================
---
trunk/perfsonar-base/base/src/test/java/net/geant/perfsonar/helpers/PerfSONARClient.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/base/src/test/java/net/geant/perfsonar/helpers/PerfSONARClient.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -15,47 +15,49 @@
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

-
public class PerfSONARClient {
- private PerfSONAR service;
+ private PerfSONAR service;

- public PerfSONARClient(PerfSONAR service) {
- this.service = service;
- }
-
- public Response echo(String id) throws SAXException {
- return new Response(invoke(NMWG.toEchoRequest(id)));
- }
-
- @SuppressWarnings("unchecked")
- public List<SelfTestResult> selfTest(String id) throws SAXException,
DeserializationException {
- final Response response = new
Response(invoke(NMWG.toSelfTestRequest(id)));
- final XPathDeserializer deserializer = new
XPathDeserializer();
- return deserializer.getObjects(SelfTestResult.class,
(List<Object>) deserializer.deserialize(new
InputSource(response.getReader())));
- }
-
- public SelfTestResult selfTest(String id, String testName) throws
Throwable {
- final Response response = new
Response(invoke(NMWG.toSelfTestRequest(id, testName)));
- final XPathDeserializer deserializer = new
XPathDeserializer();
- @SuppressWarnings("unchecked")
- final List<SelfTestResult> result =
deserializer.getObjects(SelfTestResult.class, (List<Object>)
deserializer.deserialize(new InputSource(response.getReader())));
-
- if (result.size() != 1)
- throw new SAXException("Invalid number of self test
results: " + result.size());
-
- return result.get(0);
- }
-
- public StreamSource invoke(Reader request) throws SAXException {
- final StreamSource source = service.invoke(new
StreamSource(request));
- return source;
- }
+ public PerfSONARClient(PerfSONAR service) {
+ this.service = service;
+ }

- public Response listAvailableCommands(String id) throws SAXException {
- return new Response(invoke(NMWG.toMetadataKeyRequest(id)));
- }
+ public Response echo(String id) throws SAXException {
+ return new Response(invoke(NMWG.toEchoRequest(id)));
+ }

- public Response executeCommands(String id, Command... commands)
throws SAXException {
- return new Response(invoke(NMWG.toSetupDataRequest(id,
commands)));
- }
+ @SuppressWarnings("unchecked")
+ public List<SelfTestResult> selfTest(String id) throws SAXException,
DeserializationException {
+ final Response response = new
Response(invoke(NMWG.toSelfTestRequest(id)));
+ final XPathDeserializer deserializer = new XPathDeserializer();
+ return deserializer.getObjects(SelfTestResult.class,
+ (List<Object>) deserializer.deserialize(new
InputSource(response.getReader())));
+ }
+
+ public SelfTestResult selfTest(String id, String testName) throws
Throwable {
+ final Response response = new
Response(invoke(NMWG.toSelfTestRequest(id, testName)));
+ final XPathDeserializer deserializer = new XPathDeserializer();
+ @SuppressWarnings("unchecked")
+ final List<SelfTestResult> result =
deserializer.getObjects(SelfTestResult.class,
+ (List<Object>) deserializer.deserialize(new
InputSource(response.getReader())));
+
+ if (result.size() != 1) {
+ throw new SAXException("Invalid number of self test results: " +
result.size());
+ }
+
+ return result.get(0);
+ }
+
+ public StreamSource invoke(Reader request) throws SAXException {
+ final StreamSource source = service.invoke(new
StreamSource(request));
+ return source;
+ }
+
+ public Response listAvailableCommands(String id) throws SAXException {
+ return new Response(invoke(NMWG.toMetadataKeyRequest(id)));
+ }
+
+ public Response executeCommands(String id, Command... commands) throws
SAXException {
+ return new Response(invoke(NMWG.toSetupDataRequest(id, commands)));
+ }
}

Modified:
trunk/perfsonar-base/base/src/test/java/net/geant/perfsonar/helpers/PerfSONARServiceClient.java
===================================================================
---
trunk/perfsonar-base/base/src/test/java/net/geant/perfsonar/helpers/PerfSONARServiceClient.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/base/src/test/java/net/geant/perfsonar/helpers/PerfSONARServiceClient.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -13,29 +13,27 @@

import org.xml.sax.SAXException;

-
public class PerfSONARServiceClient {
- private Dispatch<StreamSource> client;
+ private Dispatch<StreamSource> client;

- public PerfSONARServiceClient(String url) {
- final String NAMESPACE = "http://base3.perfsonar.geant.net/";;
- final QName PORT = new QName(NAMESPACE, "PerfSONARPort");
- final Service service = Service.create(new QName(NAMESPACE,
- "PerfSONARService"));
- service.addPort(PORT, SOAPBinding.SOAP11HTTP_BINDING, url);
- client = service.createDispatch(PORT, StreamSource.class,
Service.Mode.PAYLOAD);
- }
-
- public Response echo(String id) throws SAXException {
- return new Response(invoke(NMWG.toEchoRequest(id)));
- }
-
- public Response selfTest(String id) throws SAXException {
- return new Response(invoke(NMWG.toSelfTestRequest(id)));
- }
-
- public InputStream invoke(Reader request) throws SAXException {
- final StreamSource source = client.invoke(new
StreamSource(request));
- return source.getInputStream();
- }
+ public PerfSONARServiceClient(String url) {
+ final String namespace = "http://base3.perfsonar.geant.net/";;
+ final QName port = new QName(namespace, "PerfSONARPort");
+ final Service service = Service.create(new QName(namespace,
"PerfSONARService"));
+ service.addPort(port, SOAPBinding.SOAP11HTTP_BINDING, url);
+ client = service.createDispatch(port, StreamSource.class,
Service.Mode.PAYLOAD);
+ }
+
+ public Response echo(String id) throws SAXException {
+ return new Response(invoke(NMWG.toEchoRequest(id)));
+ }
+
+ public Response selfTest(String id) throws SAXException {
+ return new Response(invoke(NMWG.toSelfTestRequest(id)));
+ }
+
+ public InputStream invoke(Reader request) throws SAXException {
+ final StreamSource source = client.invoke(new StreamSource(request));
+ return source.getInputStream();
+ }
}

Modified:
trunk/perfsonar-base/base/src/test/java/net/geant/perfsonar/helpers/Response.java
===================================================================
---
trunk/perfsonar-base/base/src/test/java/net/geant/perfsonar/helpers/Response.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/base/src/test/java/net/geant/perfsonar/helpers/Response.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -16,16 +16,19 @@

public class Response {
protected Logger logger = LoggerFactory.getLogger(getClass());
- private final Reader input;
- // The stream can only be parsed once, so we need to store it as a
string to re-use it
- // Otherwise, we run into "Premature end of file errors" when parsing
twice
- // See
http://www.danielschneller.com/2008/01/saxparseexception-1-1-premature-end-of.html
- private String inputString;
-
+ private final Reader input;
+ // The stream can only be parsed once, so we need to store it as a
string to
+ // re-use it
+ // Otherwise, we run into "Premature end of file errors" when parsing
twice
+ // See
+ //
http://www.danielschneller.com/2008/01/saxparseexception-1-1-premature-end-of.html
+ private String inputString;
+
public Response(InputStream input) {
- if (input == null)
- throw new NullPointerException("Response InputStream cannot
be null.");
- try {
+ if (input == null) {
+ throw new NullPointerException("Response InputStream cannot be
null.");
+ }
+ try {
this.input = new InputStreamReader(input, "UTF-8");
toString(this.input);
} catch (UnsupportedEncodingException e) {
@@ -34,31 +37,31 @@
throw new RuntimeException(msg, e);
}
}
-
+
private void toString(Reader input) {
- final StringBuffer buffer = new StringBuffer();
- try {
- int ch = input.read();
- for (; ch != -1; ) {
- buffer.append((char) ch);
- ch = input.read();
- }
- } catch (IOException e) {
- logger.error("Error converting Response to string
(returning null!): {}", e.getMessage());
- return;
- }
- inputString = buffer.toString();
- }
+ final StringBuffer buffer = new StringBuffer();
+ try {
+ int ch = input.read();
+ for (; ch != -1;) {
+ buffer.append((char) ch);
+ ch = input.read();
+ }
+ } catch (IOException e) {
+ logger.error("Error converting Response to string (returning
null!): {}", e.getMessage());
+ return;
+ }
+ inputString = buffer.toString();
+ }

- public Response(StreamSource source) {
- if (source.getInputStream() == null) {
- if (source.getReader() == null) {
- String msg = "Response StreamSource Reader cannot be
null.";
- logger.error(msg);
- throw new NullPointerException();
- }
- this.input = source.getReader();
- } else
+ public Response(StreamSource source) {
+ if (source.getInputStream() == null) {
+ if (source.getReader() == null) {
+ String msg = "Response StreamSource Reader cannot be null.";
+ logger.error(msg);
+ throw new NullPointerException();
+ }
+ this.input = source.getReader();
+ } else {
try {
this.input = new InputStreamReader(source.getInputStream(),
"UTF-8");
} catch (UnsupportedEncodingException e) {
@@ -66,55 +69,58 @@
logger.error(msg);
throw new RuntimeException(msg, e);
}
-
- toString(input);
+ }
+
+ toString(input);
}
-
+
public Response(Reader input) {
- if (input == null) {
- String msg = "Response Reader cannot be null.";
- logger.error(msg);
- throw new NullPointerException();
- }
- this.input = input;
- toString(input);
+ if (input == null) {
+ String msg = "Response Reader cannot be null.";
+ logger.error(msg);
+ throw new NullPointerException();
+ }
+ this.input = input;
+ toString(input);
}
-
+
public boolean equals(Object obj) {
- if (obj == null) {
- String msg = "Cannot compare against null object.";
- logger.error(msg);
- throw new NullPointerException();
- }
-
- if (obj instanceof Response)
- return equals(((Response) obj).inputString);
-
- if (!(obj instanceof String))
- return false;
-
- try {
- Diff diff = new Diff((String) obj, inputString);
- return diff.identical();
- } catch (SAXParseException ex) {
- String msg = "Cannot compare XML responses at line: "
+ ex.getLineNumber() + "; column: " + ex.getColumnNumber() + "; " +
ex.getException();
- logger.error(msg);
- throw new RuntimeException(msg, ex);
- } catch (Exception ex) {
- String msg = "Cannot compare XML responses (" +
ex.getClass() + "): " + ex.getMessage();
- logger.error(msg);
- throw new RuntimeException(msg, ex);
- }
-
-
+ if (obj == null) {
+ String msg = "Cannot compare against null object.";
+ logger.error(msg);
+ throw new NullPointerException();
+ }
+
+ if (obj instanceof Response) {
+ return equals(((Response) obj).inputString);
+ }
+
+ if (!(obj instanceof String)) {
+ return false;
+ }
+
+ try {
+ Diff diff = new Diff((String) obj, inputString);
+ return diff.identical();
+ } catch (SAXParseException ex) {
+ String msg = "Cannot compare XML responses at line: " +
ex.getLineNumber() + "; column: "
+ + ex.getColumnNumber() + "; " + ex.getException();
+ logger.error(msg);
+ throw new RuntimeException(msg, ex);
+ } catch (Exception ex) {
+ String msg = "Cannot compare XML responses (" + ex.getClass() +
"): " + ex.getMessage();
+ logger.error(msg);
+ throw new RuntimeException(msg, ex);
+ }
+
}
-
+
public Reader getReader() {
- //return this.input;
- return new StringReader(inputString);
+ // return this.input;
+ return new StringReader(inputString);
}
-
+
public String toString() {
- return inputString;
+ return inputString;
}
}

Modified:
trunk/perfsonar-base/base/src/test/java/net/geant/perfsonar/mp/sshtelnet/ServiceController.java
===================================================================
---
trunk/perfsonar-base/base/src/test/java/net/geant/perfsonar/mp/sshtelnet/ServiceController.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/base/src/test/java/net/geant/perfsonar/mp/sshtelnet/ServiceController.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -5,13 +5,14 @@
import java.util.List;

public class ServiceController {
- public ServiceController() { }
-
- public List<String> listAvailableRoutersAndCommands() throws
UnknownHostException {
- return null;
- }
-
- public String execute(String command) throws IOException {
- return null;
- }
+ public ServiceController() {
+ }
+
+ public List<String> listAvailableRoutersAndCommands() throws
UnknownHostException {
+ return null;
+ }
+
+ public String execute(String command) throws IOException {
+ return null;
+ }
}


Property changes on: trunk/perfsonar-base/ls
___________________________________________________________________
Modified: svn:ignore
- .settings
.classpath
.project

target
velocity.log*

logs

+ .settings
.classpath
.project

target
velocity.log*

logs

.pmd

.pmdruleset


Modified:
trunk/perfsonar-base/ls/src/main/java/net/geant/perfsonar/ls/LSRegistrationTask.java
===================================================================
---
trunk/perfsonar-base/ls/src/main/java/net/geant/perfsonar/ls/LSRegistrationTask.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/ls/src/main/java/net/geant/perfsonar/ls/LSRegistrationTask.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -31,125 +31,133 @@
import org.xml.sax.InputSource;

/**
- * Scheduler task that registers a service to Lookup Service.
- * If the service is already registered (key was returned from LS
successfully) it sends keepalive messages.
- * It uses LSRegister.template template found in the directory where the
controller method that provides data for registration is defined.
+ * Scheduler task that registers a service to Lookup Service. If the service
is
+ * already registered (key was returned from LS successfully) it sends
keepalive
+ * messages. It uses LSRegister.template template found in the directory
where
+ * the controller method that provides data for registration is defined.
*
- * In order to configure the handler for the Lookup Service registration the
following
- * code snippet must be used:
+ * In order to configure the handler for the Lookup Service registration the
+ * following code snippet must be used:
*
<code>configure(registerToLookupService(ServiceController.class).details())</code>
- * where configure method belongs to Configuration class.
- *
+ * where configure method belongs to Configuration class.
+ *
* @author <a
href="mailto:">Blazej
Pietrzak</a>
*/
public class LSRegistrationTask implements Runnable {
-
- private static List<String> lsAddresses = new ArrayList<String>();
-
- public List<String> getLSAddresses() {
- return lsAddresses;
- }

- public void addLSAddress(String address) {
- if (address == null)
- return;
-
- if (!lsAddresses.contains(address))
- lsAddresses.add(address);
- }
-
- @SuppressWarnings("unchecked")
- public static <T> T registerToLookupService(Class<T> controller) {
- return (T) Enhancer.create(controller, new
HandlerConfiguration("LSRegister"));
- }
+ private static List<String> lsAddresses = new ArrayList<String>();

- private Map<String, String> keys = new Hashtable<String, String>();
- private Logger logger;
- private PerfSONAR service;
-
- public LSRegistrationTask(Logger logger, PerfSONAR service) {
- this.logger = logger;
- this.service = service;
- }
-
- public LSRegistrationTask() {
- this(null, null);
- }
-
- public void run() {
- for (String address : getLSAddresses()) {
- try {
- registerToLookupService(address);
- } catch (Exception ex) {
- logger.error("Could not register to Lookup
Service at: " + address, ex);
- }
- }
- }
-
- @SuppressWarnings("unchecked")
- protected synchronized void registerToLookupService(final String
address) throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException, InstantiationException, IOException {
- final Method m = Configuration.getHandler("LSRegister");
- if (m == null)
- return;
-
- final PipedInputStream in = new PipedInputStream();
- final PipedOutputStream out = new PipedOutputStream(in);
-
service.getScheduler().runInParallel(createLSMessageTask(address, m, out));
-
- if (keys.get(address) == null) {
- final XPathDeserializer deserializer = new
XPathDeserializer();
- final NMWGMessage msg;
- try {
- msg =
deserializer.getObjects(NMWGMessage.class, (List<Object>)
deserializer.deserialize(new InputSource(getLSClient(address).invoke(new
StreamSource(in)).getInputStream()))).get(0);
- if (msg.getKey() != null) {
- keys.put(address, msg.getKey());
- }
- } catch (Exception e) {
- logger.error("Could not deserialize key from
Lookup Service response.", e);
- }
- } else
- getLSClient(address).invoke(new StreamSource(in));
- }
+ public List<String> getLSAddresses() {
+ return lsAddresses;
+ }

- private Runnable createLSMessageTask(final String address, final
Method m, final OutputStream out) {
- return new Runnable() {
+ public void addLSAddress(String address) {
+ if (address == null) {
+ return;
+ }

- private final Writer writer = new
OutputStreamWriter(out);
-
- public void run() {
- try {
- if (keys.get(address) == null) {
-
TemplateEngine.put("requestId", "request1");
- TemplateEngine.put("result",
m.invoke(m.getDeclaringClass().newInstance()));
- TemplateEngine.put("service",
service);
-
TemplateEngine.evaluate(writer, m.getDeclaringClass(), "LSRegister.template");
- } else {
-
writer.write(getKeepAliveMessage(keys.get(address)));
- }
- writer.flush();
- writer.close();
- out.close();
- } catch (Exception ex) {
- logger.error("Could not register in
LookupService.", ex);
- }
- }
+ if (!lsAddresses.contains(address)) {
+ lsAddresses.add(address);
+ }
+ }

- private String getKeepAliveMessage(String key) {
- return "<?xml version='1.0'
encoding='UTF-8'?>"
- + "<nmwg:message id='request1'
type='LSKeepaliveRequest' xmlns:nmwg='http://ggf.org/ns/nmwg/base/2.0/'>"
- + "<nmwg:metadata
id='key_to_keepalive'><nmwg:key>" + key + "</nmwg:key></nmwg:metadata>"
- + "<nmwg:data id='d1'
metadataIdRef='key_to_keepalive' />"
- + "</nmwg:message>\n";
- }
- };
- }
+ @SuppressWarnings("unchecked")
+ public static <T> T registerToLookupService(Class<T> controller) {
+ return (T) Enhancer.create(controller, new
HandlerConfiguration("LSRegister"));
+ }

- private Dispatch<StreamSource> getLSClient(final String address) {
- final String NAMESPACE = "http://base3.perfsonar.geant.net/";;
- final QName PORT = new QName(NAMESPACE, "PerfSONARPort");
- final Service service = Service.create(new QName(NAMESPACE,
"PerfSONARService"));
- service.addPort(PORT, SOAPBinding.SOAP11HTTP_BINDING,
address);
- final Dispatch<StreamSource> client =
service.createDispatch(PORT, StreamSource.class, Service.Mode.PAYLOAD);
- return client;
- }
+ private Map<String, String> keys = new Hashtable<String, String>();
+ private Logger logger;
+ private PerfSONAR service;
+
+ public LSRegistrationTask(Logger logger, PerfSONAR service) {
+ this.logger = logger;
+ this.service = service;
+ }
+
+ public LSRegistrationTask() {
+ this(null, null);
+ }
+
+ public void run() {
+ for (String address : getLSAddresses()) {
+ try {
+ registerToLookupService(address);
+ } catch (Exception ex) {
+ logger.error("Could not register to Lookup Service at: " +
address, ex);
+ }
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ protected synchronized void registerToLookupService(final String
address) throws IllegalAccessException,
+ InvocationTargetException, InstantiationException, IOException {
+ final Method m = Configuration.getHandler("LSRegister");
+ if (m == null) {
+ return;
+ }
+
+ final PipedInputStream in = new PipedInputStream();
+ final PipedOutputStream out = new PipedOutputStream(in);
+ service.getScheduler().runInParallel(createLSMessageTask(address, m,
out));
+
+ if (keys.get(address) == null) {
+ final XPathDeserializer deserializer = new XPathDeserializer();
+ final NMWGMessage msg;
+ try {
+ msg = deserializer.getObjects(
+ NMWGMessage.class,
+ (List<Object>) deserializer.deserialize(new
InputSource(getLSClient(address).invoke(
+ new
StreamSource(in)).getInputStream()))).get(0);
+ if (msg.getKey() != null) {
+ keys.put(address, msg.getKey());
+ }
+ } catch (Exception e) {
+ logger.error("Could not deserialize key from Lookup Service
response.", e);
+ }
+ } else {
+ getLSClient(address).invoke(new StreamSource(in));
+ }
+ }
+
+ private Runnable createLSMessageTask(final String address, final Method
m, final OutputStream out) {
+ return new Runnable() {
+
+ private final Writer writer = new OutputStreamWriter(out);
+
+ public void run() {
+ try {
+ if (keys.get(address) == null) {
+ TemplateEngine.put("requestId", "request1");
+ TemplateEngine.put("result",
m.invoke(m.getDeclaringClass().newInstance()));
+ TemplateEngine.put("service", service);
+ TemplateEngine.evaluate(writer,
m.getDeclaringClass(), "LSRegister.template");
+ } else {
+ writer.write(getKeepAliveMessage(keys.get(address)));
+ }
+ writer.flush();
+ writer.close();
+ out.close();
+ } catch (Exception ex) {
+ logger.error("Could not register in LookupService.", ex);
+ }
+ }
+
+ private String getKeepAliveMessage(String key) {
+ return "<?xml version='1.0' encoding='UTF-8'?>"
+ + "<nmwg:message id='request1'
type='LSKeepaliveRequest' xmlns:nmwg='http://ggf.org/ns/nmwg/base/2.0/'>"
+ + "<nmwg:metadata id='key_to_keepalive'><nmwg:key>"
+ key + "</nmwg:key></nmwg:metadata>"
+ + "<nmwg:data id='d1'
metadataIdRef='key_to_keepalive' />" + "</nmwg:message>\n";
+ }
+ };
+ }
+
+ private Dispatch<StreamSource> getLSClient(final String address) {
+ final String namespace = "http://base3.perfsonar.geant.net/";;
+ final QName port = new QName(namespace, "PerfSONARPort");
+ final Service myService = Service.create(new QName(namespace,
"PerfSONARService"));
+ myService.addPort(port, SOAPBinding.SOAP11HTTP_BINDING, address);
+ final Dispatch<StreamSource> client = myService.createDispatch(port,
StreamSource.class, Service.Mode.PAYLOAD);
+ return client;
+ }
}

Modified:
trunk/perfsonar-base/ls/src/test/java/net/geant/perfsonar/ls/LSEnabledService.java
===================================================================
---
trunk/perfsonar-base/ls/src/test/java/net/geant/perfsonar/ls/LSEnabledService.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/ls/src/test/java/net/geant/perfsonar/ls/LSEnabledService.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -16,52 +16,53 @@
*/
@WebServiceProvider
public class LSEnabledService extends PerfSONAR {
- private static final int TWO_SECONDS = 2;
-
- private final LSRegistrationTask lsRegistrationTask = new
LSRegistrationTask(logger, this);
- private int lsInterval = TWO_SECONDS;
-
- public LSEnabledService() {
- super();
+ private static final int TWO_SECONDS = 2;

- scheduler.runEvery(TWO_SECONDS, lsRegistrationTask);
- }
-
- static {
- try {
-
configure(registerToLookupService(ServiceController.class).listAvailableRoutersAndCommands());
- } catch (Exception ex) { }
- }
-
- /**
- * Sets timeout in seconds between subsequent
registrations/keepalives to Lookup
- * Service.
- */
- public synchronized void setLookupServiceInterval(String interval) {
- lsInterval = Integer.parseInt(interval);
- scheduler.stop(lsRegistrationTask);
- scheduler.runEvery(lsInterval, lsRegistrationTask);
- }
+ private final LSRegistrationTask lsRegistrationTask = new
LSRegistrationTask(logger, this);
+ private int lsInterval = TWO_SECONDS;

- /**
- * Returns timeout in seconds between subsequent
registrations/keepalives to Lookup
- * Service.
- */
- public synchronized int getLookupServiceInterval() {
- return lsInterval;
- }
+ public LSEnabledService() {
+ super();

- @Override
- public ServiceType getServiceType() {
- return ServiceType.MA;
- }
+ scheduler.runEvery(TWO_SECONDS, lsRegistrationTask);
+ }

- @Override
- public String getServiceName() {
- return "SQL";
- }
+ static {
+ try {
+
configure(registerToLookupService(ServiceController.class).listAvailableRoutersAndCommands());
+ } catch (Exception ex) {
+ }
+ }

- public void setLSAddress(String address) {
- lsRegistrationTask.addLSAddress(address);
- }
+ /**
+ * Sets timeout in seconds between subsequent registrations/keepalives to
+ * Lookup Service.
+ */
+ public synchronized void setLookupServiceInterval(String interval) {
+ lsInterval = Integer.parseInt(interval);
+ scheduler.stop(lsRegistrationTask);
+ scheduler.runEvery(lsInterval, lsRegistrationTask);
+ }
+
+ /**
+ * Returns timeout in seconds between subsequent
registrations/keepalives to
+ * Lookup Service.
+ */
+ public synchronized int getLookupServiceInterval() {
+ return lsInterval;
+ }
+
+ @Override
+ public ServiceType getServiceType() {
+ return ServiceType.MA;
+ }
+
+ @Override
+ public String getServiceName() {
+ return "SQL";
+ }
+
+ public void setLSAddress(String address) {
+ lsRegistrationTask.addLSAddress(address);
+ }
}

Modified:
trunk/perfsonar-base/ls/src/test/java/net/geant/perfsonar/ls/LSRegisterTest.java
===================================================================
---
trunk/perfsonar-base/ls/src/test/java/net/geant/perfsonar/ls/LSRegisterTest.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/ls/src/test/java/net/geant/perfsonar/ls/LSRegisterTest.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -3,17 +3,17 @@
import net.geant.perfsonar.PerfSONAR;

public class LSRegisterTest extends LSRegisterTestBase {
- private static final int TWO_SECONDS = 2000;
+ private static final int TWO_SECONDS = 2000;

- @Override
- protected PerfSONAR givenService() {
- LSEnabledService result = new LSEnabledService();
- ((LSEnabledService) result).setLSAddress(MOCK_LS_URL);
- return result;
- }
-
- @Override
- protected int getLSInterval() {
- return TWO_SECONDS;
- }
+ @Override
+ protected PerfSONAR givenService() {
+ LSEnabledService result = new LSEnabledService();
+ ((LSEnabledService) result).setLSAddress(MOCK_LS_URL);
+ return result;
+ }
+
+ @Override
+ protected int getLSInterval() {
+ return TWO_SECONDS;
+ }
}

Modified:
trunk/perfsonar-base/ls/src/test/java/net/geant/perfsonar/ls/LSRegisterTestBase.java
===================================================================
---
trunk/perfsonar-base/ls/src/test/java/net/geant/perfsonar/ls/LSRegisterTestBase.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/ls/src/test/java/net/geant/perfsonar/ls/LSRegisterTestBase.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -19,38 +19,38 @@
* @author <a
href="mailto:>Blazej
Pietrzak</a>
*/
public abstract class LSRegisterTestBase {
- protected static final String MOCK_LS_URL =
"http://localhost:9000/perfsonar-ls";;
- private MockLSService ls = new MockLSService();
-
- private PerfSONAR service;
- private Endpoint endpoint;
-
- @Before
- public void publishServices() throws InterruptedException,
IOException {
- ls.publish("http://localhost:9000/perfsonar-ls";);
- service = givenService();
- endpoint =
Endpoint.publish("http://localhost:9000/perfsonar-java-sshtelnet-mp";,
service);
- }
+ protected static final String MOCK_LS_URL =
"http://localhost:9000/perfsonar-ls";;
+ private MockLSService ls = new MockLSService();

- protected abstract PerfSONAR givenService();
- protected abstract int getLSInterval();
-
- @After
- public void stopServices() {
- endpoint.stop();
- service.stop();
- ls.stop();
- endpoint = null;
- ls = null;
- service = null;
- }
-
- @Test
- public void shouldRegisterToLookupService() throws Exception {
- Thread.sleep(getLSInterval() * 3 + 500);
- assertEquals(1, ls.getRegisterCount());
- assertTrue(
- "Keep alive should be sent at least 2x but was "
- + ls.getKeepAliveCount(),
ls.getKeepAliveCount() >= 2);
- }
+ private PerfSONAR service;
+ private Endpoint endpoint;
+
+ @Before
+ public void publishServices() throws InterruptedException, IOException {
+ ls.publish("http://localhost:9000/perfsonar-ls";);
+ service = givenService();
+ endpoint =
Endpoint.publish("http://localhost:9000/perfsonar-java-sshtelnet-mp";,
service);
+ }
+
+ protected abstract PerfSONAR givenService();
+
+ protected abstract int getLSInterval();
+
+ @After
+ public void stopServices() {
+ endpoint.stop();
+ service.stop();
+ ls.stop();
+ endpoint = null;
+ ls = null;
+ service = null;
+ }
+
+ @Test
+ public void shouldRegisterToLookupService() throws Exception {
+ Thread.sleep(getLSInterval() * 3 + 500);
+ assertEquals(1, ls.getRegisterCount());
+ assertTrue("Keep alive should be sent at least 2x but was " +
ls.getKeepAliveCount(),
+ ls.getKeepAliveCount() >= 2);
+ }
}

Modified:
trunk/perfsonar-base/ls/src/test/java/net/geant/perfsonar/ls/MockLSService.java
===================================================================
---
trunk/perfsonar-base/ls/src/test/java/net/geant/perfsonar/ls/MockLSService.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/ls/src/test/java/net/geant/perfsonar/ls/MockLSService.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -16,47 +16,48 @@
import org.xml.sax.InputSource;

/**
- * Mock implementation of Lookup Service.
- * It is used in automated tests.
+ * Mock implementation of Lookup Service. It is used in automated tests.
*
* @author <a
href="mailto:">Blazej
Pietrzak</a>
*/
@WebServiceProvider
public class MockLSService implements Provider<StreamSource> {
- private int lsKeepAliveCount = 0;
- private int lsRegisterCount = 0;
- private Endpoint endpoint;
+ private int lsKeepAliveCount = 0;
+ private int lsRegisterCount = 0;
+ private Endpoint endpoint;

- @SuppressWarnings("unchecked")
- public StreamSource invoke(StreamSource input) {
- final XPathDeserializer deserializer = new
XPathDeserializer();
- NMWGMessage msg;
- try {
- msg = deserializer.getObjects(NMWGMessage.class,
(List<Object>) deserializer.deserialize(new
InputSource(input.getInputStream()))).get(0);
- if (msg.getType().equals("LSKeepaliveRequest"))
- lsKeepAliveCount++;
- else if (msg.getType().equals("LSRegisterRequest"))
- lsRegisterCount++;
- return new
StreamSource(NMWG.toLSResponse(msg.getId()));
- } catch (Exception ex) {
- fail(ex.toString());
- }
- return null;
- }
+ @SuppressWarnings("unchecked")
+ public StreamSource invoke(StreamSource input) {
+ final XPathDeserializer deserializer = new XPathDeserializer();
+ NMWGMessage msg;
+ try {
+ msg = deserializer.getObjects(NMWGMessage.class,
+ (List<Object>) deserializer.deserialize(new
InputSource(input.getInputStream()))).get(0);
+ if (msg.getType().equals("LSKeepaliveRequest")) {
+ lsKeepAliveCount++;
+ } else if (msg.getType().equals("LSRegisterRequest")) {
+ lsRegisterCount++;
+ }
+ return new StreamSource(NMWG.toLSResponse(msg.getId()));
+ } catch (Exception ex) {
+ fail(ex.toString());
+ }
+ return null;
+ }

- public int getKeepAliveCount() {
- return lsKeepAliveCount;
- }
+ public int getKeepAliveCount() {
+ return lsKeepAliveCount;
+ }

- public int getRegisterCount() {
- return lsRegisterCount;
- }
-
- public void publish(String url) {
- endpoint = Endpoint.publish(url, this);
- }
-
- public void stop() {
- endpoint.stop();
- }
+ public int getRegisterCount() {
+ return lsRegisterCount;
+ }
+
+ public void publish(String url) {
+ endpoint = Endpoint.publish(url, this);
+ }
+
+ public void stop() {
+ endpoint.stop();
+ }
}

Modified:
trunk/perfsonar-base/ls/src/test/resources/net/geant/perfsonar/mp/sshtelnet/LSRegister.template
===================================================================
---
trunk/perfsonar-base/ls/src/test/resources/net/geant/perfsonar/mp/sshtelnet/LSRegister.template
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/ls/src/test/resources/net/geant/perfsonar/mp/sshtelnet/LSRegister.template
2013-05-08 20:41:45 UTC (rev 6371)
@@ -11,20 +11,20 @@
</nmwg:subject>
</nmwg:metadata>
<nmwg:data metadataIdRef="serviceLookupInfo">
- <nmwg:metadata id="metadata0">
- <nmwg:subject
id="subject0">DummyCiscoRouter</nmwg:subject>
- <nmwg:parameters id="metaParams0">
- <nmwg:parameter name="class_name"
value="org.perfsonar.service.measurementPoint.lookingGlassType.engine.adapters.CiscoAdapter"
/>
- <nmwg:parameter name="url" value="0.0.0.0" />
- <nmwg:parameter name="port" value="0" />
- <nmwg:parameter name="prompt"
value="DummyRouter&gt;" />
- <nmwg:parameter name="rate" value="500" />
- <nmwg:parameter name="username"
value="dummyUser" />
- <nmwg:parameter name="password"
value="ab05D8Z22537EdEzaWmlmA==" />
- <nmwg:parameter name="timeout" value="10000"
/>
- <nmwg:parameter name="numberOfUsers"
value="0" />
- <nmwg:parameter name="cache" value="0" />
- </nmwg:parameters>
- </nmwg:metadata>
- </nmwg:data>
+ <nmwg:metadata id="metadata0">
+ <nmwg:subject id="subject0">DummyCiscoRouter</nmwg:subject>
+ <nmwg:parameters id="metaParams0">
+ <nmwg:parameter name="class_name"
value="org.perfsonar.service.measurementPoint.lookingGlassType.engine.adapters.CiscoAdapter"
/>
+ <nmwg:parameter name="url" value="0.0.0.0" />
+ <nmwg:parameter name="port" value="0" />
+ <nmwg:parameter name="prompt" value="DummyRouter&gt;" />
+ <nmwg:parameter name="rate" value="500" />
+ <nmwg:parameter name="username" value="dummyUser" />
+ <nmwg:parameter name="password"
value="ab05D8Z22537EdEzaWmlmA==" />
+ <nmwg:parameter name="timeout" value="10000" />
+ <nmwg:parameter name="numberOfUsers" value="0" />
+ <nmwg:parameter name="cache" value="0" />
+ </nmwg:parameters>
+ </nmwg:metadata>
+ </nmwg:data>
</nmwg:message>


Property changes on: trunk/perfsonar-base/messaging
___________________________________________________________________
Modified: svn:ignore
- .settings
.project
.classpath
target

velocity.log*

+ .settings
.project
.classpath
target

velocity.log*

.pmd

.pmdruleset


Modified:
trunk/perfsonar-base/messaging/src/main/java/net/geant/perfsonar/messaging/DeserializationException.java
===================================================================
---
trunk/perfsonar-base/messaging/src/main/java/net/geant/perfsonar/messaging/DeserializationException.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/messaging/src/main/java/net/geant/perfsonar/messaging/DeserializationException.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -5,49 +5,51 @@
import java.util.List;

public class DeserializationException extends Exception implements
Iterable<Throwable> {
- private static final long serialVersionUID = 2627705969628394226L;
- private List<Throwable> exceptions = new ArrayList<Throwable>();
+ private static final long serialVersionUID = 2627705969628394226L;
+ private List<Throwable> exceptions = new ArrayList<Throwable>();

- public DeserializationException(List<Throwable> exceptions) {
- super(toString(exceptions));
- this.exceptions.addAll(exceptions);
- }
+ public DeserializationException(List<Throwable> exceptions) {
+ super(toString(exceptions));
+ this.exceptions.addAll(exceptions);
+ }

- public DeserializationException(Throwable... ex) {
- super(toString(ex));
- for (Throwable t : ex) {
- exceptions.add(t);
- }
- }
-
- private static String toString(Throwable[] ex) {
- final StringBuffer text = new StringBuffer();
- boolean firstTime = true;
- for (Throwable t : ex) {
- if (firstTime)
- firstTime = false;
- else
- text.append("\n");
- text.append(t.getMessage());
- }
- return text.toString();
- }
+ public DeserializationException(Throwable... ex) {
+ super(toString(ex));
+ for (Throwable t : ex) {
+ exceptions.add(t);
+ }
+ }

- private static String toString(List<Throwable> exceptions) {
- final StringBuffer text = new StringBuffer();
- boolean firstTime = true;
- for (Throwable ex : exceptions) {
- if (firstTime)
- firstTime = false;
- else
- text.append("\n");
- text.append(ex.getMessage());
- }
- return text.toString();
- }
+ private static String toString(Throwable[] ex) {
+ final StringBuffer text = new StringBuffer();
+ boolean firstTime = true;
+ for (Throwable t : ex) {
+ if (firstTime) {
+ firstTime = false;
+ } else {
+ text.append("\n");
+ }
+ text.append(t.getMessage());
+ }
+ return text.toString();
+ }

- @Override
- public Iterator<Throwable> iterator() {
- return exceptions.iterator();
- }
+ private static String toString(List<Throwable> exceptions) {
+ final StringBuffer text = new StringBuffer();
+ boolean firstTime = true;
+ for (Throwable ex : exceptions) {
+ if (firstTime) {
+ firstTime = false;
+ } else {
+ text.append("\n");
+ }
+ text.append(ex.getMessage());
+ }
+ return text.toString();
+ }
+
+ @Override
+ public Iterator<Throwable> iterator() {
+ return exceptions.iterator();
+ }
}

Modified:
trunk/perfsonar-base/messaging/src/main/java/net/geant/perfsonar/messaging/Helper.java
===================================================================
---
trunk/perfsonar-base/messaging/src/main/java/net/geant/perfsonar/messaging/Helper.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/messaging/src/main/java/net/geant/perfsonar/messaging/Helper.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -1,17 +1,20 @@
package net.geant.perfsonar.messaging;

-
/**
* Helper class for creating subclasses on the fly.
*
* @author <a
href="mailto:">Blazej
Pietrzak</a>
*/
-public class Helper {
- /**
- * @return <code>true</code> if the object is a subclass
- * generated by <code>createMock</code> method.
- */
- public static boolean isConfigurationInstance(Object object) {

- return
object.getClass().getName().contains("EnhancerByCGLIB");
- }
+public final class Helper {
+ private Helper() {
+ // Utility class, we don't want to be instantiated directly, we're
private
+ super();
+ }
+ /**
+ * @return <code>true</code> if the object is a subclass generated by
+ * <code>createMock</code> method.
+ */
+ public static boolean isConfigurationInstance(Object object) {
+ return object.getClass().getName().contains("EnhancerByCGLIB");
+ }
}

Modified:
trunk/perfsonar-base/messaging/src/main/java/net/geant/perfsonar/messaging/InMemoryInstancesListener.java
===================================================================
---
trunk/perfsonar-base/messaging/src/main/java/net/geant/perfsonar/messaging/InMemoryInstancesListener.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/messaging/src/main/java/net/geant/perfsonar/messaging/InMemoryInstancesListener.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -18,45 +18,47 @@
* @author <a
href="mailto:">Blazej
Pietrzak</a>
*/
public class InMemoryInstancesListener extends InstantEvaluationListener {
- final Map<Class<?>, List<Object>> instances = new Hashtable<Class<?>,
List<Object>>();
- final List<Throwable> exceptions = new ArrayList<Throwable>();
-
+ private final Map<Class<?>, List<Object>> instances = new
Hashtable<Class<?>, List<Object>>();
+ private final List<Throwable> exceptions = new ArrayList<Throwable>();
+
@Override
public void onNodeHit(Expression expression, NodeItem nodeItem) {
- final Method method =
XPathDeserializer.getXPathMethod(expression.getXPath());
- executeMethod(method, nodeItem.value, instances, expression);
+ final Method method =
XPathDeserializer.getXPathMethod(expression.getXPath());
+ executeMethod(method, nodeItem.value, instances, expression);
}

@Override
public void finishedNodeSet(Expression expression) {
- //Empty implementation
+ // Empty implementation
}

@Override
public void onResult(Expression expression, Object result) {
- final Method method =
XPathDeserializer.getXPathMethod(expression.getXPath());
- executeMethod(method, (String) result.toString(), instances,
expression);
+ final Method method =
XPathDeserializer.getXPathMethod(expression.getXPath());
+ executeMethod(method, (String) result.toString(), instances,
expression);
}

- public List<?> getObjects() {
- final List<Object> result = new ArrayList<Object>();
- for (List<Object> temp : instances.values())
- result.addAll(temp);
- return result;
- }
+ public List<?> getObjects() {
+ final List<Object> result = new ArrayList<Object>();
+ for (List<Object> temp : instances.values()) {
+ result.addAll(temp);
+ }
+ return result;
+ }

- private void executeMethod(final Method method, String value, final
Map<Class<?>,
- List<Object>> instances, Expression expr) {
- if (value == null)
- exceptions.add(new XPathException("XPath(" +
expr.getXPath() + ") returned null."));
- try {
- method.execute(value, instances);
- } catch (Throwable ex) {
- exceptions.add(ex);
- }
- }
+ private void executeMethod(final Method method, String value, final
Map<Class<?>, List<Object>> instances,
+ Expression expr) {
+ if (value == null) {
+ exceptions.add(new XPathException("XPath(" + expr.getXPath() +
") returned null."));
+ }
+ try {
+ method.execute(value, instances);
+ } catch (Throwable ex) {
+ exceptions.add(ex);
+ }
+ }

- public List<Throwable> getExceptions() {
- return Collections.unmodifiableList(exceptions);
- }
+ public List<Throwable> getExceptions() {
+ return Collections.unmodifiableList(exceptions);
+ }
}

Modified:
trunk/perfsonar-base/messaging/src/main/java/net/geant/perfsonar/messaging/Method.java
===================================================================
---
trunk/perfsonar-base/messaging/src/main/java/net/geant/perfsonar/messaging/Method.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/messaging/src/main/java/net/geant/perfsonar/messaging/Method.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -8,100 +8,109 @@

public class Method {

- private final java.lang.reflect.Method method;
- private int count = 0;
-
- private final java.lang.reflect.Method identifierMethod;
- private final Object object;
-
- public Method(java.lang.reflect.Method method) {
- this(method, null, null);
- }
+ private final java.lang.reflect.Method method;
+ private int count = 0;

- public Method(java.lang.reflect.Method method,
java.lang.reflect.Method identifierMethod) {
- this(method, identifierMethod, null);
- }
-
- public Method(java.lang.reflect.Method method,
java.lang.reflect.Method identifierMethod, Object object) {
- this.method = method;
- this.identifierMethod = identifierMethod;
- this.object = object;
- }
-
- public void execute(String arg, Map<Class<?>, List<Object>>
instances) throws Throwable {
- try {
- if (getParameterType().equals(String.class)) {
- method.invoke(getInstance(instances), arg);
- } else {
- final Object reference =
getReference(instances, arg);
- if (reference == null)
- return;
- method.invoke(getInstance(instances),
reference);
- }
- } catch (InvocationTargetException ex) {
- throw new RuntimeException("Method: " + toString(),
ex.getTargetException());
- //throw ex.getTargetException();
- }
-
- count++;
- }
-
- public int getCount() {
- return count;
- }
-
- protected Object getInstance(Map<Class<?>, List<Object>> instances)
throws InstantiationException, IllegalAccessException {
- if (Modifier.isStatic(method.getModifiers()))
- throw new IllegalStateException("Static methods are
forbidden for xpath configuration: " + method);
- if (object != null)
- return object;
- if (instances.get(method.getDeclaringClass()) == null) {
- instances.put(method.getDeclaringClass(), new
ArrayList<Object>());
- }
- if (instances.get(method.getDeclaringClass()).size() < count
+ 1)
-
instances.get(method.getDeclaringClass()).add(method.getDeclaringClass().newInstance());
+ private final java.lang.reflect.Method identifierMethod;
+ private final Object object;

- try {
- return instances.get(method.getDeclaringClass()).get(count);
- } catch (IndexOutOfBoundsException ex) {
- ex.printStackTrace();
- throw ex;
- }
- }
-
- protected Object getReference(Map<Class<?>, List<Object>> instances,
String value) throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException {
- if (identifierMethod == null)
- return null;
-
- if (instances.get(identifierMethod.getDeclaringClass()) ==
null)
- return null;
-
- for (Object instance :
instances.get(identifierMethod.getDeclaringClass())) {
- try {
- if
(identifierMethod.invoke(instance).equals(value))
- return instance;
- } catch (NullPointerException ex) {
- throw new NullPointerException("Identifier
value is not set for " + instance
- + ". Check xpath for setting
identifier or verify whether xpath for reference is correct.");
- }
- }
-
- return null;
- }
+ public Method(java.lang.reflect.Method method) {
+ this(method, null, null);
+ }

- public boolean isParameterType(Class<?> type) {
- return getParameterType().equals(type);
- }
+ public Method(java.lang.reflect.Method method, java.lang.reflect.Method
identifierMethod) {
+ this(method, identifierMethod, null);
+ }

- private Class<?> getParameterType() {
- return method.getParameterTypes()[0];
- }
+ public Method(java.lang.reflect.Method method, java.lang.reflect.Method
identifierMethod, Object object) {
+ this.method = method;
+ this.identifierMethod = identifierMethod;
+ this.object = object;
+ }

- public void resetCount() {
- count = 0;
- }
-
- public String toString() {
- return this.method.toString() + " [" + count + "]";
- }
+ public void execute(String arg, Map<Class<?>, List<Object>> instances)
throws Throwable {
+ try {
+ if (getParameterType().equals(String.class)) {
+ method.invoke(getInstance(instances), arg);
+ } else {
+ final Object reference = getReference(instances, arg);
+ if (reference == null) {
+ return;
+ }
+ method.invoke(getInstance(instances), reference);
+ }
+ } catch (InvocationTargetException ex) {
+ throw new RuntimeException("Method: " + toString(),
ex.getTargetException());
+ // throw ex.getTargetException();
+ }
+
+ count++;
+ }
+
+ public int getCount() {
+ return count;
+ }
+
+ protected Object getInstance(Map<Class<?>, List<Object>> instances)
throws InstantiationException,
+ IllegalAccessException {
+ if (Modifier.isStatic(method.getModifiers())) {
+ throw new IllegalStateException("Static methods are forbidden
for xpath configuration: " + method);
+ }
+ if (object != null) {
+ return object;
+ }
+ if (instances.get(method.getDeclaringClass()) == null) {
+ instances.put(method.getDeclaringClass(), new
ArrayList<Object>());
+ }
+ if (instances.get(method.getDeclaringClass()).size() < count + 1) {
+
instances.get(method.getDeclaringClass()).add(method.getDeclaringClass().newInstance());
+ }
+
+ try {
+ return instances.get(method.getDeclaringClass()).get(count);
+ } catch (IndexOutOfBoundsException ex) {
+ ex.printStackTrace();
+ throw ex;
+ }
+ }
+
+ protected Object getReference(Map<Class<?>, List<Object>> instances,
String value) throws IllegalAccessException,
+ InvocationTargetException {
+ if (identifierMethod == null) {
+ return null;
+ }
+
+ if (instances.get(identifierMethod.getDeclaringClass()) == null) {
+ return null;
+ }
+
+ for (Object instance :
instances.get(identifierMethod.getDeclaringClass())) {
+ try {
+ if (identifierMethod.invoke(instance).equals(value)) {
+ return instance;
+ }
+ } catch (NullPointerException ex) {
+ throw new NullPointerException("Identifier value is not set
for " + instance
+ + ". Check xpath for setting identifier or verify
whether xpath for reference is correct.");
+ }
+ }
+
+ return null;
+ }
+
+ public boolean isParameterType(Class<?> type) {
+ return getParameterType().equals(type);
+ }
+
+ private Class<?> getParameterType() {
+ return method.getParameterTypes()[0];
+ }
+
+ public void resetCount() {
+ count = 0;
+ }
+
+ public String toString() {
+ return this.method.toString() + " [" + count + "]";
+ }
}

Modified:
trunk/perfsonar-base/messaging/src/main/java/net/geant/perfsonar/messaging/ReferenceInterceptor.java
===================================================================
---
trunk/perfsonar-base/messaging/src/main/java/net/geant/perfsonar/messaging/ReferenceInterceptor.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/messaging/src/main/java/net/geant/perfsonar/messaging/ReferenceInterceptor.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -6,24 +6,25 @@
import net.sf.cglib.proxy.MethodProxy;

/**
- * Used for reference configurations.
- * Decides what will happen when a method is invoked when configuring a
reference.
+ * Used for reference configurations. Decides what will happen when a method
is
+ * invoked when configuring a reference.
*
* @author <a
href="mailto:">Blazej
Pietrzak</a>
*/
public class ReferenceInterceptor implements MethodInterceptor {

- public Object intercept(Object obj, Method method, Object[] args,
- MethodProxy proxy) throws Throwable {
-
- if (method.getName().equals("equals") ||
method.getName().equals("toString") || method.getName().equals("hashCode") ||
method.getName().equals("finalize")) {
- return proxy.invokeSuper(obj, args);
- }
-
- if (args.length != 0)
- throw new IllegalArgumentException(method + "
identifier method must have zero arguments.");
-
- XPathDeserializer.putIdentifier(method.getDeclaringClass(),
method);
- return null;
- }
+ public Object intercept(Object obj, Method method, Object[] args,
MethodProxy proxy) throws Throwable {
+
+ if (method.getName().equals("equals") ||
method.getName().equals("toString")
+ || method.getName().equals("hashCode") ||
method.getName().equals("finalize")) {
+ return proxy.invokeSuper(obj, args);
+ }
+
+ if (args.length != 0) {
+ throw new IllegalArgumentException(method + " identifier method
must have zero arguments.");
+ }
+
+ XPathDeserializer.putIdentifier(method.getDeclaringClass(), method);
+ return null;
+ }
}

Modified:
trunk/perfsonar-base/messaging/src/main/java/net/geant/perfsonar/messaging/SelfTestResult.java
===================================================================
---
trunk/perfsonar-base/messaging/src/main/java/net/geant/perfsonar/messaging/SelfTestResult.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/messaging/src/main/java/net/geant/perfsonar/messaging/SelfTestResult.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -4,6 +4,9 @@
import static net.geant.perfsonar.messaging.XPathDeserializer.declarePrefix;
import static net.geant.perfsonar.messaging.XPathDeserializer.whenXPath;

+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
/**
* This class is used in unit tests to check the behavior of a service wrt
self
* tests
@@ -13,150 +16,154 @@
*
*/
public class SelfTestResult implements Comparable<SelfTestResult> {
- static {
- declarePrefix("nmwg", "http://ggf.org/ns/nmwg/base/2.0/";);
- try {
-
whenXPath("nmwg:message/nmwg:data/nmwg:metadata/@id").then(
-
SelfTestResult.class).setName(any(String.class));
+ protected static Logger logger =
LoggerFactory.getLogger("SelfTestResult");
+ static {
+ declarePrefix("nmwg", "http://ggf.org/ns/nmwg/base/2.0/";);
+ try {
+
whenXPath("nmwg:message/nmwg:data/nmwg:metadata/@id").then(SelfTestResult.class).setName(any(String.class));

-
whenXPath("nmwg:message/nmwg:data/nmwg:data/nmwg:datum/text()")
-
.then(SelfTestResult.class).setMessage(any(String.class));
+
whenXPath("nmwg:message/nmwg:data/nmwg:data/nmwg:datum/text()").then(SelfTestResult.class).setMessage(
+ any(String.class));

- whenXPath(
-
"nmwg:message/nmwg:data/nmwg:metadata/nmwg:eventType/text()")
-
.then(SelfTestResult.class).setEventType(any(String.class));
- } catch (Exception ex) {
- }
- }
+
whenXPath("nmwg:message/nmwg:data/nmwg:metadata/nmwg:eventType/text()").then(SelfTestResult.class)
+ .setEventType(any(String.class));
+ } catch (Exception ex) {
+ logger.debug(ex.getMessage());
+ }
+ }

- protected String name;
- protected String message;
- protected String status;
- protected String serviceName;
- protected String serviceType;
+ protected String name;
+ protected String message;
+ protected String status;
+ protected String serviceName;
+ protected String serviceType;

- public SelfTestResult(String name, String message, String status,
- String serviceName, String serviceType) {
- this.name = name;
- this.message = message;
- this.status = status;
- this.serviceName = serviceName;
- this.serviceType = serviceType;
- }
+ public SelfTestResult(String name, String message, String status, String
serviceName, String serviceType) {
+ this.name = name;
+ this.message = message;
+ this.status = status;
+ this.serviceName = serviceName;
+ this.serviceType = serviceType;
+ }

- public SelfTestResult() {
- }
+ public SelfTestResult() {
+ }

- public static SelfTestResult failure(String name, String message,
- String serviceName, String serviceType) {
- return new SelfTestResult(name, message, "failure",
serviceName,
- serviceType);
- }
+ public static SelfTestResult failure(String name, String message, String
serviceName, String serviceType) {
+ return new SelfTestResult(name, message, "failure", serviceName,
serviceType);
+ }

- public static SelfTestResult success(String name, String message,
- String serviceName, String serviceType) {
- return new SelfTestResult(name, message, "success",
serviceName,
- serviceType);
- }
+ public static SelfTestResult success(String name, String message, String
serviceName, String serviceType) {
+ return new SelfTestResult(name, message, "success", serviceName,
serviceType);
+ }

- public void setName(String name) {
- this.name = name;
- }
+ public void setName(String name) {
+ this.name = name;
+ }

- public String getName() {
- return name;
- }
+ public String getName() {
+ return name;
+ }

- public void setMessage(String message) {
- this.message = message;
- }
+ public void setMessage(String message) {
+ this.message = message;
+ }

- public String getMessage() {
- return message;
- }
+ public String getMessage() {
+ return message;
+ }

- public void setStatus(String status) {
- this.status = status;
- }
+ public void setStatus(String status) {
+ this.status = status;
+ }

- public String getStatus() {
- return status;
- }
+ public String getStatus() {
+ return status;
+ }

- @Override
- public int compareTo(SelfTestResult arg) {
- return getName().compareTo(arg.getName());
- }
+ @Override
+ public int compareTo(SelfTestResult arg) {
+ return getName().compareTo(arg.getName());
+ }

- public void setEventType(String eventType) {
- if (eventType.contains("success"))
- status = "success";
- else
- status = "failure";
+ public void setEventType(String eventType) {
+ if (eventType.contains("success")) {
+ status = "success";
+ } else {
+ status = "failure";
+ }

- String[] elems = eventType.substring(
-
"http://schemas.perfsonar.net/tools/admin/selftest/".length())
- .split("/");
-
- serviceType = elems[0];
- serviceName = elems[1];
- }
+ String[] elems =
eventType.substring("http://schemas.perfsonar.net/tools/admin/selftest/".length()).split("/");

- @Override
- public String toString() {
- return status + " (name=" + name + ", message=" + message
- + ", service-name=" + serviceName + ",
service-type="
- + serviceType + ")";
- }
+ serviceType = elems[0];
+ serviceName = elems[1];
+ }

- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((message == null) ? 0 :
message.hashCode());
- result = prime * result + ((name == null) ? 0 :
name.hashCode());
- result = prime * result
- + ((serviceName == null) ? 0 :
serviceName.hashCode());
- result = prime * result
- + ((serviceType == null) ? 0 :
serviceType.hashCode());
- result = prime * result + ((status == null) ? 0 :
status.hashCode());
- return result;
- }
+ @Override
+ public String toString() {
+ return status + " (name=" + name + ", message=" + message + ",
service-name=" + serviceName + ", service-type="
+ + serviceType + ")";
+ }

- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- SelfTestResult other = (SelfTestResult) obj;
- if (message == null) {
- if (other.message != null)
- return false;
- } else if (!message.equals(other.message))
- return false;
- if (name == null) {
- if (other.name != null)
- return false;
- } else if (!name.equals(other.name))
- return false;
- if (serviceName == null) {
- if (other.serviceName != null)
- return false;
- } else if (!serviceName.equals(other.serviceName))
- return false;
- if (serviceType == null) {
- if (other.serviceType != null)
- return false;
- } else if (!serviceType.equals(other.serviceType))
- return false;
- if (status == null) {
- if (other.status != null)
- return false;
- } else if (!status.equals(other.status))
- return false;
- return true;
- }
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((message == null) ? 0 :
message.hashCode());
+ result = prime * result + ((name == null) ? 0 : name.hashCode());
+ result = prime * result + ((serviceName == null) ? 0 :
serviceName.hashCode());
+ result = prime * result + ((serviceType == null) ? 0 :
serviceType.hashCode());
+ result = prime * result + ((status == null) ? 0 : status.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null) {
+ return false;
+ }
+ if (getClass() != obj.getClass()) {
+ return false;
+ }
+ SelfTestResult other = (SelfTestResult) obj;
+ if (message == null) {
+ if (other.message != null) {
+ return false;
+ }
+ } else if (!message.equals(other.message)) {
+ return false;
+ }
+ if (name == null) {
+ if (other.name != null) {
+ return false;
+ }
+ } else if (!name.equals(other.name)) {
+ return false;
+ }
+ if (serviceName == null) {
+ if (other.serviceName != null) {
+ return false;
+ }
+ } else if (!serviceName.equals(other.serviceName)) {
+ return false;
+ }
+ if (serviceType == null) {
+ if (other.serviceType != null) {
+ return false;
+ }
+ } else if (!serviceType.equals(other.serviceType)) {
+ return false;
+ }
+ if (status == null) {
+ if (other.status != null) {
+ return false;
+ }
+ } else if (!status.equals(other.status)) {
+ return false;
+ }
+ return true;
+ }
}

Modified:
trunk/perfsonar-base/messaging/src/main/java/net/geant/perfsonar/messaging/XPathConfiguration.java
===================================================================
---
trunk/perfsonar-base/messaging/src/main/java/net/geant/perfsonar/messaging/XPathConfiguration.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/messaging/src/main/java/net/geant/perfsonar/messaging/XPathConfiguration.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -15,44 +15,46 @@
*/
public class XPathConfiguration implements MethodInterceptor {

- private String xpath;
- private Object object;
-
- private static final List<String> restrictedMethodNames =
Arrays.asList("toString", "hashCode", "finalize");
+ private String xpath;
+ private Object object;

- public XPathConfiguration(String xpath) {
- this.xpath = xpath;
- }
-
- @SuppressWarnings("unchecked")
- public <T> T then(Class<T> controller) throws InstantiationException,
IllegalAccessException {
- return (T) Enhancer.create(controller, this);
- }
-
- @SuppressWarnings("unchecked")
- public <T> T then(Class<T> clazz, T object) throws
InstantiationException, IllegalAccessException {
- this.object = object;
- return (T) Enhancer.create(clazz, this);
- }
+ private static final List<String> RESTRICTED_METHODS =
Arrays.asList("toString", "hashCode", "finalize");

- public Object intercept(Object obj, Method method, Object[] args,
- MethodProxy proxy) throws Throwable {
-
- if (restrictedMethodNames.contains(method.getName())) {
- return proxy.invokeSuper(obj, args);
- }
-
- if
(!obj.getClass().getSuperclass().equals(method.getDeclaringClass()))
- return null;
-
- if (args.length != 1)
- return null;
-
- if (this.object != null)
- XPathDeserializer.putXPath(xpath, object, method);
- else
- XPathDeserializer.putXPath(xpath, method);
-
- return null;
- }
+ public XPathConfiguration(String xpath) {
+ this.xpath = xpath;
+ }
+
+ @SuppressWarnings("unchecked")
+ public <T> T then(Class<T> controller) throws InstantiationException,
IllegalAccessException {
+ return (T) Enhancer.create(controller, this);
+ }
+
+ @SuppressWarnings("unchecked")
+ public <T> T then(Class<T> clazz, T object) throws
InstantiationException, IllegalAccessException {
+ this.object = object;
+ return (T) Enhancer.create(clazz, this);
+ }
+
+ public Object intercept(Object obj, Method method, Object[] args,
MethodProxy proxy) throws Throwable {
+
+ if (RESTRICTED_METHODS.contains(method.getName())) {
+ return proxy.invokeSuper(obj, args);
+ }
+
+ if
(!obj.getClass().getSuperclass().equals(method.getDeclaringClass())) {
+ return null;
+ }
+
+ if (args.length != 1) {
+ return null;
+ }
+
+ if (this.object != null) {
+ XPathDeserializer.putXPath(xpath, object, method);
+ } else {
+ XPathDeserializer.putXPath(xpath, method);
+ }
+
+ return null;
+ }
}

Modified:
trunk/perfsonar-base/messaging/src/main/java/net/geant/perfsonar/messaging/XPathDeserializer.java
===================================================================
---
trunk/perfsonar-base/messaging/src/main/java/net/geant/perfsonar/messaging/XPathDeserializer.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/messaging/src/main/java/net/geant/perfsonar/messaging/XPathDeserializer.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -22,167 +22,169 @@
/**
* Deserializes data from XML stream.
*
- * This class provides API for configuring XPath expressions that trigger
- * method invocation with values of the expression evaluation.
- * Please note that it uses streaming XPaths, so only a subset of
expressions can
- * be used. Those that require creation of DOM tree are not allowed.
+ * This class provides API for configuring XPath expressions that trigger
method
+ * invocation with values of the expression evaluation. Please note that it
uses
+ * streaming XPaths, so only a subset of expressions can be used. Those that
+ * require creation of DOM tree are not allowed.
*
- * There are two approaches to configure deserializer: via API or via
annotations.
- * By invoking:
- * <code>declarePrefix("nmwg", uri)</code>
- * one informs the deserializer about prefixes for various namespaces.
- * By invoking:
+ * There are two approaches to configure deserializer: via API or via
+ * annotations. By invoking: <code>declarePrefix("nmwg", uri)</code> one
informs
+ * the deserializer about prefixes for various namespaces. By invoking:
*
<code>whenXPath("/nmwg:message/@id").then(NMWGMessage.class).setId(any(String.class))</code>
- * deserializer will fire setId method from instance of NMWGMesssage class
and provide
- * as an argument the result of XPath expression provided in whenXPath
method.
- * During configuration no real method is executed.
- * The following configuration is developer friendly. It statically checks
whether
- * the method exists and in case of refactoring it will be reconfigured
automatically.
+ * deserializer will fire setId method from instance of NMWGMesssage class
and
+ * provide as an argument the result of XPath expression provided in
whenXPath
+ * method. During configuration no real method is executed. The following
+ * configuration is developer friendly. It statically checks whether the
method
+ * exists and in case of refactoring it will be reconfigured automatically.
*
- * By invoking:
- * <code>whenXPath(
- *
"nmwg:message/nmwg:data[starts-with(@metadataIdRef,
'metadata')]/@metadataIdRef")
- * .then(Command.class).setCurrentRouter(
- * getReference(Router.class,
identifier(Router.class).getId()));</code>
- *
- * deserializer will invoke setCurrentRouter method and will provide a real
instance (not string)
- * of Router class identified by getId method in defined in Router class.
+ * By invoking: <code>whenXPath(
+ * "nmwg:message/nmwg:data[starts-with(@metadataIdRef,
'metadata')]/@metadataIdRef")
+ * .then(Command.class).setCurrentRouter(
+ * getReference(Router.class,
identifier(Router.class).getId()));</code>
*
- * Configuring deserializer via annotations requires psbase3-apt tool to be
present on the classpath during compilation.
- * By invoking:
+ * deserializer will invoke setCurrentRouter method and will provide a real
+ * instance (not string) of Router class identified by getId method in
defined
+ * in Router class.
+ *
+ * Configuring deserializer via annotations requires psbase3-apt tool to be
+ * present on the classpath during compilation. By invoking:
*
<code>@XPath(xpath="nmwg:message/nmwg:metadata[@id='meta']/nmwg:eventType/text()",
- *
namespaces=@Namespace(prefix="nmwg",
uri=NMWG_URI)) public void setEventType(String type)</code>
- *
- * setEventType method will be invoked when the xpath will be evaluated.
+ *
namespaces=@Namespace(prefix="nmwg",
uri=NMWG_URI)) public void setEventType(String type)</code>
*
+ * setEventType method will be invoked when the xpath will be evaluated.
+ *
* @author <a
href="mailto:">Blazej
Pietrzak</a>
- *
+ *
*/
public class XPathDeserializer {
- private final static DefaultNamespaceContext context = new
DefaultNamespaceContext();
- private final static Map<String, Method> xpaths = new
Hashtable<String, Method>();
- private final static Map<Class<?>, java.lang.reflect.Method>
identifiers = new Hashtable<Class<?>, java.lang.reflect.Method>();
-
- public static void declarePrefix(String prefix, String uri) {
- context.declarePrefix(prefix, uri);
- }
-
- public static XPathConfiguration whenXPath(String xpath) {
- return new XPathConfiguration(xpath);
- }
-
- public static <T> T getReference(Class<T> type, String id) throws
InstantiationException, IllegalAccessException {
- return type.newInstance();
- }
-
- @SuppressWarnings("unchecked")
- public static <T> T identifier(Class<T> type) {
- return (T) Enhancer.create(type, new ReferenceInterceptor());
- }
-
- public static java.lang.reflect.Method findIdentifier(Class<?> type) {
- return identifiers.get(type);
- }
-
- public static <T> T any(Class<T> type) {
- return null;
- }
-
- public static void putXPath(String xpath, Object object,
java.lang.reflect.Method method) {
- xpaths.put(xpath, new Method(method,
identifiers.get(method.getParameterTypes()[0]), object));
- }
-
- public static synchronized void putXPath(String xpath,
java.lang.reflect.Method method) {
- xpaths.put(xpath, new Method(method,
identifiers.get(method.getParameterTypes()[0])));
- }
-
- protected static void putIdentifier(Class<?> declaringClass,
java.lang.reflect.Method method) {
- XPathDeserializer.identifiers.put(declaringClass, method);
- }
-
- public static void clearConfiguration() {
- xpaths.clear();
- }
-
- private static synchronized Set<String> getXPaths() {
- return xpaths.keySet();
- }
-
- protected static Method getXPathMethod(String xpath) {
- return xpaths.get(xpath);
- }
-
- public static Map<String, Method> getConfiguration() {
- return xpaths;
- }
+ private static final DefaultNamespaceContext CONTEXT = new
DefaultNamespaceContext();
+ private static final Map<String, Method> XPATHS = new Hashtable<String,
Method>();
+ private static final Map<Class<?>, java.lang.reflect.Method> IDENTIFIERS
= new Hashtable<Class<?>, java.lang.reflect.Method>();

- public XPathDeserializer() {
- }
-
- public static String validate(String xpath) {
- final XMLDog dog = new XMLDog(context);
- try {
- dog.addXPath(xpath);
- } catch (XPathSyntaxException ex) {
- return "Invalid XPath: " + ex.getMultilineMessage();
- } catch (SAXPathException ex) {
- return "Invalid XPath: " + ex.getMessage();
- }
-
- return null;
- }
+ public static void declarePrefix(String prefix, String uri) {
+ CONTEXT.declarePrefix(prefix, uri);
+ }

- /**
- * Deserializes objects from xml stream using streaming XPath
expressions.
- * @throws Throwable
- */
- public List<?> deserialize(InputSource reader) throws
DeserializationException {
- final XMLDog dog = new XMLDog(context);
- final List<Throwable> exceptions = new ArrayList<Throwable>();
- for (Iterator<String> iter =
XPathDeserializer.getXPaths().iterator(); iter.hasNext(); ) {
- try {
- dog.addXPath(iter.next());
- } catch (XPathSyntaxException ex) {
- exceptions.add(new XPathException("Invalid
XPath: " + ex.getMultilineMessage()));
- } catch (SAXPathException ex) {
- exceptions.add(new XPathException("Invalid
XPath: " + ex.getMessage()));
- }
- }
-
- if (exceptions.size() > 0)
- throw new DeserializationException(exceptions);
-
- final Event event = dog.createEvent(); // must be after all
expressions are added.
- event.setXMLBuilder(new DOMBuilder());
-
- final InMemoryInstancesListener listener = new
InMemoryInstancesListener();
-
- event.setListener(listener);
-
- try {
- dog.sniff(event, reader, false/*useSTAX*/);
- } catch (XPathException ex) {
- throw new DeserializationException(ex);
- } finally {
- for (Method method : xpaths.values()) {
- method.resetCount();
- }
- }
-
- if (listener.getExceptions().size() > 0)
- throw new
DeserializationException(listener.getExceptions());
-
- return listener.getObjects();
- }
-
- @SuppressWarnings("unchecked")
- public <T> List<T> getObjects(Class<T> type, List<Object> objects) {
- final List<T> result = new ArrayList<T>();
- for (Object obj : objects) {
- if (obj.getClass().equals(type)) {
- result.add((T) obj);
- }
- }
- return result;
- }
+ public static XPathConfiguration whenXPath(String xpath) {
+ return new XPathConfiguration(xpath);
+ }
+
+ public static <T> T getReference(Class<T> type, String id) throws
InstantiationException, IllegalAccessException {
+ return type.newInstance();
+ }
+
+ @SuppressWarnings("unchecked")
+ public static <T> T identifier(Class<T> type) {
+ return (T) Enhancer.create(type, new ReferenceInterceptor());
+ }
+
+ public static java.lang.reflect.Method findIdentifier(Class<?> type) {
+ return IDENTIFIERS.get(type);
+ }
+
+ public static <T> T any(Class<T> type) {
+ return null;
+ }
+
+ public static void putXPath(String xpath, Object object,
java.lang.reflect.Method method) {
+ XPATHS.put(xpath, new Method(method,
IDENTIFIERS.get(method.getParameterTypes()[0]), object));
+ }
+
+ public static synchronized void putXPath(String xpath,
java.lang.reflect.Method method) {
+ XPATHS.put(xpath, new Method(method,
IDENTIFIERS.get(method.getParameterTypes()[0])));
+ }
+
+ protected static void putIdentifier(Class<?> declaringClass,
java.lang.reflect.Method method) {
+ XPathDeserializer.IDENTIFIERS.put(declaringClass, method);
+ }
+
+ public static void clearConfiguration() {
+ XPATHS.clear();
+ }
+
+ private static synchronized Set<String> getXPaths() {
+ return XPATHS.keySet();
+ }
+
+ protected static Method getXPathMethod(String xpath) {
+ return XPATHS.get(xpath);
+ }
+
+ public static Map<String, Method> getConfiguration() {
+ return XPATHS;
+ }
+
+ public XPathDeserializer() {
+ }
+
+ public static String validate(String xpath) {
+ final XMLDog dog = new XMLDog(CONTEXT);
+ try {
+ dog.addXPath(xpath);
+ } catch (XPathSyntaxException ex) {
+ return "Invalid XPath: " + ex.getMultilineMessage();
+ } catch (SAXPathException ex) {
+ return "Invalid XPath: " + ex.getMessage();
+ }
+
+ return null;
+ }
+
+ /**
+ * Deserializes objects from xml stream using streaming XPath
expressions.
+ *
+ * @throws Throwable
+ */
+ public List<?> deserialize(InputSource reader) throws
DeserializationException {
+ final XMLDog dog = new XMLDog(CONTEXT);
+ final List<Throwable> exceptions = new ArrayList<Throwable>();
+ for (Iterator<String> iter =
XPathDeserializer.getXPaths().iterator(); iter.hasNext();) {
+ try {
+ dog.addXPath(iter.next());
+ } catch (XPathSyntaxException ex) {
+ exceptions.add(new XPathException("Invalid XPath: " +
ex.getMultilineMessage()));
+ } catch (SAXPathException ex) {
+ exceptions.add(new XPathException("Invalid XPath: " +
ex.getMessage()));
+ }
+ }
+
+ if (exceptions.size() > 0) {
+ throw new DeserializationException(exceptions);
+ }
+
+ final Event event = dog.createEvent(); // must be after all
expressions
+ // are added.
+ event.setXMLBuilder(new DOMBuilder());
+
+ final InMemoryInstancesListener listener = new
InMemoryInstancesListener();
+
+ event.setListener(listener);
+
+ try {
+ dog.sniff(event, reader, false/* useSTAX */);
+ } catch (XPathException ex) {
+ throw new DeserializationException(ex);
+ } finally {
+ for (Method method : XPATHS.values()) {
+ method.resetCount();
+ }
+ }
+
+ if (listener.getExceptions().size() > 0) {
+ throw new DeserializationException(listener.getExceptions());
+ }
+
+ return listener.getObjects();
+ }
+
+ @SuppressWarnings("unchecked")
+ public <T> List<T> getObjects(Class<T> type, List<Object> objects) {
+ final List<T> result = new ArrayList<T>();
+ for (Object obj : objects) {
+ if (obj.getClass().equals(type)) {
+ result.add((T) obj);
+ }
+ }
+ return result;
+ }
}

Modified:
trunk/perfsonar-base/messaging/src/main/java/net/geant/perfsonar/templates/TemplateEngine.java
===================================================================
---
trunk/perfsonar-base/messaging/src/main/java/net/geant/perfsonar/templates/TemplateEngine.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/messaging/src/main/java/net/geant/perfsonar/templates/TemplateEngine.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -7,6 +7,8 @@

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;

/**
* Provides facade to the underlying template engine. This implementation
uses
@@ -15,51 +17,57 @@
* @author <a
href="mailto:">Blazej
Pietrzak</a>
*
*/
-public class TemplateEngine {
- private final static VelocityEngine templateEngine = new
VelocityEngine();
- private final static VelocityContext context = new VelocityContext();
+public final class TemplateEngine {
+ private static final Logger LOGGER =
LoggerFactory.getLogger("SelfTestResult");
+ private static final VelocityEngine TEMPLATE_ENGINE = new
VelocityEngine();
+ private static final VelocityContext CONTEXT = new VelocityContext();

- static {
- try {
- templateEngine.init();
- } catch (Exception ex) { }
- }
+ private TemplateEngine() {
+ // Utility class, we don't want to be instantiated directly, we're
private
+ super();
+ }
+
+ static {
+ try {
+ TEMPLATE_ENGINE.init();
+ } catch (Exception ex) {
+ LOGGER.debug("Exception during engine initialisation ({}): {}",
ex.getClass(), ex.getMessage());
+ }
+ }

- private static InputStream getTemplate(Class<?> homeDir, String name)
- throws IOException {
+ private static InputStream getTemplate(Class<?> homeDir, String name)
throws IOException {

- final InputStream in = homeDir.getResourceAsStream(name);
+ final InputStream in = homeDir.getResourceAsStream(name);

- if (in == null)
- throw new IOException("Template " + name + " cannot
be found.");
- return in;
- }
+ if (in == null) {
+ throw new IOException("Template " + name + " cannot be found.");
+ }
+ return in;
+ }

- /**
- * Writes to the stream provided by writer argument, the template
found in
- * the directory where the given class is stored using the template
provided
- * by name.
- *
- */
- public static void evaluate(Writer writer, Class<?> homeDir, String
name)
- throws IOException {
- // TODO change to not deprecated
- templateEngine.evaluate(context, writer, "successMessage",
- getTemplate(homeDir, name));
- }
+ /**
+ * Writes to the stream provided by writer argument, the template found
in
+ * the directory where the given class is stored using the template
provided
+ * by name.
+ *
+ */
+ public static void evaluate(Writer writer, Class<?> homeDir, String
name) throws IOException {
+ // TODO change to not deprecated
+ TEMPLATE_ENGINE.evaluate(CONTEXT, writer, "successMessage",
getTemplate(homeDir, name));
+ }

public static String evaluate(String template) {
- final StringWriter out = new StringWriter();
- templateEngine.evaluate(context, out, "successMessage", template);
- return out.toString();
+ final StringWriter out = new StringWriter();
+ TEMPLATE_ENGINE.evaluate(CONTEXT, out, "successMessage", template);
+ return out.toString();
}
-
- /**
- * Put data to the context. Data can be used in templates with a
macro ${identifier}
- * where identifier is the name put in the context.
- * More on template engine can be found at Apache Velocity website.
- */
- public static void put(String name, Object value) {
- context.put(name, value);
- }
+
+ /**
+ * Put data to the CONTEXT. Data can be used in templates with a macro
+ * ${identifier} where identifier is the name put in the CONTEXT. More on
+ * template engine can be found at Apache Velocity website.
+ */
+ public static void put(String name, Object value) {
+ CONTEXT.put(name, value);
+ }
}

Modified:
trunk/perfsonar-base/messaging/src/test/groovy/net/geant/perfsonar/templates/NMWG.groovy
===================================================================
---
trunk/perfsonar-base/messaging/src/test/groovy/net/geant/perfsonar/templates/NMWG.groovy
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/messaging/src/test/groovy/net/geant/perfsonar/templates/NMWG.groovy
2013-05-08 20:41:45 UTC (rev 6371)
@@ -18,203 +18,203 @@
*
*/
class NMWG {
- private static Reader createRequest(id, eventType, version) {
- def writer = new StringWriter()
- MarkupBuilder xml = new MarkupBuilder(writer)
- xml.mkp.xmlDeclaration(version:"1.0", encoding:"UTF-8")
-
xml.'nmwg:message'('xmlns:nmwg':'http://ggf.org/ns/nmwg/base/2.0/', id:id,
type:"EchoRequest") {
- 'nmwg:metadata'(id:"meta") {
- 'nmwg:eventType'
"http://schemas.perfsonar.net/tools/admin/${eventType}/${version}";
- }
- 'nmwg:data'(id:"data", metadataIdRef:"meta")
- }
-
- writer.write("\n");
- new StringReader(writer.toString())
- }
-
- static Reader toEchoRequest(String id) {
- createRequest(id, "echo", "2.0")
- }
-
- static Reader toSelfTestRequest(String id) {
- createRequest(id, "selftest", "1.0")
- }
-
- static Reader toSelfTestRequest(String id, String testName) {
- createRequest(id, "selftest", "1.0/${testName}")
- }
-
- static Reader toMetadataKeyRequest(String id) {
- def writer = new StringWriter()
- MarkupBuilder xml = new MarkupBuilder(writer)
-
xml.'nmwg:message'('xmlns:nmwg':'http://ggf.org/ns/nmwg/base/2.0/', id:id,
type:"MetadataKeyRequest") {
- 'nmwg:metadata'(id:"meta") {
- 'nmwg:subject'(id:"server") {
- 'nmwg:parameters'(id:"params") {
-
'nmwg:parameter'(name:"param", "SES")
- }
- }
- }
- 'nmwg:data'(id:"data", metadataIdRef:"meta")
- }
-
- new StringReader(writer.toString())
- }
-
- static Reader toSetupDataRequest(String id, Command... commands) {
- def idx = 0;
- final def writer = new StringWriter()
- final MarkupBuilder xml = new MarkupBuilder(writer)
- xml.mkp.xmlDeclaration(version:"1.0", encoding:"UTF-8")
-
xml.'nmwg:message'('xmlns:nmwg':'http://ggf.org/ns/nmwg/base/2.0/',
'xmlns:nmwgtopo':'http://ggf.org/ns/nmwg/topology/2.0/', id:id,
type:"SetupDataRequest") {
- commands.each { command ->
- 'nmwg:metadata'(id:"meta${idx}") {
- 'nmwg:subject'(id:"subject${idx}") {
-
'nmwgtopo:endPoint'(type:"hostname", command.routerName)
- }
- 'nmwg:parameters'(id:"params${idx}") {
-
'nmwg:parameter'(name:"command", value:command.name)
-
'nmwg:parameter'(name:"description", value:command.description)
-
'nmwg:parameter'(name:"syntax", value:command.syntax)
- }
- 'nmwg:eventType' command.eventType
- }
- 'nmwg:data'(id:"data${idx}",
metadataIdRef:"meta${idx}")
- }
- }
- new StringReader(writer.toString())
- }
-
- static Reader toSelfTestResponse(requestId, SelfTestResult... tests) {
- createResponse(requestId) {
- 'nmwg:metadata'(id:"meta") {
- 'nmwg:eventType'
"http://schemas.perfsonar.net/tools/admin/selftest/1.0";
- }
- 'nmwg:data'(id:"data", metadataIdRef:"meta") {
- tests.each { test ->
- 'nmwg:metadata'(id:"${test.name}") {
- 'nmwg:eventType'
"http://schemas.perfsonar.net/tools/admin/selftest/${test.serviceType}/${test.serviceName}/${test.name}/${test.status}/1.0";
- }
- 'nmwg:data'(id:"data_${test.name}",
metadataIdRef:"${test.name}") {
- 'nmwg:datum' test.message
- }
- }
- }
- }
- }
-
- static Reader toEchoResponse(requestId) {
- createResponse(requestId) {
- 'nmwg:metadata'(id:"result-code") {
- 'nmwg:eventType' "echo/success"
- }
- 'nmwg:data'(id:"result-code-description",
metadataIdRef:"result-code") {
-
'nmwgr:datum'('xmlns:nmwgr':"http://ggf.org/ns/nmwg/result/2.0/";,
- "This is the success echo response
from the service.")
- }
- }
- }
-
- private static Reader createResponse(requestId, body) {
- final def writer = new StringWriter()
- final MarkupBuilder xml = new MarkupBuilder(writer)
- xml.mkp.xmlDeclaration(version:"1.0", encoding:"UTF-8")
-
xml.'nmwg:message'('xmlns:nmwg':"http://ggf.org/ns/nmwg/base/2.0/";,
- id:"Resp_${requestId}", messageIdRef:"${requestId}",
type:"EchoResponse", body)
-
- new StringReader(writer.toString())
- }
+ private static Reader createRequest(id, eventType, version) {
+ def writer = new StringWriter()
+ MarkupBuilder xml = new MarkupBuilder(writer)
+ xml.mkp.xmlDeclaration(version:"1.0", encoding:"UTF-8")
+ xml.'nmwg:message'('xmlns:nmwg':'http://ggf.org/ns/nmwg/base/2.0/',
id:id, type:"EchoRequest") {
+ 'nmwg:metadata'(id:"meta") {
+ 'nmwg:eventType'
"http://schemas.perfsonar.net/tools/admin/${eventType}/${version}";
+ }
+ 'nmwg:data'(id:"data", metadataIdRef:"meta")
+ }

- public static Reader toMetadataKeyResponse(String requestId,
Router... routers) {
- def idx = 0;
- final def writer = new StringWriter()
- final MarkupBuilder xml = new MarkupBuilder(writer)
- xml.mkp.xmlDeclaration(version:"1.0", encoding:"UTF-8")
-
xml.'nmwg:message'('xmlns:nmwg':"http://ggf.org/ns/nmwg/base/2.0/";,
- id:"${requestId}_resp", messageIdRef:"${requestId}",
type:"MetadataKeyResponse") {
-
- routers.each { router ->
- 'nmwg:metadata'(id:"metadata${idx}") {
- 'nmwg:subject'(id:"subject${idx}",
router.name)
-
'nmwg:parameters'(id:"metaParams${idx}") {
- 'nmwg:parameter'(name:"url",
value:router.address.hostAddress)
- }
- }
- 'nmwg:metadata'(id:"resultCodeMeta_${idx}") {
-
'nmwg:subject'(id:"resultCodeSubj_${idx}", metadataIdRef:"metadata${idx}")
-
'nmwg:eventType'("success.mp.sshtelnet")
- }
- 'nmwg:data'(id:"resultCodeMeta_${idx}",
metadataIdRef:"resultCodeMeta_${idx}") {
-
'nmwgr:datum'('xmlns:nmwgr':"http://ggf.org/ns/nmwg/result/2.0/";,
"Successfully executed MetaDataKeyRequest")
- }
- idx++
- }
-
- idx = 0
- routers.each { router ->
- 'nmwg:data'(id:"data${idx}",
metadataIdRef:"metadata${idx}") {
- router.commands.each { command ->
-
'nmwgr:datum'('xmlns:nmwgr':"http://ggf.org/ns/nmwg/result/2.0/";) {
-
'nmwg:parameters'(id:"params${idx}") {

-
'nmwg:parameter'(name:"command", value:command.name)
-
'nmwg:parameter'(name:"description", value:command.description)
-
'nmwg:parameter'(name:"syntax", value:command.syntax)
- }
-
'nmwg:eventType'(command.eventType)
- }
- }
- }
- idx++
- }
- }
-
- new StringReader(writer.toString())
- }
+ writer.write("\n");
+ new StringReader(writer.toString())
+ }
+
+ static Reader toEchoRequest(String id) {
+ createRequest(id, "echo", "2.0")
+ }
+
+ static Reader toSelfTestRequest(String id) {
+ createRequest(id, "selftest", "1.0")
+ }

- public static Reader toSetupDataResponse(String requestId, Command...
commands) {
- def idx = 0;
- final def writer = new StringWriter()
- final MarkupBuilder xml = new MarkupBuilder(writer)
- xml.mkp.xmlDeclaration(version:"1.0", encoding:"UTF-8")
-
xml.'nmwg:message'('xmlns:nmwg':"http://ggf.org/ns/nmwg/base/2.0/";,
id:"${requestId}_resp", messageIdRef:"${requestId}",
type:"SetupDataResponse") {
- commands.each { command ->
- 'nmwg:metadata'(id:"meta${idx}") {
- 'nmwg:subject'(id:"subject${idx}") {
-
'nmwgtopo:endPoint'('xmlns:nmwgtopo':"http://ggf.org/ns/nmwg/topology/2.0/";,
type:"hostname", command.routerName)
- }
- 'nmwg:parameters'(id:"params${idx}")
- 'nmwg:eventType'(command.eventType)
- }
-
- 'nmwg:data'(id:"data${idx}",
metadataIdRef:"meta${idx}") {
- 'nmwg:datum'(command.result)
- }
-
'nmwg:metadata'(id:"resultCodeMeta_meta${idx}") {
-
'nmwg:subject'(id:"resultCodeSubj_meta${idx}", metadataIdRef:"meta${idx}")
- 'nmwg:eventType'("success.mp.sshtelnet")
- }
- 'nmwg:data'(id:"resultCodeData_meta${idx}",
metadataIdRef:"resultCodeMeta_meta${idx}") {
-
'nmwgr:datum'('xmlns:nmwgr':"http://ggf.org/ns/nmwg/result/2.0/";,
"Successfully executed request")
- }
-
- idx++
- }
- }
- new StringReader(writer.toString())
- }
+ static Reader toSelfTestRequest(String id, String testName) {
+ createRequest(id, "selftest", "1.0/${testName}")
+ }
+
+ static Reader toMetadataKeyRequest(String id) {
+ def writer = new StringWriter()
+ MarkupBuilder xml = new MarkupBuilder(writer)
+ xml.'nmwg:message'('xmlns:nmwg':'http://ggf.org/ns/nmwg/base/2.0/',
id:id, type:"MetadataKeyRequest") {
+ 'nmwg:metadata'(id:"meta") {
+ 'nmwg:subject'(id:"server") {
+ 'nmwg:parameters'(id:"params") {
+ 'nmwg:parameter'(name:"param", "SES")
+ }
+ }
+ }
+ 'nmwg:data'(id:"data", metadataIdRef:"meta")
+ }
+
+ new StringReader(writer.toString())
+ }
+
+ static Reader toSetupDataRequest(String id, Command... commands) {
+ def idx = 0;
+ final def writer = new StringWriter()
+ final MarkupBuilder xml = new MarkupBuilder(writer)
+ xml.mkp.xmlDeclaration(version:"1.0", encoding:"UTF-8")
+ xml.'nmwg:message'('xmlns:nmwg':'http://ggf.org/ns/nmwg/base/2.0/',
'xmlns:nmwgtopo':'http://ggf.org/ns/nmwg/topology/2.0/', id:id,
type:"SetupDataRequest") {
+ commands.each { command ->
+ 'nmwg:metadata'(id:"meta${idx}") {
+ 'nmwg:subject'(id:"subject${idx}") {
+ 'nmwgtopo:endPoint'(type:"hostname", command.routerName)
+ }
+ 'nmwg:parameters'(id:"params${idx}") {
+ 'nmwg:parameter'(name:"command", value:command.name)
+ 'nmwg:parameter'(name:"description",
value:command.description)
+ 'nmwg:parameter'(name:"syntax", value:command.syntax)
+ }
+ 'nmwg:eventType' command.eventType
+ }
+ 'nmwg:data'(id:"data${idx}", metadataIdRef:"meta${idx}")
+ }
+ }
+ new StringReader(writer.toString())
+ }
+
+ static Reader toSelfTestResponse(requestId, SelfTestResult... tests) {
+ createResponse(requestId) {
+ 'nmwg:metadata'(id:"meta") {
+ 'nmwg:eventType'
"http://schemas.perfsonar.net/tools/admin/selftest/1.0";
+ }
+ 'nmwg:data'(id:"data", metadataIdRef:"meta") {
+ tests.each { test ->
+ 'nmwg:metadata'(id:"${test.name}") {
+ 'nmwg:eventType'
"http://schemas.perfsonar.net/tools/admin/selftest/${test.serviceType}/${test.serviceName}/${test.name}/${test.status}/1.0";
+ }
+ 'nmwg:data'(id:"data_${test.name}",
metadataIdRef:"${test.name}") {
+ 'nmwg:datum' test.message
+ }
+ }
+ }
+ }
+ }
+
+ static Reader toEchoResponse(requestId) {
+ createResponse(requestId) {
+ 'nmwg:metadata'(id:"result-code") {
+ 'nmwg:eventType' "echo/success"
+ }
+ 'nmwg:data'(id:"result-code-description",
metadataIdRef:"result-code") {
+
'nmwgr:datum'('xmlns:nmwgr':"http://ggf.org/ns/nmwg/result/2.0/";,
+ "This is the success echo response from the
service.")
+ }
+ }
+ }

- public static Reader toLSResponse(String id) {
- def writer = new StringWriter()
- MarkupBuilder xml = new MarkupBuilder(writer)
-
xml.'nmwg:message'('xmlns:nmwg':'http://ggf.org/ns/nmwg/base/2.0/',
id:"${id}_resp", messageIdRef:id, type:"LSRegisterResponse") {
- 'nmwg:metadata'(id:"meta") {
- 'nmwg:eventType' "success"
- 'nmwg:key' "${id}"
- }
- 'nmwg:data'(id:"data", metadataIdRef:"meta")
- }
-
- new StringReader(writer.toString())
- }
+ private static Reader createResponse(requestId, body) {
+ final def writer = new StringWriter()
+ final MarkupBuilder xml = new MarkupBuilder(writer)
+ xml.mkp.xmlDeclaration(version:"1.0", encoding:"UTF-8")
+ xml.'nmwg:message'('xmlns:nmwg':"http://ggf.org/ns/nmwg/base/2.0/";,
+ id:"Resp_${requestId}", messageIdRef:"${requestId}",
type:"EchoResponse", body)
+
+ new StringReader(writer.toString())
+ }
+
+ public static Reader toMetadataKeyResponse(String requestId, Router...
routers) {
+ def idx = 0;
+ final def writer = new StringWriter()
+ final MarkupBuilder xml = new MarkupBuilder(writer)
+ xml.mkp.xmlDeclaration(version:"1.0", encoding:"UTF-8")
+ xml.'nmwg:message'('xmlns:nmwg':"http://ggf.org/ns/nmwg/base/2.0/";,
+ id:"${requestId}_resp", messageIdRef:"${requestId}",
type:"MetadataKeyResponse") {
+
+ routers.each { router ->
+ 'nmwg:metadata'(id:"metadata${idx}") {
+ 'nmwg:subject'(id:"subject${idx}", router.name)
+ 'nmwg:parameters'(id:"metaParams${idx}") {
+ 'nmwg:parameter'(name:"url",
value:router.address.hostAddress)
+ }
+ }
+ 'nmwg:metadata'(id:"resultCodeMeta_${idx}") {
+ 'nmwg:subject'(id:"resultCodeSubj_${idx}",
metadataIdRef:"metadata${idx}")
+ 'nmwg:eventType'("success.mp.sshtelnet")
+ }
+ 'nmwg:data'(id:"resultCodeMeta_${idx}",
metadataIdRef:"resultCodeMeta_${idx}") {
+
'nmwgr:datum'('xmlns:nmwgr':"http://ggf.org/ns/nmwg/result/2.0/";,
"Successfully executed MetaDataKeyRequest")
+ }
+ idx++
+ }
+
+ idx = 0
+ routers.each { router ->
+ 'nmwg:data'(id:"data${idx}",
metadataIdRef:"metadata${idx}") {
+ router.commands.each { command ->
+
'nmwgr:datum'('xmlns:nmwgr':"http://ggf.org/ns/nmwg/result/2.0/";) {
+ 'nmwg:parameters'(id:"params${idx}") {
+ 'nmwg:parameter'(name:"command",
value:command.name)
+ 'nmwg:parameter'(name:"description",
value:command.description)
+ 'nmwg:parameter'(name:"syntax",
value:command.syntax)
+ }
+ 'nmwg:eventType'(command.eventType)
+ }
+ }
+ }
+ idx++
+ }
+ }
+
+ new StringReader(writer.toString())
+ }
+
+ public static Reader toSetupDataResponse(String requestId, Command...
commands) {
+ def idx = 0;
+ final def writer = new StringWriter()
+ final MarkupBuilder xml = new MarkupBuilder(writer)
+ xml.mkp.xmlDeclaration(version:"1.0", encoding:"UTF-8")
+ xml.'nmwg:message'('xmlns:nmwg':"http://ggf.org/ns/nmwg/base/2.0/";,
id:"${requestId}_resp", messageIdRef:"${requestId}",
type:"SetupDataResponse") {
+ commands.each { command ->
+ 'nmwg:metadata'(id:"meta${idx}") {
+ 'nmwg:subject'(id:"subject${idx}") {
+
'nmwgtopo:endPoint'('xmlns:nmwgtopo':"http://ggf.org/ns/nmwg/topology/2.0/";,
type:"hostname", command.routerName)
+ }
+ 'nmwg:parameters'(id:"params${idx}")
+ 'nmwg:eventType'(command.eventType)
+ }
+
+ 'nmwg:data'(id:"data${idx}", metadataIdRef:"meta${idx}") {
+ 'nmwg:datum'(command.result)
+ }
+ 'nmwg:metadata'(id:"resultCodeMeta_meta${idx}") {
+ 'nmwg:subject'(id:"resultCodeSubj_meta${idx}",
metadataIdRef:"meta${idx}")
+ 'nmwg:eventType'("success.mp.sshtelnet")
+ }
+ 'nmwg:data'(id:"resultCodeData_meta${idx}",
metadataIdRef:"resultCodeMeta_meta${idx}") {
+
'nmwgr:datum'('xmlns:nmwgr':"http://ggf.org/ns/nmwg/result/2.0/";,
"Successfully executed request")
+ }
+
+ idx++
+ }
+ }
+ new StringReader(writer.toString())
+ }
+
+ public static Reader toLSResponse(String id) {
+ def writer = new StringWriter()
+ MarkupBuilder xml = new MarkupBuilder(writer)
+ xml.'nmwg:message'('xmlns:nmwg':'http://ggf.org/ns/nmwg/base/2.0/',
id:"${id}_resp", messageIdRef:id, type:"LSRegisterResponse") {
+ 'nmwg:metadata'(id:"meta") {
+ 'nmwg:eventType' "success"
+ 'nmwg:key' "${id}"
+ }
+ 'nmwg:data'(id:"data", metadataIdRef:"meta")
+ }
+
+ new StringReader(writer.toString())
+ }
}

Modified:
trunk/perfsonar-base/messaging/src/test/java/net/geant/perfsonar/messaging/InvalidXPathsTest.java
===================================================================
---
trunk/perfsonar-base/messaging/src/test/java/net/geant/perfsonar/messaging/InvalidXPathsTest.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/messaging/src/test/java/net/geant/perfsonar/messaging/InvalidXPathsTest.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -23,70 +23,68 @@
import org.xml.sax.InputSource;

public class InvalidXPathsTest {
- private static final String REQUEST_ID = "1";
+ private static final String REQUEST_ID = "1";

- private Reader reader;
- private XPathDeserializer deserializer;
+ private Reader reader;
+ private XPathDeserializer deserializer;

- @Before
- public void givenMessageAndDeserializationConfigured() throws
Exception {
- reader = NMWG.toMetadataKeyResponse(REQUEST_ID, new
Router("metadata0",
- "test1",
InetAddress.getAllByName("192.168.1.1")[0],
- Command.PING_IPV6));
+ @Before
+ public void givenMessageAndDeserializationConfigured() throws Exception {
+ reader = NMWG.toMetadataKeyResponse(REQUEST_ID,
+ new Router("metadata0", "test1",
InetAddress.getAllByName("192.168.1.1")[0], Command.PING_IPV6));

- declarePrefix("nmwg", "http://ggf.org/ns/nmwg/base/2.0/";);
- deserializer = new XPathDeserializer();
- }
+ declarePrefix("nmwg", "http://ggf.org/ns/nmwg/base/2.0/";);
+ deserializer = new XPathDeserializer();
+ }

- @After
- public void clearConfiguration() {
- XPathDeserializer.clearConfiguration();
- }
+ @After
+ public void clearConfiguration() {
+ XPathDeserializer.clearConfiguration();
+ }

- @Test
- public void shouldThrowExceptionWhenInvalidXPathSyntax() throws
Exception {
- whenXPath("invalid
xpath1").then(Router.class).setId(any(String.class));
- whenXPath("invalid xpath2").then(Router.class).setAddress(
- any(String.class));
+ @Test
+ public void shouldThrowExceptionWhenInvalidXPathSyntax() throws
Exception {
+ whenXPath("invalid
xpath1").then(Router.class).setId(any(String.class));
+ whenXPath("invalid
xpath2").then(Router.class).setAddress(any(String.class));

- try {
- deserializer.deserialize(new InputSource(reader));
- fail("DeserializationException was not thrown");
- } catch (DeserializationException ex) {
- final Iterator<Throwable> iter = ex.iterator();
- assertEquals(XPathException.class,
iter.next().getClass());
- assertEquals(XPathException.class,
iter.next().getClass());
- assertFalse(iter.hasNext());
- }
- }
+ try {
+ deserializer.deserialize(new InputSource(reader));
+ fail("DeserializationException was not thrown");
+ } catch (DeserializationException ex) {
+ final Iterator<Throwable> iter = ex.iterator();
+ assertEquals(XPathException.class, iter.next().getClass());
+ assertEquals(XPathException.class, iter.next().getClass());
+ assertFalse(iter.hasNext());
+ }
+ }

- @Test
- public void shouldThrowExceptionWhenXPathReturnsNull() throws
Exception {
-
whenXPath("nmwg:message/nmwg:metadata[nmwg:parameters]/nmwg:subject")
-
.then(Router.class).setName(any(String.class));
+ @Test
+ public void shouldThrowExceptionWhenXPathReturnsNull() throws Exception {
+
whenXPath("nmwg:message/nmwg:metadata[nmwg:parameters]/nmwg:subject").then(Router.class).setName(
+ any(String.class));

- try {
- deserializer.deserialize(new InputSource(reader));
- fail("DeserializationException was not thrown");
- } catch (DeserializationException ex) {
- final Iterator<Throwable> iter = ex.iterator();
- assertEquals(XPathException.class,
iter.next().getClass());
- assertFalse(iter.hasNext());
- }
- }
-
- @Test
- public void shouldThrowExceptionWhenUndeclaredPrefix() throws
Exception {
-
whenXPath("nmwg:message/nmwg:data/nmwgr:datum/nmwg:eventType/text()")
-
.then(Command.class).setEventType(any(String.class));
+ try {
+ deserializer.deserialize(new InputSource(reader));
+ fail("DeserializationException was not thrown");
+ } catch (DeserializationException ex) {
+ final Iterator<Throwable> iter = ex.iterator();
+ assertEquals(XPathException.class, iter.next().getClass());
+ assertFalse(iter.hasNext());
+ }
+ }

- try {
- deserializer.deserialize(new InputSource(reader));
- fail("DeserializationException was not thrown");
- } catch (DeserializationException ex) {
- final Iterator<Throwable> iter = ex.iterator();
- assertEquals(XPathException.class,
iter.next().getClass());
- assertFalse(iter.hasNext());
- }
- }
+ @Test
+ public void shouldThrowExceptionWhenUndeclaredPrefix() throws Exception {
+
whenXPath("nmwg:message/nmwg:data/nmwgr:datum/nmwg:eventType/text()").then(Command.class).setEventType(
+ any(String.class));
+
+ try {
+ deserializer.deserialize(new InputSource(reader));
+ fail("DeserializationException was not thrown");
+ } catch (DeserializationException ex) {
+ final Iterator<Throwable> iter = ex.iterator();
+ assertEquals(XPathException.class, iter.next().getClass());
+ assertFalse(iter.hasNext());
+ }
+ }
}

Modified:
trunk/perfsonar-base/messaging/src/test/java/net/geant/perfsonar/messaging/MethodOnObjectTest.java
===================================================================
---
trunk/perfsonar-base/messaging/src/test/java/net/geant/perfsonar/messaging/MethodOnObjectTest.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/messaging/src/test/java/net/geant/perfsonar/messaging/MethodOnObjectTest.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -1,6 +1,6 @@
package net.geant.perfsonar.messaging;

-import static org.junit.Assert.*;
+import static org.junit.Assert.assertTrue;

import java.util.Hashtable;
import java.util.List;
@@ -13,28 +13,28 @@
import org.junit.Test;

public class MethodOnObjectTest {
- final Map<Class<?>, List<Object>> instances = new Hashtable<Class<?>,
List<Object>>();
- final Command expected = new Command();
- private Method method;
-
- @Before
- public void givenMethodWithObject() throws Exception {
- expected.setName("object");
- method = new Method(Command.class.getMethod("setName",
String.class), null, expected);
- }
+ private final Map<Class<?>, List<Object>> instances = new
Hashtable<Class<?>, List<Object>>();
+ private final Command expected = new Command();
+ private Method method;

- @After
- public void tearDown() throws Exception {
- method = null;
- }
+ @Before
+ public void givenMethodWithObject() throws Exception {
+ expected.setName("object");
+ method = new Method(Command.class.getMethod("setName",
String.class), null, expected);
+ }

- @Test
- public void shouldReturnObject() throws Exception {
- assertTrue(expected == method.getInstance(instances));
- }
-
- @Test
- public void shouldBeEmpty() {
- assertTrue(instances.isEmpty());
- }
+ @After
+ public void tearDown() throws Exception {
+ method = null;
+ }
+
+ @Test
+ public void shouldReturnObject() throws Exception {
+ assertTrue(expected == method.getInstance(instances));
+ }
+
+ @Test
+ public void shouldBeEmpty() {
+ assertTrue(instances.isEmpty());
+ }
}

Modified:
trunk/perfsonar-base/messaging/src/test/java/net/geant/perfsonar/messaging/MethodTest.java
===================================================================
---
trunk/perfsonar-base/messaging/src/test/java/net/geant/perfsonar/messaging/MethodTest.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/messaging/src/test/java/net/geant/perfsonar/messaging/MethodTest.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -14,86 +14,85 @@
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
-
+
public class MethodTest {
- private Method eventTypeMethod;
- private Method commandNameMethod;
- private Method currentRouterMethod;
- private Method routerIdMethod;
- private Method routerNameMethod;
-
- private final Map<Class<?>, List<Object>> instances = new
Hashtable<Class<?>, List<Object>>();
- private final Map<Class<?>, List<Object>> expected = new
Hashtable<Class<?>, List<Object>>();
+ private Method eventTypeMethod;
+ private Method commandNameMethod;
+ private Method currentRouterMethod;
+ private Method routerIdMethod;
+ private Method routerNameMethod;

- @Before
- public void setUp() throws Throwable {
- new Command();
- eventTypeMethod = createCommandMethod("setEventType",
String.class);
- commandNameMethod = createCommandMethod("setName",
String.class);
- currentRouterMethod = new
Method(RouterReference.class.getMethod("setCurrentRouter", Router.class),
Router.class.getMethod("getId"));
- routerIdMethod = new Method(Router.class.getMethod("setId",
String.class), Router.class.getMethod("getId"));
- routerNameMethod = new
Method(Router.class.getMethod("setName", String.class),
Router.class.getMethod("getId"));
- //instances.put((Class)Router.class,
(List)Arrays.asList(router));
- whenExecutingMethods(instances);
- }
+ private final Map<Class<?>, List<Object>> instances = new
Hashtable<Class<?>, List<Object>>();
+ private final Map<Class<?>, List<Object>> expected = new
Hashtable<Class<?>, List<Object>>();

- private Method createCommandMethod(String methodName, Class<?>...
params) throws NoSuchMethodException {
- return new Method(Command.class.getMethod(methodName,
params), Command.class.getMethod("getId"));
- }
+ @Before
+ public void setUp() throws Throwable {
+ new Command();
+ eventTypeMethod = createCommandMethod("setEventType", String.class);
+ commandNameMethod = createCommandMethod("setName", String.class);
+ currentRouterMethod = new
Method(RouterReference.class.getMethod("setCurrentRouter", Router.class),
+ Router.class.getMethod("getId"));
+ routerIdMethod = new Method(Router.class.getMethod("setId",
String.class), Router.class.getMethod("getId"));
+ routerNameMethod = new Method(Router.class.getMethod("setName",
String.class), Router.class.getMethod("getId"));
+ // instances.put((Class)Router.class, (List)Arrays.asList(router));
+ whenExecutingMethods(instances);
+ }

- @After
- public void tearDown() throws Exception {
- instances.clear();
- expected.clear();
- new RouterReference().setCurrentRouter(null);
- }
+ private Method createCommandMethod(String methodName, Class<?>...
params) throws NoSuchMethodException {
+ return new Method(Command.class.getMethod(methodName, params),
Command.class.getMethod("getId"));
+ }

- @SuppressWarnings({ "unchecked", "rawtypes" })
- @Test
- public void shouldReturnTwoCommandsAndRouter() throws Throwable {
- final Router router = createRouter();
- expected.put((Class<?>) Router.class, (List)
Arrays.asList(createRouter()));
- expected.put((Class<?>) Command.class, (List)
router.getCommands());
- expected.put((Class<?>) RouterReference.class,
instances.get(RouterReference.class));
-
- assertEquals(expected, instances);
- }
-
- @Test
- public void shouldSetCurrentRouter() {
- assertEquals(createRouter(),
-
- RouterReference.getCurrentRouter());
- }
+ @After
+ public void tearDown() throws Exception {
+ instances.clear();
+ expected.clear();
+ new RouterReference().setCurrentRouter(null);
+ }

- private Router createRouter() {
- return new Router("router2", "router", null,
- new Command("test1", null, null, "testing1"),
- new Command("test2", null, null, "testing2"));
- }
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ @Test
+ public void shouldReturnTwoCommandsAndRouter() throws Throwable {
+ final Router router = createRouter();
+ expected.put((Class<?>) Router.class, (List)
Arrays.asList(createRouter()));
+ expected.put((Class<?>) Command.class, (List) router.getCommands());
+ expected.put((Class<?>) RouterReference.class,
instances.get(RouterReference.class));

- private void whenExecutingMethods(
- final Map<Class<?>, List<Object>> instances) throws
Throwable {
+ assertEquals(expected, instances);
+ }

- //router.setId("router2");
- routerIdMethod.execute("router2", instances);
-
- //router.setName("router");
- routerNameMethod.execute("router", instances);
-
- //RouterReference.setCurrentRouter(getReference("router2"));
- currentRouterMethod.execute("router2", instances);
-
- //command1.setEventType("testing1");
- eventTypeMethod.execute("testing1", instances);
-
- //command1.setName("test1");
- commandNameMethod.execute("test1", instances);
-
- //command2.setName("test2");
- commandNameMethod.execute("test2", instances);
-
- //command2.setEventType("testing2");
- eventTypeMethod.execute("testing2", instances);
- }
+ @Test
+ public void shouldSetCurrentRouter() {
+ assertEquals(createRouter(),
+
+ RouterReference.getCurrentRouter());
+ }
+
+ private Router createRouter() {
+ return new Router("router2", "router", null, new Command("test1",
null, null, "testing1"), new Command("test2",
+ null, null, "testing2"));
+ }
+
+ private void whenExecutingMethods(final Map<Class<?>, List<Object>>
instances) throws Throwable {
+
+ // router.setId("router2");
+ routerIdMethod.execute("router2", instances);
+
+ // router.setName("router");
+ routerNameMethod.execute("router", instances);
+
+ // RouterReference.setCurrentRouter(getReference("router2"));
+ currentRouterMethod.execute("router2", instances);
+
+ // command1.setEventType("testing1");
+ eventTypeMethod.execute("testing1", instances);
+
+ // command1.setName("test1");
+ commandNameMethod.execute("test1", instances);
+
+ // command2.setName("test2");
+ commandNameMethod.execute("test2", instances);
+
+ // command2.setEventType("testing2");
+ eventTypeMethod.execute("testing2", instances);
+ }
}

Modified:
trunk/perfsonar-base/messaging/src/test/java/net/geant/perfsonar/messaging/StaticMethodTest.java
===================================================================
---
trunk/perfsonar-base/messaging/src/test/java/net/geant/perfsonar/messaging/StaticMethodTest.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/messaging/src/test/java/net/geant/perfsonar/messaging/StaticMethodTest.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -12,30 +12,31 @@
import org.junit.Test;

public class StaticMethodTest {
-
- final Map<Class<?>, List<Object>> instances = new Hashtable<Class<?>,
List<Object>>();
- private Method method;
-
- public static void staticMethod() { }

- @Before
- public void givenStaticMethod() throws Exception {
- method = new
Method(StaticMethodTest.class.getMethod("staticMethod"));
- }
+ private final Map<Class<?>, List<Object>> instances = new
Hashtable<Class<?>, List<Object>>();
+ private Method method;

- @After
- public void tearDown() throws Exception {
- method = null;
- }
+ public static void staticMethod() {
+ }

- @Test(expected=IllegalStateException.class)
- public void shouldThrowException() throws Exception {
- assertNull(method.getInstance(instances));
- }
-
- @Test
- public void shouldBeEmpty() {
- assertTrue(instances.isEmpty());
- }
+ @Before
+ public void givenStaticMethod() throws Exception {
+ method = new
Method(StaticMethodTest.class.getMethod("staticMethod"));
+ }

+ @After
+ public void tearDown() throws Exception {
+ method = null;
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void shouldThrowException() throws Exception {
+ assertNull(method.getInstance(instances));
+ }
+
+ @Test
+ public void shouldBeEmpty() {
+ assertTrue(instances.isEmpty());
+ }
+
}

Modified:
trunk/perfsonar-base/messaging/src/test/java/net/geant/perfsonar/messaging/XMLDogTest.java
===================================================================
---
trunk/perfsonar-base/messaging/src/test/java/net/geant/perfsonar/messaging/XMLDogTest.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/messaging/src/test/java/net/geant/perfsonar/messaging/XMLDogTest.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -17,69 +17,75 @@
import org.xml.sax.InputSource;

public class XMLDogTest {
- private static final String REQUEST_ID = "request1";
- private DefaultNamespaceContext nsContext;
- private XMLDog dog;
- private String xpathResult;
-
- @Before
- public void givenXMLDog() {
- nsContext = new DefaultNamespaceContext();
- nsContext.declarePrefix("nmwg",
"http://ggf.org/ns/nmwg/base/2.0/";);
- dog = new XMLDog(nsContext);
- }
+ private static final String REQUEST_ID = "request1";
+ private DefaultNamespaceContext nsContext;
+ private XMLDog dog;
+ private String xpathResult;

- @Test
- public void shouldEvaluatePrimitiveTypesFromStream() throws Exception
{
- final Event event = createEvent("string(nmwg:message/@id)",
new InstantEvaluationListener() {
- @Override
- public void onNodeHit(Expression expression, NodeItem
nodeItem) { fail(); }
+ @Before
+ public void givenXMLDog() {
+ nsContext = new DefaultNamespaceContext();
+ nsContext.declarePrefix("nmwg", "http://ggf.org/ns/nmwg/base/2.0/";);
+ dog = new XMLDog(nsContext);
+ }

- @Override
- public void finishedNodeSet(Expression expression) {
fail(); }
+ @Test
+ public void shouldEvaluatePrimitiveTypesFromStream() throws Exception {
+ final Event event = createEvent("string(nmwg:message/@id)", new
InstantEvaluationListener() {
+ @Override
+ public void onNodeHit(Expression expression, NodeItem nodeItem) {
+ fail();
+ }

- @Override
- public void onResult(Expression expression, Object
result) {
- xpathResult = result.toString();
- }
- });
-
- dog.sniff(event, new
InputSource(NMWG.toEchoRequest(REQUEST_ID)), false/*useSTAX*/);
- Thread.sleep(1000);
- assertEquals(REQUEST_ID, xpathResult);
- }
-
- @Test
- public void shouldEvaluateNodesFromStream() throws Exception {
- final Event event = createEvent("nmwg:message/@id", new
InstantEvaluationListener() {
- private String tempResult;
- @Override
- public void onNodeHit(Expression expression, NodeItem
nodeItem) {
- tempResult = nodeItem.value;
- }
+ @Override
+ public void finishedNodeSet(Expression expression) {
+ fail();
+ }

- @Override
- public void finishedNodeSet(Expression expression) {
- xpathResult = tempResult;
- }
+ @Override
+ public void onResult(Expression expression, Object result) {
+ xpathResult = result.toString();
+ }
+ });

- @Override
- public void onResult(Expression expression, Object
result) {
- fail();
- }
- });
-
- dog.sniff(event, new
InputSource(NMWG.toEchoRequest(REQUEST_ID)), false/*useSTAX*/);
- Thread.sleep(1000);
- assertEquals(REQUEST_ID, xpathResult);
- }
+ dog.sniff(event, new InputSource(NMWG.toEchoRequest(REQUEST_ID)),
false/* useSTAX */);
+ Thread.sleep(1000);
+ assertEquals(REQUEST_ID, xpathResult);
+ }

- private Event createEvent(String xpath, InstantEvaluationListener
listener) throws SAXPathException {
- dog.addXPath(xpath);
- final Event event = dog.createEvent(); // must be after all
expressions are added.
- event.setXMLBuilder(new DOMBuilder());
- event.setListener(listener);
- return event;
- }
+ @Test
+ public void shouldEvaluateNodesFromStream() throws Exception {
+ final Event event = createEvent("nmwg:message/@id", new
InstantEvaluationListener() {
+ private String tempResult;

+ @Override
+ public void onNodeHit(Expression expression, NodeItem nodeItem) {
+ tempResult = nodeItem.value;
+ }
+
+ @Override
+ public void finishedNodeSet(Expression expression) {
+ xpathResult = tempResult;
+ }
+
+ @Override
+ public void onResult(Expression expression, Object result) {
+ fail();
+ }
+ });
+
+ dog.sniff(event, new InputSource(NMWG.toEchoRequest(REQUEST_ID)),
false/* useSTAX */);
+ Thread.sleep(1000);
+ assertEquals(REQUEST_ID, xpathResult);
+ }
+
+ private Event createEvent(String xpath, InstantEvaluationListener
listener) throws SAXPathException {
+ dog.addXPath(xpath);
+ final Event event = dog.createEvent(); // must be after all
expressions
+ // are added.
+ event.setXMLBuilder(new DOMBuilder());
+ event.setListener(listener);
+ return event;
+ }
+
}

Modified:
trunk/perfsonar-base/messaging/src/test/java/net/geant/perfsonar/messaging/XPathDeserializerTest.java
===================================================================
---
trunk/perfsonar-base/messaging/src/test/java/net/geant/perfsonar/messaging/XPathDeserializerTest.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/messaging/src/test/java/net/geant/perfsonar/messaging/XPathDeserializerTest.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -23,75 +23,70 @@
import org.xml.sax.InputSource;

public class XPathDeserializerTest {
- private static final String REQUEST_ID = "1";
+ private static final String REQUEST_ID = "1";

- private Router[] routers;
- private Reader reader;
- private XPathDeserializer deserializer;
+ private Router[] routers;
+ private Reader reader;
+ private XPathDeserializer deserializer;

- @Before
- public void givenMessageAndDeserializationConfigured() throws
Exception {
+ @Before
+ public void givenMessageAndDeserializationConfigured() throws Exception {

- routers = new Router[] {
- new Router("metadata0", "test1",
-
InetAddress.getAllByName("192.168.1.1")[0],
- Command.PING_IPV6),
- new Router("metadata1", "test2",
-
InetAddress.getAllByName("192.168.1.2")[0],
- Command.SHOW_ENVIRONMENT) };
+ routers = new Router[] {
+ new Router("metadata0", "test1",
InetAddress.getAllByName("192.168.1.1")[0], Command.PING_IPV6),
+ new Router("metadata1", "test2",
InetAddress.getAllByName("192.168.1.2")[0], Command.SHOW_ENVIRONMENT) };

- reader = NMWG.toMetadataKeyResponse(REQUEST_ID, routers);
+ reader = NMWG.toMetadataKeyResponse(REQUEST_ID, routers);

- declarePrefix("nmwg", "http://ggf.org/ns/nmwg/base/2.0/";);
- declarePrefix("nmwgr", "http://ggf.org/ns/nmwg/result/2.0/";);
+ declarePrefix("nmwg", "http://ggf.org/ns/nmwg/base/2.0/";);
+ declarePrefix("nmwgr", "http://ggf.org/ns/nmwg/result/2.0/";);

- whenXPath("nmwg:message/nmwg:metadata[nmwg:parameters]/@id")
- .then(Router.class).setId(any(String.class));
+
whenXPath("nmwg:message/nmwg:metadata[nmwg:parameters]/@id").then(Router.class).setId(any(String.class));

- whenXPath(
-
"nmwg:message/nmwg:metadata/nmwg:parameters/nmwg:parameter[@name='url']/@value")
-
.then(Router.class).setAddress(any(String.class));
-
- whenXPath(
-
"nmwg:message/nmwg:metadata[nmwg:parameters]/nmwg:subject/text()")
-
.then(Router.class).setName(any(String.class));
+
whenXPath("nmwg:message/nmwg:metadata/nmwg:parameters/nmwg:parameter[@name='url']/@value").then(Router.class)
+ .setAddress(any(String.class));

- whenXPath(
-
"nmwg:message/nmwg:data[starts-with(@metadataIdRef,
'metadata')]/@metadataIdRef")
- .then(RouterReference.class).setCurrentRouter(
- getReference(Router.class,
identifier(Router.class).getId()));
+
whenXPath("nmwg:message/nmwg:metadata[nmwg:parameters]/nmwg:subject/text()").then(Router.class).setName(
+ any(String.class));

- whenXPath(
-
"nmwg:message/nmwg:data[starts-with(@metadataIdRef,
'metadata')]/nmwgr:datum/nmwg:parameters/nmwg:parameter[@name='command']/@value")
-
.then(Command.class).setName(any(String.class));
+ whenXPath("nmwg:message/nmwg:data[starts-with(@metadataIdRef,
'metadata')]/@metadataIdRef").then(
+
RouterReference.class).setCurrentRouter(getReference(Router.class,
identifier(Router.class).getId()));

- whenXPath(
-
"nmwg:message/nmwg:data[starts-with(@metadataIdRef,
'metadata')]/nmwgr:datum/nmwg:parameters/nmwg:parameter[@name='description']/@value")
-
.then(Command.class).setDescription(any(String.class));
+ whenXPath(
+ "nmwg:message/nmwg:data[starts-with(@metadataIdRef,
'metadata')]"
+ +
"/nmwgr:datum/nmwg:parameters/nmwg:parameter[@name='command']/@value")
+ .then(Command.class).setName(any(String.class));

- whenXPath(
-
"nmwg:message/nmwg:data[starts-with(@metadataIdRef,
'metadata')]/nmwgr:datum/nmwg:parameters/nmwg:parameter[@name='syntax']/@value")
-
.then(Command.class).setSyntax(any(String.class));
-
- whenXPath(
-
"nmwg:message/nmwg:data/nmwgr:datum/nmwg:eventType/text()")
-
.then(Command.class).setEventType(any(String.class));
-
- deserializer = new XPathDeserializer();
- }
+ whenXPath(
+ "nmwg:message/nmwg:data[starts-with(@metadataIdRef,
'metadata')]"
+ +
"/nmwgr:datum/nmwg:parameters/nmwg:parameter[@name='description']/@value")
+ .then(Command.class).setDescription(any(String.class));

- @After
- public void clearConfiguration() {
- XPathDeserializer.clearConfiguration();
- }
+ whenXPath(
+ "nmwg:message/nmwg:data[starts-with(@metadataIdRef,
'metadata')]"
+ +
"/nmwgr:datum/nmwg:parameters/nmwg:parameter[@name='syntax']/@value")
+ .then(Command.class).setSyntax(any(String.class));

- @SuppressWarnings("unchecked")
- @Test
- public void shouldReturnRouters() throws Throwable {
- final List<Object> actual = (List<Object>)
deserializer.deserialize(new InputSource(reader));
-
- assertEquals(Arrays.asList(Command.PING_IPV6,
Command.SHOW_ENVIRONMENT), deserializer.getObjects(Command.class, actual));
- assertEquals(Arrays.asList(new Router("metadata0", "test1",
InetAddress.getAllByName("192.168.1.1")[0], Command.PING_IPV6),
- new Router("metadata1", "test2",
InetAddress.getAllByName("192.168.1.2")[0], Command.SHOW_ENVIRONMENT)),
deserializer.getObjects(Router.class, actual));
- }
+
whenXPath("nmwg:message/nmwg:data/nmwgr:datum/nmwg:eventType/text()").then(Command.class).setEventType(
+ any(String.class));
+
+ deserializer = new XPathDeserializer();
+ }
+
+ @After
+ public void clearConfiguration() {
+ XPathDeserializer.clearConfiguration();
+ }
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public void shouldReturnRouters() throws Throwable {
+ final List<Object> actual = (List<Object>)
deserializer.deserialize(new InputSource(reader));
+
+ assertEquals(Arrays.asList(Command.PING_IPV6,
Command.SHOW_ENVIRONMENT),
+ deserializer.getObjects(Command.class, actual));
+ assertEquals(Arrays.asList(new Router("metadata0", "test1",
InetAddress.getAllByName("192.168.1.1")[0],
+ Command.PING_IPV6), new Router("metadata1", "test2",
InetAddress.getAllByName("192.168.1.2")[0],
+ Command.SHOW_ENVIRONMENT)),
deserializer.getObjects(Router.class, actual));
+ }
}

Modified:
trunk/perfsonar-base/messaging/src/test/java/net/geant/perfsonar/mp/sshtelnet/Command.java
===================================================================
---
trunk/perfsonar-base/messaging/src/test/java/net/geant/perfsonar/mp/sshtelnet/Command.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/messaging/src/test/java/net/geant/perfsonar/mp/sshtelnet/Command.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -3,196 +3,225 @@
import java.io.IOException;

public class Command {
-
- public static final Command PING = new Command("ping", "ping an [ip
address]", "[ip address]", "IP_PING");

- public static Command SHOW_ENVIRONMENT = new Command("show
environment", "show chassis environment", "",
"http://schemas.perfsonar.net/tools/sshtelnet/STATUS_SHOW_ENVIRONMENT/1.0";);
-
- public static final Command TRACE_IPV4 = new Command("trace", "trace
the IPv4 path to [ip address]", "[ip address]",
"http://schemas.perfsonar.net/tools/sshtelnet/IP_TRACEROUTE/1.0";);
+ public static final Command PING = new Command("ping", "ping an [ip
address]", "[ip address]", "IP_PING");

- public static final Command TRACE_IPV6 = new Command("trace ipv6",
"trace the ipv6 path to [IPv6 address]", "[IPv6 address]",
"http://schemas.perfsonar.net/tools/sshtelnet/IPv6_TRACEROUTE/1.0";);
+ public static final Command SHOW_ENVIRONMENT = new Command("show
environment", "show chassis environment", "",
+
"http://schemas.perfsonar.net/tools/sshtelnet/STATUS_SHOW_ENVIRONMENT/1.0";);

- public static final Command SHOW_INTERFACES_FILTERS = new
Command("show interfaces filters", "display ip access lists", "",
"http://schemas.perfsonar.net/tools/sshtelnet/IP_ACCESS_LIST/1.0";);
-
- //public static final Command SHOW_IPV6_INTERFACES_FILTERS = new
Command("show interfaces filters", "display IPv6 access lists");
-
- public static final Command SHOW_IPV6_INTERFACES = new Command("show
interfaces", "display the interfaces which are configured for IPv6",
"[interface] extensive",
"http://schemas.perfsonar.net/tools/sshtelnet/IPv6_INTERFACES/1.0";);
+ public static final Command TRACE_IPV4 = new Command("trace", "trace the
IPv4 path to [ip address]",
+ "[ip address]",
"http://schemas.perfsonar.net/tools/sshtelnet/IP_TRACEROUTE/1.0";);

- public static final Command PING_IPV6 = new Command("ping inet6",
"ping an [IPv6 address]", "[IPv6 address]",
"http://schemas.perfsonar.net/tools/sshtelnet/IPv6_PING/1.0";);
+ public static final Command TRACE_IPV6 = new Command("trace ipv6",
"trace the ipv6 path to [IPv6 address]",
+ "[IPv6 address]",
"http://schemas.perfsonar.net/tools/sshtelnet/IPv6_TRACEROUTE/1.0";);

- public static final Command TRACEROUTER_IPV6 = new
Command("traceroute inet6", "trace the ipv6 path to [ipv6 address]", "[IPv6
address]",
"http://schemas.perfsonar.net/tools/sshtelnet/IPv6_TRACEROUTE/1.0";);
-
- private String routerName;
- private String name;
- private String description;
- private String syntax;
- private String eventType;
- private String id;
- private String result;
-
- private Router router;
-
- Command(Command cmd, String routerName) {
- setDescription(cmd.description);
- setEventType(cmd.eventType);
- setName(cmd.name);
- setSyntax(cmd.syntax);
- setRouterName(routerName);
- }
-
- public Command(String name, String description, String syntax, String
eventType) {
- this(RouterReference.getCurrentRouter(), name, description,
syntax, eventType);
- }
-
- private Command(Router router, String name, String description,
String syntax, String eventType) {
- this.name = name;
- this.description = description;
- this.syntax = syntax;
- this.eventType = eventType;
- setRouter(router);
- }
-
- public Command() {
- this(RouterReference.getCurrentRouter(), null, null, null,
null);
- }
-
- public String getEventType() {
- return eventType;
- }
-
- public void setEventType(String eventType) {
- this.eventType = eventType;
- }
-
- public String getName() {
- return name;
- }
+ public static final Command SHOW_IFACES_FILTERS = new Command("show
interfaces filters", "display ip access lists",
+ "",
"http://schemas.perfsonar.net/tools/sshtelnet/IP_ACCESS_LIST/1.0";);

- public String getDescription() {
- return description;
- }
+ // public static final Command SHOW_IPV6_INTERFACES_FILTERS = new
+ // Command("show interfaces filters", "display IPv6 access lists");

- public String getSyntax() {
- return syntax;
- }
-
- public void execute() throws IOException {
- //router.execute(this);
- result = "For address family: IPv4 Unicast@@@@@@For address
family: IPv6 Unicast@@@@@@For address family: VPNv4 Unicast@@@@@@For address
family: IPv4 Multicast@@@@@@For address family: IPv6 Multicast@@@@@@For
address family: NSAP Unicast@@@---END---";
- }
+ public static final Command SHOW_IPV6_IFACES = new Command("show
interfaces",
+ "display the interfaces which are configured for IPv6",
"[interface] extensive",
+
"http://schemas.perfsonar.net/tools/sshtelnet/IPv6_INTERFACES/1.0";);

- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result
- + ((description == null) ? 0 :
description.hashCode());
- result = prime * result
- + ((eventType == null) ? 0 :
eventType.hashCode());
- result = prime * result + ((id == null) ? 0 : id.hashCode());
- result = prime * result + ((name == null) ? 0 :
name.hashCode());
- result = prime * result
- + ((this.result == null) ? 0 :
this.result.hashCode());
- result = prime * result + ((router == null) ? 0 :
router.hashCode());
- result = prime * result
- + ((routerName == null) ? 0 :
routerName.hashCode());
- result = prime * result + ((syntax == null) ? 0 :
syntax.hashCode());
- return result;
- }
+ public static final Command PING_IPV6 = new Command("ping inet6", "ping
an [IPv6 address]", "[IPv6 address]",
+ "http://schemas.perfsonar.net/tools/sshtelnet/IPv6_PING/1.0";);

- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- Command other = (Command) obj;
-
- if (description == null) {
- if (other.description != null)
- return false;
- } else if (!description.equals(other.description))
- return false;
- if (eventType == null) {
- if (other.eventType != null)
- return false;
- } else if (!eventType.equals(other.eventType))
- return false;
- if (name == null) {
- if (other.name != null)
- return false;
- } else if (!name.equals(other.name))
- return false;
- if (result == null) {
- if (other.result != null)
- return false;
- } else if (!result.equals(other.result))
- return false;
- if (router == null) {
- if (other.router != null)
- return false;
- } else if (!router.getName().equals(other.router.getName()))
- return false;
- if (routerName == null) {
- if (other.routerName != null)
- return false;
- } else if (!routerName.equals(other.routerName))
- return false;
- if (syntax == null) {
- if (other.syntax != null)
- return false;
- } else if (!syntax.equals(other.syntax))
- return false;
- return true;
- }
-
- public void setRouter(Router router) {
- this.router = router;
- if (router != null)
- router.addCommand(this);
- }
+ public static final Command TRACEROUTER_IPV6 = new Command("traceroute
inet6",
+ "trace the ipv6 path to [ipv6 address]", "[IPv6 address]",
+
"http://schemas.perfsonar.net/tools/sshtelnet/IPv6_TRACEROUTE/1.0";);

- public void setName(String name) {
- this.name = name;
- }
+ private String routerName;
+ private String name;
+ private String description;
+ private String syntax;
+ private String eventType;
+ private String id;
+ private String result;

- public void setDescription(String description) {
- this.description = description;
- }
+ private Router router;

- public void setSyntax(String syntax) {
- this.syntax = syntax;
- }
+ public Command(Command cmd, String routerName) {
+ this.description = cmd.description;
+ this.eventType = cmd.eventType;
+ this.name = cmd.name;
+ this.syntax = cmd.syntax;
+ this.routerName = routerName;
+ }

- @Override
- public String toString() {
- return "Command [id=" + id + ", name=" + name + ",
eventType=" + eventType + ", description=" + description
- + ", syntax=" + syntax + ", router=" +
(router != null ? router.getName() : routerName) + "]";
- }
+ public Command(String name, String description, String syntax, String
eventType) {
+ this(RouterReference.getCurrentRouter(), name, description, syntax,
eventType);
+ }

- public String getResult() {
- return result;
- }
+ private Command(Router router, String name, String description, String
syntax, String eventType) {
+ this.name = name;
+ this.description = description;
+ this.syntax = syntax;
+ this.eventType = eventType;
+ setRouter(router);
+ }

- public String getRouterName() {
- return routerName;
- }
+ public Command() {
+ this(RouterReference.getCurrentRouter(), null, null, null, null);
+ }

- public void setRouterName(String routerName) {
- this.routerName = routerName;
- }
+ public String getEventType() {
+ return eventType;
+ }

- public void setId(String id) {
- this.id = id;
- }
+ public void setEventType(String eventType) {
+ this.eventType = eventType;
+ }

- public String getId() {
- return id;
- }
+ public String getName() {
+ return name;
+ }

- public void setResult(String result) {
- this.result = result;
- }
+ public String getDescription() {
+ return description;
+ }
+
+ public String getSyntax() {
+ return syntax;
+ }
+
+ public void execute() throws IOException {
+ // router.execute(this);
+ result = "For address family: IPv4 Unicast@@@@@@"
+ + "For address family: IPv6 Unicast@@@@@@"
+ + "For address family: VPNv4 Unicast@@@@@@"
+ + "For address family: IPv4 Multicast@@@@@@"
+ + "For address family: IPv6 Multicast@@@@@@"
+ + "For address family: NSAP Unicast@@@---END---";
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int myResult = 1;
+ myResult = prime * myResult + ((description == null) ? 0 :
description.hashCode());
+ myResult = prime * myResult + ((eventType == null) ? 0 :
eventType.hashCode());
+ myResult = prime * myResult + ((id == null) ? 0 : id.hashCode());
+ myResult = prime * myResult + ((name == null) ? 0 : name.hashCode());
+ myResult = prime * myResult + ((this.result == null) ? 0 :
this.result.hashCode());
+ myResult = prime * myResult + ((router == null) ? 0 :
router.hashCode());
+ myResult = prime * myResult + ((routerName == null) ? 0 :
routerName.hashCode());
+ myResult = prime * myResult + ((syntax == null) ? 0 :
syntax.hashCode());
+ return myResult;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null) {
+ return false;
+ }
+ if (getClass() != obj.getClass()) {
+ return false;
+ }
+ Command other = (Command) obj;
+
+ if (description == null) {
+ if (other.description != null) {
+ return false;
+ }
+ } else if (!description.equals(other.description)) {
+ return false;
+ }
+ if (eventType == null) {
+ if (other.eventType != null) {
+ return false;
+ }
+ } else if (!eventType.equals(other.eventType)) {
+ return false;
+ }
+ if (name == null) {
+ if (other.name != null) {
+ return false;
+ }
+ } else if (!name.equals(other.name)) {
+ return false;
+ }
+ if (result == null) {
+ if (other.result != null) {
+ return false;
+ }
+ } else if (!result.equals(other.result)) {
+ return false;
+ }
+ if (router == null) {
+ if (other.router != null) {
+ return false;
+ }
+ } else if (!router.getName().equals(other.router.getName())) {
+ return false;
+ }
+ if (routerName == null) {
+ if (other.routerName != null) {
+ return false;
+ }
+ } else if (!routerName.equals(other.routerName)) {
+ return false;
+ }
+ if (syntax == null) {
+ if (other.syntax != null) {
+ return false;
+ }
+ } else if (!syntax.equals(other.syntax)) {
+ return false;
+ }
+ return true;
+ }
+
+ public void setRouter(Router router) {
+ this.router = router;
+ if (router != null) {
+ router.addCommand(this);
+ }
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public void setSyntax(String syntax) {
+ this.syntax = syntax;
+ }
+
+ @Override
+ public String toString() {
+ return "Command [id=" + id + ", name=" + name + ", eventType=" +
eventType + ", description=" + description
+ + ", syntax=" + syntax + ", router=" + (router != null ?
router.getName() : routerName) + "]";
+ }
+
+ public String getResult() {
+ return result;
+ }
+
+ public String getRouterName() {
+ return routerName;
+ }
+
+ public void setRouterName(String routerName) {
+ this.routerName = routerName;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ public void setResult(String result) {
+ this.result = result;
+ }
}

Modified:
trunk/perfsonar-base/messaging/src/test/java/net/geant/perfsonar/mp/sshtelnet/Router.java
===================================================================
---
trunk/perfsonar-base/messaging/src/test/java/net/geant/perfsonar/mp/sshtelnet/Router.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/messaging/src/test/java/net/geant/perfsonar/mp/sshtelnet/Router.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -8,135 +8,144 @@
import java.util.List;

public class Router {
-
- private static final int PORT_UNDEFINED = -1;

+ private static final int PORT_UNDEFINED = -1;
+
private String name;
-
+
private InetAddress address;
-
- private int port;
-
- private String id;
-
- private List<Command> commands = new ArrayList<Command>();
-
- public Router() {
- }
-
- public Router(String id, String name, InetAddress address, Command...
commands) {
- this(id, name, address, PORT_UNDEFINED, commands);
- }
-
- public Router(String id, String name, InetAddress address, int port,
Command... commands) {
- this.id = id;
- this.name = name;
- this.address = address;
- this.port = port;
- for (Command c : commands) {
- c.setRouter(this);
- }
- }
-
- public String getName() {
- return name;
- }
-
- public InetAddress getAddress() {
- return address;
- }
-
- public int getPort() {
- return port;
- }
-
- public void addCommand(Command command) {
- if (!commands.contains(command))
- commands.add(command);
- }
-
- public List<Command> getCommands() {
- return Collections.unmodifiableList(commands);
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((address == null) ? 0 :
address.hashCode());
- result = prime * result
- + ((commands == null) ? 0 :
commands.hashCode());
- result = prime * result + ((id == null) ? 0 : id.hashCode());
- result = prime * result + ((name == null) ? 0 :
name.hashCode());
- return result;
- }

- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- Router other = (Router) obj;
- if (address == null) {
- if (other.address != null)
- return false;
- } else if (!address.equals(other.address))
- return false;
- if (commands == null) {
- if (other.commands != null)
- return false;
- } else if (!commands.equals(other.commands))
- return false;
- if (name == null) {
- if (other.name != null)
- return false;
- } else if (!name.equals(other.name))
- return false;
- return true;
- }
+ private int port;

- public void connect() throws IOException {
- throw new IOException("Not implemented yet.");
- }
-
- @Override
- public String toString() {
- return "Router [name=" + name + ", address=" + address + ",
id=" + id
- + ", commands=" + commands + "]";
- }
+ private String id;

- public void setName(String name) {
- this.name = name;
- }
+ private List<Command> commands = new ArrayList<Command>();

- public void setAddress(String address) throws UnknownHostException {
- this.address = InetAddress.getAllByName(address)[0];
- }
-
- public void setId(String id) {
- this.id = id;
- }
-
- public String getId() {
- return id;
- }
+ public Router() {
+ }

- public void startAddingCommands(String routerId) {
- // TODO Auto-generated method stub
-
- }
+ public Router(String id, String name, InetAddress address, Command...
commands) {
+ this(id, name, address, PORT_UNDEFINED, commands);
+ }

-// public void execute(Command command) throws IOException {
-// RouterConnection conn = null;
-// try {
-// conn = connect();
-// //command.result =
device.filter(conn.execute(device.toCommand(command)));
-// } finally {
-// if (conn != null)
-// conn.close();
-// }
-// }
+ public Router(String id, String name, InetAddress address, int port,
Command... commands) {
+ this.id = id;
+ this.name = name;
+ this.address = address;
+ this.port = port;
+ for (Command c : commands) {
+ c.setRouter(this);
+ }
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public InetAddress getAddress() {
+ return address;
+ }
+
+ public int getPort() {
+ return port;
+ }
+
+ public void addCommand(Command command) {
+ if (!commands.contains(command)) {
+ commands.add(command);
+ }
+ }
+
+ public List<Command> getCommands() {
+ return Collections.unmodifiableList(commands);
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((address == null) ? 0 :
address.hashCode());
+ result = prime * result + ((commands == null) ? 0 :
commands.hashCode());
+ result = prime * result + ((id == null) ? 0 : id.hashCode());
+ result = prime * result + ((name == null) ? 0 : name.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null) {
+ return false;
+ }
+ if (getClass() != obj.getClass()) {
+ return false;
+ }
+ Router other = (Router) obj;
+ if (address == null) {
+ if (other.address != null) {
+ return false;
+ }
+ } else if (!address.equals(other.address)) {
+ return false;
+ }
+ if (commands == null) {
+ if (other.commands != null) {
+ return false;
+ }
+ } else if (!commands.equals(other.commands)) {
+ return false;
+ }
+ if (name == null) {
+ if (other.name != null) {
+ return false;
+ }
+ } else if (!name.equals(other.name)) {
+ return false;
+ }
+ return true;
+ }
+
+ public void connect() throws IOException {
+ throw new IOException("Not implemented yet.");
+ }
+
+ @Override
+ public String toString() {
+ return "Router [name=" + name + ", address=" + address + ", id=" +
id + ", commands=" + commands + "]";
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public void setAddress(String address) throws UnknownHostException {
+ this.address = InetAddress.getAllByName(address)[0];
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ public void startAddingCommands(String routerId) {
+ // TODO Auto-generated method stub
+
+ }
+
+ // public void execute(Command command) throws IOException {
+ // RouterConnection conn = null;
+ // try {
+ // conn = connect();
+ // //command.result =
+ // device.filter(conn.execute(device.toCommand(command)));
+ // } finally {
+ // if (conn != null)
+ // conn.close();
+ // }
+ // }
}

Modified:
trunk/perfsonar-base/messaging/src/test/java/net/geant/perfsonar/mp/sshtelnet/RouterReference.java
===================================================================
---
trunk/perfsonar-base/messaging/src/test/java/net/geant/perfsonar/mp/sshtelnet/RouterReference.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/messaging/src/test/java/net/geant/perfsonar/mp/sshtelnet/RouterReference.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -1,28 +1,28 @@
package net.geant.perfsonar.mp.sshtelnet;

-
/**
* Used for injecting Router instances in Command objects.
*
* @author <a
href="mailto:">Blazej
Pietrzak</a>
- *
+ *
*/
public class RouterReference {

- private static Router currentRouter = null;
-
- public void setCurrentRouter(Router router) {
- RouterReference.currentRouter = router;
- }
-
- public static Router getCurrentRouter() {
- return RouterReference.currentRouter;
- }
-
- public boolean equals(Object obj) {
- if (obj == null)
- return false;
-
- return (obj instanceof RouterReference);
- }
+ private static Router currentRouter = null;
+
+ public void setCurrentRouter(Router router) {
+ RouterReference.currentRouter = router;
+ }
+
+ public static Router getCurrentRouter() {
+ return RouterReference.currentRouter;
+ }
+
+ public boolean equals(Object obj) {
+ if (obj == null) {
+ return false;
+ }
+
+ return obj instanceof RouterReference;
+ }
}

Modified:
trunk/perfsonar-base/messaging/src/test/java/net/geant/perfsonar/templates/TemplateEngineTest.java
===================================================================
---
trunk/perfsonar-base/messaging/src/test/java/net/geant/perfsonar/templates/TemplateEngineTest.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/messaging/src/test/java/net/geant/perfsonar/templates/TemplateEngineTest.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -1,6 +1,6 @@
package net.geant.perfsonar.templates;

-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;

import java.io.StringWriter;
import net.geant.perfsonar.messaging.data.Dummy;
@@ -9,12 +9,12 @@

public class TemplateEngineTest {

- @Test
- public void shouldProcessTemplateFromJar() throws Exception {
- final StringWriter out = new StringWriter();
- TemplateEngine.put("name", "John Doe");
- TemplateEngine.evaluate(out, Dummy.class, "Hello.template");
- assertEquals("Hello John Doe!", out.toString());
- }
+ @Test
+ public void shouldProcessTemplateFromJar() throws Exception {
+ final StringWriter out = new StringWriter();
+ TemplateEngine.put("name", "John Doe");
+ TemplateEngine.evaluate(out, Dummy.class, "Hello.template");
+ assertEquals("Hello John Doe!", out.toString());
+ }

}


Property changes on: trunk/perfsonar-base/messaging-test-data
___________________________________________________________________
Modified: svn:ignore
- target

.settings

.project

.classpath

+ target

.settings

.project

.classpath

.pmd

.pmdruleset


Modified: trunk/perfsonar-base/messaging-test-data/pom.xml
===================================================================
--- trunk/perfsonar-base/messaging-test-data/pom.xml 2013-05-07 14:18:22
UTC (rev 6370)
+++ trunk/perfsonar-base/messaging-test-data/pom.xml 2013-05-08 20:41:45
UTC (rev 6371)
@@ -5,7 +5,7 @@
<parent>
<groupId>net.geant.perfsonar</groupId>
<artifactId>parent</artifactId>
- <version>1.0.1</version>
+ <version>1.0.3-SNAPSHOT</version>
<relativePath>../../parent/</relativePath>
</parent>


Modified:
trunk/perfsonar-base/messaging-test-data/src/main/java/net/geant/perfsonar/messaging/data/Dummy.java
===================================================================
---
trunk/perfsonar-base/messaging-test-data/src/main/java/net/geant/perfsonar/messaging/data/Dummy.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/messaging-test-data/src/main/java/net/geant/perfsonar/messaging/data/Dummy.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -2,4 +2,8 @@

public class Dummy {

+ public Dummy() {
+ super();
+ }
+
}


Property changes on: trunk/perfsonar-base/sample-service
___________________________________________________________________
Modified: svn:ignore
- target

.settings

.project

.classpath

+ target

.settings

.project

.classpath

.pmd

.pmdruleset


Modified:
trunk/perfsonar-base/sample-service/src/main/java/net/geant/perfsonar/mp/sshtelnet/Command.java
===================================================================
---
trunk/perfsonar-base/sample-service/src/main/java/net/geant/perfsonar/mp/sshtelnet/Command.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/sample-service/src/main/java/net/geant/perfsonar/mp/sshtelnet/Command.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -13,217 +13,245 @@
* @author <a
href="mailto:">Blazej
Pietrzak</a>
*/
public class Command {
-
- public static final Command PING = new Command("ping", "ping an [ip
address]", "[ip address]", "IP_PING");

- public static Command SHOW_ENVIRONMENT = new Command("show
environment", "show chassis environment", "",
"http://schemas.perfsonar.net/tools/sshtelnet/STATUS_SHOW_ENVIRONMENT/1.0";);
-
- public static final Command TRACE_IPV4 = new Command("trace", "trace
the IPv4 path to [ip address]", "[ip address]",
"http://schemas.perfsonar.net/tools/sshtelnet/IP_TRACEROUTE/1.0";);
+ public static final Command PING = new Command("ping", "ping an [ip
address]", "[ip address]", "IP_PING");

- public static final Command TRACE_IPV6 = new Command("trace ipv6",
"trace the ipv6 path to [IPv6 address]", "[IPv6 address]",
"http://schemas.perfsonar.net/tools/sshtelnet/IPv6_TRACEROUTE/1.0";);
+ public static final Command SHOW_ENVIRONMENT = new Command("show
environment", "show chassis environment", "",
+
"http://schemas.perfsonar.net/tools/sshtelnet/STATUS_SHOW_ENVIRONMENT/1.0";);

- public static final Command SHOW_INTERFACES_FILTERS = new
Command("show interfaces filters", "display ip access lists", "",
"http://schemas.perfsonar.net/tools/sshtelnet/IP_ACCESS_LIST/1.0";);
-
- //public static final Command SHOW_IPV6_INTERFACES_FILTERS = new
Command("show interfaces filters", "display IPv6 access lists");
-
- public static final Command SHOW_IPV6_INTERFACES = new Command("show
interfaces", "display the interfaces which are configured for IPv6",
"[interface] extensive",
"http://schemas.perfsonar.net/tools/sshtelnet/IPv6_INTERFACES/1.0";);
+ public static final Command TRACE_IPV4 = new Command("trace", "trace the
IPv4 path to [ip address]",
+ "[ip address]",
"http://schemas.perfsonar.net/tools/sshtelnet/IP_TRACEROUTE/1.0";);

- public static final Command PING_IPV6 = new Command("ping inet6",
"ping an [IPv6 address]", "[IPv6 address]",
"http://schemas.perfsonar.net/tools/sshtelnet/IPv6_PING/1.0";);
+ public static final Command TRACE_IPV6 = new Command("trace ipv6",
"trace the ipv6 path to [IPv6 address]",
+ "[IPv6 address]",
"http://schemas.perfsonar.net/tools/sshtelnet/IPv6_TRACEROUTE/1.0";);

- public static final Command TRACEROUTER_IPV6 = new
Command("traceroute inet6", "trace the ipv6 path to [ipv6 address]", "[IPv6
address]",
"http://schemas.perfsonar.net/tools/sshtelnet/IPv6_TRACEROUTE/1.0";);
-
- private String routerName;
- private String name;
- private String description;
- private String syntax;
- private String eventType;
- private String id;
- private String result;
-
- private Router router;
-
- Command(Command cmd, String routerName) {
- setDescription(cmd.description);
- setEventType(cmd.eventType);
- setName(cmd.name);
- setSyntax(cmd.syntax);
- setRouterName(routerName);
- }
-
- private Command(String name, String description, String syntax,
String eventType) {
- this(RouterReference.getCurrentRouter(), name, description,
syntax, eventType);
- }
-
- private Command(Router router, String name, String description,
String syntax, String eventType) {
- this.name = name;
- this.description = description;
- this.syntax = syntax;
- this.eventType = eventType;
- this.router = router;
- if (router != null)
- router.addCommand(this);
- }
-
- public Command() {
- this(RouterReference.getCurrentRouter(), null, null, null,
null);
- }
-
- public void setRouter(Router router) {
- this.router = router;
- }
-
- public String getEventType() {
- return eventType;
- }
-
- @XPaths({
-
@XPath(xpath="nmwg:message[@type='MetadataKeyResponse']/nmwg:data/nmwgr:datum/nmwg:eventType/text()",

namespaces=@Namespace(prefix="nmwgr",
uri="http://ggf.org/ns/nmwg/result/2.0/";)),
-
@XPath(xpath="nmwg:message[@type='SetupDataRequest']/nmwg:metadata/nmwg:eventType/text()"),
-
@XPath(xpath="nmwg:message[@type='SetupDataResponse']/nmwg:metadata[nmwg:subject/nmwgtopo:endPoint]/nmwg:eventType/text()")
- })
- public void setEventType(String eventType) {
- this.eventType = eventType;
- }
-
- public String getName() {
- return name;
- }
+ public static final Command SHOW_IFACES_FILTERS = new Command("show
interfaces filters",
+ "display ip access lists", "",
"http://schemas.perfsonar.net/tools/sshtelnet/IP_ACCESS_LIST/1.0";);

- public String getDescription() {
- return description;
- }
+ // public static final Command SHOW_IPV6_INTERFACES_FILTERS = new
+ // Command("show interfaces filters", "display IPv6 access lists");

- public String getSyntax() {
- return syntax;
- }
-
- public void execute() throws IOException {
- //router.execute(this);
- result = "For address family: IPv4 Unicast@@@@@@For address
family: IPv6 Unicast@@@@@@For address family: VPNv4 Unicast@@@@@@For address
family: IPv4 Multicast@@@@@@For address family: IPv6 Multicast@@@@@@For
address family: NSAP Unicast@@@---END---";
- }
+ public static final Command SHOW_IPV6_INTERFACES = new Command("show
interfaces",
+ "display the interfaces which are configured for IPv6",
"[interface] extensive",
+
"http://schemas.perfsonar.net/tools/sshtelnet/IPv6_INTERFACES/1.0";);

- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result
- + ((description == null) ? 0 :
description.hashCode());
- result = prime * result
- + ((eventType == null) ? 0 :
eventType.hashCode());
- result = prime * result + ((id == null) ? 0 : id.hashCode());
- result = prime * result + ((name == null) ? 0 :
name.hashCode());
- result = prime * result
- + ((this.result == null) ? 0 :
this.result.hashCode());
- result = prime * result + ((router == null) ? 0 :
router.hashCode());
- result = prime * result
- + ((routerName == null) ? 0 :
routerName.hashCode());
- result = prime * result + ((syntax == null) ? 0 :
syntax.hashCode());
- return result;
- }
+ public static final Command PING_IPV6 = new Command("ping inet6", "ping
an [IPv6 address]", "[IPv6 address]",
+ "http://schemas.perfsonar.net/tools/sshtelnet/IPv6_PING/1.0";);

- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- Command other = (Command) obj;
-
- if (description == null) {
- if (other.description != null)
- return false;
- } else if (!description.equals(other.description))
- return false;
- if (eventType == null) {
- if (other.eventType != null)
- return false;
- } else if (!eventType.equals(other.eventType))
- return false;
- if (name == null) {
- if (other.name != null)
- return false;
- } else if (!name.equals(other.name))
- return false;
- if (result == null) {
- if (other.result != null)
- return false;
- } else if (!result.equals(other.result))
- return false;
- if (router == null) {
- if (other.router != null)
- return false;
- } else if (!router.getName().equals(other.router.getName()))
- return false;
- if (routerName == null) {
- if (other.routerName != null)
- return false;
- } else if (!routerName.equals(other.routerName))
- return false;
- if (syntax == null) {
- if (other.syntax != null)
- return false;
- } else if (!syntax.equals(other.syntax))
- return false;
- return true;
- }
+ public static final Command TRACEROUTER_IPV6 = new Command("traceroute
inet6",
+ "trace the ipv6 path to [ipv6 address]", "[IPv6 address]",
+
"http://schemas.perfsonar.net/tools/sshtelnet/IPv6_TRACEROUTE/1.0";);

- @XPaths({
-
@XPath(xpath="nmwg:message/nmwg:data[starts-with(@metadataIdRef,
'metadata')]/nmwgr:datum/nmwg:parameters/nmwg:parameter[@name='command']/@value",

namespaces=@Namespace(prefix="nmwgr",
uri="http://ggf.org/ns/nmwg/result/2.0/";)),
-
@XPath(xpath="nmwg:message/nmwg:metadata/nmwg:parameters/nmwg:parameter[@name='command']/@value")
- })
- public void setName(String name) {
- this.name = name;
- }
+ private String routerName;
+ private String name;
+ private String description;
+ private String syntax;
+ private String eventType;
+ private String id;
+ private String result;

- @XPaths({
- @XPath(xpath="nmwg:message/nmwg:data[starts-with(@metadataIdRef,
'metadata')]/nmwgr:datum/nmwg:parameters/nmwg:parameter[@name='description']/@value"),
-
@XPath(xpath="nmwg:message/nmwg:metadata/nmwg:parameters/nmwg:parameter[@name='description']/@value")
- })
- public void setDescription(String description) {
- this.description = description;
- }
+ private Router router;

- @XPaths({
-
@XPath(xpath="nmwg:message/nmwg:data[starts-with(@metadataIdRef,
'metadata')]/nmwgr:datum/nmwg:parameters/nmwg:parameter[@name='syntax']/@value"),
-
@XPath(xpath="nmwg:message/nmwg:metadata/nmwg:parameters/nmwg:parameter[@name='syntax']/@value")
- })
- public void setSyntax(String syntax) {
- this.syntax = syntax;
- }
+ Command(Command cmd, String routerName) {
+ setDescription(cmd.description);
+ setEventType(cmd.eventType);
+ setName(cmd.name);
+ setSyntax(cmd.syntax);
+ setRouterName(routerName);
+ }

- @Override
- public String toString() {
- return "Command [id=" + id + ", name=" + name + ",
eventType=" + eventType + ", description=" + description
- + ", syntax=" + syntax + ", router=" +
(router != null ? router.getName() : routerName) + "]";
- }
+ private Command(String name, String description, String syntax, String
eventType) {
+ this(RouterReference.getCurrentRouter(), name, description, syntax,
eventType);
+ }

- public String getResult() {
- return result;
- }
+ private Command(Router router, String name, String description, String
syntax, String eventType) {
+ this.name = name;
+ this.description = description;
+ this.syntax = syntax;
+ this.eventType = eventType;
+ this.router = router;
+ if (router != null) {
+ router.addCommand(this);
+ }
+ }

- public String getRouterName() {
- return routerName;
- }
+ public Command() {
+ this(RouterReference.getCurrentRouter(), null, null, null, null);
+ }

-
@XPath(xpath="nmwg:message/nmwg:metadata/nmwg:subject/nmwgtopo:endPoint/text()",

namespaces=@Namespace(prefix="nmwgtopo",
uri="http://ggf.org/ns/nmwg/topology/2.0/";))
- public void setRouterName(String routerName) {
- this.routerName = routerName;
- }
+ public void setRouter(Router router) {
+ this.router = router;
+ }

-
@XPath(xpath="nmwg:message[@type='SetupDataResponse']/nmwg:metadata[nmwg:subject/nmwgtopo:endPoint]/@id")
- public void setId(String id) {
- this.id = id;
- }
+ public String getEventType() {
+ return eventType;
+ }

- @Identifier
- public String getId() {
- return id;
- }
+ @XPaths({
+ @XPath(xpath =
"nmwg:message[@type='MetadataKeyResponse']/nmwg:data/nmwgr:datum/nmwg:eventType/text()",
+ namespaces = @Namespace(prefix = "nmwgr", uri =
"http://ggf.org/ns/nmwg/result/2.0/";)),
+ @XPath(xpath =
"nmwg:message[@type='SetupDataRequest']/nmwg:metadata/nmwg:eventType/text()"),
+ @XPath(xpath =
"nmwg:message[@type='SetupDataResponse']/nmwg:metadata[nmwg:subject/nmwgtopo:endPoint]/nmwg:eventType/text()")
})
+ public void setEventType(String eventType) {
+ this.eventType = eventType;
+ }

- @XPath(xpath="nmwg:message/nmwg:data[starts-with(@metadataIdRef,
'meta')]/nmwg:datum/text()")
- public void setResult(String result) {
- this.result = result;
- }
+ public String getName() {
+ return name;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public String getSyntax() {
+ return syntax;
+ }
+
+ public void execute() throws IOException {
+ // router.execute(this);
+ result = "For address family: IPv4 Unicast@@@@@@For address family:
IPv6 Unicast@@@@@@"
+ + "For address family: VPNv4 Unicast@@@@@@For address
family: IPv4 Multicast@@@@@@"
+ + "For address family: IPv6 Multicast@@@@@@For address
family: NSAP Unicast@@@---END---";
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int myResult = 1;
+ myResult = prime * myResult + ((description == null) ? 0 :
description.hashCode());
+ myResult = prime * myResult + ((eventType == null) ? 0 :
eventType.hashCode());
+ myResult = prime * myResult + ((id == null) ? 0 : id.hashCode());
+ myResult = prime * myResult + ((name == null) ? 0 : name.hashCode());
+ myResult = prime * myResult + ((this.result == null) ? 0 :
this.result.hashCode());
+ myResult = prime * myResult + ((router == null) ? 0 :
router.hashCode());
+ myResult = prime * myResult + ((routerName == null) ? 0 :
routerName.hashCode());
+ myResult = prime * myResult + ((syntax == null) ? 0 :
syntax.hashCode());
+ return myResult;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null) {
+ return false;
+ }
+ if (getClass() != obj.getClass()) {
+ return false;
+ }
+ Command other = (Command) obj;
+
+ if (description == null) {
+ if (other.description != null) {
+ return false;
+ }
+ } else if (!description.equals(other.description)) {
+ return false;
+ }
+ if (eventType == null) {
+ if (other.eventType != null) {
+ return false;
+ }
+ } else if (!eventType.equals(other.eventType)) {
+ return false;
+ }
+ if (name == null) {
+ if (other.name != null) {
+ return false;
+ }
+ } else if (!name.equals(other.name)) {
+ return false;
+ }
+ if (result == null) {
+ if (other.result != null) {
+ return false;
+ }
+ } else if (!result.equals(other.result)) {
+ return false;
+ }
+ if (router == null) {
+ if (other.router != null) {
+ return false;
+ }
+ } else if (!router.getName().equals(other.router.getName())) {
+ return false;
+ }
+ if (routerName == null) {
+ if (other.routerName != null) {
+ return false;
+ }
+ } else if (!routerName.equals(other.routerName)) {
+ return false;
+ }
+ if (syntax == null) {
+ if (other.syntax != null) {
+ return false;
+ }
+ } else if (!syntax.equals(other.syntax)) {
+ return false;
+ }
+ return true;
+ }
+
+ @XPaths({
+ @XPath(xpath =
"nmwg:message/nmwg:data[starts-with(@metadataIdRef, 'metadata')]/"
+ +
"nmwgr:datum/nmwg:parameters/nmwg:parameter[@name='command']/@value",
+ namespaces = @Namespace(prefix = "nmwgr", uri =
"http://ggf.org/ns/nmwg/result/2.0/";)),
+ @XPath(xpath =
"nmwg:message/nmwg:metadata/nmwg:parameters/nmwg:parameter[@name='command']/@value")
})
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @XPaths({
+ @XPath(xpath =
"nmwg:message/nmwg:data[starts-with(@metadataIdRef, 'metadata')]/"
+ +
"nmwgr:datum/nmwg:parameters/nmwg:parameter[@name='description']/@value"),
+ @XPath(xpath =
"nmwg:message/nmwg:metadata/nmwg:parameters/nmwg:parameter[@name='description']/@value")
})
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ @XPaths({
+ @XPath(xpath =
"nmwg:message/nmwg:data[starts-with(@metadataIdRef, 'metadata')]/"
+ +
"nmwgr:datum/nmwg:parameters/nmwg:parameter[@name='syntax']/@value"),
+ @XPath(xpath =
"nmwg:message/nmwg:metadata/nmwg:parameters/nmwg:parameter[@name='syntax']/@value")
})
+ public void setSyntax(String syntax) {
+ this.syntax = syntax;
+ }
+
+ @Override
+ public String toString() {
+ return "Command [id=" + id + ", name=" + name + ", eventType=" +
eventType + ", description=" + description
+ + ", syntax=" + syntax + ", router=" + (router != null ?
router.getName() : routerName) + "]";
+ }
+
+ public String getResult() {
+ return result;
+ }
+
+ public String getRouterName() {
+ return routerName;
+ }
+
+ @XPath(xpath =
"nmwg:message/nmwg:metadata/nmwg:subject/nmwgtopo:endPoint/text()",
+ namespaces = @Namespace(prefix = "nmwgtopo", uri =
"http://ggf.org/ns/nmwg/topology/2.0/";))
+ public void setRouterName(String routerName) {
+ this.routerName = routerName;
+ }
+
+ @XPath(xpath =
"nmwg:message[@type='SetupDataResponse']/nmwg:metadata[nmwg:subject/nmwgtopo:endPoint]/@id")
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ @Identifier
+ public String getId() {
+ return id;
+ }
+
+ @XPath(xpath = "nmwg:message/nmwg:data[starts-with(@metadataIdRef,
'meta')]/nmwg:datum/text()")
+ public void setResult(String result) {
+ this.result = result;
+ }
}

Modified:
trunk/perfsonar-base/sample-service/src/main/java/net/geant/perfsonar/mp/sshtelnet/ConfigurationFileChecker.java
===================================================================
---
trunk/perfsonar-base/sample-service/src/main/java/net/geant/perfsonar/mp/sshtelnet/ConfigurationFileChecker.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/sample-service/src/main/java/net/geant/perfsonar/mp/sshtelnet/ConfigurationFileChecker.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -14,75 +14,81 @@
import org.xml.sax.InputSource;

/**
- * Scheduler task that checks every second whether configuration file has
changed.
- * When it's changed it reads the configuration and injects to object model.
+ * Scheduler task that checks every second whether configuration file has
+ * changed. When it's changed it reads the configuration and injects to
object
+ * model.
*
* @author <a
href="mailto:">Blazej
Pietrzak</a>
*/
public class ConfigurationFileChecker implements Runnable {

- private File file = new File("src/main/resources/configuration.xml");
- private long lastModified = 0;
- private final SSHTelnetMPService service;
-
- public ConfigurationFileChecker(SSHTelnetMPService
sshTelnetMPService) {
- this.service = sshTelnetMPService;
- }
+ private File file = new File("src/main/resources/configuration.xml");
+ private long lastModified = 0;
+ private final SSHTelnetMPService service;

- public void run() {
- if (!configurationExists()) {
- System.err.println("Configuration file: " +
file.getAbsolutePath()
- + " is missing");
- return;
- }
+ public ConfigurationFileChecker(SSHTelnetMPService sshTelnetMPService) {
+ this.service = sshTelnetMPService;
+ }

- if (isModified()) {
- lastModified = file.lastModified();
- configureDeserialization();
- XPathDeserializer deserializer = new
XPathDeserializer();
- try {
- deserializer.deserialize(new InputSource(new
FileInputStream(file)));
- } catch (Throwable ex) {
- ex.printStackTrace();
- }
- }
- }
+ public void run() {
+ if (!configurationExists()) {
+ System.err.println("Configuration file: " +
file.getAbsolutePath() + " is missing");
+ return;
+ }

- protected boolean configurationExists() {
- return file.exists();
- }
+ if (isModified()) {
+ lastModified = file.lastModified();
+ configureDeserialization();
+ XPathDeserializer deserializer = new XPathDeserializer();
+ try {
+ deserializer.deserialize(new InputSource(new
FileInputStream(file)));
+ } catch (Throwable ex) {
+ ex.printStackTrace();
+ }
+ }
+ }

- protected boolean isModified() {
- return file.lastModified() > lastModified;
- }
-
- protected long getCurrentModified() {
- return lastModified;
- }
-
- protected long lastModified() {
- return file.lastModified();
- }
-
- private void configureDeserialization() {
- //When configuring XPath the configurator creates a subclass
of SSHTelnetMPService that registers method invocations.
- //The instance executes base class constructor of
SSHTelnetMPService which creates this task.
- //This guard prevents calls from subclass instances forever
when configuring XPath.
- if (Helper.isConfigurationInstance(service))
- return;
-
- declarePrefix("ns",
"http://service.perfsonar.org/ns/config/base/0.9/";);
+ protected boolean configurationExists() {
+ return file.exists();
+ }

- try {
- whenXPath(
-
"ns:configuration/ns:service/ns:auxiliaryComponents/ns:component[@name='scheduling']/ns:actions/ns:action[@name='registration']/ns:option[@name='interval']/@value")
- .then(SSHTelnetMPService.class,
service).setLookupServiceInterval(any(String.class));
-
- whenXPath(
-
"ns:configuration/ns:service/ns:auxiliaryComponents/ns:component[@name='scheduling']/ns:actions/ns:action[@name='registration']/ns:option[starts-with(@name,
'lsAddress')]/@value")
-
.then(LSRegistrationTask.class).addLSAddress(any(String.class));
- } catch (Exception ex) {
- ex.printStackTrace();
- }
- }
+ protected boolean isModified() {
+ return file.lastModified() > lastModified;
+ }
+
+ protected long getCurrentModified() {
+ return lastModified;
+ }
+
+ protected long lastModified() {
+ return file.lastModified();
+ }
+
+ private void configureDeserialization() {
+ // When configuring XPath the configurator creates a subclass of
+ // SSHTelnetMPService that registers method invocations.
+ // The instance executes base class constructor of SSHTelnetMPService
+ // which creates this task.
+ // This guard prevents calls from subclass instances forever when
+ // configuring XPath.
+ if (Helper.isConfigurationInstance(service)) {
+ return;
+ }
+
+ declarePrefix("ns",
"http://service.perfsonar.org/ns/config/base/0.9/";);
+
+ try {
+ whenXPath(
+
"ns:configuration/ns:service/ns:auxiliaryComponents/ns:component[@name='scheduling']/"
+ +
"ns:actions/ns:action[@name='registration']/ns:option[@name='interval']/@value")
+ .then(SSHTelnetMPService.class,
service).setLookupServiceInterval(any(String.class));
+
+ whenXPath(
+
"ns:configuration/ns:service/ns:auxiliaryComponents/ns:component[@name='scheduling']/"
+ +
"ns:actions/ns:action[@name='registration']/ns:option[starts-with(@name,
'lsAddress')]/@value")
+
.then(LSRegistrationTask.class).addLSAddress(any(String.class));
+ } catch (Exception ex) {
+ ex.printStackTrace();
+ }
+ }
}

Modified:
trunk/perfsonar-base/sample-service/src/main/java/net/geant/perfsonar/mp/sshtelnet/Router.java
===================================================================
---
trunk/perfsonar-base/sample-service/src/main/java/net/geant/perfsonar/mp/sshtelnet/Router.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/sample-service/src/main/java/net/geant/perfsonar/mp/sshtelnet/Router.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -16,140 +16,149 @@
* @author <a
href="mailto:">Blazej
Pietrzak</a>
*/
public class Router {
-
- private static final int PORT_UNDEFINED = -1;

+ private static final int PORT_UNDEFINED = -1;
+
private String name;
-
+
private InetAddress address;
-
- private int port;
-
- private String id;
-
- private List<Command> commands = new ArrayList<Command>();
-
- public Router() {
- }
-
- public Router(String id, String name, InetAddress address, Command...
commands) {
- this(id, name, address, PORT_UNDEFINED, commands);
- }
-
- public Router(String id, String name, InetAddress address, int port,
Command... commands) {
- this.id = id;
- this.name = name;
- this.address = address;
- this.port = port;
- for (Command c : commands) {
- addCommand(c);
- c.setRouter(this);
- }
- }
-
- public String getName() {
- return name;
- }
-
- public InetAddress getAddress() {
- return address;
- }
-
- public int getPort() {
- return port;
- }
-
- public void addCommand(Command command) {
- if (!commands.contains(command))
- commands.add(command);
- }
-
- public List<Command> getCommands() {
- return Collections.unmodifiableList(commands);
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((address == null) ? 0 :
address.hashCode());
- result = prime * result
- + ((commands == null) ? 0 :
commands.hashCode());
- result = prime * result + ((id == null) ? 0 : id.hashCode());
- result = prime * result + ((name == null) ? 0 :
name.hashCode());
- return result;
- }

- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- Router other = (Router) obj;
- if (address == null) {
- if (other.address != null)
- return false;
- } else if (!address.equals(other.address))
- return false;
- if (commands == null) {
- if (other.commands != null)
- return false;
- } else if (!commands.equals(other.commands))
- return false;
- if (name == null) {
- if (other.name != null)
- return false;
- } else if (!name.equals(other.name))
- return false;
- return true;
- }
+ private int port;

- public void connect() throws IOException {
- throw new IOException("Not implemented yet.");
- }
-
- @Override
- public String toString() {
- return "Router [name=" + name + ", address=" + address + ",
id=" + id
- + ", commands=" + commands + "]";
- }
+ private String id;

-
@XPath(xpath="nmwg:message[@type='MetadataKeyResponse']/nmwg:metadata[nmwg:parameters]/nmwg:subject/text()")
- public void setName(String name) {
- this.name = name;
- }
+ private List<Command> commands = new ArrayList<Command>();

-
@XPath(xpath="nmwg:message[@type='MetadataKeyResponse']/nmwg:metadata/nmwg:parameters/nmwg:parameter[@name='url']/@value")
- public void setAddress(String address) throws UnknownHostException {
- this.address = InetAddress.getAllByName(address)[0];
- }
-
-
@XPath(xpath="nmwg:message[@type='MetadataKeyResponse']/nmwg:metadata[nmwg:parameters]/@id")
- public void setId(String id) {
- this.id = id;
- }
-
- @Identifier
- public String getId() {
- return id;
- }
+ public Router() {
+ }

- public void startAddingCommands(String routerId) {
- // TODO Auto-generated method stub
-
- }
+ public Router(String id, String name, InetAddress address, Command...
commands) {
+ this(id, name, address, PORT_UNDEFINED, commands);
+ }

-// public void execute(Command command) throws IOException {
-// RouterConnection conn = null;
-// try {
-// conn = connect();
-// //command.result =
device.filter(conn.execute(device.toCommand(command)));
-// } finally {
-// if (conn != null)
-// conn.close();
-// }
-// }
+ public Router(String id, String name, InetAddress address, int port,
Command... commands) {
+ this.id = id;
+ this.name = name;
+ this.address = address;
+ this.port = port;
+ for (Command c : commands) {
+ addCommand(c);
+ c.setRouter(this);
+ }
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public InetAddress getAddress() {
+ return address;
+ }
+
+ public int getPort() {
+ return port;
+ }
+
+ public void addCommand(Command command) {
+ if (!commands.contains(command)) {
+ commands.add(command);
+ }
+ }
+
+ public List<Command> getCommands() {
+ return Collections.unmodifiableList(commands);
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((address == null) ? 0 :
address.hashCode());
+ result = prime * result + ((commands == null) ? 0 :
commands.hashCode());
+ result = prime * result + ((id == null) ? 0 : id.hashCode());
+ result = prime * result + ((name == null) ? 0 : name.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null) {
+ return false;
+ }
+ if (getClass() != obj.getClass()) {
+ return false;
+ }
+ Router other = (Router) obj;
+ if (address == null) {
+ if (other.address != null) {
+ return false;
+ }
+ } else if (!address.equals(other.address)) {
+ return false;
+ }
+ if (commands == null) {
+ if (other.commands != null) {
+ return false;
+ }
+ } else if (!commands.equals(other.commands)) {
+ return false;
+ }
+ if (name == null) {
+ if (other.name != null) {
+ return false;
+ }
+ } else if (!name.equals(other.name)) {
+ return false;
+ }
+ return true;
+ }
+
+ public void connect() throws IOException {
+ throw new IOException("Not implemented yet.");
+ }
+
+ @Override
+ public String toString() {
+ return "Router [name=" + name + ", address=" + address + ", id=" +
id + ", commands=" + commands + "]";
+ }
+
+ @XPath(xpath =
"nmwg:message[@type='MetadataKeyResponse']/nmwg:metadata[nmwg:parameters]/nmwg:subject/text()")
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @XPath(xpath =
"nmwg:message[@type='MetadataKeyResponse']/nmwg:metadata/nmwg:parameters/nmwg:parameter[@name='url']/@value")
+ public void setAddress(String address) throws UnknownHostException {
+ this.address = InetAddress.getAllByName(address)[0];
+ }
+
+ @XPath(xpath =
"nmwg:message[@type='MetadataKeyResponse']/nmwg:metadata[nmwg:parameters]/@id")
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ @Identifier
+ public String getId() {
+ return id;
+ }
+
+ public void startAddingCommands(String routerId) {
+ // TODO Auto-generated method stub
+
+ }
+
+ // public void execute(Command command) throws IOException {
+ // RouterConnection conn = null;
+ // try {
+ // conn = connect();
+ // //command.result =
+ // device.filter(conn.execute(device.toCommand(command)));
+ // } finally {
+ // if (conn != null)
+ // conn.close();
+ // }
+ // }
}

Modified:
trunk/perfsonar-base/sample-service/src/main/java/net/geant/perfsonar/mp/sshtelnet/RouterReference.java
===================================================================
---
trunk/perfsonar-base/sample-service/src/main/java/net/geant/perfsonar/mp/sshtelnet/RouterReference.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/sample-service/src/main/java/net/geant/perfsonar/mp/sshtelnet/RouterReference.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -2,23 +2,22 @@

import net.geant.perfsonar.annotations.XPath;

-
/**
* Used for injecting Router instances in Command objects.
*
* @author <a
href="mailto:">Blazej
Pietrzak</a>
- *
+ *
*/
public class RouterReference {

- private static Router currentRouter = null;
-
-
@XPath(xpath="nmwg:message[@type='MetadataKeyResponse']/nmwg:data/@metadataIdRef")
- public void setCurrentRouter(Router router) {
- RouterReference.currentRouter = router;
- }
-
- public static Router getCurrentRouter() {
- return RouterReference.currentRouter;
- }
+ private static Router currentRouter = null;
+
+ @XPath(xpath =
"nmwg:message[@type='MetadataKeyResponse']/nmwg:data/@metadataIdRef")
+ public void setCurrentRouter(Router router) {
+ RouterReference.currentRouter = router;
+ }
+
+ public static Router getCurrentRouter() {
+ return RouterReference.currentRouter;
+ }
}

Modified:
trunk/perfsonar-base/sample-service/src/main/java/net/geant/perfsonar/mp/sshtelnet/SSHTelnetMPService.java
===================================================================
---
trunk/perfsonar-base/sample-service/src/main/java/net/geant/perfsonar/mp/sshtelnet/SSHTelnetMPService.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/sample-service/src/main/java/net/geant/perfsonar/mp/sshtelnet/SSHTelnetMPService.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -1,4 +1,4 @@
-package net.geant.perfsonar.mp.sshtelnet;
+package net.geant.perfsonar.mp.sshtelnet; //NOPMD

import static net.geant.perfsonar.Configuration.configure;
import static net.geant.perfsonar.Configuration.when;
@@ -18,104 +18,96 @@
import net.geant.perfsonar.ServiceType;
import net.geant.perfsonar.ls.LSRegistrationTask;

-/**
+/**
* @author <a
href="mailto:">Blazej
Pietrzak</a>
*/
@WebServiceProvider
public class SSHTelnetMPService extends PerfSONAR {

- private static final int HOUR = 60 * 60;
+ private static final int HOUR = 60 * 60;

- private static final int SECOND = 1;
+ private static final int SECOND = 1;

- private final LSRegistrationTask lsRegistrationTask = new
LSRegistrationTask(
- logger, this);
- private int lsInterval = HOUR;
+ private final LSRegistrationTask lsRegistrationTask = new
LSRegistrationTask(logger, this);
+ private int lsInterval = HOUR;

- public SSHTelnetMPService() {
- super();
-
- configureService();
+ public SSHTelnetMPService() {
+ super();

- scheduler.runEvery(HOUR, lsRegistrationTask);
- scheduler.runEvery(SECOND, new
ConfigurationFileChecker(this));
- }
+ configureService();

- @Override
- public ServiceType getServiceType() {
- return ServiceType.MP;
- }
+ scheduler.runEvery(HOUR, lsRegistrationTask);
+ scheduler.runEvery(SECOND, new ConfigurationFileChecker(this));
+ }

- @Override
- public String getServiceName() {
- return "SSHTELNET";
- }
+ @Override
+ public ServiceType getServiceType() {
+ return ServiceType.MP;
+ }

- private void configureService() {
- try {
- if (!usingAPT) {
- // if apt is not in classpath (maven dependencies)
one must
- // provide configuration using API
- configure(when("MetadataKeyRequest").then(
- ServiceController.class)
-
.listAvailableRoutersAndCommands());
+ @Override
+ public String getServiceName() {
+ return "SSHTELNET";
+ }

- configure(when("SetupDataRequest")
-
.then(ServiceController.class).execute(
-
any(Command.class)));
+ private void configureService() {
+ try {
+ if (!usingAPT) {
+ // if apt is not in classpath (maven dependencies) one must
+ // provide configuration using API
+
configure(when("MetadataKeyRequest").then(ServiceController.class).listAvailableRoutersAndCommands());

-
configure(registerToLookupService(ServiceController.class)
-
.listAvailableRoutersAndCommands());
+
configure(when("SetupDataRequest").then(ServiceController.class).execute(any(Command.class)));

- whenXPath(
-
"nmwg:message/nmwg:metadata/nmwg:subject/nmwgtopo:endPoint/text()")
-
.then(Command.class).setRouterName(any(String.class));
+
configure(registerToLookupService(ServiceController.class).listAvailableRoutersAndCommands());

-
whenXPath("nmwg:message[@type='SetupDataRequest']/nmwg:metadata/nmwg:eventType/text()")
-
.then(Command.class).setEventType(any(String.class));
+
whenXPath("nmwg:message/nmwg:metadata/nmwg:subject/nmwgtopo:endPoint/text()").then(Command.class)
+ .setRouterName(any(String.class));

- whenXPath(
-
"nmwg:message/nmwg:metadata/nmwg:parameters/nmwg:parameter[@name='command']/@value")
-
.then(Command.class).setName(any(String.class));
+
whenXPath("nmwg:message[@type='SetupDataRequest']/nmwg:metadata/nmwg:eventType/text()").then(
+ Command.class).setEventType(any(String.class));

- whenXPath(
-
"nmwg:message/nmwg:metadata/nmwg:parameters/nmwg:parameter[@name='description']/@value")
-
.then(Command.class).setDescription(any(String.class));
+
whenXPath("nmwg:message/nmwg:metadata/nmwg:parameters/nmwg:parameter[@name='command']/@value").then(
+ Command.class).setName(any(String.class));

- whenXPath(
-
"nmwg:message/nmwg:metadata/nmwg:parameters/nmwg:parameter[@name='syntax']/@value")
-
.then(Command.class).setSyntax(any(String.class));
-
- addSelfTest("connect to
${arg.getAddress().toString()}", "Connected to
${arg.getAddress().toString()}",
ServiceController.class).connect(any(Router.class));
- configureForType(Router.class,
selfTestData(ServiceController.class).listAvailableRoutersAndCommands());
- }
- } catch (Exception ex) {
- }
- }
-
- public boolean isAPT() {
- return usingAPT;
- }
+
whenXPath("nmwg:message/nmwg:metadata/nmwg:parameters/nmwg:parameter[@name='description']/@value")
+
.then(Command.class).setDescription(any(String.class));

- /**
- * Sets timeout in seconds between subsequent
registrations/keepalives to
- * Lookup Service.
- */
- public synchronized void setLookupServiceInterval(String interval) {
- lsInterval = Integer.parseInt(interval);
- scheduler.stop(lsRegistrationTask);
- scheduler.runEvery(lsInterval, lsRegistrationTask);
- }
+
whenXPath("nmwg:message/nmwg:metadata/nmwg:parameters/nmwg:parameter[@name='syntax']/@value").then(
+ Command.class).setSyntax(any(String.class));

- /**
- * Returns timeout in seconds between subsequent
registrations/keepalives to
- * Lookup Service.
- */
- public synchronized int getLookupServiceInterval() {
- return lsInterval;
- }
-
- protected List<String> getLSAddresses() {
- return
Collections.unmodifiableList(lsRegistrationTask.getLSAddresses());
- }
+ addSelfTest("connect to ${arg.getAddress().toString()}",
"Connected to ${arg.getAddress().toString()}",
+ ServiceController.class).connect(any(Router.class));
+ configureForType(Router.class,
selfTestData(ServiceController.class).listAvailableRoutersAndCommands());
+ }
+ } catch (Exception ex) {
+ ex.printStackTrace();
+ }
+ }
+
+ public boolean isAPT() {
+ return usingAPT;
+ }
+
+ /**
+ * Sets timeout in seconds between subsequent registrations/keepalives to
+ * Lookup Service.
+ */
+ public synchronized void setLookupServiceInterval(String interval) {
+ lsInterval = Integer.parseInt(interval);
+ scheduler.stop(lsRegistrationTask);
+ scheduler.runEvery(lsInterval, lsRegistrationTask);
+ }
+
+ /**
+ * Returns timeout in seconds between subsequent
registrations/keepalives to
+ * Lookup Service.
+ */
+ public synchronized int getLookupServiceInterval() {
+ return lsInterval;
+ }
+
+ protected List<String> getLSAddresses() {
+ return
Collections.unmodifiableList(lsRegistrationTask.getLSAddresses());
+ }
}

Modified:
trunk/perfsonar-base/sample-service/src/main/java/net/geant/perfsonar/mp/sshtelnet/ServiceController.java
===================================================================
---
trunk/perfsonar-base/sample-service/src/main/java/net/geant/perfsonar/mp/sshtelnet/ServiceController.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/sample-service/src/main/java/net/geant/perfsonar/mp/sshtelnet/ServiceController.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -16,27 +16,27 @@
* @author <a
href="mailto:">Blazej
Pietrzak</a>
*/
public class ServiceController {
- public ServiceController() { }
-
- @SelfTestData
- @MetadataKey
- @LookupServiceRegister
- public List<Router> listAvailableRoutersAndCommands() throws
UnknownHostException {
- return Arrays.asList(
- new Router("metadata0", "Cisco",
InetAddress.getAllByName("10.10.14.4")[0],
- Command.SHOW_ENVIRONMENT, Command.PING),
- new Router("metadata1", "JuniperGeantAmsterdam",
InetAddress.getByName("10.10.14.5"),
- Command.SHOW_INTERFACES_FILTERS));
- }
-
- @SetupData
- public Command execute(Command command) throws IOException {
- command.execute();
- return command;
- }
-
- @SelfTest(name = "connect to ${arg.getAddress().toString()}",
successMessage = "Connected to ${arg.getAddress().toString()}")
- public void connect(Router router) throws IOException {
- router.connect();
- }
+ public ServiceController() {
+ }
+
+ @SelfTestData
+ @MetadataKey
+ @LookupServiceRegister
+ public List<Router> listAvailableRoutersAndCommands() throws
UnknownHostException {
+ return Arrays.asList(new Router("metadata0", "Cisco",
InetAddress.getAllByName("10.10.14.4")[0], // NOPMD
+ Command.SHOW_ENVIRONMENT, Command.PING),
+ new Router("metadata1", "JuniperGeantAmsterdam",
InetAddress.getByName("10.10.14.5"), // NOPMD
+ Command.SHOW_IFACES_FILTERS));
+ }
+
+ @SetupData
+ public Command execute(Command command) throws IOException {
+ command.execute();
+ return command;
+ }
+
+ @SelfTest(name = "connect to ${arg.getAddress().toString()}",
successMessage = "Connected to ${arg.getAddress().toString()}")
+ public void connect(Router router) throws IOException {
+ router.connect();
+ }
}

Modified:
trunk/perfsonar-base/sample-service/src/main/resources/configuration.xml
===================================================================
--- trunk/perfsonar-base/sample-service/src/main/resources/configuration.xml
2013-05-07 14:18:22 UTC (rev 6370)
+++ trunk/perfsonar-base/sample-service/src/main/resources/configuration.xml
2013-05-08 20:41:45 UTC (rev 6371)
@@ -1,132 +1,115 @@
<?xml version='1.0' encoding='UTF-8'?>

<configuration xmlns="http://service.perfsonar.org/ns/config/base/0.9/";>
- <service name="sshtelnet-mp">
- <lookupInformation>
- <option name="accessPoint"
value="http://localhost:${tomcat.port}/${project.artifactId}/services/SSHTelnet"/>
- <option name="serviceName" value="Geant3 JAVA - SSHTelnet MP"/>
- <option name="serviceType" value="MP"/>
- </lookupInformation>
+ <service name="sshtelnet-mp">
+ <lookupInformation>
+ <option name="accessPoint"
value="http://localhost:${tomcat.port}/${project.artifactId}/services/SSHTelnet";
/>
+ <option name="serviceName" value="Geant3 JAVA - SSHTelnet MP" />
+ <option name="serviceType" value="MP" />
+ </lookupInformation>

- <!-- Message Handlers - message types and service engines -->
+ <!-- Message Handlers - message types and service engines -->

- <messageHandler>
-
- <message type="EchoRequest"
-
handler="org.perfsonar.base2.service.messages.GenericMessageHandler">
- <option name="ServiceEngine"
-
value="org.perfsonar.service.measurementPoint.EchoServiceEngine" />
- <option name="authN" value="no" />
- </message>
-
- <message type="MetadataKeyRequest"
-
handler="org.perfsonar.base2.service.messages.GenericMessageHandler">
- <option name="ServiceEngine"
-
value="org.perfsonar.service.measurementPoint.ServiceCapabilitiesEngine" />
- <option name="authN" value="no" />
- </message>
+ <messageHandler>

- <message type="SetupDataRequest"
-
handler="org.perfsonar.base2.service.messages.GenericMessageHandler">
- <option name="ServiceEngine"
-
value="org.perfsonar.service.measurementPoint.SetupDataServiceEngine" />
- <option name="authN" value="no" />
- </message>
-
- </messageHandler>
+ <message type="EchoRequest"
handler="org.perfsonar.base2.service.messages.GenericMessageHandler">
+ <option name="ServiceEngine"
value="org.perfsonar.service.measurementPoint.EchoServiceEngine" />
+ <option name="authN" value="no" />
+ </message>

- <!-- Additional auxiliary components -->
+ <message type="MetadataKeyRequest"
handler="org.perfsonar.base2.service.messages.GenericMessageHandler">
+ <option name="ServiceEngine"
value="org.perfsonar.service.measurementPoint.ServiceCapabilitiesEngine" />
+ <option name="authN" value="no" />
+ </message>

- <auxiliaryComponents>
- <component name="migrator"
className="org.perfsonar.base2.service.configuration.migration.MigratorComponent">
- <option name="config-directory" value="${old-config-directory}" />
- </component>
- <component name="XMLDB"
className="org.perfsonar.base2.service.storage.xml.XMLDBComponent">
- <option name="dataStorageClassName"
value="org.perfsonar.base2.service.storage.xml.exist.ExistHTTPDataStorage" />
- <option name="uri"
value="http://localhost:${tomcat.port}/exist/rest/db"/>
- <option name="username" value="sshtelnet"/>
- <option name="password" value="sshtelnet"/>
- </component>
-
- <component name="Configuration"
className="org.perfsonar.service.measurementPoint.Configuration">
- <option name="metadata-file"
value="${config.path}/sshtelnetmetadata.xml" />
- <option name="token-path" value="${token.path}" />
- </component>
-
- <!-- auth configuration -->
- <component name="auth"
className="org.perfsonar.base2.service.authn.component.wssec.WSSecAuthNComponent">
- <option name="as_endpoint"
value="http://homer.rediris.es:8080/geant2-java-as-1.2/services/SimpleService"/>
- <option name="comp_id" value="urn:compId"/>
- </component>
-
- <!-- Scheduler -->
- <component name="scheduling"
className="org.perfsonar.base2.service.scheduler.SchedulingComponent">
- <option name="schedulerClassName"
value="org.perfsonar.base2.service.scheduler.SimpleScheduler"/>
- <option name="interval" value="60"/>
+ <message type="SetupDataRequest"
handler="org.perfsonar.base2.service.messages.GenericMessageHandler">
+ <option name="ServiceEngine"
value="org.perfsonar.service.measurementPoint.SetupDataServiceEngine" />
+ <option name="authN" value="no" />
+ </message>

- <actions>
- <action name="registration"
className="org.perfsonar.base2.service.registration.LSRegistrationAction">
- <option name="status" value="on" />
- <option name="interval" value="2" />
- <option name="registerDataSource"
value="org.perfsonar.base2.service.registration.MetadataExistDBRegisterDataSource"/>

- <option name="registerEventType"
value="http://ogf.org/ns/nmwg/tools/org/perfsonar/service/lookup/registration/summary/2.0"/>
- <option name="registrator"
value="org.perfsonar.base2.service.registration.GenericLSRegistrator"/>
- <option name="lsAddress-1"
value="http://localhost:9000/perfsonar-ls"/>
- </action>
-
- <!-- Checks whether a given metadata file has changed and updates
it in the database.
- If the given metadata file is not stored in the database it
is added. -->
- <action name="metadata-updater"
className="org.perfsonar.service.measurementPoint.MetadataUpdater">
- <!-- Should the user configured in the "Configuration" section
be created if it does not exist -->
- <option name="create-user" value="yes" />
-
- <!-- login and password for the user that has rights to create
user accounts. Obligatory only when "create-user" option is set to "yes" -->
- <option name="username" value="admin" />
- <option name="password" value="" />
- </action>
- </actions>
- </component>
- </auxiliaryComponents>
-
- <extension name="registerExtension-registerDataSource">
- <option name="exist-config" value="XMLDB" />
- </extension>
+ </messageHandler>

- <!--
....................................................................................
-->
+ <!-- Additional auxiliary components -->

- <!-- Protocol mappings, XML elements and their bingings -->
+ <auxiliaryComponents>
+ <component name="migrator"
className="org.perfsonar.base2.service.configuration.migration.MigratorComponent">
+ <option name="config-directory"
value="${old-config-directory}" />
+ </component>
+ <component name="XMLDB"
className="org.perfsonar.base2.service.storage.xml.XMLDBComponent">
+ <option name="dataStorageClassName"
value="org.perfsonar.base2.service.storage.xml.exist.ExistHTTPDataStorage" />
+ <option name="uri"
value="http://localhost:${tomcat.port}/exist/rest/db"; />
+ <option name="username" value="sshtelnet" />
+ <option name="password" value="sshtelnet" />
+ </component>

- <protocolMappings>
+ <component name="Configuration"
className="org.perfsonar.service.measurementPoint.Configuration">
+ <option name="metadata-file"
value="${config.path}/sshtelnetmetadata.xml" />
+ <option name="token-path" value="${token.path}" />
+ </component>

+ <!-- auth configuration -->
+ <component name="auth"
className="org.perfsonar.base2.service.authn.component.wssec.WSSecAuthNComponent">
+ <option name="as_endpoint"
value="http://homer.rediris.es:8080/geant2-java-as-1.2/services/SimpleService";
/>
+ <option name="comp_id" value="urn:compId" />
+ </component>

- <!-- default mapping -->
+ <!-- Scheduler -->
+ <component name="scheduling"
className="org.perfsonar.base2.service.scheduler.SchedulingComponent">
+ <option name="schedulerClassName"
value="org.perfsonar.base2.service.scheduler.SimpleScheduler" />
+ <option name="interval" value="60" />

+ <actions>
+ <action name="registration"
className="org.perfsonar.base2.service.registration.LSRegistrationAction">
+ <option name="status" value="on" />
+ <option name="interval" value="2" />
+ <option name="registerDataSource"
value="org.perfsonar.base2.service.registration.MetadataExistDBRegisterDataSource"
/>
+ <option name="registerEventType"
+
value="http://ogf.org/ns/nmwg/tools/org/perfsonar/service/lookup/registration/summary/2.0";
/>
+ <option name="registrator"
value="org.perfsonar.base2.service.registration.GenericLSRegistrator" />
+ <option name="lsAddress-1"
value="http://localhost:9000/perfsonar-ls"; />
+ </action>

- <!-- general mappings -->
- <element name="{*}message"
- mapping="org.perfsonar.base2.xml.nmwg.Message"/>
- <element name="{*}metadata"
- mapping="org.perfsonar.base2.xml.nmwg.Metadata"/>
- <element name="{*}eventType"
- mapping="org.perfsonar.base2.xml.nmwg.EventType"/>
- <element name="{*}data"
- mapping="org.perfsonar.base2.xml.nmwg.Data"/>
- <element name="{*}subject"
- mapping="org.perfsonar.base2.xml.nmwg.Subject"/>
- <element name="{*}parameters"
- mapping="org.perfsonar.base2.xml.nmwg.Parameters"/>
- <element name="{*}parameter"
- mapping="org.perfsonar.base2.xml.nmwg.Parameter"/>
- <element name="*"
- mapping="org.perfsonar.base2.xml.Element"/>
- <element
name="{http://ggf.org/ns/nmwg/tools/org/perfsonar/service/lookup/xquery/1.0/}subject";

- mapping="org.perfsonar.base2.xml.TextElement"/>
-
-
- </protocolMappings>
+ <!-- Checks whether a given metadata file has changed
and updates it in the database. If the given metadata
+ file is not stored in the database it is added. -->
+ <action name="metadata-updater"
className="org.perfsonar.service.measurementPoint.MetadataUpdater">
+ <!-- Should the user configured in the
"Configuration" section be created if it does not exist -->
+ <option name="create-user" value="yes" />

+ <!-- login and password for the user that has rights
to create user accounts. Obligatory only when
+ "create-user" option is set to "yes" -->
+ <option name="username" value="admin" />
+ <option name="password" value="" />
+ </action>
+ </actions>
+ </component>
+ </auxiliaryComponents>

- </service>
+ <extension name="registerExtension-registerDataSource">
+ <option name="exist-config" value="XMLDB" />
+ </extension>

+ <!--
....................................................................................
-->

+ <!-- Protocol mappings, XML elements and their bingings -->
+
+ <protocolMappings>
+ <!-- default mapping -->
+
+
+ <!-- general mappings -->
+ <element name="{*}message"
mapping="org.perfsonar.base2.xml.nmwg.Message" />
+ <element name="{*}metadata"
mapping="org.perfsonar.base2.xml.nmwg.Metadata" />
+ <element name="{*}eventType"
mapping="org.perfsonar.base2.xml.nmwg.EventType" />
+ <element name="{*}data"
mapping="org.perfsonar.base2.xml.nmwg.Data" />
+ <element name="{*}subject"
mapping="org.perfsonar.base2.xml.nmwg.Subject" />
+ <element name="{*}parameters"
mapping="org.perfsonar.base2.xml.nmwg.Parameters" />
+ <element name="{*}parameter"
mapping="org.perfsonar.base2.xml.nmwg.Parameter" />
+ <element name="*" mapping="org.perfsonar.base2.xml.Element" />
+ <element
name="{http://ggf.org/ns/nmwg/tools/org/perfsonar/service/lookup/xquery/1.0/}subject";
+ mapping="org.perfsonar.base2.xml.TextElement" />
+
+ </protocolMappings>
+
+ </service>
+
</configuration>

Modified:
trunk/perfsonar-base/sample-service/src/main/resources/net/geant/perfsonar/mp/sshtelnet/LSRegister.template
===================================================================
---
trunk/perfsonar-base/sample-service/src/main/resources/net/geant/perfsonar/mp/sshtelnet/LSRegister.template
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/sample-service/src/main/resources/net/geant/perfsonar/mp/sshtelnet/LSRegister.template
2013-05-08 20:41:45 UTC (rev 6371)
@@ -11,20 +11,20 @@
</nmwg:subject>
</nmwg:metadata>
<nmwg:data metadataIdRef="serviceLookupInfo">
- <nmwg:metadata id="metadata0">
- <nmwg:subject
id="subject0">DummyCiscoRouter</nmwg:subject>
- <nmwg:parameters id="metaParams0">
- <nmwg:parameter name="class_name"
value="org.perfsonar.service.measurementPoint.lookingGlassType.engine.adapters.CiscoAdapter"
/>
- <nmwg:parameter name="url" value="0.0.0.0" />
- <nmwg:parameter name="port" value="0" />
- <nmwg:parameter name="prompt"
value="DummyRouter&gt;" />
- <nmwg:parameter name="rate" value="500" />
- <nmwg:parameter name="username"
value="dummyUser" />
- <nmwg:parameter name="password"
value="ab05D8Z22537EdEzaWmlmA==" />
- <nmwg:parameter name="timeout" value="10000"
/>
- <nmwg:parameter name="numberOfUsers"
value="0" />
- <nmwg:parameter name="cache" value="0" />
- </nmwg:parameters>
- </nmwg:metadata>
- </nmwg:data>
+ <nmwg:metadata id="metadata0">
+ <nmwg:subject id="subject0">DummyCiscoRouter</nmwg:subject>
+ <nmwg:parameters id="metaParams0">
+ <nmwg:parameter name="class_name"
value="org.perfsonar.service.measurementPoint.lookingGlassType.engine.adapters.CiscoAdapter"
/>
+ <nmwg:parameter name="url" value="0.0.0.0" />
+ <nmwg:parameter name="port" value="0" />
+ <nmwg:parameter name="prompt" value="DummyRouter&gt;" />
+ <nmwg:parameter name="rate" value="500" />
+ <nmwg:parameter name="username" value="dummyUser" />
+ <nmwg:parameter name="password"
value="ab05D8Z22537EdEzaWmlmA==" />
+ <nmwg:parameter name="timeout" value="10000" />
+ <nmwg:parameter name="numberOfUsers" value="0" />
+ <nmwg:parameter name="cache" value="0" />
+ </nmwg:parameters>
+ </nmwg:metadata>
+ </nmwg:data>
</nmwg:message>

Modified:
trunk/perfsonar-base/sample-service/src/main/resources/net/geant/perfsonar/mp/sshtelnet/MetadataKeyResponse.template
===================================================================
---
trunk/perfsonar-base/sample-service/src/main/resources/net/geant/perfsonar/mp/sshtelnet/MetadataKeyResponse.template
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/sample-service/src/main/resources/net/geant/perfsonar/mp/sshtelnet/MetadataKeyResponse.template
2013-05-08 20:41:45 UTC (rev 6371)
@@ -33,4 +33,4 @@
</nmwg:data>
#set( $idx = $idx + 1 )
#end
-</nmwg:message>
\ No newline at end of file
+</nmwg:message>

Modified:
trunk/perfsonar-base/sample-service/src/main/resources/net/geant/perfsonar/mp/sshtelnet/SetupDataResponse.template
===================================================================
---
trunk/perfsonar-base/sample-service/src/main/resources/net/geant/perfsonar/mp/sshtelnet/SetupDataResponse.template
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/sample-service/src/main/resources/net/geant/perfsonar/mp/sshtelnet/SetupDataResponse.template
2013-05-08 20:41:45 UTC (rev 6371)
@@ -2,23 +2,23 @@
<nmwg:message xmlns:nmwg="http://ggf.org/ns/nmwg/base/2.0/";
id="${requestId}_resp" messageIdRef="${requestId}" type="SetupDataResponse">
#set ($idx = 0)
#foreach ($command in $result)
- <nmwg:metadata id="meta${idx}">
- <nmwg:subject id="subject${idx}">
- <nmwgtopo:endPoint
xmlns:nmwgtopo="http://ggf.org/ns/nmwg/topology/2.0/";
type="hostname">${command.routerName}</nmwgtopo:endPoint>
- </nmwg:subject>
- <nmwg:parameters id="params${idx}" />
- <nmwg:eventType>${command.eventType}</nmwg:eventType>
- </nmwg:metadata>
- <nmwg:data id="data${idx}" metadataIdRef="meta${idx}">
- <nmwg:datum>${command.result}</nmwg:datum>
- </nmwg:data>
- <nmwg:metadata id="resultCodeMeta_meta${idx}">
- <nmwg:subject id="resultCodeSubj_meta${idx}"
metadataIdRef="meta${idx}" />
- <nmwg:eventType>success.mp.sshtelnet</nmwg:eventType>
- </nmwg:metadata>
- <nmwg:data id="resultCodeData_meta${idx}"
metadataIdRef="resultCodeMeta_meta${idx}">
- <nmwgr:datum
xmlns:nmwgr="http://ggf.org/ns/nmwg/result/2.0/";>Successfully executed
request</nmwgr:datum>
+ <nmwg:metadata id="meta${idx}">
+ <nmwg:subject id="subject${idx}">
+ <nmwgtopo:endPoint
xmlns:nmwgtopo="http://ggf.org/ns/nmwg/topology/2.0/";
type="hostname">${command.routerName}</nmwgtopo:endPoint>
+ </nmwg:subject>
+ <nmwg:parameters id="params${idx}" />
+ <nmwg:eventType>${command.eventType}</nmwg:eventType>
+ </nmwg:metadata>
+ <nmwg:data id="data${idx}" metadataIdRef="meta${idx}">
+ <nmwg:datum>${command.result}</nmwg:datum>
</nmwg:data>
+ <nmwg:metadata id="resultCodeMeta_meta${idx}">
+ <nmwg:subject id="resultCodeSubj_meta${idx}"
metadataIdRef="meta${idx}" />
+ <nmwg:eventType>success.mp.sshtelnet</nmwg:eventType>
+ </nmwg:metadata>
+ <nmwg:data id="resultCodeData_meta${idx}"
metadataIdRef="resultCodeMeta_meta${idx}">
+ <nmwgr:datum
xmlns:nmwgr="http://ggf.org/ns/nmwg/result/2.0/";>Successfully executed
request</nmwgr:datum>
+ </nmwg:data>
#set ($idx = $idx + 1)
#end
</nmwg:message>

Modified:
trunk/perfsonar-base/sample-service/src/test/java/net/geant/perfsonar/mp/sshtelnet/ConfigurationFileCheckerTest.java
===================================================================
---
trunk/perfsonar-base/sample-service/src/test/java/net/geant/perfsonar/mp/sshtelnet/ConfigurationFileCheckerTest.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/sample-service/src/test/java/net/geant/perfsonar/mp/sshtelnet/ConfigurationFileCheckerTest.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -9,30 +9,29 @@

public class ConfigurationFileCheckerTest {

- private SSHTelnetMPService service;
-
- @Before
- public void givenService() {
- service = new SSHTelnetMPService();
- }
+ private SSHTelnetMPService service;

- @After
- public void tearDown() throws Exception {
- service.stop();
- service = null;
- }
+ @Before
+ public void givenService() {
+ service = new SSHTelnetMPService();
+ }

- @Test
- public void shouldReadLookupServiceInterval() {
- ConfigurationFileChecker config = new
ConfigurationFileChecker(service);
-
- assertTrue(config.isModified());
- assertTrue(config.configurationExists());
-
- config.run();
- assertEquals(2, service.getLookupServiceInterval());
-
-
- }
+ @After
+ public void tearDown() throws Exception {
+ service.stop();
+ service = null;
+ }

+ @Test
+ public void shouldReadLookupServiceInterval() {
+ ConfigurationFileChecker config = new
ConfigurationFileChecker(service);
+
+ assertTrue(config.isModified());
+ assertTrue(config.configurationExists());
+
+ config.run();
+ assertEquals(2, service.getLookupServiceInterval());
+
+ }
+
}

Modified:
trunk/perfsonar-base/sample-service/src/test/java/net/geant/perfsonar/mp/sshtelnet/LSRegisterTest.java
===================================================================
---
trunk/perfsonar-base/sample-service/src/test/java/net/geant/perfsonar/mp/sshtelnet/LSRegisterTest.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/sample-service/src/test/java/net/geant/perfsonar/mp/sshtelnet/LSRegisterTest.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -4,17 +4,18 @@
import net.geant.perfsonar.ls.LSRegisterTestBase;

public class LSRegisterTest extends LSRegisterTestBase {
- private SSHTelnetMPService service;
+ private SSHTelnetMPService service;

- @Override
- protected PerfSONAR givenService() {
- if (service == null)
- service = new SSHTelnetMPService();
- return service;
- }
+ @Override
+ protected PerfSONAR givenService() {
+ if (service == null) {
+ service = new SSHTelnetMPService();
+ }
+ return service;
+ }

- @Override
- protected int getLSInterval() {
- return service.getLookupServiceInterval();
- }
+ @Override
+ protected int getLSInterval() {
+ return service.getLookupServiceInterval();
+ }
}

Modified:
trunk/perfsonar-base/sample-service/src/test/java/net/geant/perfsonar/mp/sshtelnet/SSHTelnetMPTest.java
===================================================================
---
trunk/perfsonar-base/sample-service/src/test/java/net/geant/perfsonar/mp/sshtelnet/SSHTelnetMPTest.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-base/sample-service/src/test/java/net/geant/perfsonar/mp/sshtelnet/SSHTelnetMPTest.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -7,13 +7,9 @@
import static net.geant.perfsonar.messaging.XPathDeserializer.identifier;
import static net.geant.perfsonar.messaging.XPathDeserializer.whenXPath;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;

-import java.io.IOException;
-import java.io.Reader;
import java.net.InetAddress;
import java.net.UnknownHostException;
-import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@@ -33,151 +29,157 @@

protected Logger logger = LoggerFactory.getLogger(getClass());

- static final String REQUEST_ID = "request1";
+ static final String REQUEST_ID = "request1";
private PerfSONARClient client;
- private SSHTelnetMPService service;
+ private SSHTelnetMPService service;

- @Before
- public void givenPerfSONARClient() {
- service = new SSHTelnetMPService();
- client = new PerfSONARClient(service);
- new RouterReference().setCurrentRouter(null);
- }
-
- @After
- public void tearDown() {
- client = null;
- service.stop();
- service = null;
- }
-
- @Test
- public void checkEcho() throws Exception {
- assertEquals(new Response(NMWG.toEchoResponse(REQUEST_ID)),
client.echo(REQUEST_ID));
- }
+ @Before
+ public void givenPerfSONARClient() {
+ service = new SSHTelnetMPService();
+ client = new PerfSONARClient(service);
+ new RouterReference().setCurrentRouter(null);
+ }

- @Test
- public void checkSelfTest() throws Exception {
- assertEquals(Arrays.asList(
- failure("connect to /10.10.14.4", "Not implemented
yet.", "SSHTELNET", "MP"),
- failure("connect to /10.10.14.5", "Not implemented
yet.", "SSHTELNET", "MP")),
- sort(client.selfTest(REQUEST_ID)));
- }
+ @After
+ public void tearDown() {
+ client = null;
+ service.stop();
+ service = null;
+ }

- private <T> List<T> sort(List<T> list) {
- @SuppressWarnings("unchecked")
- final T[] result = (T[]) list.toArray();
- Arrays.sort(result);
- return Arrays.asList(result);
- }
+ @Test
+ public void checkEcho() throws Exception {
+ assertEquals(new Response(NMWG.toEchoResponse(REQUEST_ID)),
client.echo(REQUEST_ID));
+ }

- @Test
- public void checkMetadataKey() throws Exception {
- configureResponseDeserialization();
-
- final XPathDeserializer deserializer = new
XPathDeserializer();
-
- @SuppressWarnings("unchecked")
- final List<Object> actual = (List<Object>)
deserializer.deserialize(new
InputSource(client.listAvailableCommands(REQUEST_ID).getReader()));
-
- assertEquals(Arrays.asList(Command.SHOW_ENVIRONMENT,
Command.PING, Command.SHOW_INTERFACES_FILTERS),
deserializer.getObjects(Command.class, actual));
-
- assertEquals(Arrays.asList(
- new Router("metadata0", "Cisco",
InetAddress.getAllByName("10.10.14.4")[0], Command.SHOW_ENVIRONMENT,
Command.PING),
- new Router("metadata1", "JuniperGeantAmsterdam",
InetAddress.getByName("10.10.14.5"), Command.SHOW_INTERFACES_FILTERS)),
-
- deserializer.getObjects(Router.class, actual));
- }
+ @Test
+ public void checkSelfTest() throws Exception {
+ assertEquals(
+ Arrays.asList(failure("connect to /10.10.14.4", "Not
implemented yet.", "SSHTELNET", "MP"),
+ failure("connect to /10.10.14.5", "Not implemented
yet.", "SSHTELNET", "MP")),
+ sort(client.selfTest(REQUEST_ID)));
+ }

- private void configureResponseDeserialization() throws
InstantiationException,
- IllegalAccessException, UnknownHostException {
-
- if (service.isAPT())
- return;
-
- declarePrefix("nmwg", "http://ggf.org/ns/nmwg/base/2.0/";);
- declarePrefix("nmwgr", "http://ggf.org/ns/nmwg/result/2.0/";);
- declarePrefix("nmwgtopo",
"http://ggf.org/ns/nmwg/topology/2.0/";);
+ private <T> List<T> sort(List<T> list) {
+ @SuppressWarnings("unchecked")
+ final T[] result = (T[]) list.toArray();
+ Arrays.sort(result);
+ return Arrays.asList(result);
+ }

-
whenXPath("nmwg:message[@type='MetadataKeyResponse']/nmwg:metadata[nmwg:parameters]/@id")
- .then(Router.class).setId(any(String.class));
+ @Test
+ public void checkMetadataKey() throws Exception {
+ configureResponseDeserialization();

- whenXPath(
-
"nmwg:message[@type='MetadataKeyResponse']/nmwg:metadata[nmwg:parameters]/nmwg:subject/text()")
-
.then(Router.class).setName(any(String.class));
+ final XPathDeserializer deserializer = new XPathDeserializer();

- whenXPath(
-
"nmwg:message[@type='MetadataKeyResponse']/nmwg:metadata/nmwg:parameters/nmwg:parameter[@name='url']/@value")
-
.then(Router.class).setAddress(any(String.class));
+ @SuppressWarnings("unchecked")
+ final List<Object> actual = (List<Object>)
deserializer.deserialize(new InputSource(client
+ .listAvailableCommands(REQUEST_ID).getReader()));

- whenXPath(
-
"nmwg:message[@type='MetadataKeyResponse']/nmwg:data/@metadataIdRef")
- .then(RouterReference.class).setCurrentRouter(
- getReference(Router.class,
identifier(Router.class).getId()));
+ assertEquals(Arrays.asList(Command.SHOW_ENVIRONMENT, Command.PING,
Command.SHOW_IFACES_FILTERS),
+ deserializer.getObjects(Command.class, actual));

- whenXPath(
-
"nmwg:message/nmwg:data[starts-with(@metadataIdRef,
'metadata')]/nmwgr:datum/nmwg:parameters/nmwg:parameter[@name='command']/@value")
-
.then(Command.class).setName(any(String.class));
+ assertEquals(Arrays.asList(new Router("metadata0", "Cisco",
InetAddress.getAllByName("10.10.14.4")[0],
+ Command.SHOW_ENVIRONMENT, Command.PING),
+ new Router("metadata1", "JuniperGeantAmsterdam",
InetAddress.getByName("10.10.14.5"),
+ Command.SHOW_IFACES_FILTERS)),

- whenXPath(
-
"nmwg:message/nmwg:data[starts-with(@metadataIdRef,
'metadata')]/nmwgr:datum/nmwg:parameters/nmwg:parameter[@name='description']/@value")
-
.then(Command.class).setDescription(any(String.class));
+ deserializer.getObjects(Router.class, actual));
+ }

- whenXPath(
-
"nmwg:message/nmwg:data[starts-with(@metadataIdRef,
'metadata')]/nmwgr:datum/nmwg:parameters/nmwg:parameter[@name='syntax']/@value")
-
.then(Command.class).setSyntax(any(String.class));
-
- whenXPath(
-
"nmwg:message[@type='MetadataKeyResponse']/nmwg:data/nmwgr:datum/nmwg:eventType/text()")
-
.then(Command.class).setEventType(any(String.class));
-
- //SetupData
-
whenXPath("nmwg:message/nmwg:metadata/nmwg:parameters/nmwg:parameter[@name='command']/@value")
-
.then(Command.class).setName(any(String.class));
-
-
whenXPath("nmwg:message/nmwg:metadata/nmwg:parameters/nmwg:parameter[@name='description']/@value")
-
.then(Command.class).setDescription(any(String.class));
-
-
whenXPath("nmwg:message/nmwg:metadata/nmwg:parameters/nmwg:parameter[@name='syntax']/@value")
-
.then(Command.class).setSyntax(any(String.class));
-
-
whenXPath("nmwg:message[@type='SetupDataResponse']/nmwg:metadata[nmwg:subject/nmwgtopo:endPoint]/@id")
- .then(Command.class).setId(any(String.class));
-
- whenXPath(
-
"nmwg:message[@type='SetupDataResponse']/nmwg:metadata/nmwg:subject/nmwgtopo:endPoint/text()")
-
.then(Command.class).setRouterName(any(String.class));
-
- whenXPath(
-
"nmwg:message[@type='SetupDataResponse']/nmwg:metadata[nmwg:subject/nmwgtopo:endPoint]/nmwg:eventType/text()")
-
.then(Command.class).setEventType(any(String.class));
-
- whenXPath(
-
"nmwg:message/nmwg:data[starts-with(@metadataIdRef,
'meta')]/nmwg:datum/text()")
-
.then(Command.class).setResult(any(String.class));
- }
+ private void configureResponseDeserialization() throws
InstantiationException, IllegalAccessException,
+ UnknownHostException {

- @Test
- public void checkSetupDataRequest() throws Exception {
- final Command command1 = new
Command(Command.SHOW_ENVIRONMENT, "host1");
- final Command command2 = new Command(Command.PING_IPV6,
"host2");
-
- configureResponseDeserialization();
- final XPathDeserializer deserializer = new
XPathDeserializer();
-
- @SuppressWarnings("unchecked")
- final List<Object> actual = (List<Object>)
deserializer.deserialize(new InputSource(client.executeCommands(REQUEST_ID,
command1, command2).getReader()));
-
- command1.setResult("For address family: IPv4 Unicast@@@@@@For
address family: IPv6 Unicast@@@@@@For address family: VPNv4 Unicast@@@@@@For
address family: IPv4 Multicast@@@@@@For address family: IPv6
Multicast@@@@@@For address family: NSAP Unicast@@@---END---");
- command2.setResult("For address family: IPv4 Unicast@@@@@@For
address family: IPv6 Unicast@@@@@@For address family: VPNv4 Unicast@@@@@@For
address family: IPv4 Multicast@@@@@@For address family: IPv6
Multicast@@@@@@For address family: NSAP Unicast@@@---END---");
- resetUnneededFields(command1);
- resetUnneededFields(command2);
- assertEquals(Arrays.asList(command1, command2),
deserializer.getObjects(Command.class, actual));
- }
+ if (service.isAPT()) {
+ return;
+ }

- private void resetUnneededFields(Command cmd) {
- cmd.setDescription(null);
- cmd.setName(null);
- cmd.setSyntax(null);
- }
+ declarePrefix("nmwg", "http://ggf.org/ns/nmwg/base/2.0/";);
+ declarePrefix("nmwgr", "http://ggf.org/ns/nmwg/result/2.0/";);
+ declarePrefix("nmwgtopo", "http://ggf.org/ns/nmwg/topology/2.0/";);
+
+
whenXPath("nmwg:message[@type='MetadataKeyResponse']/nmwg:metadata[nmwg:parameters]/@id").then(Router.class)
+ .setId(any(String.class));
+
+
whenXPath("nmwg:message[@type='MetadataKeyResponse']/nmwg:metadata[nmwg:parameters]/nmwg:subject/text()").then(
+ Router.class).setName(any(String.class));
+
+ whenXPath(
+
"nmwg:message[@type='MetadataKeyResponse']/nmwg:metadata/nmwg:parameters/nmwg:parameter[@name='url']/@value")
+ .then(Router.class).setAddress(any(String.class));
+
+
whenXPath("nmwg:message[@type='MetadataKeyResponse']/nmwg:data/@metadataIdRef").then(RouterReference.class)
+ .setCurrentRouter(getReference(Router.class,
identifier(Router.class).getId()));
+
+ whenXPath(
+ "nmwg:message/nmwg:data[starts-with(@metadataIdRef,
'metadata')]"
+ +
"/nmwgr:datum/nmwg:parameters/nmwg:parameter[@name='command']/@value")
+ .then(Command.class).setName(any(String.class));
+
+ whenXPath(
+ "nmwg:message/nmwg:data[starts-with(@metadataIdRef,
'metadata')]"
+ +
"/nmwgr:datum/nmwg:parameters/nmwg:parameter[@name='description']/@value")
+ .then(Command.class).setDescription(any(String.class));
+
+ whenXPath(
+ "nmwg:message/nmwg:data[starts-with(@metadataIdRef,
'metadata')]"
+ +
"/nmwgr:datum/nmwg:parameters/nmwg:parameter[@name='syntax']/@value")
+ .then(Command.class).setSyntax(any(String.class));
+
+
whenXPath("nmwg:message[@type='MetadataKeyResponse']/nmwg:data/nmwgr:datum/nmwg:eventType/text()").then(
+ Command.class).setEventType(any(String.class));
+
+ // SetupData
+
whenXPath("nmwg:message/nmwg:metadata/nmwg:parameters/nmwg:parameter[@name='command']/@value").then(
+ Command.class).setName(any(String.class));
+
+
whenXPath("nmwg:message/nmwg:metadata/nmwg:parameters/nmwg:parameter[@name='description']/@value").then(
+ Command.class).setDescription(any(String.class));
+
+
whenXPath("nmwg:message/nmwg:metadata/nmwg:parameters/nmwg:parameter[@name='syntax']/@value").then(
+ Command.class).setSyntax(any(String.class));
+
+
whenXPath("nmwg:message[@type='SetupDataResponse']/nmwg:metadata[nmwg:subject/nmwgtopo:endPoint]/@id").then(
+ Command.class).setId(any(String.class));
+
+
whenXPath("nmwg:message[@type='SetupDataResponse']/nmwg:metadata/nmwg:subject/nmwgtopo:endPoint/text()").then(
+ Command.class).setRouterName(any(String.class));
+
+ whenXPath(
+
"nmwg:message[@type='SetupDataResponse']/nmwg:metadata[nmwg:subject/nmwgtopo:endPoint]/nmwg:eventType/text()")
+ .then(Command.class).setEventType(any(String.class));
+
+ whenXPath("nmwg:message/nmwg:data[starts-with(@metadataIdRef,
'meta')]/nmwg:datum/text()").then(Command.class)
+ .setResult(any(String.class));
+ }
+
+ @Test
+ public void checkSetupDataRequest() throws Exception {
+ final Command command1 = new Command(Command.SHOW_ENVIRONMENT,
"host1");
+ final Command command2 = new Command(Command.PING_IPV6, "host2");
+
+ configureResponseDeserialization();
+ final XPathDeserializer deserializer = new XPathDeserializer();
+
+ @SuppressWarnings("unchecked")
+ final List<Object> actual = (List<Object>)
deserializer.deserialize(new InputSource(client.executeCommands(
+ REQUEST_ID, command1, command2).getReader()));
+
+ command1.setResult("For address family: IPv4 Unicast@@@@@@For
address family: IPv6 Unicast@@@@@@"
+ + "For address family: VPNv4 Unicast@@@@@@For address
family: IPv4 Multicast@@@@@@For address family: IPv6 Multicast@@@@@@"
+ + "For address family: NSAP Unicast@@@---END---");
+ command2.setResult("For address family: IPv4 Unicast@@@@@@For
address family: IPv6 Unicast@@@@@@"
+ + "For address family: VPNv4 Unicast@@@@@@For address
family: IPv4 Multicast@@@@@@For address family: IPv6 Multicast@@@@@@"
+ + "For address family: NSAP Unicast@@@---END---");
+ resetUnneededFields(command1);
+ resetUnneededFields(command2);
+ assertEquals(Arrays.asList(command1, command2),
deserializer.getObjects(Command.class, actual));
+ }
+
+ private void resetUnneededFields(Command cmd) {
+ cmd.setDescription(null);
+ cmd.setName(null);
+ cmd.setSyntax(null);
+ }
}

Modified:
trunk/perfsonar-java-rrd-ma-SQL_backend/src/main/java/org/perfsonar/service/temp/FetchData.java
===================================================================
---
trunk/perfsonar-java-rrd-ma-SQL_backend/src/main/java/org/perfsonar/service/temp/FetchData.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-java-rrd-ma-SQL_backend/src/main/java/org/perfsonar/service/temp/FetchData.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -13,12 +13,8 @@
public class FetchData
{
private final ConnectionTester ct = new ConnectionTester();
- private String resultXML = ""; // tutaj bedziemy budowac wynikowy xml
message
private final List<Metadata> metadataList = new ArrayList<Metadata>();

- private List<String> metadataStringList = new ArrayList<String>();
- private List<String> dataStringList = new ArrayList<String>();
-
private Statement statement;

private String metadataContent;
@@ -47,8 +43,6 @@
+ " xmlns=\"http://ggf.org/ns/nmwg/base/2.0/\";>\n";
StringBuilder sb = new StringBuilder();
sb.append(metadataContent);
- String metadataS = "";
- String dataS = "";

try {
statement = conn.createStatement();
@@ -58,7 +52,6 @@
while (!rs.isLast()) {
rs.next();
sb.append(fetchMetadataRowNmwg(rs));
- //metadataStringList.add(fetchMetadataRowNmwg(rs));
}


@@ -67,16 +60,8 @@
while (!rs.isLast()) {
rs.next();
sb.append(fetchDataRowNmwg(rs));
- //dataStringList.add(fetchDataRowNmwg(rs));
}

- /*
- for (Iterator iterator = metadataStringList.iterator();
iterator.hasNext();) {
- String m = (String) iterator.next();
- metadataContent = metadataContent.concat(m);
- }
- */
-
sb.append("</nmwg:message>");
metadataContent = sb.toString();
conn.close();
@@ -167,7 +152,6 @@

public String fetchDataRowNmwg(ResultSet rs)
{
- String data = "";
StringBuilder sb = new StringBuilder();
try {
sb.append("<nmwg:data
xmlns:nmwg=\"http://ggf.org/ns/nmwg/base/2.0/\"; id=\"").append(

Modified:
trunk/perfsonar-java-rrd-ma-SQL_backend/src/main/resources/perfsonar/conf/rrdma_db.sql
===================================================================
---
trunk/perfsonar-java-rrd-ma-SQL_backend/src/main/resources/perfsonar/conf/rrdma_db.sql
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-java-rrd-ma-SQL_backend/src/main/resources/perfsonar/conf/rrdma_db.sql
2013-05-08 20:41:45 UTC (rev 6371)
@@ -36,4 +36,3 @@
dataSourceMinValue VARCHAR(20),
dataSourceMaxValue VARCHAR(20),
PRIMARY KEY (metadataId));
-
\ No newline at end of file

Modified:
trunk/perfsonar-java-rrd-ma-SQL_backend/src/main/resources/perfsonar/conf/test_rrdma_db.sql
===================================================================
---
trunk/perfsonar-java-rrd-ma-SQL_backend/src/main/resources/perfsonar/conf/test_rrdma_db.sql
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-java-rrd-ma-SQL_backend/src/main/resources/perfsonar/conf/test_rrdma_db.sql
2013-05-08 20:41:45 UTC (rev 6371)
@@ -3,7 +3,7 @@
# You can install this testing DB content by running:
# mysql -u root -p < test_rrdma_db.sql

-USE perfsonar_rrdma
+USE perfsonar_rrdma

INSERT
INTO interfaces
@@ -46,4 +46,3 @@
'1000000000', 'project:geant2',
'http://ggf.org/ns/nmwg/characteristic/utilization/2.0',

'/usr/lib/perfsonar/services/perfsonar-java-rrd-ma/WEB-INF/samples/rrd/test.rrd',
'inoctets', 'Bps', '300', 'ABSOLUTE', '100', '0', '10000000');
-


Property changes on: trunk/perfsonar-java-rrd-ma-base3
___________________________________________________________________
Modified: svn:ignore
- logs
velocity.log*
target
.apt_generated
.settings

.classpath

.project

.checkstyle

.ruleset

.pmd

+ logs
velocity.log*
target
.apt_generated
.settings

.classpath

.project

.checkstyle

.ruleset

.pmd

.pmdruleset


Modified: trunk/perfsonar-java-rrd-ma-base3/pom.xml
===================================================================
--- trunk/perfsonar-java-rrd-ma-base3/pom.xml 2013-05-07 14:18:22 UTC (rev
6370)
+++ trunk/perfsonar-java-rrd-ma-base3/pom.xml 2013-05-08 20:41:45 UTC (rev
6371)
@@ -69,26 +69,6 @@
</webResources>
</configuration>
</plugin>
-
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
-
<artifactId>maven-checkstyle-plugin</artifactId>
- </plugin>
-
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-pmd-plugin</artifactId>
- </plugin>
-
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>findbugs-maven-plugin</artifactId>
- </plugin>
-
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-site-plugin</artifactId>
- </plugin>
</plugins>

</build>

Modified:
trunk/perfsonar-java-rrd-ma-base3/src/test/java/net/geant/perfsonar/ma/rrd/RRDMATest.java
===================================================================
---
trunk/perfsonar-java-rrd-ma-base3/src/test/java/net/geant/perfsonar/ma/rrd/RRDMATest.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-java-rrd-ma-base3/src/test/java/net/geant/perfsonar/ma/rrd/RRDMATest.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -1,8 +1,6 @@
package net.geant.perfsonar.ma.rrd;

import static org.junit.Assert.assertEquals;
-import static net.geant.perfsonar.messaging.SelfTestResult.failure;
-import static net.geant.perfsonar.messaging.SelfTestResult.success;

import java.io.IOException;
import java.io.Reader;
@@ -13,8 +11,6 @@
import net.geant.perfsonar.helpers.Response;
import net.geant.perfsonar.ma.RRDMAService;
import net.geant.perfsonar.ma.RRDMAServiceController;
-import net.geant.perfsonar.messaging.DeserializationException;
-import net.geant.perfsonar.messaging.SelfTestResult;

import org.junit.Before;
import org.junit.Ignore;


Property changes on:
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component
___________________________________________________________________
Modified: svn:ignore
- target

.project

.classpath

.settings

+ target

.project

.classpath

.settings

.pmd

.pmdruleset


Modified:
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/config/HTMLGenerator.java
===================================================================
---
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/config/HTMLGenerator.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/config/HTMLGenerator.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -24,472 +24,502 @@

public class HTMLGenerator {

- private final Logger logger = LoggerFactory.getLogger(getClass());
+ private final Logger logger = LoggerFactory.getLogger(getClass());

- public enum UIType {
- DROPDOWN, RADIO, RADIOGROUP, TEXTBOX, PASSOWRD;
- public static UIType fromString(String s) {
- s = s.toLowerCase();
- if (s.equals("dropdown"))
- return DROPDOWN;
- else if (s.equals("radio"))
- return RADIO;
- else if (s.equals("radiogroup"))
- return RADIOGROUP;
- else if (s.equals("textbox"))
- return TEXTBOX;
- else if (s.equals("password"))
- return PASSOWRD;
- else
- throw new RuntimeException("Bad string");
- }
+ public enum UIType {
+ DROPDOWN, RADIO, RADIOGROUP, TEXTBOX, PASSOWRD;
+ public static UIType fromString(String s) {
+ if (s.equalsIgnoreCase("dropdown")) {
+ return DROPDOWN;
+ } else if (s.equalsIgnoreCase("radio")) {
+ return RADIO;
+ } else if (s.equalsIgnoreCase("radiogroup")) {
+ return RADIOGROUP;
+ } else if (s.equalsIgnoreCase("textbox")) {
+ return TEXTBOX;
+ } else if (s.equalsIgnoreCase("password")) {
+ return PASSOWRD;
+ } else {
+ // TODO: We should use perfSONAR exceptions (check the whole
class/file)
+ throw new RuntimeException("Bad string");
+ }
+ }

- public String toString() {
- switch (this) {
- case DROPDOWN:
- return "dropdown";
- case RADIO:
- return "radio";
- case RADIOGROUP:
- return "radiogroup";
- case TEXTBOX:
- return "textbox";
- case PASSOWRD:
- return "password";
- }
- return "";
- }
- };
+ public String toString() {
+ switch (this) {
+ case DROPDOWN:
+ return "dropdown";
+ case RADIO:
+ return "radio";
+ case RADIOGROUP:
+ return "radiogroup";
+ case TEXTBOX:
+ return "textbox";
+ case PASSOWRD:
+ return "password";
+ default:
+ break;
+ }
+ return "";
+ }
+ };

- private StringBuffer htmlOutput = null;
- private boolean plainContext = true;
- private ObjectMap objectMap = null;
- private HTMLUtil htmlUtil = null;
+ private StringBuffer htmlOutput = null;
+ private boolean plainContext = true;
+ private ObjectMap objectMap = null;
+ private HTMLUtil htmlUtil = null;

- private String[] getLinksList(List<LinkType> blist, boolean big,
- boolean advanced) {
- String basic = "";
- List<String> result = new ArrayList<String>();
+ private String[] getLinksList(List<LinkType> blist, boolean big, boolean
advanced) {
+ String basic = "";
+ List<String> result = new ArrayList<String>();

- if (big) {
- String cls = advanced ? "configheadinglavender" :
"configheading";
- for (Object o : blist) {
- LinkType l = (LinkType) o;
+ if (big) {
+ String cls = advanced ? "configheadinglavender" :
"configheading";
+ for (Object o : blist) {
+ LinkType l = (LinkType) o;

- String pageId = l.getPageId();
- String servletId = l.getServletId();
-
- if (pageId != null) {
- basic = HTMLUtil.tag("tr",
HTMLUtil.tag("td", HTMLUtil.att("class", cls),
-
HTMLUtil.tag("p", HTMLUtil.tag("a",
-
HTMLUtil.att("href", "config?page=" + pageId)
- +
HTMLUtil.att("target", "_self"), l.getTitle()))
- +
HTMLUtil.tag("p", "&nbsp")
- + HTMLUtil.tag("p",
"&nbsp")))
- + "\n";
- } else if (servletId != null) {
- basic = HTMLUtil.tag("tr",
HTMLUtil.tag("td", HTMLUtil.att("class", cls),
-
HTMLUtil.tag("p", HTMLUtil.tag("a",
-
HTMLUtil.att("href", servletId)
- +
HTMLUtil.att("target", "_self"), l.getTitle()))
- +
HTMLUtil.tag("p", "&nbsp")
- + HTMLUtil.tag("p",
"&nbsp")))
- + "\n";
- } else {
- basic = HTMLUtil.tag("tr",
HTMLUtil.tag("td", HTMLUtil.att("class", cls),
-
HTMLUtil.tag("p", HTMLUtil.tag("a",
-
HTMLUtil.att("href", l.getRedirectTo())
- +
HTMLUtil.att("target", "_blank"), l.getTitle()))
- +
HTMLUtil.tag("p", "&nbsp")
- + HTMLUtil.tag("p",
"&nbsp")))
- + "\n";
- }
- result.add(basic);
- }
- } else {
- for (Object o : blist) {
- LinkType l = (LinkType) o;
+ String pageId = l.getPageId();
+ String servletId = l.getServletId();

- String pageId = l.getPageId();
- String servletId = l.getServletId();
+ if (pageId != null) {
+ basic = HTMLUtil.tag(
+ "tr",
+ HTMLUtil.tag(
+ "td",
+ HTMLUtil.att("class", cls),
+ HTMLUtil.tag(
+ "p",
+ HTMLUtil.tag(
+ "a",
+ HTMLUtil.att("href",
"config?page=" + pageId)
+ +
HTMLUtil.att("target", "_self"), l.getTitle()))
+ + HTMLUtil.tag("p", "&nbsp") +
HTMLUtil.tag("p", "&nbsp")))
+ + "\n";
+ } else if (servletId != null) {
+ basic = HTMLUtil.tag(
+ "tr",
+ HTMLUtil.tag(
+ "td",
+ HTMLUtil.att("class", cls),
+ HTMLUtil.tag("p", HTMLUtil.tag("a",
+ HTMLUtil.att("href", servletId)
+ HTMLUtil.att("target", "_self"),
+ l.getTitle()))
+ + HTMLUtil.tag("p", "&nbsp") +
HTMLUtil.tag("p", "&nbsp")))
+ + "\n";
+ } else {
+ basic = HTMLUtil.tag(
+ "tr",
+ HTMLUtil.tag(
+ "td",
+ HTMLUtil.att("class", cls),
+ HTMLUtil.tag(
+ "p",
+ HTMLUtil.tag(
+ "a",
+ HTMLUtil.att("href",
l.getRedirectTo())
+ +
HTMLUtil.att("target", "_blank"), l.getTitle()))
+ + HTMLUtil.tag("p", "&nbsp") +
HTMLUtil.tag("p", "&nbsp")))
+ + "\n";
+ }
+ result.add(basic);
+ }
+ } else {
+ for (Object o : blist) {
+ LinkType l = (LinkType) o;

- if (pageId != null) {
- basic = HTMLUtil.tag("a",
HTMLUtil.att("href", "config?page=" + pageId)
- +
HTMLUtil.att("target", "_self"), l.getTitle())
- + "<br/>";
- } else if (servletId != null) {
- basic = HTMLUtil.tag("a",
HTMLUtil.att("href", servletId)
- +
HTMLUtil.att("target", "_self"), l.getTitle())
- + "<br/>";
- } else {
- basic = HTMLUtil.tag("a",
HTMLUtil.att("href", l.getRedirectTo())
- +
HTMLUtil.att("target", "_blank"), l.getTitle())
- + "<br/>";
- }
+ String pageId = l.getPageId();
+ String servletId = l.getServletId();

- if (!basic.equals("")) {
- result.add("<p><span
class=\"navtex\">" + basic
- + "</span> </p>");
- }
- }
- }
+ if (pageId != null) {
+ basic = HTMLUtil.tag("a",
+ HTMLUtil.att("href", "config?page=" + pageId) +
HTMLUtil.att("target", "_self"),
+ l.getTitle())
+ + "<br/>";
+ } else if (servletId != null) {
+ basic = HTMLUtil.tag("a", HTMLUtil.att("href",
servletId) + HTMLUtil.att("target", "_self"),
+ l.getTitle())
+ + "<br/>";
+ } else {
+ basic = HTMLUtil.tag("a",
+ HTMLUtil.att("href", l.getRedirectTo()) +
HTMLUtil.att("target", "_blank"), l.getTitle())
+ + "<br/>";
+ }

- return result.toArray(new String[result.size()]);
- }
+ if (!basic.equals("")) {
+ result.add("<p><span class=\"navtex\">" + basic +
"</span> </p>");
+ }
+ }
+ }

- public String[] getBasicLinks(ObjectMap o, boolean big) {
- WebAdminInterface wai;
- if (o == null)
- throw new RuntimeException("Null object map");
- else if ((wai = o.getWA()) == null)
- throw new RuntimeException("Null web admin
interface");
- return getLinksList(wai.getBasiclink(), big, false);
- }
+ return result.toArray(new String[result.size()]);
+ }

- public String getServiceName(ObjectMap o) {
- WebAdminInterface wai;
- if (o == null)
- throw new RuntimeException("Null object map");
- else if ((wai = o.getWA()) == null)
- throw new RuntimeException("Null web admin
interface");
- return wai.getServiceInformation().getServiceName();
- }
+ public String[] getBasicLinks(ObjectMap o, boolean big) {
+ if (o == null) {
+ logger.warn("ObjectMap is null, cannot process");
+ throw new RuntimeException("Null object map");
+ }
+ if (o.getWA() == null) {
+ throw new RuntimeException("Null web admin interface");
+ }
+ return getLinksList(o.getWA().getBasiclink(), big, false);
+ }

- public String getVersion(ObjectMap o) {
- WebAdminInterface wai;
- if (o == null)
- throw new RuntimeException("Null object map");
- else if ((wai = o.getWA()) == null)
- throw new RuntimeException("Null web admin
interface");
- return wai.getServiceInformation().getVersion();
- }
+ public String getServiceName(ObjectMap o) {
+ if (o == null) {
+ logger.warn("ObjectMap is null, cannot process");
+ throw new RuntimeException("Null object map");
+ }
+ if (o.getWA() == null) {
+ logger.warn("WebAdminInterface is null, cannot process");
+ throw new RuntimeException("Null web admin interface");
+ }
+ return o.getWA().getServiceInformation().getServiceName();
+ }

- public String[] getAdvancedLinks(ObjectMap o, boolean big) {
- WebAdminInterface wai;
- if (o == null) {
- logger.warn("ObjectMap is null, cannot process");
- throw new RuntimeException("Null object map");
- }
- else if ((wai = o.getWA()) == null) {
- logger.warn("WebAdminInterface is null, cannot
process");
- throw new RuntimeException("Null web admin
interface");
- }
- return getLinksList(wai.getAdvancedlink(), big, true);
- }
+ public String getVersion(ObjectMap o) {
+ if (o == null) {
+ logger.warn("ObjectMap is null, cannot process");
+ throw new RuntimeException("Null object map");
+ } else if (o.getWA() == null) {
+ logger.warn("WebAdminInterface is null, cannot process");
+ throw new RuntimeException("Null web admin interface");
+ }
+ return o.getWA().getServiceInformation().getVersion();
+ }

- /**
- * Look for a given pageName in the ObjectMap, translate it to HTML
code and output it to the outputStream
- * @param pageName
- * @param o
- * @param outputStream
- * @return
- */
- public boolean translate(String pageName, ObjectMap o, StringBuffer
out) {
- //TODO: wouldn't it be better to have objectMap set in the
constructor?
- objectMap = o;
- WebAdminInterface wai = objectMap.getWA();
- if (wai == null) {
- logger.warn("Cannot translate a null
WebAdminInterface.");
- return false;
- }
+ public String[] getAdvancedLinks(ObjectMap o, boolean big) {
+ if (o == null) {
+ logger.warn("ObjectMap is null, cannot process");
+ throw new RuntimeException("Null object map");
+ }
+ if (o.getWA() == null) {
+ logger.warn("WebAdminInterface is null, cannot process");
+ throw new RuntimeException("Null web admin interface");
+ }
+ return getLinksList(o.getWA().getAdvancedlink(), big, true);
+ }

- // We copy the output buffer, so we can play around with
it... FIXME We really shouldn't do that, all too tricky
- htmlOutput = out;
- htmlUtil = new HTMLUtil(out);
- List<PageType> pageList = wai.getPage();
- for (int i = 0, sz = pageList.size(); i < sz; i++) {
- // We look for the requested page
- PageType page = pageList.get(i);
- if (raw(getData(page.getPageId())).equals(pageName)) {
- logger.debug("Let's process page \"" +
pageName + "\"");
- return translate(page);
- }
- }
- String errMsg = "We haven't found page \"" + pageName + "\"
in the WebAdminInterface object.";
- logger.warn(errMsg);
- htmlUtil.errorBox(errMsg);
- return false;
- }
+ /**
+ * Look for a given pageName in the ObjectMap, translate it to HTML code
and
+ * output it to the outputStream
+ *
+ * @param pageName
+ * @param o
+ * @param outputStream
+ * @return
+ */
+ public boolean translate(String pageName, ObjectMap o, StringBuffer out)
{
+ // TODO: wouldn't it be better to have objectMap set in the
constructor?
+ objectMap = o;
+ WebAdminInterface wai = objectMap.getWA();
+ if (wai == null) {
+ logger.warn("Cannot translate a null WebAdminInterface.");
+ return false;
+ }

- /**
- * Translate a given page object to HTML code
- * @param page
- */
- public boolean translate(PageType page) {
- if (page == null) {
- logger.warn("Cannot translate a null page.");
- return false;
- }
- GroupsType groups = page.getGroups();
- List<PlainType> plain = page.getPlain();
- boolean result;
- if (groups != null) {
- logger.debug("The page contains groups");
- // We first have groups of elements
- boolean oldContext = plainContext;
- plainContext = false;
- result = translate(groups);
- plainContext = oldContext;
- } else if (plain != null) {
- logger.debug("The page contains plain elements");
- boolean oldContext = plainContext;
- plainContext = true;
- for (int i = 0, sz = plain.size(); i < sz; i++) {
- // We translate each plain element
- translate((PlainType) plain.get(i));
- }
- plainContext = oldContext;
- result = true;
- } else {
- String errMsg = "Page \"" + page.getPageId() + "\"
doesn't contain any groups nor plain elements.";
- logger.warn(errMsg);
- htmlUtil.errorBox(errMsg);
- result = false;
- }
- return result;
- }
+ // We copy the output buffer, so we can play around with it... FIXME
We
+ // really shouldn't do that, all too tricky
+ htmlOutput = out;
+ htmlUtil = new HTMLUtil(out);
+ List<PageType> pageList = wai.getPage();
+ for (int i = 0, sz = pageList.size(); i < sz; i++) {
+ // We look for the requested page
+ PageType page = pageList.get(i);
+ if (raw(getData(page.getPageId())).equals(pageName)) {
+ logger.debug("Let's process page \"" + pageName + "\"");
+ return translate(page);
+ }
+ }
+ String errMsg = "We haven't found page \"" + pageName + "\" in the
WebAdminInterface object.";
+ logger.warn(errMsg);
+ htmlUtil.errorBox(errMsg);
+ return false;
+ }

- public boolean translate(GroupsType g) {
- // TODO: implement groups
- String errMsg = "Groups type not implemented yet.";
- logger.warn(errMsg);
- htmlUtil.errorBox(errMsg);
- return false;
- }
+ /**
+ * Translate a given page object to HTML code
+ *
+ * @param page
+ */
+ public boolean translate(PageType page) {
+ if (page == null) {
+ logger.warn("Cannot translate a null page.");
+ return false;
+ }
+ GroupsType groups = page.getGroups();
+ List<PlainType> plain = page.getPlain();
+ boolean result;
+ if (groups != null) {
+ logger.debug("The page contains groups");
+ // We first have groups of elements
+ boolean oldContext = plainContext;
+ plainContext = false;
+ result = translate(groups);
+ plainContext = oldContext;
+ } else if (plain != null) {
+ logger.debug("The page contains plain elements");
+ boolean oldContext = plainContext;
+ plainContext = true;
+ for (int i = 0, sz = plain.size(); i < sz; i++) {
+ // We translate each plain element
+ translate((PlainType) plain.get(i));
+ }
+ plainContext = oldContext;
+ result = true;
+ } else {
+ String errMsg = "Page \"" + page.getPageId() + "\" doesn't
contain any groups nor plain elements.";
+ logger.warn(errMsg);
+ htmlUtil.errorBox(errMsg);
+ result = false;
+ }
+ return result;
+ }

- /**
- * From here and all the sub types, the translate method doesn't
return a boolean.
- * It just print a error message if something goes wrong, but
continue processing the objectMap
- * @param p
- */
- public void translate(PlainType p) {
- if (p == null) {
- String errMsg = "Cannot translate a null plain type.";
- logger.warn(errMsg);
- htmlUtil.simplelineoftext(errMsg, "red");
- return;
- }
- if (p.getTextbox() != null)
- translateBaseUI(p.getTextbox(), UIType.TEXTBOX);
- else if (p.getRadiogroup() != null)
- translate(p.getRadiogroup(), UIType.RADIOGROUP);
- else if (p.getRadio() != null)
- translate(p.getRadio(), UIType.RADIO);
- else if (p.getDropdown() != null)
- translate(p.getDropdown(), UIType.DROPDOWN);
- else if (p.getPassword() != null)
- translateBaseUI(p.getPassword(), UIType.PASSOWRD);
- else {
- String errMsg = "PlainType doesn't contain any known
UI type.";
- logger.warn(errMsg);
- htmlUtil.simplelineoftext(errMsg, "red");
- }
- }
+ public boolean translate(GroupsType g) {
+ // TODO: implement groups
+ String errMsg = "Groups type not implemented yet.";
+ logger.warn(errMsg);
+ htmlUtil.errorBox(errMsg);
+ return false;
+ }

- /**
- * A BaseUI is either a TEXTBOX or a PASSWORD field.
- * @param b
- * @param u
- */
- public void translateBaseUI(BaseUIType b, UIType u) {
- switch (u) {
- case TEXTBOX:
- drawTextBox(getRawData(b.getTitle()),
getSingleData(b.getDefault()));
- break;
- case PASSOWRD:
- drawPasswordBox(getRawData(b.getTitle()),
getSingleData(b.getDefault()));
- break;
+ /**
+ * From here and all the sub types, the translate method doesn't return a
+ * boolean. It just print a error message if something goes wrong, but
+ * continue processing the objectMap
+ *
+ * @param p
+ */
+ public void translate(PlainType p) {
+ if (p == null) {
+ String errMsg = "Cannot translate a null plain type.";
+ logger.warn(errMsg);
+ htmlUtil.simplelineoftext(errMsg, "red");
+ return;
+ }
+ if (p.getTextbox() != null) {
+ translateBaseUI(p.getTextbox(), UIType.TEXTBOX);
+ } else if (p.getRadiogroup() != null) {
+ translate(p.getRadiogroup(), UIType.RADIOGROUP);
+ } else if (p.getRadio() != null) {
+ translate(p.getRadio(), UIType.RADIO);
+ } else if (p.getDropdown() != null) {
+ translate(p.getDropdown(), UIType.DROPDOWN);
+ } else if (p.getPassword() != null) {
+ translateBaseUI(p.getPassword(), UIType.PASSOWRD);
+ } else {
+ String errMsg = "PlainType doesn't contain any known UI type.";
+ logger.warn(errMsg);
+ htmlUtil.simplelineoftext(errMsg, "red");
+ }
+ }

- default:
- String errMsg = "Cannot translate Base UI element,
UIType unknown.";
- logger.warn(errMsg);
- htmlUtil.simplelineoftext(errMsg, "red");
- }
- }
+ /**
+ * A BaseUI is either a TEXTBOX or a PASSWORD field.
+ *
+ * @param b
+ * @param u
+ */
+ public void translateBaseUI(BaseUIType b, UIType u) {
+ switch (u) {
+ case TEXTBOX:
+ drawTextBox(getRawData(b.getTitle()),
getSingleData(b.getDefault()));
+ break;
+ case PASSOWRD:
+ drawPasswordBox(getRawData(b.getTitle()),
getSingleData(b.getDefault()));
+ break;

- /**
- * A ComplexGroupUI can only be a RADIOGROUP
- * @param cgui
- * @param u
- */
- public void translate(ComplexGroupUIType cgui, UIType u) {
- switch (u) {
- case RADIOGROUP:
- List<PlainType> plains = cgui.getPlain();
- if (plains == null)
- return;
- // FIXME: trick, we save the current output buffer,
so we can temporarily generate a new one
- StringBuffer oldOut = htmlOutput;
- htmlOutput = new StringBuffer();
- for (int i = 0, sz = plains.size(); i < sz; i++) {
- // We loop through all the plain element
inside the Complex Group
- translate((PlainType) plains.get(i));
- }
- String innerHTML = htmlOutput.toString();
- htmlOutput = oldOut;
- drawRadiogroup(getData(cgui.getValues()), innerHTML);
- break;
- default:
- String errMsg = "Cannot translate Complex Group UI
element, UIType unknown.";
- logger.warn(errMsg);
- htmlUtil.simplelineoftext(errMsg, "red");
- }
- }
+ default:
+ String errMsg = "Cannot translate Base UI element, UIType
unknown.";
+ logger.warn(errMsg);
+ htmlUtil.simplelineoftext(errMsg, "red");
+ }
+ }

- public void translate(ComplexUIType cui, UIType u) {
- Tuple<Integer, String[]> def = getData(cui.getDefault());
- Tuple<Integer, String[]> all = getData(cui.getValues());
- String[] alls = all.second()[0].split(",");
- Set<String> set = new HashSet<String>(def.second().length+
all.second().length);
+ /**
+ * A ComplexGroupUI can only be a RADIOGROUP
+ *
+ * @param cgui
+ * @param u
+ */
+ public void translate(ComplexGroupUIType cgui, UIType u) {
+ switch (u) {
+ case RADIOGROUP:
+ List<PlainType> plains = cgui.getPlain();
+ if (plains == null) {
+ return;
+ }
+ // FIXME: trick, we save the current output buffer, so we can
+ // temporarily generate a new one
+ StringBuffer oldOut = htmlOutput;
+ htmlOutput = new StringBuffer();
+ for (int i = 0, sz = plains.size(); i < sz; i++) {
+ // We loop through all the plain element inside the Complex
+ // Group
+ translate((PlainType) plains.get(i));
+ }
+ String innerHTML = htmlOutput.toString();
+ htmlOutput = oldOut;
+ drawRadiogroup(getData(cgui.getValues()), innerHTML);
+ break;
+ default:
+ String errMsg = "Cannot translate Complex Group UI element,
UIType unknown.";
+ logger.warn(errMsg);
+ htmlUtil.simplelineoftext(errMsg, "red");
+ }
+ }

- for (String s : alls)
- set.add(s);
- HashSet<String> singleton = new HashSet<String>(1);
- singleton.add(def.second()[0]);
- set.removeAll(singleton);
+ public void translate(ComplexUIType cui, UIType u) {
+ Tuple<Integer, String[]> def = getData(cui.getDefault());
+ Tuple<Integer, String[]> all = getData(cui.getValues());
+ String[] alls = all.second()[0].split(",");
+ Set<String> set = new HashSet<String>(def.second().length +
all.second().length);

- String[] rets = new String[set.size() + 1];
- rets[0] = def.second()[0];
- int i = rets.length - 1;
- for (Object o : set)
- rets[i--] = (String) o;
+ for (String s : alls) {
+ set.add(s);
+ }

- Tuple<Integer, String[]> ret = new Tuple<Integer,
String[]>(def.first(), rets);
+ HashSet<String> singleton = new HashSet<String>(1);
+ singleton.add(def.second()[0]);
+ set.removeAll(singleton);

- switch (u) {
- case RADIO:
- drawRadio(getSingleData(cui.getTitle()), ret);
- break;
- case DROPDOWN:
- drawDropdown(getSingleData(cui.getTitle()), ret);
- break;
- default:
- String errMsg = "Cannot translate Complex UI element,
UIType unknown.";
- logger.warn(errMsg);
- htmlUtil.simplelineoftext(errMsg, "red");
- }
- }
+ String[] rets = new String[set.size() + 1];
+ rets[0] = def.second()[0];
+ int i = rets.length - 1;
+ for (Object o : set) {
+ rets[i--] = (String) o;
+ }

- private static String raw(Tuple<Integer, String[]> t) {
- return (t.second())[0];
- }
+ Tuple<Integer, String[]> ret = new Tuple<Integer,
String[]>(def.first(), rets);

- private static Tuple<Integer, String> single(Tuple<Integer, String[]>
t) {
- return new Tuple<Integer, String>(t.first(), raw(t));
- }
+ switch (u) {
+ case RADIO:
+ drawRadio(getSingleData(cui.getTitle()), ret);
+ break;
+ case DROPDOWN:
+ drawDropdown(getSingleData(cui.getTitle()), ret);
+ break;
+ default:
+ String errMsg = "Cannot translate Complex UI element, UIType
unknown.";
+ logger.warn(errMsg);
+ htmlUtil.simplelineoftext(errMsg, "red");
+ }
+ }

- private Tuple<Integer, String> getSingleData(BaseType b) {
- return single(getData(b));
- }
+ private static String raw(Tuple<Integer, String[]> t) {
+ return t.second()[0];
+ }

- private String getRawData(BaseType b) {
- return raw(getData(b));
- }
+ private static Tuple<Integer, String> single(Tuple<Integer, String[]> t)
{
+ return new Tuple<Integer, String>(t.first(), raw(t));
+ }

- // ////////////////////////////////////////////////////
- private Tuple<Integer, String[]> getData(BaseType b) // FIXME
- {
- if (b.getText() != null && !b.getText().equals(""))
- return new Tuple<Integer,
String[]>(objectMap.registerObject(b),
- new String[] { b.getText().trim() });
// maybe a list
- else {
- Tuple<String, String> t =
XMLUtil.parseXPath(b.getXpath());
- NSContext ns = objectMap.getMap();
- try {
- NodeList nl = XMLUtil.query(ns, t.second(),
objectMap
- .getDocument(t.first()));
- int sz = nl.getLength();
- String[] lst = new String[sz];
- String value;
- for (int i = 0; i < sz; i++) {
- value = nl.item(i).getNodeValue();
- if (value == null) {
- value =
nl.item(i).getTextContent();
- }
- lst[i] = value;
- }
- return new Tuple<Integer, String[]>(objectMap
- .registerObject(nl), lst);
- } catch (Exception e) {
- e.printStackTrace();
- }
+ private Tuple<Integer, String> getSingleData(BaseType b) {
+ return single(getData(b));
+ }

- return null;
- }
+ private String getRawData(BaseType b) {
+ return raw(getData(b));
+ }

- }
+ // ////////////////////////////////////////////////////
+ // FIXME
+ private Tuple<Integer, String[]> getData(BaseType b) {
+ if (b.getText() != null && !b.getText().equals("")) {
+ return new Tuple<Integer, String[]>(objectMap.registerObject(b),
new String[] {b.getText().trim() }); // maybe
+ } else {
+ Tuple<String, String> t = XMLUtil.parseXPath(b.getXpath());
+ NSContext ns = objectMap.getMap();
+ try {
+ NodeList nl = XMLUtil.query(ns, t.second(),
objectMap.getDocument(t.first()));
+ int sz = nl.getLength();
+ String[] lst = new String[sz];
+ String value;
+ for (int i = 0; i < sz; i++) {
+ value = nl.item(i).getNodeValue();
+ if (value == null) {
+ value = nl.item(i).getTextContent();
+ }
+ lst[i] = value;
+ }
+ return new Tuple<Integer,
String[]>(objectMap.registerObject(nl), lst);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }

- public void drawPasswordBox(String title, Tuple<Integer, String> t) {
- logger.trace("WA --- Drawing a password box : title: \"" +
title
- + "\" value: \"" + t.second() + "\"");
- try {
-// htmlUtil.singlerow_begin(5);
- htmlUtil.passtextbox(t.first() + "", title,
t.second());
-// htmlUtil.singlerow_end();
- } catch (Exception e) {
- // FIXME: no point in outputing a stack trace
- e.printStackTrace();
- }
- }
+ return null;
+ }

- // ////////////////////////////////////////////////////
- // TODO: External HTMLUtil.java -> HTML tags and so on
- public void drawTextBox(String title, Tuple<Integer, String> t) {
- logger.trace("WA --- Drawing a box : title: \"" + title
- + "\" value : \"" + t.second() + "\"");
- try {
-// htmlUtil.singlerow_begin(5);
- htmlUtil.textbox(t.first() + "", title, t.second());
-// htmlUtil.singlerow_end();
- } catch (Exception e) {
- // FIXME: no point in outputing a stack trace
- e.printStackTrace();
- }
- }
+ }

- public void drawRadio(Tuple<Integer, String> title,
- Tuple<Integer, String[]> values) {
- logger.trace("WA --- Drawing a radio : title: \"" +
title.second() + "\"");
- // for( String s : values.second() ) println("\nradio value :
" + s);
- try {
-// htmlUtil.singlerow_begin(5);
- htmlUtil.radio(values.first() + "", title.second(),
values.second());
-// htmlUtil.singlerow_end();
- } catch (Exception e) {
- // FIXME: no point in outputing a stack trace
- e.printStackTrace();
- }
- }
+ public void drawPasswordBox(String title, Tuple<Integer, String> t) {
+ logger.trace("WA --- Drawing a password box : title: \"" + title +
"\" value: \"" + t.second() + "\"");
+ try {
+ // htmlUtil.singlerow_begin(5);
+ htmlUtil.passtextbox(t.first() + "", title, t.second());
+ // htmlUtil.singlerow_end();
+ } catch (Exception e) {
+ // FIXME: no point in outputing a stack trace
+ e.printStackTrace();
+ }
+ }

- public void drawDropdown(Tuple<Integer, String> title,
- Tuple<Integer, String[]> values) {
- logger.trace("WA --- Drawing a drop-down : title: \"" +
title.second() + "\"");
- // for( String s : values.second() ) println("\ndrop-down
value : " +
- // s);
- try {
-// htmlUtil.singlerow_begin(5);
- htmlUtil.dropdown(values.first() + "",
title.second(), values.second());
-// htmlUtil.singlerow_end();
- } catch (Exception e) {
- // FIXME: no point in outputing a stack trace
- e.printStackTrace();
- }
+ // ////////////////////////////////////////////////////
+ // TODO: External HTMLUtil.java -> HTML tags and so on
+ public void drawTextBox(String title, Tuple<Integer, String> t) {
+ logger.trace("WA --- Drawing a box : title: \"" + title + "\" value
: \"" + t.second() + "\"");
+ try {
+ // htmlUtil.singlerow_begin(5);
+ htmlUtil.textbox(t.first() + "", title, t.second());
+ // htmlUtil.singlerow_end();
+ } catch (Exception e) {
+ // FIXME: no point in outputing a stack trace
+ e.printStackTrace();
+ }
+ }

- }
+ public void drawRadio(Tuple<Integer, String> title, Tuple<Integer,
String[]> values) {
+ logger.trace("WA --- Drawing a radio : title: \"" + title.second() +
"\"");
+ // for( String s : values.second() ) println("\nradio value : " + s);
+ try {
+ // htmlUtil.singlerow_begin(5);
+ htmlUtil.radio(values.first() + "", title.second(),
values.second());
+ // htmlUtil.singlerow_end();
+ } catch (Exception e) {
+ // FIXME: no point in outputing a stack trace
+ e.printStackTrace();
+ }
+ }

- public void drawRadiogroup(Tuple<Integer, String[]> values, String
innerHTML) {
- logger.trace("Drawing a group radio: ");
- boolean enabled = false;
- // FIXME: Hardcoded values
- try {
-// htmlUtil.singlerow_begin(5);
- htmlUtil.radiogroup_begin("key3", "Grouped box",
"yes", "no", enabled);
- htmlUtil.println(innerHTML);
- htmlUtil.radiogroup_end();
-// htmlUtil.singlerow_end();
- } catch (Exception e) {
- // FIXME: no point in outputing a stack trace
- e.printStackTrace();
- }
- }
+ public void drawDropdown(Tuple<Integer, String> title, Tuple<Integer,
String[]> values) {
+ logger.trace("WA --- Drawing a drop-down : title: \"" +
title.second() + "\"");
+ // for( String s : values.second() ) println("\ndrop-down value : " +
+ // s);
+ try {
+ // htmlUtil.singlerow_begin(5);
+ htmlUtil.dropdown(values.first() + "", title.second(),
values.second());
+ // htmlUtil.singlerow_end();
+ } catch (Exception e) {
+ // FIXME: no point in outputing a stack trace
+ e.printStackTrace();
+ }
+
+ }
+
+ public void drawRadiogroup(Tuple<Integer, String[]> values, String
innerHTML) {
+ logger.trace("Drawing a group radio: ");
+ boolean enabled = false;
+ // FIXME: Hardcoded values
+ try {
+ // htmlUtil.singlerow_begin(5);
+ htmlUtil.radiogroupBegin("key3", "Grouped box", "yes", "no",
enabled);
+ htmlUtil.println(innerHTML);
+ htmlUtil.radiogroupEnd();
+ // htmlUtil.singlerow_end();
+ } catch (Exception e) {
+ // FIXME: no point in outputing a stack trace
+ e.printStackTrace();
+ }
+ }
};

Modified:
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/config/ObjectMap.java
===================================================================
---
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/config/ObjectMap.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/config/ObjectMap.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -34,170 +34,172 @@
@SuppressWarnings("serial")
public class ObjectMap extends Hashtable<Integer, Object> {

- private final Logger logger = LoggerFactory.getLogger(getClass());
+ private final Logger logger = LoggerFactory.getLogger(getClass());

- Tuple<WebAdminInterface, JAXBContext> waconfig;
- String waconfigfile = "";
- Hashtable<String, Document> file2doc = new Hashtable<String,
Document>();
- String basePath = "";
- NSContext namespaces;
- boolean sync = false;
+ private Tuple<WebAdminInterface, JAXBContext> waconfig;
+ private String waconfigfile = "";
+ private Hashtable<String, Document> file2doc = new Hashtable<String,
Document>();
+ private String basePath = "";
+ private NSContext namespaces;
+ private boolean sync = false;

- public ObjectMap(String basePath, String confPath, String file) {
- waconfigfile = basePath + File.separatorChar + confPath +
File.separatorChar + file;
- try {
- waconfig = WAXMLReader.parseFile(waconfigfile);
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (MalformedURLException e) {
- e.printStackTrace();
- } catch (JAXBException e) {
- e.printStackTrace();
- }
- this.basePath = basePath;
- makeMap();
- }
+ public ObjectMap(String basePath, String confPath, String file) {
+ waconfigfile = basePath + File.separatorChar + confPath +
File.separatorChar + file;
+ try {
+ waconfig = WAXMLReader.parseFile(waconfigfile);
+ } catch (FileNotFoundException e) {
+ e.printStackTrace();
+ } catch (MalformedURLException e) {
+ e.printStackTrace();
+ } catch (JAXBException e) {
+ e.printStackTrace();
+ }
+ this.basePath = basePath;
+ makeMap();
+ }

- private void makeMap() {
- NSContext nsc = new NSContext();
- List<NsMap> map = getWA().getMap();
- NsMap ns;
- for (Object o : map) {
- ns = (NsMap) o;
- nsc.put(ns.getNs(), ns.getUrl());
- }
- namespaces = nsc;
- }
+ private void makeMap() {
+ NSContext nsc = new NSContext();
+ List<NsMap> map = getWA().getMap();
+ NsMap ns;
+ for (Object o : map) {
+ ns = (NsMap) o;
+ nsc.put(ns.getNs(), ns.getUrl());
+ }
+ namespaces = nsc;
+ }

- public NSContext getMap() {
- return namespaces;
- }
+ public NSContext getMap() {
+ return namespaces;
+ }

- public WebAdminInterface getWA() {
- return waconfig.first();
- }
+ public WebAdminInterface getWA() {
+ return waconfig.first();
+ }

- private int _registerObject(Object ui) {
- int id = ((Object) ui).hashCode();
- put(id, ui);
- return id;
+ private int registerObjectInternal(Object ui) {
+ int id = ((Object) ui).hashCode();
+ put(id, ui);
+ return id;

- }
+ }

- /**
- * Actually call the file output classes to save to disk
- * @return
- */
- private boolean saveExternal() {
- Set<Entry<String, Document>> entrySet = file2doc.entrySet();
- for (Entry<String, Document> o : entrySet) {
- try {
- XMLUtil.writeXml(o.getValue(), new
java.io.FileOutputStream(
- basePath + "/" + o.getKey()));
- } catch (Exception e) {
- logger.error("Error trying to save ourselves
to disk: " + e.getMessage());
- return false;
- }
- }
- return true;
- }
+ /**
+ * Actually call the file output classes to save to disk
+ *
+ * @return
+ */
+ private boolean saveExternal() {
+ Set<Entry<String, Document>> entrySet = file2doc.entrySet();
+ for (Entry<String, Document> o : entrySet) {
+ try {
+ XMLUtil.writeXml(o.getValue(), new
java.io.FileOutputStream(basePath + "/" + o.getKey()));
+ } catch (Exception e) {
+ logger.error("Error trying to save ourselves to disk: " +
e.getMessage());
+ return false;
+ }
+ }
+ return true;
+ }

- /**
- * Save ourselves to disk
- * @return
- */
- public synchronized boolean save() {
- boolean saved = saveExternal();
- if (saved) {
- sync = false;
- }
- return saved;
- }
+ /**
+ * Save ourselves to disk
+ *
+ * @return
+ */
+ public synchronized boolean save() {
+ boolean saved = saveExternal();
+ if (saved) {
+ sync = false;
+ }
+ return saved;
+ }

- public synchronized int registerObject(BaseType ui) {
- return _registerObject(ui);
- }
+ public synchronized int registerObject(BaseType ui) {
+ return registerObjectInternal(ui);
+ }

- public synchronized int registerObject(NodeList n) {
- return _registerObject(n);
- }
+ public synchronized int registerObject(NodeList n) {
+ return registerObjectInternal(n);
+ }

- public synchronized Document getDocument(String uri) throws Exception
{
- Document ret = file2doc.get(uri);
- if (ret != null)
- return ret;
- String path = new File(basePath + "/" +
uri).toURI().toASCIIString();
- logger.debug("Attempting to locate URI : \"" + path + "\"");
- file2doc.put(uri, (ret = XMLUtil.readDocument(path)));
- return ret;
- }
+ public synchronized Document getDocument(String uri) throws Exception {
+ Document ret = file2doc.get(uri);
+ if (ret != null) {
+ return ret;
+ }
+ String path = new File(basePath + "/" + uri).toURI().toASCIIString();
+ logger.debug("Attempting to locate URI : \"" + path + "\"");
+ ret = XMLUtil.readDocument(path);
+ file2doc.put(uri, ret);
+ return ret;
+ }

- public synchronized void updateObjects(Map<String, String[]> pmap) {
- Object myobj = null;
- for (Entry<String, String[]> entry : pmap.entrySet()) {
- try {
- Integer inputName =
Integer.parseInt(entry.getKey());
- myobj = get(inputName);
- if (myobj == null) {
- logger.warn("element " +
entry.getKey() + " not found !");
- }
- if (myobj instanceof BaseType)
- updateBase((BaseType) myobj,
entry.getValue());
- else if (myobj instanceof NodeList)
- updateNodeList((NodeList) myobj,
entry.getValue());
- else {
- logger.warn(" Cannot match object
type :"
- + myobj.getClass());
- }
- } catch (NumberFormatException ex) {
- logger.info("Key - " + entry.getKey()
- + " is not a number - ignore
it");
- }
- }
- sync = true;
- }
+ public synchronized void updateObjects(Map<String, String[]> pmap) {
+ Object myobj = null;
+ for (Entry<String, String[]> entry : pmap.entrySet()) {
+ try {
+ Integer inputName = Integer.parseInt(entry.getKey());
+ myobj = get(inputName);
+ if (myobj == null) {
+ logger.warn("element " + entry.getKey() + " not found
!");
+ }
+ if (myobj instanceof BaseType) {
+ updateBase((BaseType) myobj, entry.getValue());
+ } else if (myobj instanceof NodeList) {
+ updateNodeList((NodeList) myobj, entry.getValue());
+ } else {
+ logger.warn(" Cannot match object type :" +
myobj.getClass());
+ }
+ } catch (NumberFormatException ex) {
+ logger.info("Key - " + entry.getKey() + " is not a number -
ignore it");
+ }
+ }
+ sync = true;
+ }

- public synchronized boolean needSync() {
- return sync;
- }
+ public synchronized boolean needSync() {
+ return sync;
+ }

- private void updateBase(BaseType o, String[] valueArray) {
- logger.debug("Should update base type");
- if (valueArray.length == 0) {
- logger.debug("value is empty");
- return;
- }
+ private void updateBase(BaseType o, String[] valueArray) {
+ logger.debug("Should update base type");
+ if (valueArray.length == 0) {
+ logger.debug("value is empty");
+ return;
+ }

- String s = valueArray[0];
- for (int i = 1; i < valueArray.length; i++)
- s += "," + valueArray[i];
- // NOTE:Assuming that this is a text element (not xpath)
- o.setText(s);
- logger.debug("base type updated");
- }
+ String s = valueArray[0];
+ for (int i = 1; i < valueArray.length; i++) {
+ s += "," + valueArray[i];
+ }
+ // NOTE:Assuming that this is a text element (not xpath)
+ o.setText(s);
+ logger.debug("base type updated");
+ }

- private void updateNodeList(NodeList t, String[] valueArray) {
- if (t.getLength() == 0) {
- logger.debug("empty node list");
- return;
- } else if (valueArray.length == 0) {
- logger.debug("value is empty !");
- return;
- }
- Node n = t.item(0);
- String s = valueArray[0];
- for (int i = 1; i < valueArray.length; i++) {
- s += "," + valueArray[i];
- }
- if (n.getNodeValue() != null) {
- // if value comes from tag attribute
- n.setNodeValue(s);
- } else {
- // if value comes from tag value
- n.setTextContent(s);
- }
+ private void updateNodeList(NodeList t, String[] valueArray) {
+ if (t.getLength() == 0) {
+ logger.debug("empty node list");
+ return;
+ } else if (valueArray.length == 0) {
+ logger.debug("value is empty !");
+ return;
+ }
+ Node n = t.item(0);
+ String s = valueArray[0];
+ for (int i = 1; i < valueArray.length; i++) {
+ s += "," + valueArray[i];
+ }
+ if (n.getNodeValue() != null) {
+ // if value comes from tag attribute
+ n.setNodeValue(s);
+ } else {
+ // if value comes from tag value
+ n.setTextContent(s);
+ }

- logger.debug("list node updated");
- }
+ logger.debug("list node updated");
+ }

};

Modified:
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/filters/AuthFilter.java
===================================================================
---
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/filters/AuthFilter.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/filters/AuthFilter.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -16,38 +16,38 @@
import org.slf4j.LoggerFactory;

/**
- * This filter checks the user is authenticated.
- * If he/she is not he/she is redirected to the login page.
+ * This filter checks the user is authenticated. If he/she is not he/she is
+ * redirected to the login page.
*
* @author Antoine Delvaux - DANTE
*/
public class AuthFilter implements Filter {

- protected Logger logger = LoggerFactory.getLogger(getClass());
+ protected Logger logger = LoggerFactory.getLogger(getClass());

- @Override
- public void init(FilterConfig filterConfig) throws ServletException {
- }
+ @Override
+ public void init(FilterConfig filterConfig) throws ServletException {
+ }

- @Override
- public void destroy() {
- }
+ @Override
+ public void destroy() {
+ }

- /**
- * Main filtering action, checking for the session attribute "logged"
- * This attribute should be set in the LoginServlet
- */
- @Override
- public void doFilter(ServletRequest servletRequest, ServletResponse
servletResponse, FilterChain filterChain)
- throws IOException, ServletException {
- HttpServletRequest request = (HttpServletRequest)
servletRequest;
- HttpSession session = request.getSession();
- if (session.getAttribute("logged") == null) {
- logger.debug("User is not authenticated, we display
the login form");
- HttpServletResponse response = (HttpServletResponse)
servletResponse;
- response.sendRedirect("login");
- } else {
- filterChain.doFilter(servletRequest, servletResponse);
- }
- }
+ /**
+ * Main filtering action, checking for the session attribute "logged"
This
+ * attribute should be set in the LoginServlet
+ */
+ @Override
+ public void doFilter(ServletRequest servletRequest, ServletResponse
servletResponse, FilterChain filterChain)
+ throws IOException, ServletException {
+ HttpServletRequest request = (HttpServletRequest) servletRequest;
+ HttpSession session = request.getSession();
+ if (session.getAttribute("logged") == null) {
+ logger.debug("User is not authenticated, we display the login
form");
+ HttpServletResponse response = (HttpServletResponse)
servletResponse;
+ response.sendRedirect("login");
+ } else {
+ filterChain.doFilter(servletRequest, servletResponse);
+ }
+ }
}

Modified:
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/servlet/BasicServlet.java
===================================================================
---
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/servlet/BasicServlet.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/servlet/BasicServlet.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -10,23 +10,24 @@
import org.slf4j.LoggerFactory;

/**
- * This abstract Servlet is the common ancestor to all WebAdmin Servlets.
- * It only initialise the logger and read the WebAdmin configuration file in
an objectMap.
+ * This abstract Servlet is the common ancestor to all WebAdmin Servlets. It
+ * only initialise the logger and read the WebAdmin configuration file in an
+ * objectMap.
*
* @author Antoine Delvaux - DANTE
- *
+ *
*/
@SuppressWarnings("serial")
public abstract class BasicServlet extends HttpServlet {

- protected Logger logger = LoggerFactory.getLogger(getClass());
-
- protected ObjectMap objectMap;
+ protected Logger logger = LoggerFactory.getLogger(getClass());

- public void init(ServletConfig arg0) throws ServletException {
- super.init(arg0);
- logger.debug("perfSONAR Basic Servlet initialised");
- objectMap =
ConfigurationServletHelper.objectMap(getServletContext());
- }
+ protected ObjectMap objectMap;

+ public void init(ServletConfig arg0) throws ServletException {
+ super.init(arg0);
+ logger.debug("perfSONAR Basic Servlet initialised");
+ objectMap =
ConfigurationServletHelper.objectMap(getServletContext());
+ }
+
}

Modified:
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/servlet/ConfigurationServlet.java
===================================================================
---
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/servlet/ConfigurationServlet.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/servlet/ConfigurationServlet.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -9,7 +9,8 @@
import org.perfsonar.webadmin.servlet.util.ConfigurationServletHelper;

/**
- * The ConfigurationServlet is in charge of dispatching requests for the
configuration file edition.
+ * The ConfigurationServlet is in charge of dispatching requests for the
+ * configuration file edition.
*
* @author Slawomir Trzaszczka
* @author Antoine Delvaux - DANTE
@@ -18,46 +19,45 @@
@SuppressWarnings("serial")
public class ConfigurationServlet extends BasicServlet {

- /**
- * We receive a GET request and we present the config file data to be
edited in a form
- */
- @Override
- protected void doGet(HttpServletRequest request,
- HttpServletResponse response) throws
ServletException, IOException {
+ /**
+ * We receive a GET request and we present the config file data to be
edited
+ * in a form
+ */
+ @Override
+ protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {

- // We get the config file content from the
ConfigurationServletHelper
- ConfigurationServletHelper config = new
ConfigurationServletHelper(request, response, getServletContext());
- String htmlContent = config.getHTMLContent();
+ // We get the config file content from the ConfigurationServletHelper
+ ConfigurationServletHelper config = new
ConfigurationServletHelper(request, response, getServletContext());
+ String htmlContent = config.getHTMLContent();

- if (htmlContent != null) {
- // The "form" attribute will store the generated FORM
- request.setAttribute("form", htmlContent);
- } else {
- logger.warn("form html content is null !");
- }
- // We forward the request to the index.jsp that will render
our form
- getServletConfig().getServletContext().getRequestDispatcher(
- "/index.jsp?page=form").forward(request, response);
- }
+ if (htmlContent != null) {
+ // The "form" attribute will store the generated FORM
+ request.setAttribute("form", htmlContent);
+ } else {
+ logger.warn("form html content is null !");
+ }
+ // We forward the request to the index.jsp that will render our form
+
getServletConfig().getServletContext().getRequestDispatcher("/index.jsp?page=form").forward(request,
response);
+ }

- /**
- * We receive a POST request and we save the received data
- */
- @Override
- protected void doPost(HttpServletRequest request,
- HttpServletResponse response) throws
ServletException, IOException {
+ /**
+ * We receive a POST request and we save the received data
+ */
+ @Override
+ protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException,
+ IOException {

- ConfigurationServletHelper config = new
ConfigurationServletHelper(request, response, getServletContext());
+ ConfigurationServletHelper config = new
ConfigurationServletHelper(request, response, getServletContext());

- String urlPath = "index.jsp?page=save";
+ String urlPath = "index.jsp?page=save";

- // Try to process the received data and save it
- if (config.processData()) {
- // Everything went smoothly, we'll display a nice OK
page.
- urlPath += "&ok";
- }
- getServletContext().removeAttribute("ObjectMap");
- response.sendRedirect(urlPath);
- }
+ // Try to process the received data and save it
+ if (config.processData()) {
+ // Everything went smoothly, we'll display a nice OK page.
+ urlPath += "&ok";
+ }
+ getServletContext().removeAttribute("ObjectMap");
+ response.sendRedirect(urlPath);
+ }

}

Modified:
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/servlet/LoginServlet.java
===================================================================
---
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/servlet/LoginServlet.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/servlet/LoginServlet.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -11,44 +11,40 @@
@SuppressWarnings("serial")
public class LoginServlet extends BasicServlet {

- @Override
- protected void doGet(HttpServletRequest request,
- HttpServletResponse response) throws
ServletException, IOException {
+ @Override
+ protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {

- // Any GET request to this Servlet, removes existing
authentication
- request.getSession().removeAttribute("logged");
+ // Any GET request to this Servlet, removes existing authentication
+ request.getSession().removeAttribute("logged");

- getServletConfig().getServletContext().getRequestDispatcher(
- "/index.jsp?page=login").forward(request, response);
- }
+
getServletConfig().getServletContext().getRequestDispatcher("/index.jsp?page=login").forward(request,
response);
+ }

- @Override
- protected void doPost(HttpServletRequest request, HttpServletResponse
response)
- throws ServletException, IOException {
+ @Override
+ protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException,
+ IOException {

- Credential credential = objectMap.getWA().getCredential();
+ Credential credential = objectMap.getWA().getCredential();

- // FIXME: we must use HTTPS, but how to get a correct
certificate?
-// if (request.isSecure()) {
- // We are receiving an authentication request
- String username = (String)
request.getParameter("username");
- String password = (String)
request.getParameter("password");
- logger.debug("We received the authentication form for
" + username);
+ // FIXME: we must use HTTPS, but how to get a correct certificate?
+ // if (request.isSecure()) {
+ // We are receiving an authentication request
+ String username = (String) request.getParameter("username");
+ String password = (String) request.getParameter("password");
+ logger.debug("We received the authentication form for " + username);

- if (credential.getUsername().equals(username) &&
credential.getPassword().equals(password)) {
- logger.info("Correct login from " +
request.getRemoteAddr());
- request.getSession().setAttribute("logged",
true);
- // We clear the attribute meant to stop the
filtering loop
- request.getSession().setAttribute("info",
"You have been authenticated.");
- } else {
- logger.debug("Incorrect login from " +
request.getRemoteAddr());
-
request.getSession().removeAttribute("logged");
- request.getSession().setAttribute("info",
"Incorrect login or password.");
- }
-// }
+ if (credential.getUsername().equals(username) &&
credential.getPassword().equals(password)) {
+ logger.info("Correct login from " + request.getRemoteAddr());
+ request.getSession().setAttribute("logged", true);
+ // We clear the attribute meant to stop the filtering loop
+ request.getSession().setAttribute("info", "You have been
authenticated.");
+ } else {
+ logger.debug("Incorrect login from " + request.getRemoteAddr());
+ request.getSession().removeAttribute("logged");
+ request.getSession().setAttribute("info", "Incorrect login or
password.");
+ }
+ // }

- response.sendRedirect("index.jsp");
-
- }
-
+ response.sendRedirect("index.jsp");
+ }
}

Modified:
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/servlet/SelfTestServlet.java
===================================================================
---
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/servlet/SelfTestServlet.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/servlet/SelfTestServlet.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -19,67 +19,67 @@
@SuppressWarnings("serial")
public class SelfTestServlet extends BasicServlet {

- private final String SELF_TEST_FILE = "/wa/soapMessages/selfTest.xml";
+ private static final String SELF_TEST_FILE =
"/wa/soapMessages/selfTest.xml";

- @Override
- protected void doGet(HttpServletRequest request, HttpServletResponse
response)
- throws ServletException, IOException {
+ @Override
+ protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {

- logger.debug("Performing self test");
- String redirectURL = "index.jsp?page=selfTest";
+ logger.debug("Performing self test");
+ String redirectURL = "index.jsp?page=selfTest";

- ObjectMap objectMap =
ConfigurationServletHelper.objectMap(getServletContext());
- String accessPoint =
objectMap.getWA().getServiceInformation().getAccessPoint();
+ ObjectMap objectMap =
ConfigurationServletHelper.objectMap(getServletContext());
+ String accessPoint =
objectMap.getWA().getServiceInformation().getAccessPoint();

- SOAPClient soapClient = new SOAPClient(accessPoint);
- String messageContent =
getFileContent(getServletContext().getRealPath("/") + SELF_TEST_FILE);
+ SOAPClient soapClient = new SOAPClient(accessPoint);
+ String messageContent =
getFileContent(getServletContext().getRealPath("/") + SELF_TEST_FILE);

- if (messageContent == null) {
- logger.warn("Self test cannot be performed because
the selfTest message is empty. Please check the wa/soapMessages/selfTest.xml
file.");
- request.setAttribute("errorMessage", "Selftest
message is empty (null).");
- } else {
- try {
- String result =
soapClient.sendMessage(messageContent);
- if (result != null) {
- if (result.contains("error") ||
result.contains("failure")) {
- logger.info("Self test
failed!");
-
getServletContext().setAttribute("errors",
StringEscapeUtils.escapeHtml4(result));
- } else if
(result.contains("success")) {
- logger.info("Self test
succeeded!");
- redirectURL = redirectURL +
"&ok";
- } else {
- logger.warn("Result of
selfTest is neither error nor success: " + result);
-
request.setAttribute("errorMessage", "Unknown response from service. Look
for more information in the logs.");
- }
-
- } else {
- logger.info("Self test was returned
an empty result.");
- request.setAttribute("errorMessage",
"Result is empty (null).");
- }
- } catch (SOAPClientException e) {
-
getServletContext().setAttribute("errorMessage", e.getMessage());
- }
- }
+ if (messageContent == null) {
+ logger.warn("Self test cannot be performed because the selfTest
message is empty. Please check the wa/soapMessages/selfTest.xml file.");
+ request.setAttribute("errorMessage", "Selftest message is empty
(null).");
+ } else {
+ try {
+ String result = soapClient.sendMessage(messageContent);
+ if (result != null) {
+ if (result.contains("error") ||
result.contains("failure")) {
+ logger.info("Self test failed!");
+ getServletContext().setAttribute("errors",
StringEscapeUtils.escapeHtml4(result));
+ } else if (result.contains("success")) {
+ logger.info("Self test succeeded!");
+ redirectURL = redirectURL + "&ok";
+ } else {
+ logger.warn("Result of selfTest is neither error nor
success: " + result);
+ request.setAttribute("errorMessage",
+ "Unknown response from service. Look for
more information in the logs.");
+ }

- response.sendRedirect(redirectURL);
- }
+ } else {
+ logger.info("Self test was returned an empty result.");
+ request.setAttribute("errorMessage", "Result is empty
(null).");
+ }
+ } catch (SOAPClientException e) {
+ getServletContext().setAttribute("errorMessage",
e.getMessage());
+ }
+ }

- private String getFileContent(String url) {
+ response.sendRedirect(redirectURL);
+ }

- byte[] buffer = new byte[(int) new File(url).length()];
- FileInputStream f;
- try {
- f = new FileInputStream(url);
- f.read(buffer);
- f.close();
- return new String(buffer);
- } catch (FileNotFoundException e) {
- logger.warn("Impossible to read " + url + ", file cannot
be found.");
- } catch (IOException e) {
- logger.warn("Error reading " + url + " : " +
e.getMessage());
- }
+ private String getFileContent(String url) {

- return null;
- }
+ byte[] buffer = new byte[(int) new File(url).length()];
+ FileInputStream f;
+ try {
+ f = new FileInputStream(url);
+ f.read(buffer);
+ f.close();
+ return new String(buffer);
+ } catch (FileNotFoundException e) {
+ logger.warn("Impossible to read " + url + ", file cannot be
found.");
+ } catch (IOException e) {
+ logger.warn("Error reading " + url + " : " + e.getMessage());
+ }

+ return null;
+ }
+
}

Modified:
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/servlet/util/ConfigurationServletHelper.java
===================================================================
---
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/servlet/util/ConfigurationServletHelper.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/servlet/util/ConfigurationServletHelper.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -15,152 +15,161 @@

public class ConfigurationServletHelper {

- private final Logger logger = LoggerFactory.getLogger(getClass());
+ private final Logger logger = LoggerFactory.getLogger(getClass());

- //TODO: Isn't the Session timeout set in the WebAdmin configuration
file?
- static final short SESSION_INTERVAL = 3600;
- /**
- * localization of the WA configuration file
- */
- public static final String WA_CONFIG_PATH = "classes/perfsonar/conf";
+ // TODO: Isn't the Session timeout set in the WebAdmin configuration
file?
+ static final short SESSION_INTERVAL = 3600;
+ /**
+ * Localisation of the WA configuration file
+ */
+ public static final String WA_CONFIG_PATH = "classes/perfsonar/conf";

- /**
- * file name of the wa.xml file
- */
- public static final String WA_FILE_NAME = "webAdminConfig.xml";
+ /**
+ * file name of the wa.xml file
+ */
+ public static final String WA_FILE_NAME = "webAdminConfig.xml";

- private HttpServletRequest request;
- private HttpSession session;
- private ServletContext context;
- private HTMLGenerator generator;
+ private HttpServletRequest request;
+ private HttpSession session;
+ private ServletContext context;
+ private HTMLGenerator generator;

- /**
- * Builds and return the ObjectMap (hash table) of the WebAdmin
components
- * @param servletContext
- * @return
- */
- public static synchronized ObjectMap objectMap(ServletContext
servletContext) {
- // First, check if we already have our ObjectMap
- ObjectMap map = (ObjectMap)
servletContext.getAttribute("ObjectMap");
- if (map != null) {
- return map;
- }
- // We don't have it, so let's build it and store it in the
servlet context
- String basePath = servletContext.getRealPath("/") +
"/WEB-INF";
- map = new ObjectMap(basePath, WA_CONFIG_PATH, WA_FILE_NAME);
- servletContext.setAttribute("ObjectMap", map);
- return map;
- }
+ /**
+ * Builds and return the ObjectMap (hash table) of the WebAdmin
components
+ *
+ * @param servletContext
+ * @return
+ */
+ public static synchronized ObjectMap objectMap(ServletContext
servletContext) {
+ // First, check if we already have our ObjectMap
+ ObjectMap map = (ObjectMap) servletContext.getAttribute("ObjectMap");
+ if (map != null) {
+ return map;
+ }
+ // We don't have it, so let's build it and store it in the servlet
+ // context
+ String basePath = servletContext.getRealPath("/") + "/WEB-INF";
+ map = new ObjectMap(basePath, WA_CONFIG_PATH, WA_FILE_NAME);
+ servletContext.setAttribute("ObjectMap", map);
+ return map;
+ }

- /**
- * If the context is already existing, we probably can directly
return the objectMap
- * @return
- */
- public ObjectMap objectMap() {
- return objectMap(context);
- }
+ /**
+ * If the context is already existing, we probably can directly return
the
+ * objectMap
+ *
+ * @return
+ */
+ public ObjectMap objectMap() {
+ return objectMap(context);
+ }

- public ConfigurationServletHelper(HttpServletRequest request,
- HttpServletResponse response, ServletContext context)
{
- this.request = request;
- this.context = context;
- this.generator = new HTMLGenerator();
-
- // Get the current session or create it
- this.session = request.getSession(true);
+ public ConfigurationServletHelper(HttpServletRequest request,
HttpServletResponse response, ServletContext context) {
+ this.request = request;
+ this.context = context;
+ this.generator = new HTMLGenerator();

- // We'll deal only with text/html
- response.setContentType("text/html");
+ // Get the current session or create it
+ this.session = request.getSession(true);

- if (session.isNew()) {
- // Set session max duration
- session.setMaxInactiveInterval(SESSION_INTERVAL);
- }
+ // We'll deal only with text/html
+ response.setContentType("text/html");

- }
+ if (session.isNew()) {
+ // Set session max duration
+ session.setMaxInactiveInterval(SESSION_INTERVAL);
+ }

- /**
- * Generates the HTML code for the corresponding page given as HTTP
Parameter
- * @return
- */
- public String getHTMLContent() {
- String pageParameterValue = getHttpParameter("page");
- return getHTMLContent(pageParameterValue);
- }
+ }

- /**
- * Generates the HTML code for the given page
- * @param pageType
- * @return
- */
- private String getHTMLContent(String pageType) {
- logger.debug("Looking up page \"" + pageType + "\"");
+ /**
+ * Generates the HTML code for the corresponding page given as HTTP
+ * Parameter
+ *
+ * @return
+ */
+ public String getHTMLContent() {
+ String pageParameterValue = getHttpParameter("page");
+ return getHTMLContent(pageParameterValue);
+ }

- StringBuffer htmlsb = new StringBuffer();
- HTMLUtil html = new HTMLUtil(htmlsb);
- try {
- html.preamble();
- StringBuffer translatesb = new StringBuffer();
- if (generator.translate(pageType, objectMap(),
translatesb)) {
- logger.debug(pageType + " page was found and
content was generated, let's wrap it in a form");
- html.form_begin("form_key", pageType,
"config?page=" + pageType, 1);
- html.simplelineoftext("Please fill in the
following fields:", "green");
- htmlsb.append(translatesb.toString());
- html.form_end();
- } else {
- logger.warn("Page \"" + pageType + "\" not
found!");
- htmlsb.append(translatesb.toString());
- }
- html.postscript();
- } catch (IOException e) {
- logger.error("Error generating HTML for " + pageType
+ " :" + e.getMessage());
- return HTMLUtil.colouredtext("Something went wrong
generating the HTML content for " + pageType
- + ". More information is available in
the log file.", "red");
- }
- return html.getContent();
- }
+ /**
+ * Generates the HTML code for the given page
+ *
+ * @param pageType
+ * @return
+ */
+ private String getHTMLContent(String pageType) {
+ logger.debug("Looking up page \"" + pageType + "\"");

- /**
- * We process the data received from a form POST
(ConfigurationServlet)
- * and we try to save it to the configuration file.
- * @return
- */
- @SuppressWarnings("unchecked")
- public boolean processData() {
- boolean saved = false;
- logger.debug("Processing data received from a form POST.");
+ StringBuffer htmlsb = new StringBuffer();
+ HTMLUtil html = new HTMLUtil(htmlsb);
+ try {
+ html.preamble();
+ StringBuffer translatesb = new StringBuffer();
+ if (generator.translate(pageType, objectMap(), translatesb)) {
+ logger.debug(pageType + " page was found and content was
generated, let's wrap it in a form");
+ html.formBegin("form_key", pageType, "config?page=" +
pageType, 1);
+ html.simplelineoftext("Please fill in the following
fields:", "green");
+ htmlsb.append(translatesb.toString());
+ html.formEnd();
+ } else {
+ logger.warn("Page \"" + pageType + "\" not found!");
+ htmlsb.append(translatesb.toString());
+ }
+ html.postscript();
+ } catch (IOException e) {
+ logger.error("Error generating HTML for " + pageType + " :" +
e.getMessage());
+ return HTMLUtil.colouredtext("Something went wrong generating
the HTML content for " + pageType
+ + ". More information is available in the log file.",
"red");
+ }
+ return html.getContent();
+ }

- // We update the objectMap with the data we received
- objectMap().updateObjects(request.getParameterMap());
-
- // Then we try to save the objectMap to the file
- if (objectMap().save()) {
- logger.debug("Configuration correctly saved");
- saved = true;
- } else {
- logger.warn("Problem saving the new configuration,
we'll display an error message.");
- // TODO: It would have been better to display the
form again, so the user could try to fix the issue.
- saved = false;
- }
- logger.debug("Done processing client data.");
+ /**
+ * We process the data received from a form POST (ConfigurationServlet)
and
+ * we try to save it to the configuration file.
+ *
+ * @return
+ */
+ @SuppressWarnings("unchecked")
+ public boolean processData() {
+ boolean saved = false;
+ logger.debug("Processing data received from a form POST.");

- return saved;
- }
+ // We update the objectMap with the data we received
+ objectMap().updateObjects(request.getParameterMap());

- /**
- * Get Parameter from HttpRequest
- *
- * @param paramName Parameter name to look for
- * @return
- */
- private String getHttpParameter(String paramName) {
- String p = request.getParameter(paramName);
- if (p == null) {
- logger.debug("Parameter \"" + paramName + "\" not
found in HTTPRequest");
- return null;
- } else {
- return p.trim();
- }
- }
+ // Then we try to save the objectMap to the file
+ if (objectMap().save()) {
+ logger.debug("Configuration correctly saved");
+ saved = true;
+ } else {
+ logger.warn("Problem saving the new configuration, we'll display
an error message.");
+ // TODO: It would have been better to display the form again, so
the
+ // user could try to fix the issue.
+ saved = false;
+ }
+ logger.debug("Done processing client data.");

+ return saved;
+ }
+
+ /**
+ * Get Parameter from HttpRequest
+ *
+ * @param paramName
+ * Parameter name to look for
+ * @return
+ */
+ private String getHttpParameter(String paramName) {
+ String p = request.getParameter(paramName);
+ if (p == null) {
+ logger.debug("Parameter \"" + paramName + "\" not found in
HTTPRequest");
+ return null;
+ } else {
+ return p.trim();
+ }
+ }
+
};

Modified:
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/test/SOAPClient.java
===================================================================
---
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/test/SOAPClient.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/test/SOAPClient.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -22,58 +22,59 @@
*/
public class SOAPClient {

- private final Logger logger = LoggerFactory.getLogger(getClass());
+ private final Logger logger = LoggerFactory.getLogger(getClass());

- private final String url;
+ private final String url;

- public SOAPClient(String url) {
- this.url = url;
- }
+ public SOAPClient(String url) {
+ this.url = url;
+ }

- /**
- * Sends a request to the web service and returns the content of the
response
- *
- * @param content
- * - content of the message (soap message)
- * @return
- * @throws UnsupportedEncodingException
- */
- public String sendMessage(String content) throws SOAPClientException {
+ /**
+ * Sends a request to the web service and returns the content of the
+ * response
+ *
+ * @param content
+ * - content of the message (soap message)
+ * @return
+ * @throws UnsupportedEncodingException
+ */
+ public String sendMessage(String content) throws SOAPClientException {

- HttpClient httpclient = new DefaultHttpClient();
- HttpPost httpPost = new HttpPost(url);
-
- // define required HTTP headers
- httpPost.setHeader("Content-type", "text/xml;
charset=UTF-8;");
- httpPost.setHeader("SOAPAction", "");
+ HttpClient httpclient = new DefaultHttpClient();
+ HttpPost httpPost = new HttpPost(url);

- StringEntity entity;
- try {
- entity = new StringEntity(content);
- httpPost.setEntity(entity);
+ // define required HTTP headers
+ httpPost.setHeader("Content-type", "text/xml; charset=UTF-8;");
+ httpPost.setHeader("SOAPAction", "");

- ResponseHandler<String> responseHandler = new
BasicResponseHandler();
+ StringEntity entity;
+ try {
+ entity = new StringEntity(content);
+ httpPost.setEntity(entity);

- try {
- return httpclient.execute(httpPost,
responseHandler);
- } catch (ClientProtocolException e) {
- logger.error("SOAP HTTP POST error: " +
e.getMessage());
- // TODO: We should use perfSONAR Exceptions
here
- throw new SOAPClientException(e);
- } catch (IOException e) {
- e.printStackTrace();
- // TODO: We should use perfSONAR Exceptions
here
- throw new SOAPClientException(e);
- } finally {
- if (httpclient != null) {
-
httpclient.getConnectionManager().shutdown();
- }
- }
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- // TODO: We should use perfSONAR Exceptions here
- throw new SOAPClientException(e);
- }
- }
+ ResponseHandler<String> responseHandler = new
BasicResponseHandler();

+ try {
+ return httpclient.execute(httpPost, responseHandler);
+ } catch (ClientProtocolException e) {
+ logger.error("SOAP HTTP POST error: " + e.getMessage());
+ // TODO: We should use perfSONAR Exceptions here
+ throw new SOAPClientException(e);
+ } catch (IOException e) {
+ e.printStackTrace();
+ // TODO: We should use perfSONAR Exceptions here
+ throw new SOAPClientException(e);
+ } finally {
+ if (httpclient != null) {
+ httpclient.getConnectionManager().shutdown();
+ }
+ }
+ } catch (UnsupportedEncodingException e) {
+ e.printStackTrace();
+ // TODO: We should use perfSONAR Exceptions here
+ throw new SOAPClientException(e);
+ }
+ }
+
}

Modified:
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/test/SOAPClientException.java
===================================================================
---
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/test/SOAPClientException.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/test/SOAPClientException.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -1,9 +1,9 @@
package org.perfsonar.webadmin.test;

@SuppressWarnings("serial")
-public class SOAPClientException extends Exception{
-
- public SOAPClientException(Throwable throwable) {
- super(throwable);
- }
+public class SOAPClientException extends Exception {
+
+ public SOAPClientException(Throwable throwable) {
+ super(throwable);
+ }
}

Modified:
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/util/HTMLUtil.java
===================================================================
---
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/util/HTMLUtil.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/util/HTMLUtil.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -3,375 +3,346 @@
import java.io.IOException;

/**
- * Generates HTML code for the WebAdmin pages.
- * This is done in a StringBufffer for ease of use.
+ * Generates HTML code for the WebAdmin pages. This is done in a
StringBufffer
+ * for ease of use.
*/
public class HTMLUtil {
// Size of all <INPUT> fields
private int inputSize = 75;
- private int colspan = 1;
- private StringBuffer sb;
+ private int colspan = 1;
+ private StringBuffer sb;

- public HTMLUtil(StringBuffer sb) {
- this.sb = sb;
- }
+ public HTMLUtil(StringBuffer sb) {
+ this.sb = sb;
+ }

- public void println(String s) {
- sb.append(s);
- }
+ public void println(String s) {
+ sb.append(s);
+ }

- public String getContent() {
- return sb.toString();
- }
+ public String getContent() {
+ return sb.toString();
+ }

- public static String tag(String name, String attr, String body) {
- return "<" + name + attr + ">" + body + "</" + name + ">\n";
- }
+ public static String tag(String name, String attr, String body) {
+ return "<" + name + attr + ">" + body + "</" + name + ">\n";
+ }

- public static String tag(String name, String body) {
- return "<" + name + ">" + body + "</" + name + ">\n";
- }
+ public static String tag(String name, String body) {
+ return "<" + name + ">" + body + "</" + name + ">\n";
+ }

- public static String atag(String name, String attr) {
- return "<" + name + attr + "/>\n";
- }
+ public static String atag(String name, String attr) {
+ return "<" + name + attr + "/>\n";
+ }

- public static String tag(String name) {
- return "<" + name + "/>\n";
- }
+ public static String tag(String name) {
+ return "<" + name + "/>\n";
+ }

- public static String btag(String name, String body, String... atts) {
- String ret = "<" + name + " ";
- if (atts != null && atts.length > 0) {
- for (String s : atts)
- ret += s + " ";
- }
- return ret + ">" + body + "</" + name + ">\n";
- }
+ public static String btag(String name, String body, String... atts) {
+ String ret = "<" + name + " ";
+ if (atts != null && atts.length > 0) {
+ for (String s : atts) {
+ ret += s + " ";
+ }
+ }
+ return ret + ">" + body + "</" + name + ">\n";
+ }

- public static String att(String attr, String val) {
- if (val == null)
- return "";
- else
- return " " + attr + " = \"" + val + "\" ";
- }
+ public static String att(String attr, String val) {
+ if (val == null) {
+ return "";
+ } else {
+ return " " + attr + " = \"" + val + "\" ";
+ }
+ }

- public static String table(boolean b, String body) {
- return btag("table", body, att("center", (b ? "center" :
null)));
- }
+ public static String table(boolean b, String body) {
+ return btag("table", body, att("center", b ? "center" : null));
+ }

- public static String div(String cls, String id, String align, String
style,
- String body) {
- return btag("div", body, att("class", cls), att("id", id),
att("align",
- align), att("style", style));
- }
+ public static String div(String cls, String id, String align, String
style, String body) {
+ return btag("div", body, att("class", cls), att("id", id),
att("align", align), att("style", style));
+ }

- public static String form(String action, String name, String method,
- String onsubmit, String body) {
- return btag("form", body, att("action", action), att("name",
name),
- att("method", method), att("onsubmit",
onsubmit));
- }
+ public static String form(String action, String name, String method,
String onsubmit, String body) {
+ return btag("form", body, att("action", action), att("name", name),
att("method", method),
+ att("onsubmit", onsubmit));
+ }

- public static String p(String cls, String body) {
- return btag("p", body, att("class", cls));
- }
+ public static String p(String cls, String body) {
+ return btag("p", body, att("class", cls));
+ }

- public static String input(String type, String name, String value,
- String onClick, String body) {
- return btag("input", body, att("type", type), att("name",
name), att(
- "value", value), att("onClick", onClick));
- }
+ public static String input(String type, String name, String value,
String onClick, String body) {
+ return btag("input", body, att("type", type), att("name", name),
att("value", value), att("onClick", onClick));
+ }

- public static String radio_chk(String type, String name, String value,
- String onClick, String body) {
- return btag("input", body, att("type", type), att("name",
name), att(
- "value", value), att("onClick", onClick),
- att("checked", "true"));
- }
+ public static String radioChk(String type, String name, String value,
String onClick, String body) {
+ return btag("input", body, att("type", type), att("name", name),
att("value", value), att("onClick", onClick),
+ att("checked", "true"));
+ }

- public static String input_id(String type, String id, String value,
- String onClick, String body) {
- return btag("input", body, att("type", type), att("id", id),
att(
- "value", value), att("onClick", onClick));
- }
+ public static String inputId(String type, String id, String value,
String onClick, String body) {
+ return btag("input", body, att("type", type), att("id", id),
att("value", value), att("onClick", onClick));
+ }

- public static String html(String body) {
- return btag("html", body);
- }
+ public static String html(String body) {
+ return btag("html", body);
+ }

- public static String body(String bd) {
- return btag("body", bd);
- }
+ public static String body(String bd) {
+ return btag("body", bd);
+ }

- public static String head(String bd) {
- return btag("head", bd);
- }
+ public static String head(String bd) {
+ return btag("head", bd);
+ }

- public static String title(String bd) {
- return btag("title", bd);
- }
+ public static String title(String bd) {
+ return btag("title", bd);
+ }

- public static String ul(String bd) {
- return btag("ul", bd);
- }
+ public static String ul(String bd) {
+ return btag("ul", bd);
+ }

- public static String li(String bd) {
- return btag("li", bd);
- }
+ public static String li(String bd) {
+ return btag("li", bd);
+ }

- public static String h1(String bd) {
- return btag("h1", bd);
- }
+ public static String h1(String bd) {
+ return btag("h1", bd);
+ }

- public static String a(String href, String bd) {
- return btag("a", bd, att("href", href));
- }
+ public static String a(String href, String bd) {
+ return btag("a", bd, att("href", href));
+ }

- public static String br(String body) {
- return btag("br", body);
- }
+ public static String br(String body) {
+ return btag("br", body);
+ }

- public static String tr(String body) {
- return btag("tr", body);
- }
+ public static String tr(String body) {
+ return btag("tr", body);
+ }

- public static String td(String body) {
- return btag("td", body);
- }
+ public static String td(String body) {
+ return btag("td", body);
+ }

- public static String td_col(String body) {
- return btag("td", body, att("colspan", "2"));
- }
+ public static String tdCol(String body) {
+ return btag("td", body, att("colspan", "2"));
+ }

- public static String span(String cls, String body) {
- return btag("span", body, att("class", cls));
- }
+ public static String span(String cls, String body) {
+ return btag("span", body, att("class", cls));
+ }

- public static String colouredtext(String text, String colour) {
- return tag("font", att("color", colour), text);
- }
+ public static String colouredtext(String text, String colour) {
+ return tag("font", att("color", colour), text);
+ }

- public static String greenasterisk() {
- return "<span class=\"greenasterisk\" >*</span>";
- }
+ public static String greenasterisk() {
+ return "<span class=\"greenasterisk\" >*</span>";
+ }

- private static final String doctype = "<!DOCTYPE HTML PUBLIC
\"-//W3C//DTD HTML 4.01"
- + " Transitional//EN\"
\"http://www.w3.org/TR/html4/loose.dtd\";> ";
- private static final String cssFile = "default.css";
- private static final String onClickAttribute = "
onclick=\"checkIt(this);\" ";
- private static final String nbsp = "&nbsp;";
- private static final String checkedAttribute = " checked =\"true\" ";
//
- private static final String blockedAttribute = "
style=\"display:block;\" ";
- private static final String unblockedAttribute = "
style=\"display:none;\" ";
+ private static final String ON_CLICK_ATTRIBUTE = "
onclick=\"checkIt(this);\" ";
+ private static final String NBSP = "&NBSP;";
+ private static final String CHECKED_ATTR = " checked =\"true\" "; //
+ private static final String BLOCKED_ATTR = " style=\"display:block;\" ";
+ private static final String UNBLOCKED_ATTR = " style=\"display:none;\" ";

- private static String times(int i) {
- String ret = "";
- for (int j = 0; j < i; j++)
- ret += nbsp;
- return ret;
- }
+ private static String times(int i) {
+ String ret = "";
+ for (int j = 0; j < i; j++) {
+ ret += NBSP;
+ }
+ return ret;
+ }

- private String getCSS() {
- String css = "<link rel=\"stylesheet\" type=\"text/css\"
href=\""
- + cssFile + "\"/>";
- return css;
- }
+ private String getScript() {
+ // FIXME Vl_ stuff
+ return "<script src=\"Service_Admin.js\">"
+ + "</script>\n"
+ + "<script src=\"wz_tooltip.js\">"
+ + "</script>\n"
+ + "<script src=\"Service_Admin.js\">"
+ + "</script>\n"
+ + "<script type=\"text/javascript\">\n"
+ + "function checkIt(el) {\n"
+ // el = clicked element
+ // el.value = value attribute of clicked element el
+ // el.name = name attribute of clicked element el
+ // if the clicked element's value is the same
+ // as the hidden tag's (whose id=Vl_ + name clicked elt)
+ // default value then
+ // disable all elements whose id is the same as the
+ // clicked element's name
+ // +
+ // "document.write(el.value
+ // +\"\\n\"+document.getElementById(\"Vl_\"+el.name).value
+ //
+\"\\n\"+document.getElementById(el.name).style.display)\n"
+ + "if (el.value == " +
"document.getElementById(\"Vl_\"+el.name).value) {\n"
+ + "document.getElementById(el.name).style.display = " +
"\"block\";\n" + "}\n" + "else {\n"
+ + "document.getElementById(el.name).style.display =" + "
\"none\";\n" + "}\n" + "}\n" + "</script>\n";
+ }

- private String getScript() // FIXME Vl_ stuff
- {
- return "<script src=\"Service_Admin.js\">"
- + "</script>\n"
- + "<script src=\"wz_tooltip.js\">"
- + "</script>\n"
- + "<script src=\"Service_Admin.js\">"
- + "</script>\n"
- + "<script type=\"text/javascript\">\n"
- + "function checkIt(el) {\n"
- // el = clicked element
- // el.value = value attribute of clicked
element el
- // el.name = name attribute of clicked
element el
- // if the clicked element's value is the same
- // as the hidden tag's (whose id=Vl_ + name
clicked elt)
- // default value then
- // disable all elements whose id is the same
as the
- // clicked element's name
- // +
- // "document.write(el.value
+\"\\n\"+document.getElementById(\"Vl_\"+el.name).value+\"\\n\"+document.getElementById(el.name).style.display)\n"
- + "if (el.value == "
- +
"document.getElementById(\"Vl_\"+el.name).value) {\n"
- +
"document.getElementById(el.name).style.display = "
- + "\"block\";\n" + "}\n" + "else {\n"
- +
"document.getElementById(el.name).style.display ="
- + " \"none\";\n" + "}\n" + "}\n" +
"</script>\n";
- }
+ public void preamble() throws IOException {
+ println(getScript());
+ println("<div class=\"main\">");
+ }

- public void preamble() throws IOException {
- println(getScript());
- println("<div class=\"main\">");
- }
+ public void postscript() throws IOException {
+ println("</div>");
+ }

- public void postscript() throws IOException {
- println("</div>");
- }
+ public void errorBox(String body) {
+ println(btag("div", body, att("class", "failed")));
+ }

- public void errorBox(String body) {
- println(btag("div", body, att("class", "failed")));
- }
+ // Specification:
+ // for each grouped radio elt
+ // there exists a hidden tag
+ // whose
+ // id = Vl_+name attr of radio elt
+ // and
+ // name denotes the disabled value
+ // there exist other elements
+ // whose
+ // id = name attr of radio elt

- // Specification:
- // for each grouped radio elt
- // there exists a hidden tag
- // whose
- // id = Vl_+name attr of radio elt
- // and
- // name denotes the disabled value
- // there exist other elements
- // whose
- // id = name attr of radio elt
+ public void radiogroupBegin(String id, String title, String yesval,
String noval, boolean enabled)
+ throws IOException {
+ println(tag(
+ "tr",
+ tag("td", title)
+ + times(13)
+ + tag("td",
+ atag("input", att("type", "hidden") +
att("value", yesval) + att("id", "Vl_" + id))
+ + tag("input", att("type", "radio")
+ att("name", id) + att("value", yesval)
+ + ON_CLICK_ATTRIBUTE +
(enabled ? CHECKED_ATTR : ""), times(2)
+ + yesval + NBSP)
+ + tag("input", att("type", "radio")
+ att("name", id) + att("value", noval)
+ + ON_CLICK_ATTRIBUTE +
(!enabled ? CHECKED_ATTR : ""), times(2)
+ + noval + times(14)))));
+ println("<tr><td>" + "<div " + att("id", id) + att("class",
"inner_properties")
+ + (!enabled ? UNBLOCKED_ATTR : BLOCKED_ATTR) + " > ");
+ tableBegin();
+ }

- public void radiogroup_begin(String id, String title, String yesval,
- String noval, boolean enabled) throws IOException {
- println(
- tag("tr", tag("td", title)
- + times(13)
- + tag("td", atag("input", att("type",
"hidden")
- + att("value", yesval) +
att("id", "Vl_" + id))
- + tag("input", att("type",
"radio") + att("name", id)
- +
att("value", yesval) + onClickAttribute
- + (enabled ?
checkedAttribute : ""), times(2)
- + yesval +
nbsp)
- + tag("input", att("type",
"radio") + att("name", id)
- +
att("value", noval) + onClickAttribute
- + (!enabled ?
checkedAttribute : ""), times(2)
- + noval +
times(14)))));
- println("<tr><td>" + "<div " + att("id", id)
- + att("class", "inner_properties")
- + (!enabled ? unblockedAttribute :
blockedAttribute) + " > ");
- table_begin();
- }
+ public void radiogroupEnd() {
+ tableEnd();

- public void radiogroup_end() {
- table_end();
+ println("</div></td></tr>");
+ }

- println("</div></td></tr>");
- }
+ private void generictextbox(String type, String key, String title,
String val) throws IOException {

- private void generictextbox(String type, String key, String title,
- String val) throws IOException {
+ println(tag(
+ "tr",
+ tag("td", att("colspan", "" + colspan), title)
+ + tag("td",
+ att("align", "left"),
+ atag("input",
+ att("class", "input_style") +
att("type", type) + att("name", key)
+ + att("size", "" +
inputSize) + att("value", val)))));
+ }

- println(tag("tr", tag("td", att("colspan", "" + colspan),
title)
- + tag("td", att("align", "left"),
atag("input", att("class",
- "input_style")
- + att("type", type)
- + att("name", key)
- + att("size", "" + inputSize)
+ att("value", val))))
- );
- }
+ public void textbox(String key, String title, String val) throws
IOException {
+ generictextbox("text", key, title, val);
+ }

- public void textbox(String key, String title, String val)
- throws IOException {
- generictextbox("text", key, title, val);
- }
+ public void passtextbox(String key, String title, String val) throws
IOException {
+ generictextbox("password", key, title, val);
+ }

- public void passtextbox(String key, String title, String val)
- throws IOException {
- generictextbox("password", key, title, val);
- }
+ // assumes keys.length = vals.length
+ public void radio(String key, String title, String[] vals) throws
IOException {
+ String opts = "";
+ for (int i = 0; i < vals.length; i++) {
+ opts += tag("input", att("type", "radio") + att("name", key) +
att("value", vals[i])
+ + (i == 0 ? CHECKED_ATTR : ""), times(2) + vals[i] +
NBSP);
+ }
+ println(tag("tr", tag("td", att("colspan", "" + colspan), title) +
tag("td", opts)));
+ }

- // assumes keys.length = vals.length
- public void radio(String key, String title, String[] vals)
- throws IOException {
- String opts = "";
- for (int i = 0; i < vals.length; i++) {
- opts += tag("input", att("type", "radio") +
att("name", key)
- + att("value", vals[i]) + (i == 0 ?
checkedAttribute : ""),
- times(2) + vals[i] + nbsp);
- }
- println(tag("tr", tag("td", att("colspan", "" + colspan),
title)
- + tag("td", opts)));
- }
+ public void dropdown(String key, String title, String[] vals) {
+ String opts = "";
+ for (int i = 0; i < vals.length; i++) {
+ opts += tag("option", att("value", vals[i]), vals[i]);
+ }
+ println(tag(
+ "tr",
+ tag("td", att("colspan", "" + colspan), title)
+ + tag("td", att("align", "left"), tag("select",
att("name", key), opts))));
+ }

- public void dropdown(String key, String title, String[] vals) {
- String opts = "";
- for (int i = 0; i < vals.length; i++)
- opts += tag("option", att("value", vals[i]), vals[i]);
- println(tag("tr", tag("td", att("colspan", "" + colspan),
title)
- + tag("td", att("align", "left"),
tag("select",
- att("name", key), opts))));
- }
+ public void formBegin(String key, String val, String url, int spacing)
throws IOException {
+ println("<div " + att("class", "properties") + " > " + "<form
action=\"" + url + "\" method=\"POST\">\n"
+ + "<input type=\"hidden\" name=\"" + key + "\" value=\"" +
val + "\">\n" + "<table align=\"center\" "
+ + att("cellspacing", spacing + "%") + " >");
+ }

- public void form_begin(String key, String val, String url, int
spacing)
- throws IOException {
- println("<div "
- + att("class", "properties")
- + " > "
- +
- "<form action=\"" + url + "\"
method=\"POST\">\n"
- + "<input type=\"hidden\" name=\"" + key +
"\" value=\"" + val
- + "\">\n" + "<table align=\"center\" "
- + att("cellspacing", spacing + "%") + " >");
- }
+ public void formBegin(String key, String val, String url) throws
IOException {
+ formBegin(key, val, url, 10);
+ }

- public void form_begin(String key, String val, String url)
- throws IOException {
- form_begin(key, val, url, 10);
- }
+ public void formEnd() throws IOException {
+ println(tag(
+ "tr",
+ tag("td", NBSP)
+ + tag("td",
+ att("align", "right") + att("colspan", "" +
colspan),
+ atag("input",
+ att("type", "submit") + att("class",
"submit_button") + att("name", "submit")
+ + att("value", "Submit"))))
+ + "</table><p/>\n" + "</form>"
+ + "</div>");
+ }

- public void form_end() throws IOException {
- println(tag("tr", tag("td", nbsp)
- + tag("td", att("align", "right") +
att("colspan", "" + colspan),
- atag("input", att("type", "submit") +
att("class", "submit_button")
- + att("name", "submit") +
att("value", "Submit"))))
- + "</table><p/>\n" + "</form>" +
- // "</center>"+
- "</div>");
- }
+ public void singlerowBegin(int spacing, int span) {

- public void singlerow_begin(int spacing, int span) {
+ println("<tr><td " + att("colspan", "" + span) + " >");
+ tableBegin(spacing);
+ }

- println("<tr><td " + att("colspan", "" + span) + " >");
- table_begin(spacing);
- }
+ public void singlerowBegin(int spacing) {
+ singlerowBegin(spacing, 1);
+ }

- public void singlerow_begin(int spacing) {
- singlerow_begin(spacing, 1);
- }
+ public void singlerowEnd() {
+ tableEnd();
+ println("</td></tr>");
+ }

- public void singlerow_end() {
- table_end();
- println("</td></tr>");
- }
+ public void tableBegin() {
+ tableBegin(10);
+ }

- public void table_begin() {
- table_begin(10);
- }
+ public void tableBegin(int spacing) {
+ println("<div " + att("class", "properties") + " > " +
"<center><table align=\"left\" "
+ + att("cellspacing", spacing + "%") + ">");
+ }

- public void table_begin(int spacing) {
- println("<div " + att("class", "properties") + " > "
- + "<center><table align=\"left\" "
- + att("cellspacing", spacing + "%") + ">");
- }
+ public void tableEnd() {
+ println("</table></center></div>");
+ }

- public void table_end() {
- println("</table></center></div>");
- }
+ public void lineoftext(String text, String colour, int fill) {
+ singlerowBegin(1, 2);
+ println(tag("tr", tag("td", colouredtext(text + times(fill),
colour))));
+ singlerowEnd();
+ }

- public void lineoftext(String text, String colour, int fill) {
- singlerow_begin(1, 2);
- println(tag("tr", tag("td", colouredtext(text + times(fill),
colour))));
- singlerow_end();
- }
+ public void simplelineoftext(String text, String colour) { // +
+ println("<tr><td " + " >\n" + tag("tr", tag("td", tag("p",
colouredtext(text, colour)))) + "</td></tr>");
+ }

- public void simplelineoftext(String text, String colour) { // +
- println("<tr><td " + " >\n"
- + tag("tr", tag("td", tag("p",
colouredtext(text, colour))))
- + "</td></tr>");
- }
+ public void simplelineoftext(String span, String text, String colour) {
//
+ println("<tr><td " + att("colspan", "" + span) + " >\n"
+ + tag("tr", tag("td", tag("p", colouredtext(text, colour))))
+ "</td></tr>");
+ }

- public void simplelineoftext(String span, String text, String colour)
{ //
- println("<tr><td " + att("colspan", "" + span) + " >\n"
- + tag("tr", tag("td", tag("p",
colouredtext(text, colour))))
- + "</td></tr>");
- }
-
};

Modified:
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/util/NSContext.java
===================================================================
---
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/util/NSContext.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/util/NSContext.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -2,30 +2,31 @@

import java.util.HashMap;
import javax.xml.namespace.NamespaceContext;
-import javax.xml.*;
+import javax.xml.XMLConstants;
import java.util.Iterator;

@SuppressWarnings("serial")
public class NSContext extends HashMap<String, String> implements
NamespaceContext {

- public NSContext() {
- put("xml", XMLConstants.XML_NS_URI);
- }
+ public NSContext() {
+ put("xml", XMLConstants.XML_NS_URI);
+ }

- public String getNamespaceURI(String prefix) {
- if (prefix == null)
- throw new NullPointerException("Null prefix");
- String s = get(prefix);
- return (s == null) ? XMLConstants.NULL_NS_URI : s;
- }
+ public String getNamespaceURI(String prefix) {
+ if (prefix == null) {
+ throw new NullPointerException("Null prefix");
+ }
+ String s = get(prefix);
+ return (s == null) ? XMLConstants.NULL_NS_URI : s;
+ }

- // FIXME: This method isn't necessary for XPath processing.
- public String getPrefix(String uri) {
- throw new UnsupportedOperationException();
- }
+ // FIXME: This method isn't necessary for XPath processing.
+ public String getPrefix(String uri) {
+ throw new UnsupportedOperationException();
+ }

- // FIXME: This method isn't necessary for XPath processing either.
- public Iterator getPrefixes(String uri) {
- throw new UnsupportedOperationException();
- }
+ // FIXME: This method isn't necessary for XPath processing either.
+ public Iterator getPrefixes(String uri) {
+ throw new UnsupportedOperationException();
+ }
};

Modified:
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/util/Tuple.java
===================================================================
---
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/util/Tuple.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/util/Tuple.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -1,19 +1,19 @@
package org.perfsonar.webadmin.util;

public class Tuple<A, B> {
- A a;
- B b;
+ private A a;
+ private B b;

- public Tuple(A a, B b) {
- this.a = a;
- this.b = b;
- }
+ public Tuple(A a, B b) {
+ this.a = a;
+ this.b = b;
+ }

- public A first() {
- return a;
- }
+ public A first() {
+ return a;
+ }

- public B second() {
- return b;
- }
+ public B second() {
+ return b;
+ }
};

Modified:
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/util/WAXMLReader.java
===================================================================
---
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/util/WAXMLReader.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/util/WAXMLReader.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -16,28 +16,31 @@
import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource;

-public class WAXMLReader {
+public final class WAXMLReader {
+ private WAXMLReader() {
+ // Utility class, we don't want to be instantiated directly, we're
private
+ }

- private final static Logger logger =
LoggerFactory.getLogger(WAXMLReader.class);
+ private static final Logger LOGGER =
LoggerFactory.getLogger(WAXMLReader.class);

- // The NS of the WebAdmin configuration file schema
- private final static String CLASS_NAME =
"org.perfsonar.webadmin.waschema.v20130205";
+ // The NS of the WebAdmin configuration file schema
+ private static final String CLASS_NAME =
"org.perfsonar.webadmin.waschema.v20130205";

- @SuppressWarnings("deprecation")
- public static Tuple<WebAdminInterface, JAXBContext> parseFile(String
fileName)
- throws FileNotFoundException, MalformedURLException,
JAXBException {
- File f = new File(fileName);
- InputSource iSource = new InputSource(new FileInputStream(f));
- iSource.setSystemId(f.toURL().toString());
- JAXBContext context = JAXBContext.newInstance(CLASS_NAME);
- Unmarshaller unmarshaller = context.createUnmarshaller();
- WebAdminInterface waIf = (WebAdminInterface)
unmarshaller.unmarshal(iSource);
- return new Tuple<WebAdminInterface, JAXBContext>(waIf,
context);
- }
+ @SuppressWarnings("deprecation")
+ public static Tuple<WebAdminInterface, JAXBContext> parseFile(String
fileName) throws FileNotFoundException,
+ MalformedURLException, JAXBException {
+ File f = new File(fileName);
+ InputSource iSource = new InputSource(new FileInputStream(f));
+ iSource.setSystemId(f.toURL().toString());
+ JAXBContext context = JAXBContext.newInstance(CLASS_NAME);
+ Unmarshaller unmarshaller = context.createUnmarshaller();
+ WebAdminInterface waIf = (WebAdminInterface)
unmarshaller.unmarshal(iSource);
+ return new Tuple<WebAdminInterface, JAXBContext>(waIf, context);
+ }

- public static void main(String[] args) throws Exception {
- WebAdminInterface r = parseFile(args[0]).first();
- List<PageType> p = r.getPage();
- logger.debug("Pages " + p.size() + " " +
p.get(0).getClass().getName());
- }
+ public static void main(String[] args) throws Exception {
+ WebAdminInterface r = parseFile(args[0]).first();
+ List<PageType> p = r.getPage();
+ LOGGER.debug("Pages " + p.size() + " " +
p.get(0).getClass().getName());
+ }
};

Modified:
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/util/WAXMLWriter.java
===================================================================
---
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/util/WAXMLWriter.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/util/WAXMLWriter.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -8,14 +8,17 @@

import org.perfsonar.webadmin.waschema.v20130205.WebAdminInterface;

-public class WAXMLWriter {
- public static void writeToFile(JAXBContext pContext,
- WebAdminInterface pObject, String pFileName) throws
JAXBException,
- IOException {
- java.io.FileOutputStream fos = new
java.io.FileOutputStream(pFileName);
- Marshaller marshaller = pContext.createMarshaller();
- marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
- marshaller.marshal(pObject, fos);
- fos.close();
- }
+public final class WAXMLWriter {
+ private WAXMLWriter() {
+ // Utility class, we don't want to be instantiated directly, we're
private
+ }
+
+ public static void writeToFile(JAXBContext pContext, WebAdminInterface
pObject, String pFileName)
+ throws JAXBException, IOException {
+ java.io.FileOutputStream fos = new
java.io.FileOutputStream(pFileName);
+ Marshaller marshaller = pContext.createMarshaller();
+ marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
+ marshaller.marshal(pObject, fos);
+ fos.close();
+ }
};

Modified:
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/util/XMLUtil.java
===================================================================
---
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/util/XMLUtil.java
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/java/org/perfsonar/webadmin/util/XMLUtil.java
2013-05-08 20:41:45 UTC (rev 6371)
@@ -29,118 +29,120 @@
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

-public class XMLUtil {
+public final class XMLUtil {

- private final static Logger logger =
LoggerFactory.getLogger(XMLUtil.class);
+ private XMLUtil() {
+ // Utility class, we don't want to be instantiated directly, we're
private
+ }
+ private static final Logger LOGGER =
LoggerFactory.getLogger(XMLUtil.class);

- @SuppressWarnings("deprecation")
- public static String readFile(String fname) throws Exception {
- java.io.File file = new File(fname);
- String ret = "";
- FileInputStream fis = null;
- BufferedInputStream bis = null;
- DataInputStream dis = null;
+ @SuppressWarnings("deprecation")
+ public static String readFile(String fname) throws Exception {
+ File file = new File(fname);
+ String ret = "";
+ FileInputStream fis = null;
+ BufferedInputStream bis = null;
+ DataInputStream dis = null;

- if (!file.exists())
- throw new Exception("File " + fname + " does not
exist ");
- else {
- try {
- fis = new FileInputStream(file);
- bis = new BufferedInputStream(fis);
- dis = new DataInputStream(bis);
- while (dis.available() != 0)
- ret += dis.readLine();
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- if (fis != null)
- fis.close();
- if (bis != null)
- bis.close();
- if (dis != null)
- dis.close();
- }
- }
- return ret;
- }
+ if (!file.exists()) {
+ throw new Exception("File " + fname + " does not exist ");
+ } else {
+ try {
+ fis = new FileInputStream(file);
+ bis = new BufferedInputStream(fis);
+ dis = new DataInputStream(bis);
+ while (dis.available() != 0) {
+ ret += dis.readLine();
+ }
+ } catch (FileNotFoundException e) {
+ e.printStackTrace();
+ } catch (IOException e) {
+ e.printStackTrace();
+ } finally {
+ if (fis != null) {
+ fis.close();
+ }
+ if (bis != null) {
+ bis.close();
+ }
+ if (dis != null) {
+ dis.close();
+ }
+ }
+ }
+ return ret;
+ }

- public static Document readDocument(String uri) throws Exception {
- DocumentBuilderFactory domFactory = DocumentBuilderFactory
- .newInstance();
- domFactory.setNamespaceAware(true); // never forget this!
- DocumentBuilder builder = domFactory.newDocumentBuilder();
- return builder.parse(uri);
- }
+ public static Document readDocument(String uri) throws Exception {
+ DocumentBuilderFactory domFactory =
DocumentBuilderFactory.newInstance();
+ domFactory.setNamespaceAware(true); // never forget this!
+ DocumentBuilder builder = domFactory.newDocumentBuilder();
+ return builder.parse(uri);
+ }

- public static NodeList query(NSContext ns, String q, Document doc)
- throws ParserConfigurationException, SAXException,
IOException,
- XPathExpressionException,
- javax.xml.xpath.XPathFactoryConfigurationException {
- System.setProperty("javax.xml.xpath.XPathFactory" + ":"
- +
javax.xml.xpath.XPathFactory.DEFAULT_OBJECT_MODEL_URI,
- "org.apache.xpath.jaxp.XPathFactoryImpl");
- XPathFactory factory = XPathFactory
-
.newInstance(javax.xml.xpath.XPathFactory.DEFAULT_OBJECT_MODEL_URI);
- XPath xpath = factory.newXPath();
- if (ns != null)
- xpath.setNamespaceContext(ns);
- XPathExpression expr = xpath.compile(q);
- Object result = expr.evaluate(doc, XPathConstants.NODESET);
- NodeList nodes = (NodeList) result;
- return nodes;
- }
+ public static NodeList query(NSContext ns, String q, Document doc)
throws ParserConfigurationException,
+ SAXException, IOException, XPathExpressionException,
javax.xml.xpath.XPathFactoryConfigurationException {
+ System.setProperty(
+ "javax.xml.xpath.XPathFactory" + ":" +
XPathFactory.DEFAULT_OBJECT_MODEL_URI,
+ "org.apache.xpath.jaxp.XPathFactoryImpl");
+ XPathFactory factory =
XPathFactory.newInstance(XPathFactory.DEFAULT_OBJECT_MODEL_URI);
+ XPath xpath = factory.newXPath();
+ if (ns != null) {
+ xpath.setNamespaceContext(ns);
+ }
+ XPathExpression expr = xpath.compile(q);
+ Object result = expr.evaluate(doc, XPathConstants.NODESET);
+ NodeList nodes = (NodeList) result;
+ return nodes;
+ }

- public static void writeXml(Document document, java.io.OutputStream
file)
- throws Exception {
- try {
- if (document == null) {
- logger.warn("WA -- Cann't write XML to file -
Null doc");
- return;
- }
- // Prepare the DOM document for writing
- Source source = new DOMSource(document);
+ public static void writeXml(Document document, java.io.OutputStream
file) throws Exception {
+ try {
+ if (document == null) {
+ LOGGER.warn("WA -- Cann't write XML to file - Null doc");
+ return;
+ }
+ // Prepare the DOM document for writing
+ Source source = new DOMSource(document);

- // Prepare the output file
- Result result = new StreamResult(file);
+ // Prepare the output file
+ Result result = new StreamResult(file);

- // Write the DOM document to the file
- // Get Transformer
- Transformer xformer = TransformerFactory.newInstance()
- .newTransformer();
-
xformer.setOutputProperty(javax.xml.transform.OutputKeys.INDENT,
- "yes");
- // xformer.getOutputProperties().store(System.out,"");
- // Write to a file
- xformer.transform(source, result);
- } catch (TransformerConfigurationException e) {
- logger.warn("TransformerConfigurationException: " +
e);
- } catch (TransformerException e) {
- logger.warn("TransformerException: " + e);
- }
- }
+ // Write the DOM document to the file
+ // Get Transformer
+ Transformer xformer =
TransformerFactory.newInstance().newTransformer();
+ xformer.setOutputProperty(javax.xml.transform.OutputKeys.INDENT,
"yes");
+ // xformer.getOutputProperties().store(System.out,"");
+ // Write to a file
+ xformer.transform(source, result);
+ } catch (TransformerConfigurationException e) {
+ LOGGER.warn("TransformerConfigurationException: " + e);
+ } catch (TransformerException e) {
+ LOGGER.warn("TransformerException: " + e);
+ }
+ }

- public static Tuple<String, String> parseXPath(String query) {
- query = query.trim();
- int i = 0;
- String[] qtoken = query.split("\\s+");
- query = "";
- for (String tk : qtoken)
- query += tk;
- String filename = "";
+ public static Tuple<String, String> parseXPath(String query) {
+ int i = 0;
+ String[] qtoken = query.trim().split("\\s+");
+ String myQuery = "";
+ for (String tk : qtoken) {
+ myQuery += tk;
+ }
+ String filename = "";

- if (query.length() < 8 || query.startsWith("doc(\"") ==
false) {
- throw new RuntimeException(
- "Did not find \"doc\" at the
beggining of query");
- } else if ((i = query.indexOf("\"", 5)) > 3) {
- if (i + 2 >= query.length()) {
- throw new RuntimeException("Invalid query");
- }
- filename = query.substring(5, i);
- query = query.substring(i + 2);
- } else
- throw new RuntimeException("Invalid query");
- return new Tuple<String, String>(filename, query);
- }
+ if (myQuery.length() < 8 || !myQuery.startsWith("doc(\"")) {
+ throw new RuntimeException("Did not find \"doc\" at the
beggining of query");
+ } else if (myQuery.indexOf("\"", 5) > 3) {
+ i = myQuery.indexOf("\"", 5);
+ if ((i + 2) >= myQuery.length()) {
+ throw new RuntimeException("Invalid query");
+ }
+ filename = myQuery.substring(5, i);
+ myQuery = myQuery.substring(i + 2);
+ } else {
+ throw new RuntimeException("Invalid query");
+ }
+ return new Tuple<String, String>(filename, myQuery);
+ }
};

Modified:
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/resources/wa.xsd
===================================================================
---
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/resources/wa.xsd
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/resources/wa.xsd
2013-05-08 20:41:45 UTC (rev 6371)
@@ -1,169 +1,132 @@
<?xml version="1.0" encoding="UTF-8"?>

-<xs:schema targetNamespace="http://webadmin.perfsonar.org/waschema/v20130205";
- xmlns:xs="http://www.w3.org/2001/XMLSchema";
xmlns:wa="http://webadmin.perfsonar.org/waschema/v20130205";
- elementFormDefault="qualified" attributeFormDefault="qualified">
+<xs:schema
targetNamespace="http://webadmin.perfsonar.org/waschema/v20130205";
xmlns:xs="http://www.w3.org/2001/XMLSchema";
+ xmlns:wa="http://webadmin.perfsonar.org/waschema/v20130205";
elementFormDefault="qualified" attributeFormDefault="qualified">

- <xs:complexType name="BaseType">
- <xs:choice>
- <xs:element name="xpath" type="xs:string"
minOccurs="1"
- maxOccurs="1" />
+ <xs:complexType name="BaseType">
+ <xs:choice>
+ <xs:element name="xpath" type="xs:string" minOccurs="1"
maxOccurs="1" />

- <xs:element name="text" type="xs:string" minOccurs="1"
- maxOccurs="1" />
- </xs:choice>
- </xs:complexType>
+ <xs:element name="text" type="xs:string" minOccurs="1"
maxOccurs="1" />
+ </xs:choice>
+ </xs:complexType>

- <xs:complexType name="BaseUIType">
- <xs:sequence>
- <xs:element name="default" type="wa:BaseType"
minOccurs="0"
- maxOccurs="1" />
- <xs:element name="title" type="wa:BaseType"
minOccurs="0"
- maxOccurs="1" />
- </xs:sequence>
- </xs:complexType>
+ <xs:complexType name="BaseUIType">
+ <xs:sequence>
+ <xs:element name="default" type="wa:BaseType" minOccurs="0"
maxOccurs="1" />
+ <xs:element name="title" type="wa:BaseType" minOccurs="0"
maxOccurs="1" />
+ </xs:sequence>
+ </xs:complexType>

- <xs:complexType name="ComplexUIType">
- <xs:complexContent>
- <xs:extension base="wa:BaseUIType">
- <xs:sequence>
- <xs:element name="values"
type="wa:BaseType" minOccurs="0"
- maxOccurs="1" />
- </xs:sequence>
- </xs:extension>
- </xs:complexContent>
- </xs:complexType>
+ <xs:complexType name="ComplexUIType">
+ <xs:complexContent>
+ <xs:extension base="wa:BaseUIType">
+ <xs:sequence>
+ <xs:element name="values" type="wa:BaseType"
minOccurs="0" maxOccurs="1" />
+ </xs:sequence>
+ </xs:extension>
+ </xs:complexContent>
+ </xs:complexType>

- <xs:complexType name="ComplexGroupUIType">
- <xs:complexContent>
- <xs:extension base="wa:BaseUIType">
- <xs:sequence>
- <xs:element name="values"
type="wa:BaseType" minOccurs="0"
- maxOccurs="1" />
- <xs:element name="plain"
type="wa:PlainType" minOccurs="1"
- maxOccurs="unbounded" />
- </xs:sequence>
- </xs:extension>
- </xs:complexContent>
- </xs:complexType>
+ <xs:complexType name="ComplexGroupUIType">
+ <xs:complexContent>
+ <xs:extension base="wa:BaseUIType">
+ <xs:sequence>
+ <xs:element name="values" type="wa:BaseType"
minOccurs="0" maxOccurs="1" />
+ <xs:element name="plain" type="wa:PlainType"
minOccurs="1" maxOccurs="unbounded" />
+ </xs:sequence>
+ </xs:extension>
+ </xs:complexContent>
+ </xs:complexType>

- <!-- Plain elements -->
- <xs:complexType name="PlainType">
- <xs:choice>
- <xs:element name="password" type="wa:BaseUIType"
- minOccurs="1" maxOccurs="1" />
- <xs:element name="textbox" type="wa:BaseUIType"
minOccurs="1"
- maxOccurs="1" />
- <xs:element name="radio" type="wa:ComplexUIType"
- minOccurs="1" maxOccurs="1" />
- <xs:element name="radiogroup"
type="wa:ComplexGroupUIType"
- minOccurs="1" maxOccurs="1" />
- <xs:element name="dropdown" type="wa:ComplexUIType"
- minOccurs="1" maxOccurs="1" />
- </xs:choice>
- </xs:complexType>
+ <!-- Plain elements -->
+ <xs:complexType name="PlainType">
+ <xs:choice>
+ <xs:element name="password" type="wa:BaseUIType" minOccurs="1"
maxOccurs="1" />
+ <xs:element name="textbox" type="wa:BaseUIType" minOccurs="1"
maxOccurs="1" />
+ <xs:element name="radio" type="wa:ComplexUIType" minOccurs="1"
maxOccurs="1" />
+ <xs:element name="radiogroup" type="wa:ComplexGroupUIType"
minOccurs="1" maxOccurs="1" />
+ <xs:element name="dropdown" type="wa:ComplexUIType"
minOccurs="1" maxOccurs="1" />
+ </xs:choice>
+ </xs:complexType>

- <!-- Groups -->
- <xs:complexType name="GroupType">
- <xs:sequence>
- <xs:element name="plain" type="wa:PlainType"
minOccurs="1"
- maxOccurs="unbounded" />
- <xs:element name="title" type="xs:string"
minOccurs="1"
- maxOccurs="1" />
- </xs:sequence>
- </xs:complexType>
+ <!-- Groups -->
+ <xs:complexType name="GroupType">
+ <xs:sequence>
+ <xs:element name="plain" type="wa:PlainType" minOccurs="1"
maxOccurs="unbounded" />
+ <xs:element name="title" type="xs:string" minOccurs="1"
maxOccurs="1" />
+ </xs:sequence>
+ </xs:complexType>

- <xs:complexType name="GroupsType">
- <xs:sequence>
- <xs:element name="group" type="wa:GroupType"
minOccurs="1"
- maxOccurs="unbounded" />
- </xs:sequence>
- </xs:complexType>
+ <xs:complexType name="GroupsType">
+ <xs:sequence>
+ <xs:element name="group" type="wa:GroupType" minOccurs="1"
maxOccurs="unbounded" />
+ </xs:sequence>
+ </xs:complexType>

- <!-- Pages -->
- <xs:complexType name="PageType">
- <xs:sequence>
- <xs:element name="pageId" type="wa:BaseType"
minOccurs="1"
- maxOccurs="1" />
- <xs:element name="title" type="wa:BaseType"
minOccurs="0"
- maxOccurs="1" />
- <xs:choice>
- <xs:element name="groups"
type="wa:GroupsType" minOccurs="1"
- maxOccurs="1" />
- <xs:element name="plain" type="wa:PlainType"
minOccurs="1"
- maxOccurs="unbounded" />
- </xs:choice>
- </xs:sequence>
- </xs:complexType>
+ <!-- Pages -->
+ <xs:complexType name="PageType">
+ <xs:sequence>
+ <xs:element name="pageId" type="wa:BaseType" minOccurs="1"
maxOccurs="1" />
+ <xs:element name="title" type="wa:BaseType" minOccurs="0"
maxOccurs="1" />
+ <xs:choice>
+ <xs:element name="groups" type="wa:GroupsType" minOccurs="1"
maxOccurs="1" />
+ <xs:element name="plain" type="wa:PlainType" minOccurs="1"
maxOccurs="unbounded" />
+ </xs:choice>
+ </xs:sequence>
+ </xs:complexType>


- <xs:complexType name="NsMap">
- <xs:sequence>
- <xs:element name="url" type="xs:string" minOccurs="1"
- maxOccurs="1" />
- <xs:element name="ns" type="xs:string" minOccurs="1"
- maxOccurs="1" />
- </xs:sequence>
- </xs:complexType>
+ <xs:complexType name="NsMap">
+ <xs:sequence>
+ <xs:element name="url" type="xs:string" minOccurs="1"
maxOccurs="1" />
+ <xs:element name="ns" type="xs:string" minOccurs="1"
maxOccurs="1" />
+ </xs:sequence>
+ </xs:complexType>

- <xs:complexType name="LinkType">
- <xs:sequence>
- <xs:choice>
- <xs:element name="pageId" type="xs:string"
minOccurs="1"
- maxOccurs="1" />
- <xs:element name="servletId" type="xs:string" minOccurs="1"
- maxOccurs="1" />
- <xs:element name="redirectTo"
type="xs:string" minOccurs="1"
- maxOccurs="1" />
- </xs:choice>
- <xs:element name="title" type="xs:string"
minOccurs="1"
- maxOccurs="1" />
- </xs:sequence>
- </xs:complexType>
+ <xs:complexType name="LinkType">
+ <xs:sequence>
+ <xs:choice>
+ <xs:element name="pageId" type="xs:string" minOccurs="1"
maxOccurs="1" />
+ <xs:element name="servletId" type="xs:string" minOccurs="1"
maxOccurs="1" />
+ <xs:element name="redirectTo" type="xs:string" minOccurs="1"
maxOccurs="1" />
+ </xs:choice>
+ <xs:element name="title" type="xs:string" minOccurs="1"
maxOccurs="1" />
+ </xs:sequence>
+ </xs:complexType>

- <xs:complexType name="Credential">
- <xs:sequence>
- <xs:element name="username" type="xs:string"
minOccurs="1"
- maxOccurs="1" />
- <xs:element name="password" type="xs:string"
minOccurs="1"
- maxOccurs="1" />
- </xs:sequence>
- </xs:complexType>
+ <xs:complexType name="Credential">
+ <xs:sequence>
+ <xs:element name="username" type="xs:string" minOccurs="1"
maxOccurs="1" />
+ <xs:element name="password" type="xs:string" minOccurs="1"
maxOccurs="1" />
+ </xs:sequence>
+ </xs:complexType>

- <xs:complexType name="ServiceInformation">
- <xs:sequence>
- <xs:element name="accessPoint" type="xs:string"
minOccurs="1"
- maxOccurs="1" />
- <xs:element name="serviceName" type="xs:string"
minOccurs="1"
- maxOccurs="1" />
- <xs:element name="version" type="xs:string"
minOccurs="1"
- maxOccurs="1" />
- </xs:sequence>
- </xs:complexType>
+ <xs:complexType name="ServiceInformation">
+ <xs:sequence>
+ <xs:element name="accessPoint" type="xs:string" minOccurs="1"
maxOccurs="1" />
+ <xs:element name="serviceName" type="xs:string" minOccurs="1"
maxOccurs="1" />
+ <xs:element name="version" type="xs:string" minOccurs="1"
maxOccurs="1" />
+ </xs:sequence>
+ </xs:complexType>

- <!-- Root -->
- <xs:element name="WebAdminInterface">
- <xs:complexType>
- <xs:sequence minOccurs="1" maxOccurs="1">
+ <!-- Root -->
+ <xs:element name="WebAdminInterface">
+ <xs:complexType>
+ <xs:sequence minOccurs="1" maxOccurs="1">

- <xs:element name="serviceInformation"
type="wa:ServiceInformation"
- minOccurs="1" maxOccurs="1" />
+ <xs:element name="serviceInformation"
type="wa:ServiceInformation" minOccurs="1" maxOccurs="1" />

- <xs:element name="credential"
type="wa:Credential"
- minOccurs="1" maxOccurs="1" />
+ <xs:element name="credential" type="wa:Credential"
minOccurs="1" maxOccurs="1" />

- <xs:element name="basiclink"
type="wa:LinkType"
- minOccurs="1" maxOccurs="unbounded" />
- <xs:element name="advancedlink"
type="wa:LinkType"
- minOccurs="0" maxOccurs="unbounded" />
+ <xs:element name="basiclink" type="wa:LinkType"
minOccurs="1" maxOccurs="unbounded" />
+ <xs:element name="advancedlink" type="wa:LinkType"
minOccurs="0" maxOccurs="unbounded" />

- <xs:element name="map" type="wa:NsMap"
minOccurs="0"
- maxOccurs="unbounded" />
- <xs:element name="page" type="wa:PageType"
minOccurs="1"
- maxOccurs="unbounded" />
- </xs:sequence>
- </xs:complexType>
+ <xs:element name="map" type="wa:NsMap" minOccurs="0"
maxOccurs="unbounded" />
+ <xs:element name="page" type="wa:PageType" minOccurs="1"
maxOccurs="unbounded" />
+ </xs:sequence>
+ </xs:complexType>

- </xs:element>
+ </xs:element>

</xs:schema>

Modified:
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/webapp/wa/scripts/Service_Admin.js
===================================================================
---
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/webapp/wa/scripts/Service_Admin.js
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/webapp/wa/scripts/Service_Admin.js
2013-05-08 20:41:45 UTC (rev 6371)
@@ -24,7 +24,7 @@
if (reset_button) {
var width = reset_button.parentNode.offsetWidth;
var offset = reset_button.parentNode.offsetLeft;
- var leftoffset = parent
+ var leftoffset = parent;
if (reset_button != null) {
if (y == 768) {
reset_button.style.top = 95 + '%';
@@ -122,7 +122,7 @@

var link = links[i];

- link.className
+ link.className;
}
}


Modified:
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/webapp/wa/scripts/wz_tooltip.js
===================================================================
---
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/webapp/wa/scripts/wz_tooltip.js
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/main/webapp/wa/scripts/wz_tooltip.js
2013-05-08 20:41:45 UTC (rev 6371)
@@ -42,9 +42,9 @@


//=================== GLOBAL TOOPTIP CONFIGURATION
=========================//
-var tt_Debug = true // false or true - recommended: false once
you release your page to the public
-var tt_Enabled = true // Allows to (temporarily) suppress
tooltips, e.g. by providing the user with a button that sets this global
variable to false
-var TagsToTip = true // false or true - if true, the script is
capable of converting HTML elements to tooltips
+var tt_Debug = true; // false or true - recommended: false once
you release your page to the public
+var tt_Enabled = true; // Allows to (temporarily) suppress
tooltips, e.g. by providing the user with a button that sets this global
variable to false
+var TagsToTip = true; // false or true - if true, the script is
capable of converting HTML elements to tooltips

// For each of the following config variables there exists a command, which
is
// just the variablename in uppercase, to be passed to Tip() or TagToTip() to
@@ -52,46 +52,46 @@
// configuration. Order of commands is arbitrary.
// Example: onmouseover="Tip('Tooltip text', LEFT, true, BGCOLOR, '#FF9900',
FADEIN, 400)"

-config. Above = false // false or true - tooltip
above mousepointer?
-config. BgColor = '#E4E7FF' // Background color
-config. BgImg = '' // Path to background image,
none if empty string ''
-config. BorderColor = '#002299'
-config. BorderStyle = 'solid' // Any permitted CSS value, but I
recommend 'solid', 'dotted' or 'dashed'
-config. BorderWidth = 1
-config. CenterMouse = false // false or true - center the tip
horizontally below (or above) the mousepointer
-config. ClickClose = false // false or true - close
tooltip if the user clicks somewhere
-config. CloseBtn = false // false or true -
closebutton in titlebar
-config. CloseBtnColors = ['#990000', '#FFFFFF', '#DD3333', '#FFFFFF'] //
[Background, text, hovered background, hovered text] - use empty strings ''
to inherit title colors
-config. CloseBtnText = '&nbsp;X&nbsp;' // Close button text (may
also be an image tag)
-config. CopyContent = true // When converting a HTML
element to a tooltip, copy only the element's content, rather than converting
the element by its own
-config. Delay = 400 // Time span in ms until
tooltip shows up
-config. Duration = 0 // Time span in ms after
which the tooltip disappears; 0 for infinite duration
-config. FadeIn = 0 // Fade-in duration in ms,
e.g. 400; 0 for no animation
-config. FadeOut = 0
-config. FadeInterval = 30 // Duration of each fade step in ms
(recommended: 30) - shorter is smoother but causes more CPU-load
-config. Fix = null // Fixated position - x- an
y-oordinates in brackets, e.g. [210, 480], or null for no fixation
-config. FollowMouse = true // false or true - tooltip
follows the mouse
-config. FontColor = '#000044'
-config. FontFace = 'Verdana,Geneva,sans-serif'
-config. FontSize = '12px' // E.g. '9pt' or '12px' -
unit is mandatory
-config. FontWeight = 'normal' // 'normal' or 'bold';
-config. Left = false // false or true - tooltip on
the left of the mouse
-config. OffsetX = 14 // Horizontal offset of
left-top corner from mousepointer
-config. OffsetY = 8 // Vertical offset
-config. Opacity = 100 // Integer between 0 and 100
- opacity of tooltip in percent
-config. Padding = 3 // Spacing between border and
content
-config. Shadow = false // false or true
-config. ShadowColor = '#C0C0C0'
-config. ShadowWidth = 5
-config. Sticky = false // Do NOT hide tooltip on
mouseout? false or true
-config. TextAlign = 'left' // 'left', 'right' or
'justify'
-config. Title = '' // Default title text applied
to all tips (no default title: empty string '')
-config. TitleAlign = 'left' // 'left' or 'right' - text
alignment inside the title bar
-config. TitleBgColor = '' // If empty string '', BorderColor
will be used
-config. TitleFontColor = '#ffffff' // Color of title text - if '',
BgColor (of tooltip body) will be used
-config. TitleFontFace = '' // If '' use FontFace (boldified)
-config. TitleFontSize = '' // If '' use FontSize
-config. Width = 0 // Tooltip width; 0 for
automatic adaption to tooltip content
+config. Above = false; // false or true - tooltip
above mousepointer?
+config. BgColor = '#E4E7FF'; // Background color
+config. BgImg = ''; // Path to background image,
none if empty string ''
+config. BorderColor = '#002299';
+config. BorderStyle = 'solid'; // Any permitted CSS value, but I
recommend 'solid', 'dotted' or 'dashed'
+config. BorderWidth = 1;
+config. CenterMouse = false; // false or true - center the tip
horizontally below (or above) the mousepointer
+config. ClickClose = false; // false or true - close
tooltip if the user clicks somewhere
+config. CloseBtn = false; // false or true -
closebutton in titlebar
+config. CloseBtnColors = ['#990000', '#FFFFFF', '#DD3333', '#FFFFFF']; //
[Background, text, hovered background, hovered text] - use empty strings ''
to inherit title colors
+config. CloseBtnText = '&nbsp;X&nbsp;'; // Close button text (may
also be an image tag)
+config. CopyContent = true; // When converting a HTML
element to a tooltip, copy only the element's content, rather than converting
the element by its own
+config. Delay = 400; // Time span in ms until
tooltip shows up
+config. Duration = 0; // Time span in ms after
which the tooltip disappears; 0 for infinite duration
+config. FadeIn = 0; // Fade-in duration in ms,
e.g. 400; 0 for no animation
+config. FadeOut = 0;
+config. FadeInterval = 30; // Duration of each fade step in ms
(recommended: 30) - shorter is smoother but causes more CPU-load
+config. Fix = null; // Fixated position - x- an
y-oordinates in brackets, e.g. [210, 480], or null for no fixation
+config. FollowMouse = true; // false or true - tooltip
follows the mouse
+config. FontColor = '#000044';
+config. FontFace = 'Verdana,Geneva,sans-serif';
+config. FontSize = '12px'; // E.g. '9pt' or '12px' -
unit is mandatory
+config. FontWeight = 'normal'; // 'normal' or 'bold';
+config. Left = false; // false or true - tooltip on
the left of the mouse
+config. OffsetX = 14; // Horizontal offset of
left-top corner from mousepointer
+config. OffsetY = 8; // Vertical offset
+config. Opacity = 100; // Integer between 0 and 100
- opacity of tooltip in percent
+config. Padding = 3; // Spacing between border and
content
+config. Shadow = false; // false or true
+config. ShadowColor = '#C0C0C0';
+config. ShadowWidth = 5;
+config. Sticky = false; // Do NOT hide tooltip on
mouseout? false or true
+config. TextAlign = 'left'; // 'left', 'right' or
'justify'
+config. Title = ''; // Default title text applied
to all tips (no default title: empty string '')
+config. TitleAlign = 'left'; // 'left' or 'right' - text
alignment inside the title bar
+config. TitleBgColor = ''; // If empty string '', BorderColor
will be used
+config. TitleFontColor = '#ffffff'; // Color of title text - if '',
BgColor (of tooltip body) will be used
+config. TitleFontFace = ''; // If '' use FontFace (boldified)
+config. TitleFontSize = ''; // If '' use FontSize
+config. Width = 0; // Tooltip width; 0 for
automatic adaption to tooltip content
//======= END OF TOOLTIP CONFIG, DO NOT CHANGE ANYTHING BELOW
==============//


@@ -852,7 +852,7 @@
tt_iState &= ~0x4;
if(tt_aV[DURATION] > 0)
tt_tDurt.Timer("tt_HideInit()", tt_aV[DURATION], true);
- tt_ExtCallFncs(0, "Show")
+ tt_ExtCallFncs(0, "Show");
css.visibility = "visible";
tt_iState |= 0x2;
if(tt_aV[FADEIN])
@@ -901,7 +901,7 @@
}
else if(!tt_ExtCallFncs(e, "MoveBefore"))
tt_SetTipPos(tt_PosX(), tt_PosY());
- tt_ExtCallFncs([tt_musX, tt_musY], "MoveAfter")
+ tt_ExtCallFncs([tt_musX, tt_musY], "MoveAfter");
}
}
}
@@ -1056,7 +1056,7 @@
{
if(!this.value || bUrge)
this.value = window.setTimeout(s, iT);
-}
+};
Number.prototype.EndTimer = function()
{
if(this.value)
@@ -1064,7 +1064,7 @@
window.clearTimeout(this.value);
this.value = 0;
}
-}
+};
function tt_SetOpa(css, opa)
{
tt_opa = opa;

Modified:
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/test/resources/soapResponse1.xml
===================================================================
---
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/test/resources/soapResponse1.xml
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/test/resources/soapResponse1.xml
2013-05-08 20:41:45 UTC (rev 6371)
@@ -24,4 +24,4 @@
<nmwg:datum value="collection LSStore-control does not exist or is not
accessible: [error.common.storage.xmldb.open]: XQuery by HTTP failed. Could
not connect to eXist via pure http, nested exception was: class
java.io.IOException : Server returned HTTP response code: 400 for URL:
http://localhost:8180/exist/rest/db/ls"/>
</nmwg:data>
</nmwg:data>
-</nmwg:message>
\ No newline at end of file
+</nmwg:message>

Modified:
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/test/resources/soapResponse2.xml
===================================================================
---
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/test/resources/soapResponse2.xml
2013-05-07 14:18:22 UTC (rev 6370)
+++
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-component/src/test/resources/soapResponse2.xml
2013-05-08 20:41:45 UTC (rev 6371)
@@ -25,4 +25,4 @@
<nmwgr:datum
xmlns:nmwgr="http://ggf.org/ns/nmwg/result/2.0/";>collection LSStore-control
does not exist or is not
accessible:[http://perfsonar.net/result/http://perfsonar.net/result/internal/error]:
Cannot initialize Db access - wrong datasource or db is not
initialized</nmwgr:datum>
</nmwg:data>
</nmwg:data>
-</nmwg:message>
\ No newline at end of file
+</nmwg:message>


Property changes on:
trunk/perfsonar-java-web-admin/perfsonar-java-web-admin-exampleservice
___________________________________________________________________
Modified: svn:ignore
- .classpath

.project

.settings

target

logs

+ .classpath

.project

.settings

target

logs

.pmd

.pmdruleset


Modified: trunk/perfsonar-java-web-admin/pom.xml
===================================================================
--- trunk/perfsonar-java-web-admin/pom.xml 2013-05-07 14:18:22 UTC (rev
6370)
+++ trunk/perfsonar-java-web-admin/pom.xml 2013-05-08 20:41:45 UTC (rev
6371)
@@ -4,7 +4,7 @@
<parent>
<groupId>net.geant.perfsonar</groupId>
<artifactId>parent</artifactId>
- <version>1.0.2</version>
+ <version>1.0.3-SNAPSHOT</version>
<relativePath>../parent/pom.xml</relativePath>
</parent>




  • [pS-dev] [GEANT/SA2/ps-java-services] r6371 - in trunk: nmwg-sql-converter/src/main/java/org/perfsonar /nmwg/converter nmwg-sql-converter/src/test/java/org/perfs onar/nmwg/converter parent parent/checkstyle perfsonar-bas e/annotations perfsonar-base/annotations/src/main/java/net /geant/perfsonar/annotations perfsonar-base/annotations/sr c/main/java/net/geant/perfsonar/annotations/request perfso nar-base/annotations/src/main/java/net/geant/perfsonar/ann otations/selftest perfsonar-base/apt perfsonar-base/apt/du mmyservice/net/geant/perfsonar/dummyservice perfsonar-base /apt/dummyservice/net/geant/perfsonar/dummyservice/selftes t perfsonar-base/apt/dummyservice/net/geant/perfsonar/dumm yservice/xpath perfsonar-base/apt/src/main/java/net/geant/ perfsonar/annotations perfsonar-base/apt/src/main/java/net /geant/perfsonar/annotations/ls perfsonar-base/apt/src/mai n/java/net/geant/perfsonar/annotations/request perfsonar-b ase/apt/src/main/java/net/geant/perfsonar/annotations/self test perfsonar-bas e/apt/src/main/java/net/geant/perfsonar /annotations/xpath perfsonar-base/apt/src/test/java/net/ge ant/perfsonar/annotations perfsonar-base/apt/src/test/java /net/geant/perfsonar/annotations/selftest perfsonar-base/a pt/src/test/java/net/geant/perfsonar/annotations/selftest/ compiler perfsonar-base/base perfsonar-base/base/src/main/ java/net/geant/perfsonar perfsonar-base/base/src/main/java /net/geant/perfsonar/base perfsonar-base/base/src/main/jav a/net/geant/perfsonar/response perfsonar-base/base/src/mai n/java/net/geant/perfsonar/selftest perfsonar-base/base/sr c/main/resources/net/geant/perfsonar/response perfsonar-ba se/base/src/test/java/net/geant/perfsonar perfsonar-base/b ase/src/test/java/net/geant/perfsonar/configuration perfso nar-base/base/src/test/java/net/geant/perfsonar/helpers pe rfsonar-base/base/src/test/java/net/geant/perfsonar/mp/ssh telnet perfsonar-base/ls perfsonar-base/ls/src/main/java/n et/geant/perfsonar/ls perfsonar-base/ls/src/test/java/net/ geant/perfsonar/ls per fsonar-base/ls/src/test/resources/n et/geant/perfsonar/mp/sshtelnet perfsonar-base/messaging p erfsonar-base/messaging/src/main/java/net/geant/perfsonar/ messaging perfsonar-base/messaging/src/main/java/net/geant /perfsonar/templates perfsonar-base/messaging/src/test/gro ovy/net/geant/perfsonar/templates perfsonar-base/messaging /src/test/java/net/geant/perfsonar/messaging perfsonar-bas e/messaging/src/test/java/net/geant/perfsonar/mp/sshtelnet perfsonar-base/messaging/src/test/java/net/geant/perfsona r/templates perfsonar-base/messaging-test-data perfsonar-b ase/messaging-test-data/src/main/java/net/geant/perfsonar/ messaging/data perfsonar-base/sample-service perfsonar-bas e/sample-service/src/main/java/net/geant/perfsonar/mp/ssht elnet perfsonar-base/sample-service/src/main/resources per fsonar-base/sample-service/src/main/resources/net/geant/pe rfsonar/mp/sshtelnet perfsonar-base/sample-service/src/tes t/java/net/geant/perfsonar/mp/sshtelnet perfsonar-java-rrd -ma-SQL_backend/src/main/j ava/org/perfsonar/service/tem p perfsonar-java-rrd-ma-SQL_backend/src/main/resources/p erfsonar/conf perfsonar-java-rrd-ma-base3 perfsonar-java-r rd-ma-base3/src/main perfsonar-java-rrd-ma-base3/src/test/ java/net/geant/perfsonar/ma/rrd perfsonar-java-web-admin p erfsonar-java-web-admin/perfsonar-java-web-admin-component perfsonar-java-web-admin/perfsonar-java-web-admin-compone nt/src/main/java/org/perfsonar/webadmin/config perfsonar-j ava-web-admin/perfsonar-java-web-admin-component/src/main/ java/org/perfsonar/webadmin/filters perfsonar-java-web-adm in/perfsonar-java-web-admin-component/src/main/java/org/pe rfsonar/webadmin/servlet perfsonar-java-web-admin/perfsona r-java-web-admin-component/src/main/java/org/perfsonar/web admin/servlet/util perfsonar-java-web-admin/perfsonar-java -web-admin-component/src/main/java/org/perfsonar/webadmin/ test perfsonar-java-web-admin/perfsonar-java-web-admin-com ponent/src/main/java/org/perfsonar/webadmin/util perfsonar -java-web-admin/perfsonar-java-web -admin-component/src/ma in/resources perfsonar-java-web-admin/perfsonar-java-web-a dmin-component/src/main/webapp/wa/scripts perfsonar-java-w eb-admin/perfsonar-java-web-admin-component/src/test/resou rces perfsonar-java-web-admin/perfsonar-java-web-admin-exa mpleservice, svn-noreply, 05/08/2013

Archive powered by MHonArc 2.6.16.

Top of Page