From c0604184b2aa8cff924ca783ec6b36f1f5988775 Mon Sep 17 00:00:00 2001 From: Zhaoxing Date: Tue, 8 Aug 2017 14:02:53 +0800 Subject: init code Change-Id: Icd0948118397b256da70dfbcbbec5520dc5eafd4 Signed-off-by: Zhaoxing --- wso2/.gitattributes | 2 + wso2/.gitignore | 8 + wso2/.gitreview | 4 + wso2/License.txt | 473 +++ wso2/baseservice-i18n/pom.xml | 66 + .../baseservice/i18n/DefaultErrorCodeI18n.java | 278 ++ .../openo/baseservice/i18n/DefaultI18nService.java | 59 + .../openo/baseservice/i18n/ErrorCodeException.java | 53 + .../org/openo/baseservice/i18n/ErrorCodeI18n.java | 151 + .../main/java/org/openo/baseservice/i18n/I18n.java | 132 + .../org/openo/baseservice/i18n/I18nContainer.java | 148 + .../java/org/openo/baseservice/i18n/I18nImpl.java | 137 + .../java/org/openo/baseservice/i18n/I18nItem.java | 53 + .../org/openo/baseservice/i18n/I18nJsonUtil.java | 170 + .../org/openo/baseservice/i18n/I18nService.java | 38 + .../baseservice/i18n/JsonResourceScanner.java | 81 + wso2/common-util/.gitignore | 5 + wso2/common-util/pom.xml | 142 + .../openo/baseservice/bus/util/BusConstant.java | 48 + .../baseservice/bus/util/RegisterService.java | 177 ++ .../bus/util/RegisterServiceListener.java | 70 + .../baseservice/encrypt/cbb/CipherCreator.java | 95 + .../baseservice/encrypt/cbb/impl/AesCipher.java | 132 + .../encrypt/cbb/impl/AesCipherFactory.java | 54 + .../encrypt/cbb/inf/AbstractCipher.java | 50 + .../encrypt/cbb/inf/AbstractCipherFactory.java | 45 + .../openo/baseservice/encrypt/cbb/sha/Sha256.java | 110 + .../java/org/openo/baseservice/util/RestUtils.java | 82 + .../util/impl/SystemEnvVariablesDefImpl.java | 68 + .../util/impl/SystemEnvVariablesFactory.java | 55 + .../baseservice/util/inf/SystemEnvVariables.java | 35 + .../baseservice/bus/util/TestRegisterService.java | 66 + .../bus/util/TestRegisterServiceListener.java | 60 + .../encrypt/cbb/impl/AesCipherTest.java | 210 ++ .../baseservice/encrypt/cbb/sha/Sha256Test.java | 193 ++ .../org/openo/baseservice/util/RestUtilsTest.java | 190 ++ .../util/impl/SystemEnvVariablesDefImplTest.java | 113 + wso2/dropwizard-ioc-container/pom.xml | 80 + .../dropwizard/ioc/annotation/BaseService.java | 34 + .../org/openo/dropwizard/ioc/annotation/Lazy.java | 34 + .../dropwizard/ioc/annotation/PostBaseService.java | 34 + .../dropwizard/ioc/annotation/PreBaseService.java | 34 + .../openo/dropwizard/ioc/annotation/PreLoad.java | 34 + .../dropwizard/ioc/annotation/PreServiceLoad.java | 35 + .../dropwizard/ioc/bundle/AutoConfigBundle.java | 430 +++ .../ioc/bundle/AutoConfigBundleBuider.java | 42 + .../dropwizard/ioc/bundle/IOCApplication.java | 42 + .../ioc/bundle/ServiceLocatorManaged.java | 51 + .../openo/dropwizard/ioc/utils/ServiceBinder.java | 52 + .../dropwizard/ioc/utils/ServiceLocatorHolder.java | 36 + .../dropwizard/ioc/test/service/IOCBundleTest.java | 49 + .../ioc/test/service/PreTestService.java | 33 + .../dropwizard/ioc/test/service/TestService.java | 41 + .../ioc/test/service/app/ExampleApp.java | 35 + .../ioc/test/service/conf/TestConfiguration.java | 26 + .../src/test/resources/example.yml | 8 + wso2/logging-sdk/pom.xml | 85 + .../main/java/org/openo/log/api/LogMessage.java | 132 + .../main/java/org/openo/log/api/LogService.java | 140 + .../java/org/openo/log/api/OperLogMessage.java | 286 ++ .../main/java/org/openo/log/api/SecLogMessage.java | 146 + .../main/java/org/openo/log/api/SysLogMessage.java | 180 ++ .../main/java/org/openo/log/impl/Facitility.java | 137 + .../java/org/openo/log/impl/InsertLogHandler.java | 265 ++ .../src/main/java/org/openo/log/impl/LogConst.java | 37 + .../main/java/org/openo/log/impl/LogIdTool.java | 67 + .../org/openo/log/test/TestLogback2Logstash.java | 58 + .../src/main/java/org/openo/log/test/logback.xml | 22 + wso2/pom.xml | 332 ++ wso2/rest-client/.gitignore | 1 + wso2/rest-client/pom.xml | 88 + .../remoteservice/exception/ExceptionArgs.java | 110 + .../remoteservice/exception/ServiceException.java | 269 ++ .../openo/baseservice/roa/util/ReaderHelper.java | 61 + .../roa/util/restclient/DefaultAsyncCallback.java | 37 + .../roa/util/restclient/HttpBaseRest.java | 273 ++ .../baseservice/roa/util/restclient/HttpRest.java | 254 ++ .../util/restclient/RestHttpContentExchange.java | 234 ++ .../baseservice/roa/util/restclient/Restful.java | 298 ++ .../roa/util/restclient/RestfulAsyncCallback.java | 43 + .../roa/util/restclient/RestfulClientConst.java | 63 + .../roa/util/restclient/RestfulConfigure.java | 162 + .../roa/util/restclient/RestfulFactory.java | 95 + .../roa/util/restclient/RestfulOptions.java | 170 + .../roa/util/restclient/RestfulParametes.java | 155 + .../roa/util/restclient/RestfulResponse.java | 144 + .../baseservice/roa/util/ReaderHelperTest.java | 116 + .../baseservice/roa/util/TestServiceUtil.java | 92 + .../roa/util/restclient/TestHttpRest.java | 1179 +++++++ .../restclient/TestRestHttpContentExchange.java | 592 ++++ .../roa/util/restclient/TestRestfulConfigure.java | 238 ++ .../roa/util/restclient/TestRestfulFactory.java | 109 + .../roa/util/restclient/TestRestfulOptions.java | 288 ++ .../roa/util/restclient/TestRestfulParametes.java | 229 ++ .../roa/util/restclient/TestRestfulResponse.java | 273 ++ .../src/test/resources/etc/conf/restclient.json | 11 + .../src/test/resources/rest-client-test.json | 11 + wso2/wso2bpel-ext/pom.xml | 45 + .../wso2bpel-core/BPEL4RESTLight/pom.xml | 181 ++ .../Bpel4RestLightExtensionBundle.java | 48 + .../bpel4restlight/Bpel4RestLightOperation.java | 147 + .../bpel4restlight/EPRDemoOperation.java | 74 + .../extensions/bpel4restlight/MethodAttribute.java | 17 + .../bpel4restlight/util/Bpel4RestLightUtil.java | 113 + .../iaas/bpel/util/BPELVariableInjectionUtil.java | 149 + .../de/unistuttgart/iaas/bpel/util/BpelUtil.java | 102 + .../de/unistuttgart/iaas/xml/DomXmlConverter.java | 179 ++ .../de/unistuttgart/iaas/xml/XPathEvaluator.java | 34 + .../bpel4restlight/rest/HighLevelRestApi.java | 178 ++ .../opentosca/bpel4restlight/rest/HttpMethod.java | 20 + .../bpel4restlight/rest/HttpResponseMessage.java | 53 + .../bpel4restlight/rest/LowLevelRestApi.java | 182 ++ .../wso2bpel-core/distribution/pom.xml | 34 + .../wso2bpel-core/distribution/standalone/pom.xml | 401 +++ .../standalone/src/main/assembly/initDB.sh | 53 + .../standalone/src/main/assembly/run.bat | 32 + .../standalone/src/main/assembly/run.sh | 32 + .../standalone/src/main/assembly/stop.bat | 28 + .../standalone/src/main/assembly/stop.sh | 30 + .../assembly/wso2bps-ext/bin/find_kill_process.bat | 24 + .../src/main/assembly/wso2bps-ext/bin/shutdown.bat | 34 + .../src/main/assembly/wso2bps-ext/bin/shutdown.sh | 61 + .../src/main/assembly/wso2bps-ext/bin/startup.bat | 42 + .../src/main/assembly/wso2bps-ext/bin/startup.sh | 36 + .../main/assembly/wso2bps-ext/conf/wso2bpel.yml | 73 + .../assembly/wso2bps/bin/find_kill_process.bat | 23 + .../src/main/assembly/wso2bps/bin/shutdown.bat | 34 + .../src/main/assembly/wso2bps/bin/shutdown.sh | 44 + .../wso2bps/dbscripts/bps/bpel/create/mysql.sql | 170 + .../bps/bpel/create/wso-bpel-mysql-createdb.sql | 31 + .../main/assembly/wso2bps/repository/conf/bps.xml | 174 + .../wso2bps/repository/conf/carbon/bps.xml | 174 + .../wso2bps/repository/conf/carbon/carbon.xml | 683 ++++ .../conf/datasources/activiti-datasources.xml | 32 + .../conf/datasources/bps-datasources.xml | 32 + .../conf/datasources/master-datasources.xml | 68 + .../main/assembly/wso2bps/wso2bps-ext.properties | 1 + wso2/wso2bpel-ext/wso2bpel-core/pom.xml | 36 + .../wso2bpel-core/wso2bpel-mgr/pom.xml | 453 +++ .../org/openo/carbon/bpel/Wso2BpelApplication.java | 106 + .../openo/carbon/bpel/Wso2BpelConfiguration.java | 200 ++ .../java/org/openo/carbon/bpel/common/Config.java | 30 + .../openo/carbon/bpel/common/ServiceRegistrer.java | 70 + .../bpel/externalservice/entity/ServiceNode.java | 33 + .../entity/ServiceRegisterEntity.java | 57 + .../msb/MicroserviceBusConsumer.java | 48 + .../externalservice/msb/MicroserviceBusRest.java | 39 + .../openo/carbon/bpel/resources/BpsPackage.java | 632 ++++ .../openo/carbon/bpel/resources/BpsProcess.java | 544 ++++ .../carbon/bpel/resources/BpsServiceException.java | 30 + .../openo/carbon/bpel/resources/RestAppConfig.java | 37 + .../openo/carbon/bpel/util/ClientWsdlLoader.java | 82 + .../java/org/openo/carbon/bpel/util/JsonUtil.java | 61 + .../openo/carbon/bpel/util/LRULinkedHashMap.java | 106 + .../java/org/openo/carbon/bpel/util/SoapUtil.java | 156 + .../org/openo/carbon/bpel/util/Xml2JsonUtil.java | 141 + .../main/resources/api-doc/META-INF/MANIFEST.MF | 3 + .../src/main/resources/api-doc/WEB-INF/web.xml | 41 + .../src/main/resources/api-doc/css/reset.css | 140 + .../src/main/resources/api-doc/css/screen.css | 1271 ++++++++ .../src/main/resources/api-doc/css/typography.css | 41 + .../api-doc/fonts/droid-sans-v6-latin-700.eot | Bin 0 -> 22924 bytes .../api-doc/fonts/droid-sans-v6-latin-700.svg | 411 +++ .../api-doc/fonts/droid-sans-v6-latin-700.ttf | Bin 0 -> 40516 bytes .../api-doc/fonts/droid-sans-v6-latin-700.woff | Bin 0 -> 25992 bytes .../api-doc/fonts/droid-sans-v6-latin-700.woff2 | Bin 0 -> 11480 bytes .../api-doc/fonts/droid-sans-v6-latin-regular.eot | Bin 0 -> 22008 bytes .../api-doc/fonts/droid-sans-v6-latin-regular.svg | 403 +++ .../api-doc/fonts/droid-sans-v6-latin-regular.ttf | Bin 0 -> 39072 bytes .../api-doc/fonts/droid-sans-v6-latin-regular.woff | Bin 0 -> 24868 bytes .../fonts/droid-sans-v6-latin-regular.woff2 | Bin 0 -> 11304 bytes .../resources/api-doc/images/explorer_icons.png | Bin 0 -> 5763 bytes .../main/resources/api-doc/images/logo_small.png | Bin 0 -> 770 bytes .../resources/api-doc/images/pet_store_api.png | Bin 0 -> 824 bytes .../src/main/resources/api-doc/images/throbber.gif | Bin 0 -> 9257 bytes .../main/resources/api-doc/images/wordnik_api.png | Bin 0 -> 980 bytes .../src/main/resources/api-doc/index.html | 115 + .../src/main/resources/api-doc/lib/backbone-min.js | 30 + .../main/resources/api-doc/lib/handlebars-2.0.0.js | 43 + .../resources/api-doc/lib/highlight.7.3.pack.js | 16 + .../main/resources/api-doc/lib/jquery-1.8.0.min.js | 17 + .../resources/api-doc/lib/jquery.ba-bbq.min.js | 25 + .../resources/api-doc/lib/jquery.slideto.min.js | 16 + .../resources/api-doc/lib/jquery.wiggle.min.js | 23 + .../src/main/resources/api-doc/lib/marked.js | 1281 ++++++++ .../src/main/resources/api-doc/lib/shred.bundle.js | 2780 ++++++++++++++++ .../main/resources/api-doc/lib/shred/content.js | 208 ++ .../main/resources/api-doc/lib/swagger-client.js | 3309 ++++++++++++++++++++ .../main/resources/api-doc/lib/swagger-oauth.js | 294 ++ .../main/resources/api-doc/lib/underscore-min.js | 21 + .../src/main/resources/api-doc/o2c.html | 37 + .../src/main/resources/api-doc/swagger-ui.js | 2255 +++++++++++++ .../src/main/resources/api-doc/swagger-ui.min.js | 17 + .../wso2bpel-mgr/src/main/resources/banner.txt | 25 + .../src/main/resources/config.properties | 16 + .../wso2bpel-mgr/src/main/resources/migrations.xml | 38 + .../src/main/resources/wso2-config.properties | 24 + wso2/wso2bpel-ext/wso2bpel-parent/pom.xml | 36 + .../wso2bpel-parent/wso2bpelparent-lite/pom.xml | 120 + .../wso2bpel-parent/wso2bpelparent/pom.xml | 124 + 200 files changed, 32374 insertions(+) create mode 100644 wso2/.gitattributes create mode 100644 wso2/.gitignore create mode 100644 wso2/.gitreview create mode 100644 wso2/License.txt create mode 100644 wso2/baseservice-i18n/pom.xml create mode 100644 wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/DefaultErrorCodeI18n.java create mode 100644 wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/DefaultI18nService.java create mode 100644 wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/ErrorCodeException.java create mode 100644 wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/ErrorCodeI18n.java create mode 100644 wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/I18n.java create mode 100644 wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/I18nContainer.java create mode 100644 wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/I18nImpl.java create mode 100644 wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/I18nItem.java create mode 100644 wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/I18nJsonUtil.java create mode 100644 wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/I18nService.java create mode 100644 wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/JsonResourceScanner.java create mode 100644 wso2/common-util/.gitignore create mode 100644 wso2/common-util/pom.xml create mode 100644 wso2/common-util/src/main/java/org/openo/baseservice/bus/util/BusConstant.java create mode 100644 wso2/common-util/src/main/java/org/openo/baseservice/bus/util/RegisterService.java create mode 100644 wso2/common-util/src/main/java/org/openo/baseservice/bus/util/RegisterServiceListener.java create mode 100644 wso2/common-util/src/main/java/org/openo/baseservice/encrypt/cbb/CipherCreator.java create mode 100644 wso2/common-util/src/main/java/org/openo/baseservice/encrypt/cbb/impl/AesCipher.java create mode 100644 wso2/common-util/src/main/java/org/openo/baseservice/encrypt/cbb/impl/AesCipherFactory.java create mode 100644 wso2/common-util/src/main/java/org/openo/baseservice/encrypt/cbb/inf/AbstractCipher.java create mode 100644 wso2/common-util/src/main/java/org/openo/baseservice/encrypt/cbb/inf/AbstractCipherFactory.java create mode 100644 wso2/common-util/src/main/java/org/openo/baseservice/encrypt/cbb/sha/Sha256.java create mode 100644 wso2/common-util/src/main/java/org/openo/baseservice/util/RestUtils.java create mode 100644 wso2/common-util/src/main/java/org/openo/baseservice/util/impl/SystemEnvVariablesDefImpl.java create mode 100644 wso2/common-util/src/main/java/org/openo/baseservice/util/impl/SystemEnvVariablesFactory.java create mode 100644 wso2/common-util/src/main/java/org/openo/baseservice/util/inf/SystemEnvVariables.java create mode 100644 wso2/common-util/src/test/java/org/openo/baseservice/bus/util/TestRegisterService.java create mode 100644 wso2/common-util/src/test/java/org/openo/baseservice/bus/util/TestRegisterServiceListener.java create mode 100644 wso2/common-util/src/test/java/org/openo/baseservice/encrypt/cbb/impl/AesCipherTest.java create mode 100644 wso2/common-util/src/test/java/org/openo/baseservice/encrypt/cbb/sha/Sha256Test.java create mode 100644 wso2/common-util/src/test/java/org/openo/baseservice/util/RestUtilsTest.java create mode 100644 wso2/common-util/src/test/java/org/openo/baseservice/util/impl/SystemEnvVariablesDefImplTest.java create mode 100644 wso2/dropwizard-ioc-container/pom.xml create mode 100644 wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/annotation/BaseService.java create mode 100644 wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/annotation/Lazy.java create mode 100644 wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/annotation/PostBaseService.java create mode 100644 wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/annotation/PreBaseService.java create mode 100644 wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/annotation/PreLoad.java create mode 100644 wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/annotation/PreServiceLoad.java create mode 100644 wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/bundle/AutoConfigBundle.java create mode 100644 wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/bundle/AutoConfigBundleBuider.java create mode 100644 wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/bundle/IOCApplication.java create mode 100644 wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/bundle/ServiceLocatorManaged.java create mode 100644 wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/utils/ServiceBinder.java create mode 100644 wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/utils/ServiceLocatorHolder.java create mode 100644 wso2/dropwizard-ioc-container/src/test/java/org/openo/dropwizard/ioc/test/service/IOCBundleTest.java create mode 100644 wso2/dropwizard-ioc-container/src/test/java/org/openo/dropwizard/ioc/test/service/PreTestService.java create mode 100644 wso2/dropwizard-ioc-container/src/test/java/org/openo/dropwizard/ioc/test/service/TestService.java create mode 100644 wso2/dropwizard-ioc-container/src/test/java/org/openo/dropwizard/ioc/test/service/app/ExampleApp.java create mode 100644 wso2/dropwizard-ioc-container/src/test/java/org/openo/dropwizard/ioc/test/service/conf/TestConfiguration.java create mode 100644 wso2/dropwizard-ioc-container/src/test/resources/example.yml create mode 100644 wso2/logging-sdk/pom.xml create mode 100644 wso2/logging-sdk/src/main/java/org/openo/log/api/LogMessage.java create mode 100644 wso2/logging-sdk/src/main/java/org/openo/log/api/LogService.java create mode 100644 wso2/logging-sdk/src/main/java/org/openo/log/api/OperLogMessage.java create mode 100644 wso2/logging-sdk/src/main/java/org/openo/log/api/SecLogMessage.java create mode 100644 wso2/logging-sdk/src/main/java/org/openo/log/api/SysLogMessage.java create mode 100644 wso2/logging-sdk/src/main/java/org/openo/log/impl/Facitility.java create mode 100644 wso2/logging-sdk/src/main/java/org/openo/log/impl/InsertLogHandler.java create mode 100644 wso2/logging-sdk/src/main/java/org/openo/log/impl/LogConst.java create mode 100644 wso2/logging-sdk/src/main/java/org/openo/log/impl/LogIdTool.java create mode 100644 wso2/logging-sdk/src/main/java/org/openo/log/test/TestLogback2Logstash.java create mode 100644 wso2/logging-sdk/src/main/java/org/openo/log/test/logback.xml create mode 100644 wso2/pom.xml create mode 100644 wso2/rest-client/.gitignore create mode 100644 wso2/rest-client/pom.xml create mode 100644 wso2/rest-client/src/main/java/org/openo/baseservice/remoteservice/exception/ExceptionArgs.java create mode 100644 wso2/rest-client/src/main/java/org/openo/baseservice/remoteservice/exception/ServiceException.java create mode 100644 wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/ReaderHelper.java create mode 100644 wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/DefaultAsyncCallback.java create mode 100644 wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/HttpBaseRest.java create mode 100644 wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/HttpRest.java create mode 100644 wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestHttpContentExchange.java create mode 100644 wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/Restful.java create mode 100644 wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulAsyncCallback.java create mode 100644 wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulClientConst.java create mode 100644 wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulConfigure.java create mode 100644 wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulFactory.java create mode 100644 wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulOptions.java create mode 100644 wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulParametes.java create mode 100644 wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulResponse.java create mode 100644 wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/ReaderHelperTest.java create mode 100644 wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/TestServiceUtil.java create mode 100644 wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestHttpRest.java create mode 100644 wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestHttpContentExchange.java create mode 100644 wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulConfigure.java create mode 100644 wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulFactory.java create mode 100644 wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulOptions.java create mode 100644 wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulParametes.java create mode 100644 wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulResponse.java create mode 100644 wso2/rest-client/src/test/resources/etc/conf/restclient.json create mode 100644 wso2/rest-client/src/test/resources/rest-client-test.json create mode 100644 wso2/wso2bpel-ext/pom.xml create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/pom.xml create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/extensions/bpel4restlight/Bpel4RestLightExtensionBundle.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/extensions/bpel4restlight/Bpel4RestLightOperation.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/extensions/bpel4restlight/EPRDemoOperation.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/extensions/bpel4restlight/MethodAttribute.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/extensions/bpel4restlight/util/Bpel4RestLightUtil.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/util/BPELVariableInjectionUtil.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/util/BpelUtil.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/xml/DomXmlConverter.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/xml/XPathEvaluator.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/org/opentosca/bpel4restlight/rest/HighLevelRestApi.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/org/opentosca/bpel4restlight/rest/HttpMethod.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/org/opentosca/bpel4restlight/rest/HttpResponseMessage.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/org/opentosca/bpel4restlight/rest/LowLevelRestApi.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/distribution/pom.xml create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/pom.xml create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/initDB.sh create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/run.bat create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/run.sh create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/stop.bat create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/stop.sh create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps-ext/bin/find_kill_process.bat create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps-ext/bin/shutdown.bat create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps-ext/bin/shutdown.sh create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps-ext/bin/startup.bat create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps-ext/bin/startup.sh create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps-ext/conf/wso2bpel.yml create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/bin/find_kill_process.bat create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/bin/shutdown.bat create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/bin/shutdown.sh create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/dbscripts/bps/bpel/create/mysql.sql create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/dbscripts/bps/bpel/create/wso-bpel-mysql-createdb.sql create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/repository/conf/bps.xml create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/repository/conf/carbon/bps.xml create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/repository/conf/carbon/carbon.xml create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/repository/conf/datasources/activiti-datasources.xml create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/repository/conf/datasources/bps-datasources.xml create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/repository/conf/datasources/master-datasources.xml create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/wso2bps-ext.properties create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/pom.xml create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/pom.xml create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/Wso2BpelApplication.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/Wso2BpelConfiguration.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/common/Config.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/common/ServiceRegistrer.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/externalservice/entity/ServiceNode.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/externalservice/entity/ServiceRegisterEntity.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/externalservice/msb/MicroserviceBusConsumer.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/externalservice/msb/MicroserviceBusRest.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/resources/BpsPackage.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/resources/BpsProcess.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/resources/BpsServiceException.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/resources/RestAppConfig.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/util/ClientWsdlLoader.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/util/JsonUtil.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/util/LRULinkedHashMap.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/util/SoapUtil.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/util/Xml2JsonUtil.java create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/META-INF/MANIFEST.MF create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/WEB-INF/web.xml create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/css/reset.css create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/css/screen.css create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/css/typography.css create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/fonts/droid-sans-v6-latin-700.eot create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/fonts/droid-sans-v6-latin-700.svg create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/fonts/droid-sans-v6-latin-700.ttf create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/fonts/droid-sans-v6-latin-700.woff create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/fonts/droid-sans-v6-latin-700.woff2 create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/fonts/droid-sans-v6-latin-regular.eot create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/fonts/droid-sans-v6-latin-regular.svg create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/fonts/droid-sans-v6-latin-regular.ttf create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/fonts/droid-sans-v6-latin-regular.woff create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/fonts/droid-sans-v6-latin-regular.woff2 create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/images/explorer_icons.png create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/images/logo_small.png create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/images/pet_store_api.png create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/images/throbber.gif create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/images/wordnik_api.png create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/index.html create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/lib/backbone-min.js create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/lib/handlebars-2.0.0.js create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/lib/highlight.7.3.pack.js create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/lib/jquery-1.8.0.min.js create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/lib/jquery.ba-bbq.min.js create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/lib/jquery.slideto.min.js create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/lib/jquery.wiggle.min.js create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/lib/marked.js create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/lib/shred.bundle.js create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/lib/shred/content.js create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/lib/swagger-client.js create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/lib/swagger-oauth.js create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/lib/underscore-min.js create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/o2c.html create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/swagger-ui.js create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/swagger-ui.min.js create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/banner.txt create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/config.properties create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/migrations.xml create mode 100644 wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/wso2-config.properties create mode 100644 wso2/wso2bpel-ext/wso2bpel-parent/pom.xml create mode 100644 wso2/wso2bpel-ext/wso2bpel-parent/wso2bpelparent-lite/pom.xml create mode 100644 wso2/wso2bpel-ext/wso2bpel-parent/wso2bpelparent/pom.xml (limited to 'wso2') diff --git a/wso2/.gitattributes b/wso2/.gitattributes new file mode 100644 index 0000000..13e92ef --- /dev/null +++ b/wso2/.gitattributes @@ -0,0 +1,2 @@ +*.java text eol=lf +*.xml text eol=lf diff --git a/wso2/.gitignore b/wso2/.gitignore new file mode 100644 index 0000000..7020020 --- /dev/null +++ b/wso2/.gitignore @@ -0,0 +1,8 @@ +target +# Eclipse +.settings/ +.classpath +.project +.idea +*.iml +dependency-reduced-pom.xml diff --git a/wso2/.gitreview b/wso2/.gitreview new file mode 100644 index 0000000..f21a39a --- /dev/null +++ b/wso2/.gitreview @@ -0,0 +1,4 @@ +[gerrit] +host=gerrit.open-o.org +port=29418 +project=common-services-common-utilities.git diff --git a/wso2/License.txt b/wso2/License.txt new file mode 100644 index 0000000..dd08487 --- /dev/null +++ b/wso2/License.txt @@ -0,0 +1,473 @@ +THIS LICENSE FILE CONTAINS THE LICENSE APPLICABLE DEPENDING ON THE TYPE OF CONTRIBUTIONS. + +APACHE LICENSE 2 IS APPLICABLE FOR SOURCE CODE, CREATIVE COMMONS ATTRIBUTION 4.0 INTERNATIONAL FOR DOCUMENTATION + ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + + +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. + +Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. + +Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. + +You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + +You must give any other recipients of the Work or Derivative Works a copy of this License; and +You must cause any modified files to carry prominent notices stating that You changed the files; and +You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and +If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. +You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. + +Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. + +This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. + +Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. + +In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. + +While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +Attribution 4.0 International + +https://creativecommons.org/licenses/by/4.0/legalcode + +--------------------------------------------------------------------------------------- + +Creative Commons Corporation ("Creative Commons") is not a law firm and +does not provide legal services or legal advice. Distribution of +Creative Commons public licenses does not create a lawyer-client or +other relationship. Creative Commons makes its licenses and related +information available on an "as-is" basis. Creative Commons gives no +warranties regarding its licenses, any material licensed under their +terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the +fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and +conditions that creators and other rights holders may use to share +original works of authorship and other material subject to copyright +and certain other rights specified in the public license below. The +following considerations are for informational purposes only, are not +exhaustive, and do not form part of our licenses. + + Considerations for licensors: Our public licenses are + intended for use by those authorized to give the public + permission to use material in ways otherwise restricted by + copyright and certain other rights. Our licenses are + irrevocable. Licensors should read and understand the terms + and conditions of the license they choose before applying it. + Licensors should also secure all rights necessary before + applying our licenses so that the public can reuse the + material as expected. Licensors should clearly mark any + material not subject to the license. This includes other CC- + licensed material, or material used under an exception or + limitation to copyright. More considerations for licensors: + wiki.creativecommons.org/Considerations_for_licensors + + Considerations for the public: By using one of our public + licenses, a licensor grants the public permission to use the + licensed material under specified terms and conditions. If + the licensor's permission is not necessary for any reason--for + example, because of any applicable exception or limitation to + copyright--then that use is not regulated by the license. Our + licenses grant only permissions under copyright and certain + other rights that a licensor has authority to grant. Use of + the licensed material may still be restricted for other + reasons, including because others have copyright or other + rights in the material. A licensor may make special requests, + such as asking that all changes be marked or described. + Although not required by our licenses, you are encouraged to + respect those requests where reasonable. More_considerations + for the public: + wiki.creativecommons.org/Considerations_for_licensees + +--------------------------------------------------------------------------------------- + +Creative Commons Attribution 4.0 International Public License + +By exercising the Licensed Rights (defined below), You accept and agree +to be bound by the terms and conditions of this Creative Commons +Attribution 4.0 International Public License ("Public License"). To the +extent this Public License may be interpreted as a contract, You are +granted the Licensed Rights in consideration of Your acceptance of +these terms and conditions, and the Licensor grants You such rights in +consideration of benefits the Licensor receives from making the +Licensed Material available under these terms and conditions. + + +Section 1 -- Definitions. + + a. Adapted Material means material subject to Copyright and Similar + Rights that is derived from or based upon the Licensed Material + and in which the Licensed Material is translated, altered, + arranged, transformed, or otherwise modified in a manner requiring + permission under the Copyright and Similar Rights held by the + Licensor. For purposes of this Public License, where the Licensed + Material is a musical work, performance, or sound recording, + Adapted Material is always produced where the Licensed Material is + synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright + and Similar Rights in Your contributions to Adapted Material in + accordance with the terms and conditions of this Public License. + + c. Copyright and Similar Rights means copyright and/or similar rights + closely related to copyright including, without limitation, + performance, broadcast, sound recording, and Sui Generis Database + Rights, without regard to how the rights are labeled or + categorized. For purposes of this Public License, the rights + specified in Section 2(b)(1)-(2) are not Copyright and Similar + Rights. + + d. Effective Technological Measures means those measures that, in the + absence of proper authority, may not be circumvented under laws + fulfilling obligations under Article 11 of the WIPO Copyright + Treaty adopted on December 20, 1996, and/or similar international + agreements. + + e. Exceptions and Limitations means fair use, fair dealing, and/or + any other exception or limitation to Copyright and Similar Rights + that applies to Your use of the Licensed Material. + + f. Licensed Material means the artistic or literary work, database, + or other material to which the Licensor applied this Public + License. + + g. Licensed Rights means the rights granted to You subject to the + terms and conditions of this Public License, which are limited to + all Copyright and Similar Rights that apply to Your use of the + Licensed Material and that the Licensor has authority to license. + + h. Licensor means the individual(s) or entity(ies) granting rights + under this Public License. + + i. Share means to provide material to the public by any means or + process that requires permission under the Licensed Rights, such + as reproduction, public display, public performance, distribution, + dissemination, communication, or importation, and to make material + available to the public including in ways that members of the + public may access the material from a place and at a time + individually chosen by them. + + j. Sui Generis Database Rights means rights other than copyright + resulting from Directive 96/9/EC of the European Parliament and of + the Council of 11 March 1996 on the legal protection of databases, + as amended and/or succeeded, as well as other essentially + equivalent rights anywhere in the world. + + k. You means the individual or entity exercising the Licensed Rights + under this Public License. Your has a corresponding meaning. + + +Section 2 -- Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, + the Licensor hereby grants You a worldwide, royalty-free, + non-sublicensable, non-exclusive, irrevocable license to + exercise the Licensed Rights in the Licensed Material to: + + a. reproduce and Share the Licensed Material, in whole or + in part; and + + b. produce, reproduce, and Share Adapted Material. + + 2. Exceptions and Limitations. For the avoidance of doubt, where + Exceptions and Limitations apply to Your use, this Public + License does not apply, and You do not need to comply with + its terms and conditions. + + 3. Term. The term of this Public License is specified in Section + 6(a). + + 4. Media and formats; technical modifications allowed. The + Licensor authorizes You to exercise the Licensed Rights in + all media and formats whether now known or hereafter created, + and to make technical modifications necessary to do so. The + Licensor waives and/or agrees not to assert any right or + authority to forbid You from making technical modifications + necessary to exercise the Licensed Rights, including + technical modifications necessary to circumvent Effective + Technological Measures. For purposes of this Public License, + simply making modifications authorized by this Section 2(a) + (4) never produces Adapted Material. + + 5. Downstream recipients. + + a. Offer from the Licensor -- Licensed Material. Every + recipient of the Licensed Material automatically + receives an offer from the Licensor to exercise the + Licensed Rights under the terms and conditions of this + Public License. + + b. No downstream restrictions. You may not offer or impose + any additional or different terms or conditions on, or + apply any Effective Technological Measures to, the + Licensed Material if doing so restricts exercise of the + Licensed Rights by any recipient of the Licensed + Material. + + 6. No endorsement. Nothing in this Public License constitutes or + may be construed as permission to assert or imply that You + are, or that Your use of the Licensed Material is, connected + with, or sponsored, endorsed, or granted official status by, + the Licensor or others designated to receive attribution as + provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not + licensed under this Public License, nor are publicity, + privacy, and/or other similar personality rights; however, to + the extent possible, the Licensor waives and/or agrees not to + assert any such rights held by the Licensor to the limited + extent necessary to allow You to exercise the Licensed + Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this + Public License. + + 3. To the extent possible, the Licensor waives any right to + collect royalties from You for the exercise of the Licensed + Rights, whether directly or through a collecting society + under any voluntary or waivable statutory or compulsory + licensing scheme. In all other cases the Licensor expressly + reserves any right to collect such royalties. + + +Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the +following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified + form), You must: + + a. retain the following if it is supplied by the Licensor + with the Licensed Material: + + i. identification of the creator(s) of the Licensed + Material and any others designated to receive + attribution, in any reasonable manner requested by + the Licensor (including by pseudonym if + designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of + warranties; + + v. a URI or hyperlink to the Licensed Material to the + extent reasonably practicable; + + b. indicate if You modified the Licensed Material and + retain an indication of any previous modifications; and + + c. indicate the Licensed Material is licensed under this + Public License, and include the text of, or the URI or + hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any + reasonable manner based on the medium, means, and context in + which You Share the Licensed Material. For example, it may be + reasonable to satisfy the conditions by providing a URI or + hyperlink to a resource that includes the required + information. + + 3. If requested by the Licensor, You must remove any of the + information required by Section 3(a)(1)(A) to the extent + reasonably practicable. + + 4. If You Share Adapted Material You produce, the Adapter's + License You apply must not prevent recipients of the Adapted + Material from complying with this Public License. + + +Section 4 -- Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that +apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right + to extract, reuse, reproduce, and Share all or a substantial + portion of the contents of the database; + + b. if You include all or a substantial portion of the database + contents in a database in which You have Sui Generis Database + Rights, then the database in which You have Sui Generis Database + Rights (but not its individual contents) is Adapted Material; and + + c. You must comply with the conditions in Section 3(a) if You Share + all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not +replace Your obligations under this Public License where the Licensed +Rights include other Copyright and Similar Rights. + + +Section 5 -- Disclaimer of Warranties and Limitation of Liability. + + a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE + EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS + AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF + ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, + IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, + WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR + PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, + ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT + KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT + ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. + + b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE + TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, + NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, + INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, + COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR + USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR + DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR + IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. + + c. The disclaimer of warranties and limitation of liability provided + above shall be interpreted in a manner that, to the extent + possible, most closely approximates an absolute disclaimer and + waiver of all liability. + + +Section 6 -- Term and Termination. + + a. This Public License applies for the term of the Copyright and + Similar Rights licensed here. However, if You fail to comply with + this Public License, then Your rights under this Public License + terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under + Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided + it is cured within 30 days of Your discovery of the + violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any + right the Licensor may have to seek remedies for Your violations + of this Public License. + + c. For the avoidance of doubt, the Licensor may also offer the + Licensed Material under separate terms or conditions or stop + distributing the Licensed Material at any time; however, doing so + will not terminate this Public License. + + d. Sections 1, 5, 6, 7, and 8 survive termination of this Public + License. + + +Section 7 -- Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different + terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the + Licensed Material not stated herein are separate from and + independent of the terms and conditions of this Public License. + + +Section 8 -- Interpretation. + + a. For the avoidance of doubt, this Public License does not, and + shall not be interpreted to, reduce, limit, restrict, or impose + conditions on any use of the Licensed Material that could lawfully + be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is + deemed unenforceable, it shall be automatically reformed to the + minimum extent necessary to make it enforceable. If the provision + cannot be reformed, it shall be severed from this Public License + without affecting the enforceability of the remaining terms and + conditions. + + c. No term or condition of this Public License will be waived and no + failure to comply consented to unless expressly agreed to by the + Licensor. + + d. Nothing in this Public License constitutes or may be interpreted + as a limitation upon, or waiver of, any privileges and immunities + that apply to the Licensor or You, including from the legal + processes of any jurisdiction or authority. + +--------------------------------------------------------------------------------------- + +Creative Commons is not a party to its public +licenses. Notwithstanding, Creative Commons may elect to apply one of +its public licenses to material it publishes and in those instances +will be considered the "Licensor." The text of the Creative Commons +public licenses is dedicated to the public domain under the CC0 Public +Domain Dedication. Except for the limited purpose of indicating that +material is shared under a Creative Commons public license or as +otherwise permitted by the Creative Commons policies published at +creativecommons.org/policies, Creative Commons does not authorize the +use of the trademark "Creative Commons" or any other trademark or logo +of Creative Commons without its prior written consent including, +without limitation, in connection with any unauthorized modifications +to any of its public licenses or any other arrangements, +understandings, or agreements concerning use of licensed material. For +the avoidance of doubt, this paragraph does not form part of the +public licenses. + +Creative Commons may be contacted at creativecommons.org. diff --git a/wso2/baseservice-i18n/pom.xml b/wso2/baseservice-i18n/pom.xml new file mode 100644 index 0000000..d110db3 --- /dev/null +++ b/wso2/baseservice-i18n/pom.xml @@ -0,0 +1,66 @@ + + + + 4.0.0 + + org.openo.common-services.common-utilities + common-setting + 1.1.0-SNAPSHOT + + baseservice-i18n + common-services-common-utilities/baseservice-i18n + + + org.reflections + reflections + 0.9.10 + + + io.dropwizard + dropwizard-core + 0.8.0 + + + junit + junit + test + 4.8.2 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.3 + + 1.8 + 1.8 + + + + maven-enforcer-plugin + + + + org.apache.maven.plugins + maven-source-plugin + + + attach-sources + + jar + + + + + + + \ No newline at end of file diff --git a/wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/DefaultErrorCodeI18n.java b/wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/DefaultErrorCodeI18n.java new file mode 100644 index 0000000..d225e1b --- /dev/null +++ b/wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/DefaultErrorCodeI18n.java @@ -0,0 +1,278 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.baseservice.i18n; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +public final class DefaultErrorCodeI18n implements ErrorCodeI18n { + + static final Logger logger = LoggerFactory.getLogger(DefaultErrorCodeI18n.class); + private static DefaultErrorCodeI18n singleton; + private static final Lock lock = new ReentrantLock(); + private Map errorItems; + + private DefaultErrorCodeI18n() { + try { + init(); + } catch (Exception e) { + logger.error("init ErrorCodeI18n failed.", e); + } + } + + private void init() throws Exception { + final ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader(); + final Map errorItems = new HashMap(); + JsonResourceScanner.findErrorCodePaths().forEach(path -> { + HashMap fileValues = null; + try (InputStream ins = systemClassLoader.getResourceAsStream(path)) { + fileValues = I18nJsonUtil.getInstance().readFromJson(ins, HashMap.class); + logger.info("load errorcode file success: " + path); + } catch (IOException ex) { + logger.info("load errorcode file failed: " + path); + logger.info( + "load errorcode file failed: " + systemClassLoader.getResource(path).toString(), + ex); + return; + } + List errcodes = (List) fileValues.get("errcodes"); + if (errcodes == null) { + logger.info("none errcodes field in: " + path); + return; + } + + String fileName = null; + int i = path.lastIndexOf("/"); + if (i > -1) { + fileName = path.substring(i + 1); + } else { + fileName = path; + } + i = fileName.indexOf("-errorcode-"); + String localeSrc = fileName.substring(i + 11, fileName.lastIndexOf(".")); + if (localeSrc.isEmpty()) { + logger.info("parse errorcode file failed: locale is null"); + return; + } + + String[] ss = localeSrc.replace("-", "_").split("_"); + String tempLocale = null; + if (ss.length == 1) { + tempLocale = new Locale(ss[0]).toString(); + } else if (ss.length == 2) { + tempLocale = new Locale(ss[0], ss[1]).toString(); + } else { + logger.info("parse i18n file failed: locale is error \"" + localeSrc + "\""); + return; + } + String locale = tempLocale; + errcodes.forEach(errorcode -> { + Map errorConfig = (Map) errorcode; + Integer code = Integer.valueOf(errorConfig.get("code")); + String level = errorConfig.get("level"); + String label = errorConfig.get("label"); + + ErrorItemImpl errorItem = errorItems.get(Integer.valueOf(code)); + if (errorItem == null) { + errorItem = new ErrorItemImpl(); + errorItem.errorCode = code.intValue(); + errorItem.level = ErrorCodeLevelUtil.transfer2Int(level); + errorItems.put(code, errorItem); + } + errorItem.addLabel(locale, label); + }); + }); + + errorItems.forEach((code, errorItem) -> { + errorItem.unmodifiable(); + }); + this.errorItems = Collections.unmodifiableMap(errorItems); + } + + + static DefaultErrorCodeI18n getInstance() { + if (singleton == null) { + lock.lock(); + try { + if (singleton == null) { + singleton = new DefaultErrorCodeI18n(); + } + } finally { + lock.unlock(); + } + } + return singleton; + } + + + /* + * (non-Javadoc) + * + * @see com.zte.ums.zenap.i18n.ErrorCodeI18n#getErrorItem(int) + */ + @Override + public Optional getErrorItem(int errorCode) { + return Optional.ofNullable(errorItems.get(Integer.valueOf(errorCode))); + } + + + public static class ErrorItemImpl implements ErrorItem { + + private int errorCode; + + private int level; + + private Map labels = new HashMap(); + + private String jsonString = null; + + @Override + public int getErrorCode() { + return errorCode; + } + + @Override + public int getLevel() { + return level; + } + + public Map getLabels() { + return labels; + } + + private void unmodifiable() { + if (labels != null) { + labels = Collections.unmodifiableMap(labels); + } + } + + private synchronized void addLabel(String locale, String label) { + labels.put(locale, label); + } + + @Override + public String getLabel(Locale theLocale) { + if (theLocale == null) { + return null; + } + return labels.get(I18nLocaleTransfer.transfer(theLocale, labels.keySet())); + } + + @Override + public String getCanonicalLabels(int errorCode) { + String jsonString = this.jsonString; + if (jsonString == null) { + ErrorItem2 errorItem2 = new ErrorItem2(); + errorItem2.setErrorCode(this.errorCode); + errorItem2.setLevel(ErrorCodeLevelUtil.transfer2String(this.errorCode)); + errorItem2.setErrlabels(labels); + try { + jsonString = I18nJsonUtil.getInstance().writeToJson(errorItem2); + } catch (Exception e) { + logger.info("getCanonicalLabels failed from with param errorCode " + errorCode + + " and this errorCode " + this.errorCode, e); + return null; + } + this.jsonString = jsonString; + } + return jsonString; + } + + } + + protected static class ErrorItem2 { + + private int errorCode; + + private String level; + + private Map errlabels; + + public ErrorItem2() { + + } + + public int getErrorCode() { + return errorCode; + } + + public void setErrorCode(int errorCode) { + this.errorCode = errorCode; + } + + public String getLevel() { + return level; + } + + public void setLevel(String level) { + this.level = level; + } + + public Map getErrlabels() { + return errlabels; + } + + public void setErrlabels(Map errlabels) { + this.errlabels = errlabels; + } + } + + protected static class ErrorCodeLevelUtil { + + public static final int ERROR_LEVEL = javax.swing.JOptionPane.ERROR_MESSAGE; + + public static final int WARN_LEVEL = javax.swing.JOptionPane.WARNING_MESSAGE; + + public static final int INFO_LEVEL = javax.swing.JOptionPane.INFORMATION_MESSAGE; + + protected static String transfer2String(int errorCode) { + switch (errorCode) { + case ERROR_LEVEL: + return "ERROR"; + case INFO_LEVEL: + return "INFO"; + case WARN_LEVEL: + return "WARN"; + } + return null; + } + + protected static int transfer2Int(String level) { + switch (level) { + case "ERROR": + return ERROR_LEVEL; + case "INFO": + return INFO_LEVEL; + case "WARN": + return WARN_LEVEL; + } + return -1; + } + + } + +} diff --git a/wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/DefaultI18nService.java b/wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/DefaultI18nService.java new file mode 100644 index 0000000..820478c --- /dev/null +++ b/wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/DefaultI18nService.java @@ -0,0 +1,59 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.baseservice.i18n; + + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.Optional; +import javax.inject.Inject; +import org.jvnet.hk2.annotations.Service; +import org.openo.baseservice.i18n.ErrorCodeI18n.ErrorItem; + +@Service +public final class DefaultI18nService implements I18nService { + + /** + * Get the corresponding examples of international documents (all languages),
+ * + * for the above example topology (for example, the Chinese definition: topo-i18n-zh-CN.json, English definition + * Topo -i18n-en-US.json), into the reference into the "TOPO" can be
+ * + * (i.e. except "-i18n-*.json" after the exact match). + * + * @param i18nFilePrefix International file prefix (-i18n-*.json front part) + * @return Optional + */ + public Optional getI18n(String i18nFilePrefix) { + return I18nContainer.getInstance().getI18n(i18nFilePrefix); + } + + /** + * Gets the corresponding error item based on the error code (including the error description information for all + * languages) + * + * @param errorCode + * @return Optional + */ + public Optional getErrorItem(int errorCode) { + return ErrorCodeI18n.getInstance().getErrorItem(errorCode); + } + + @Inject + public void setObjectMapper(ObjectMapper objectMapper) { + I18nJsonUtil.getInstance(objectMapper); + } + +} diff --git a/wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/ErrorCodeException.java b/wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/ErrorCodeException.java new file mode 100644 index 0000000..fb470ab --- /dev/null +++ b/wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/ErrorCodeException.java @@ -0,0 +1,53 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.baseservice.i18n; + +public class ErrorCodeException extends Exception { + + private static final long serialVersionUID = 5522808473663280894L; + + private int errorCode; + + /** + * Error definition placeholder replacement + */ + private String[] arguments; + + /** + * According to the original exception, error code, debug print information and construct a new anomaly placeholder + * + * @param source + * @param errorCode + * @param debugMessage + * @param arguments + */ + public ErrorCodeException(Throwable source, int errorCode, String debugMessage, String[] arguments) { + super(debugMessage, source); + + this.errorCode = errorCode; + + this.arguments = arguments; + } + + public int getErrorCode() { + return errorCode; + } + + public String[] getArguments() { + return arguments; + } + +} diff --git a/wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/ErrorCodeI18n.java b/wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/ErrorCodeI18n.java new file mode 100644 index 0000000..39738b5 --- /dev/null +++ b/wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/ErrorCodeI18n.java @@ -0,0 +1,151 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.baseservice.i18n; + +import org.openo.baseservice.i18n.DefaultErrorCodeI18n.ErrorCodeLevelUtil; +import org.openo.baseservice.i18n.DefaultErrorCodeI18n.ErrorItem2; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Locale; +import java.util.Map; +import java.util.Optional; + +public interface ErrorCodeI18n { + + static final Logger logger = LoggerFactory.getLogger(ErrorCodeI18n.class); + + /** + * Access to the internationalization of the error code examples, scanning the process of all + * classes load path, loading all the *-errorcode-*.json files, and load all the international + * language information + * + * @return + */ + static ErrorCodeI18n getInstance() { + return DefaultErrorCodeI18n.getInstance(); + } + + /** + * Gets the corresponding error item based on the error code (including the error description + * information for all languages) + * + * @param errorCode + * @return Optional + */ + public Optional getErrorItem(int errorCode); + + public static interface ErrorItem { + + public int getErrorCode(); + + public int getLevel(); + + public Map getLabels(); + + public String getLabel(Locale theLocale); + + /** + * All language error information description of assembly.
+ * + * some modules to store all the error information description or transfer, and finally the time + * to choose the appropriate value according to the locale presentation.
+ * + * it is not necessary to pass the error code (code), but in order to take into account the + * subsequent scalability, so also passed, the general module does not need this information. + * Similar form:
+ * { "code":53501, "level":"INFO", "errlabels":{"zh_CN":"拓扑定制文件无效。","en_US":"The topology + * customized file is invalid.","ru_RU":"Топология настроенный файл недействительно."} } + * + * @param errorCode + * @return + */ + public String getCanonicalLabels(int errorCode); + + /** + * With the use of the above interface, it is possible to obtain an international string + * corresponding to a specific language from the combination of all error messages + * + * @param labels Error message description string (Return value of the getCanonicalLabels + * method) + * @param theLocale + * @return + */ + public static String getLabelFromCanonicalLabels(String labels, Locale theLocale) { + if (labels == null || theLocale == null) { + return null; + } + try { + ErrorItem2 errorItem2 = I18nJsonUtil.getInstance().readFromJson(labels, ErrorItem2.class); + Map errlabels = errorItem2.getErrlabels(); + return errlabels.get(I18nLocaleTransfer.transfer(theLocale, errlabels.keySet())); + } catch (Exception e) { + logger.info( + "getLabelFromCanonicalLabels failed from " + labels + " with local " + theLocale, e); + return null; + } + } + + /** + * With the use of the above interface, we can get the error code corresponding to the specific + * language from all the error information + * + * @param labels Error message description string (Return value of the getCanonicalLabels + * method) + * @param theLocale + * @return errorCode + */ + public static int getErrorcodeFromCanonicalLabels(String labels, Locale theLocale) { + if (labels == null) { + return -1; + } + try { + ErrorItem2 errorItem2 = I18nJsonUtil.getInstance().readFromJson(labels, ErrorItem2.class); + return errorItem2.getErrorCode(); + } catch (Exception e) { + logger.info( + "getErrorcodeFromCanonicalLabels failed from " + labels + " with local " + theLocale, + e); + return -1; + } + } + + /** + * With the above interface, the error level of the corresponding string is obtained from all + * the error messages + * + * @param labels Error message description string (Return value of the getCanonicalLabels + * method) + * @param theLocale + * @return error level + */ + public static int getLevelFromCanonicalLabels(String labels, Locale theLocale) { + if (labels == null) { + return -1; + } + try { + ErrorItem2 errorItem2 = I18nJsonUtil.getInstance().readFromJson(labels, ErrorItem2.class); + return ErrorCodeLevelUtil.transfer2Int(errorItem2.getLevel()); + } catch (Exception e) { + logger.info( + "getErrorcodeFromCanonicalLabels failed from " + labels + " with local " + theLocale, + e); + return -1; + } + } + } + +} diff --git a/wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/I18n.java b/wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/I18n.java new file mode 100644 index 0000000..ec9197b --- /dev/null +++ b/wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/I18n.java @@ -0,0 +1,132 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.baseservice.i18n; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; + +public interface I18n { + static final Logger logger = LoggerFactory.getLogger(I18n.class); + + /** + * Get the corresponding examples of international documents (all languages),
+ * + * for the above example topology (for example, the Chinese definition: topo-i18n-zh-CN.json, + * English definition Topo -i18n-en-US.json), into the reference into the "TOPO" can be
+ * + * (i.e. except "-i18n-*.json" after the exact match). + * + * @param i18nFilePrefix + * @return Optional + */ + public static Optional getInstance(String i18nFilePrefix) { + return I18nContainer.getInstance().getI18n(i18nFilePrefix); + } + + /** + * According to key, the internationalization of all languages is described (Map) + * + * @param labelKey key + * @return Map + */ + public Map getLabelValues(String labelKey); + + /** + * According to key, the internationalization of all languages is described + * + * @param labelKey + * @param theLocale + * @return + */ + public String getLabelValue(String labelKey, Locale theLocale); + + /** + * According to key, the internationalization of all languages is described + * + * @param labelKey + * @param theLocale + * @param arguments + * @return + */ + public String getLabelValue(String labelKey, Locale theLocale, String[] arguments); + + /** + * Replace the placeholder that is defined in the internationalization description, as shown in + * the following example,
+ * + * {0} represents first bits, which will be replaced by a specific number of days. :
+ * + * {"col_dir_file_time_table": "save days {0} days"} + * + * @param labelKey + * @param arguments + * @return Map + */ + public Map getLabelValues(String labelKey, String[] arguments); + + /** + * According to the key to get all the international description of the language, and the results + * will be combined into a Json string, used in the log module scene,
+ * + * it is necessary to store all of the international information or transfer, and finally show the + * time according to locale to choose the appropriate value.
+ * + * (here in order to form similar to read, plus a newline)
+ * {"zh_CN":"统一公共应用","en_US":" Unified common application ","ru_RU":"Единый общий приложений"} + * + * @param labelKey key + * @return + */ + public String getCanonicalLabelValues(String labelKey); + + /** + * With the use of getCanonicalLabelValues interface, from all the international description of + * the combination of string and specific language corresponding to the international string. The + * return value of the getCanonicalLabelValues method + * + * @param values + * @param theLocale + * @return value + */ + public static String getValuefromCanonicalValues(String values, Locale theLocale) { + try { + @SuppressWarnings("unchecked") + HashMap map = I18nJsonUtil.getInstance().readFromJson(values, HashMap.class); + + return map.get(I18nLocaleTransfer.transfer(theLocale, map.keySet())); + } catch (Exception e) { + logger.error("get i18n value failed by locale:" + theLocale + " from " + values, e); + return null; + } + } + + /** + * According to the value to find the corresponding key, such as a module in accordance with + * international content filtering, search, database storage is key, then the front pass query is + * a kind of language corresponding to the value, to get the corresponding international key to + * the database query. + * + * @param value + * @return + */ + public String getKeyFromValue(String value); + +} diff --git a/wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/I18nContainer.java b/wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/I18nContainer.java new file mode 100644 index 0000000..95ae105 --- /dev/null +++ b/wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/I18nContainer.java @@ -0,0 +1,148 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.baseservice.i18n; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; + +final class I18nContainer { + + private static Logger logger = LoggerFactory.getLogger(I18nContainer.class); + + private Map i18ns; + + private I18nContainer() { + init(); + } + + + private void init() { + Map> i18nTemps = generateI18ns(); + + i18ns = new HashMap(); + for (Entry> entry : i18nTemps.entrySet()) { + String name = entry.getKey(); + Map items = entry.getValue(); + for (Entry i18nItemEntry : items.entrySet()) { + i18nItemEntry.getValue().unmodifiable(); + } + + I18n i18n = new I18nImpl(name, items); + i18ns.put(name, i18n); + } + } + + @SuppressWarnings("unchecked") + private Map> generateI18ns() { + Map> i18nTemps = new HashMap>(); + + ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader(); + JsonResourceScanner.findI18nPaths().forEach((path) -> { + HashMap fileValues = null; + try (InputStream ins = systemClassLoader.getResourceAsStream(path)) { + fileValues = I18nJsonUtil.getInstance().readFromJson(ins, HashMap.class); + logger.info("load i18n file success: " + path); + } catch (IOException ex) { + logger.info("load i18n file failed: " + path); + logger.info("load i18n file failed: " + systemClassLoader.getResource(path).toString(), ex); + return; + } + + if (!validateI18nFileValues(fileValues, path)) { + return; + } + + String fileName = null; + int i = path.lastIndexOf("/"); + if (i > -1) { + fileName = path.substring(i + 1); + } else { + fileName = path; + } + i = fileName.indexOf("-i18n-"); + String name = fileName.substring(0, i); + String localeSrc = fileName.substring(i + 6, fileName.lastIndexOf(".")); + if (name.isEmpty()) { + logger.info("parse i18n file failed: name is null"); + return; + } else if (localeSrc.isEmpty()) { + logger.info("parse i18n file failed: locale is null"); + return; + } + + String[] ss = localeSrc.replace("-", "_").split("_"); + String locale = null; + if (ss.length == 1) { + locale = new Locale(ss[0]).toString(); + } else if (ss.length == 2) { + locale = new Locale(ss[0], ss[1]).toString(); + } else { + logger.info("parse i18n file failed: locale is error \"" + localeSrc + "\""); + return; + } + + Map i18nItems = i18nTemps.get(name); + if (i18nItems == null) { + i18nItems = new HashMap(); + i18nTemps.put(name, i18nItems); + } + + for (Entry entry : fileValues.entrySet()) { + String label = entry.getKey(); + + I18nItem i18nItem = i18nItems.get(label); + if (i18nItem == null) { + i18nItem = new I18nItem(label); + i18nItems.put(label, i18nItem); + } + + i18nItem.addValue(locale, entry.getValue()); + } + }); + return i18nTemps; + } + + private boolean validateI18nFileValues(HashMap fileValues, String path) { + for (Entry entry : fileValues.entrySet()) { + if (entry.getValue() != null && !String.class.isInstance(entry.getValue())) { + logger.info("parse i18n file failed: " + path + " field's[" + entry.getKey() + + "] value is not string type"); + return false; + } + } + return true; + } + + protected static I18nContainer getInstance() { + return I18nContainerSingleton.singleton; + } + + Optional getI18n(String name) { + return Optional.ofNullable(this.i18ns.get(name)); + } + + static class I18nContainerSingleton { + private static final I18nContainer singleton = new I18nContainer(); + } +} diff --git a/wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/I18nImpl.java b/wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/I18nImpl.java new file mode 100644 index 0000000..bda6f2d --- /dev/null +++ b/wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/I18nImpl.java @@ -0,0 +1,137 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.baseservice.i18n; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.Map.Entry; + +public class I18nImpl implements I18n { + private static Logger logger = LoggerFactory.getLogger(I18nImpl.class); + + private String name; + + private Map items; + + private Map keyToValueMap; + + private Map valueToKeyMap; + + + public I18nImpl(String name, Map items) { + this.name = name; + this.items = Collections.unmodifiableMap(items); + + keyToValueMap = new HashMap<>(items.size()); + valueToKeyMap = new HashMap<>(items.size() * 3); + + try { + for (Entry entry : items.entrySet()) { + String key = entry.getKey(); + I18nItem item = entry.getValue(); + String value = I18nJsonUtil.getInstance().writeToJson(item.getValues()); + + keyToValueMap.put(key, value); + for (Entry valueEntry : item.getValues().entrySet()) { + valueToKeyMap.put(valueEntry.getValue(), key); + } + } + } catch (Exception e) { + logger.error("new I18nImpl failed:" + name, e); + } + + keyToValueMap = Collections.unmodifiableMap(keyToValueMap); + valueToKeyMap = Collections.unmodifiableMap(valueToKeyMap); + } + + @Override + public Map getLabelValues(String labelKey) { + I18nItem item = items.get(labelKey); + if (item != null) { + return item.getValues(); + } + return null; + } + + @Override + public String getLabelValue(String labelKey, Locale theLocale) { + I18nItem item = items.get(labelKey); + if (item != null) { + Map values = item.getValues(); + return values.get(I18nLocaleTransfer.transfer(theLocale, values.keySet())); + } + return null; + } + + @Override + public String getLabelValue(String labelKey, Locale theLocale, String[] arguments) { + I18nItem item = items.get(labelKey); + if (item != null) { + Map values = item.getValues(); + String value = values.get(I18nLocaleTransfer.transfer(theLocale, values.keySet())); + return replaceArguments(value, arguments); + } + return null; + } + + @Override + public Map getLabelValues(String labelKey, String[] arguments) { + I18nItem item = items.get(labelKey); + if (item != null) { + Map map = new HashMap(); + for (Entry entry : item.getValues().entrySet()) { + String value = entry.getValue(); + map.put(entry.getKey(), replaceArguments(value, arguments)); + } + return map; + } + return null; + } + + @Override + public String getCanonicalLabelValues(String labelKey) { + return keyToValueMap.get(labelKey); + } + + @Override + public String getKeyFromValue(String aValue) { + return valueToKeyMap.get(aValue); + } + + private String replaceArguments(String value, String[] arguments) { + if (value == null) { + return null; + } + if (arguments != null) { + int i = 0; + for (String argument : arguments) { + if (argument == null) { + value = value.replaceAll("\\{\\s*" + i + "\\s*\\}", ""); + } else { + value = value.replaceAll("\\{\\s*" + i + "\\s*\\}", argument); + } + i++; + } + } + return value.replaceAll("\\{\\s*\\d+\\s*\\}", ""); + } + +} diff --git a/wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/I18nItem.java b/wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/I18nItem.java new file mode 100644 index 0000000..1aaaf6f --- /dev/null +++ b/wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/I18nItem.java @@ -0,0 +1,53 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.baseservice.i18n; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +public class I18nItem { + + private String lable; + + private Map values; + + public I18nItem(String lable) { + this.lable = lable; + values = new HashMap(); + } + + public I18nItem(String lable, Map values) { + this.lable = lable; + this.values = values; + } + + public String getLable() { + return lable; + } + + public Map getValues() { + return values; + } + + public void addValue(String locale, String value) { + values.put(locale, value); + } + + public void unmodifiable() { + values = Collections.unmodifiableMap(values); + } +} diff --git a/wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/I18nJsonUtil.java b/wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/I18nJsonUtil.java new file mode 100644 index 0000000..e3746dc --- /dev/null +++ b/wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/I18nJsonUtil.java @@ -0,0 +1,170 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.baseservice.i18n; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Locale; +import java.util.Set; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +final class I18nJsonUtil { + + private static I18nJsonUtil util; + private static Lock lock = new ReentrantLock(); + private ObjectMapper objectMapper; + + public I18nJsonUtil(ObjectMapper objectMapper) { + this.objectMapper = objectMapper; + } + + T readFromJson(InputStream ins, Class clazz) + throws JsonParseException, JsonMappingException, IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + byte[] bs = new byte[1024 * 10]; + int length = -1; + while ((length = ins.read(bs)) > 0) { + baos.write(bs, 0, length); + } + bs = baos.toByteArray(); + + byte[] ubs = null; + if (bs.length > 3) { + // 删除bom头 -17, -69, -65 + if (bs[0] == -17 && bs[1] == -69 && bs[2] == -65) { + ubs = new byte[bs.length - 3]; + System.arraycopy(bs, 3, ubs, 0, ubs.length); + } + } + if (ubs == null) { + ubs = bs; + } + return objectMapper.readValue(ubs, clazz); + } + + T readFromJson(String str, Class clazz) + throws JsonParseException, JsonMappingException, IOException { + return objectMapper.readValue(str, clazz); + } + + String writeToJson(Object obj) throws JsonProcessingException { + return objectMapper.writeValueAsString(obj); + } + + static I18nJsonUtil getInstance(ObjectMapper objectMapper) { + if (util == null) { + lock.lock(); + try { + if (util == null) { + if (objectMapper == null) { + objectMapper = new ObjectMapper(); + } + util = new I18nJsonUtil(objectMapper); + } + } finally { + lock.unlock(); + } + } + return util; + } + + static I18nJsonUtil getInstance() { + return getInstance(null); + } +} + + +/** + * 国际化转换工具 + * + * @author 10163976 + */ +class I18nLocaleTransfer { + + private static Logger LOG = LoggerFactory.getLogger(I18nLocaleTransfer.class); + + /** + * 方言转换
如果存在直接返回
如果不存在,则获取语言进行模糊匹配,未匹配上则返回默认方言
+ * + * @param theLocale 待转换方言 + * @param locales 存在的方言 + * @return 转换后的方言 + */ + public static String transfer(Locale theLocale, Set locales) { + if (locales == null || locales.isEmpty()) { + LOG.debug("locales is NULL or empty"); + return null; + } + if (theLocale == null) { + String result = fetchDefault(locales); + LOG.debug("transfer NULL --> " + result + " in " + locales); + return result; + } + String locale = theLocale.toString(); + if (locale.isEmpty()) { + String result = fetchDefault(locales); + LOG.debug("transfer EMPTY --> " + result + " in " + locales); + return result; + } + // 精确匹配 + if (locales.contains(locale)) { + return locale; + } + + // 根据语言模糊匹配 + String language = theLocale.getLanguage(); + if (locales.contains(language)) { + LOG.debug("transfer " + locale + " --> " + language + " in " + locales); + return language; + } + + language = language + "_"; + for (String temp : locales) { + if (temp.startsWith(language)) { + LOG.debug("transfer " + locale + " --> " + temp + " in " + locales); + return temp; + } + } + String result = fetchDefault(locales); + LOG.debug("transfer " + locale + " --> " + result + " in " + locales); + return result; + } + + /** + * 返回默认方言,优先级为en,en_US,zh,zh_CN,如果都不存在,则随机返回一个 + */ + private static String fetchDefault(Set locales) { + if (locales.contains("en")) { + return "en"; + } else if (locales.contains("en_US")) { + return "en_US"; + } + if (locales.contains("zh")) { + return "zh"; + } else if (locales.contains("zh_CN")) { + return "zh_CN"; + } + return locales.iterator().next(); + } +} diff --git a/wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/I18nService.java b/wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/I18nService.java new file mode 100644 index 0000000..a643356 --- /dev/null +++ b/wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/I18nService.java @@ -0,0 +1,38 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.baseservice.i18n; + + +import java.util.Optional; +import org.jvnet.hk2.annotations.Contract; +import org.openo.baseservice.i18n.ErrorCodeI18n.ErrorItem; + +@Contract +public interface I18nService { + + /** + * Get the corresponding examples of international documents (all languages),
for the above + * example topology (for example, the Chinese definition: topo-i18n-zh-CN.json, English + * definition Topo -i18n-en-US.json), into the reference into the "TOPO" can be
(i.e. + * except "-i18n-*.json" after the exact match). + * + * @return Optional + */ + public Optional getI18n(String i18nFilePrefix); + + public Optional getErrorItem(int errorCode); + +} diff --git a/wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/JsonResourceScanner.java b/wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/JsonResourceScanner.java new file mode 100644 index 0000000..9f5ef3a --- /dev/null +++ b/wso2/baseservice-i18n/src/main/java/org/openo/baseservice/i18n/JsonResourceScanner.java @@ -0,0 +1,81 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.baseservice.i18n; + +import org.reflections.Reflections; +import org.reflections.scanners.ResourcesScanner; +import org.reflections.util.ClasspathHelper; +import org.reflections.util.ConfigurationBuilder; + +import java.io.File; +import java.net.URL; +import java.util.Collection; +import java.util.Collections; +import java.util.Iterator; +import java.util.Set; +import java.util.regex.Pattern; + +final class JsonResourceScanner { + private static final org.slf4j.Logger LOG = + org.slf4j.LoggerFactory.getLogger(JsonResourceScanner.class); + private static final Pattern PATTERN_OF_I18N_FILE_NAME = + Pattern.compile(".*?\\-i18n\\-.*?\\.json"); + private static final Pattern PATTERN_OF_ERROR_CODE_FILE_NAME = + Pattern.compile(".*?\\-errorcode\\-.*?\\.json"); + + private static Collection findFromClassPath(Pattern pattern) { + ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); + Collection urls = ClasspathHelper.forJavaClassPath(); + + for (Iterator iter = urls.iterator(); iter.hasNext();) { + URL url = iter.next(); + boolean exist = false; + try { + exist = new File(url.getFile()).exists(); + if (!exist) { + LOG.info("class path url ignored for not exists: " + url.toString()); + } + } catch (Exception e) { + LOG.info("class path url ignored for exception: " + url.toString(), e); + exist = false; + } + if (!exist) { + iter.remove(); + } + } + for (URL url : urls) { + LOG.info("class path url:" + url.toString()); + } + configurationBuilder.addUrls(urls); + configurationBuilder.setScanners(new ResourcesScanner()); + configurationBuilder.useParallelExecutor(); + Reflections reflections = new Reflections(configurationBuilder); + Set results = reflections.getResources(pattern); + if (results == null) { + return Collections.emptySet(); + } else { + return results; + } + } + + static Collection findI18nPaths() { + return findFromClassPath(PATTERN_OF_I18N_FILE_NAME); + } + + static Collection findErrorCodePaths() { + return findFromClassPath(PATTERN_OF_ERROR_CODE_FILE_NAME); + } +} diff --git a/wso2/common-util/.gitignore b/wso2/common-util/.gitignore new file mode 100644 index 0000000..be68b59 --- /dev/null +++ b/wso2/common-util/.gitignore @@ -0,0 +1,5 @@ +/target/ +# Eclipse +.settings/ +.classpath +.project diff --git a/wso2/common-util/pom.xml b/wso2/common-util/pom.xml new file mode 100644 index 0000000..074cf13 --- /dev/null +++ b/wso2/common-util/pom.xml @@ -0,0 +1,142 @@ + + + + 4.0.0 + + org.openo.common-services.common-utilities + common-setting + 1.1.0-SNAPSHOT + + commonlib-cbb + jar + + 3.1.6 + + + + com.googlecode.jmockit + jmockit + test + 1.1 + + + + junit + junit + test + 4.8.2 + + + + org.apache.commons + commons-lang3 + + + commons-io + commons-io + + + + org.slf4j + slf4j-log4j12 + + + + org.codehaus.jackson + jackson-mapper-asl + + + net.sf.json-lib + json-lib + jdk15 + + + javax.servlet + servlet-api + 2.5 + provided + + + com.github.stephenc.jcip + jcip-annotations + 1.0-1 + test + + + org.apache.cxf + cxf-rt-frontend-jaxrs + ${cxf.version} + + + org.apache.cxf + cxf-rt-rs-client + ${cxf.version} + + + org.apache.cxf + cxf-rt-transports-http-hc + ${cxf.version} + + + org.codehaus.jackson + jackson-jaxrs + 1.9.2 + + + + + + org.apache.maven.plugins + maven-release-plugin + 2.5.2 + + + org.apache.maven.plugins + maven-surefire-plugin + + -XX:-UseSplitVerifier + ${maven.test.skip} + ${maven.test.failure.ignore} + + ${excludesFile} + + + + + org.codehaus.mojo + cobertura-maven-plugin + 2.6 + + + xml + html + + + + + package + + cobertura + + + + + + + + +common-services-common-utilities/common-util diff --git a/wso2/common-util/src/main/java/org/openo/baseservice/bus/util/BusConstant.java b/wso2/common-util/src/main/java/org/openo/baseservice/bus/util/BusConstant.java new file mode 100644 index 0000000..ab2bcd1 --- /dev/null +++ b/wso2/common-util/src/main/java/org/openo/baseservice/bus/util/BusConstant.java @@ -0,0 +1,48 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.baseservice.bus.util; + +/** + *

+ * An class which holds the all the constant values for the Bus register CBB. + *

+ *
+ * + * @author + * @version + */ +public final class BusConstant { + + public static final String JSON = "json"; + + public static final String BUS_CONFIGURE_FILE = "/etc/microservice.ini"; + + public static final String BUS_SERVICE_URL = "/openoapi/microservices/v1/services"; + + public static final String BUS_ADDRESS_KEY = "msb.address"; + + public static final String APPLICATION_JSON_HEADER = "application/json"; + + public static final String CREATE_OR_UPDATE = "createOrUpdate"; + + public static final String MICROSERVICE_DEFAULT = "msb.openo.org:80"; + + public static final String MICROSERVICE_PATH = "/etc/microservice"; + + public static final String POST_METHOD = "POST"; + + public static final String HTTP_HEAD = "http://"; +} diff --git a/wso2/common-util/src/main/java/org/openo/baseservice/bus/util/RegisterService.java b/wso2/common-util/src/main/java/org/openo/baseservice/bus/util/RegisterService.java new file mode 100644 index 0000000..d1926c7 --- /dev/null +++ b/wso2/common-util/src/main/java/org/openo/baseservice/bus/util/RegisterService.java @@ -0,0 +1,177 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.baseservice.bus.util; + +import java.io.FileInputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +import javax.ws.rs.core.Response; + +import org.apache.cxf.jaxrs.client.WebClient; +import org.codehaus.jackson.jaxrs.JacksonJsonProvider; +import org.openo.baseservice.util.impl.SystemEnvVariablesFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Provide the service register cbb for common use.
+ *

+ *

+ * + * @author + * @version + */ +public class RegisterService { + + private static final Logger LOGGER = LoggerFactory.getLogger(RegisterService.class); + + private static String busPath = null; + + /** + * Constructor
+ *

+ *

+ * + * @throws IOException + * + * @since + */ + private RegisterService() { + } + + /** + * register the micro service.
+ * + * @param jsonPath: + * the service json object to register to the bus. + * @param createOrUpdate: + * true, create and update the old ip port. false, create and + * delete the old one; + * @return + * @throws IOException + * @since + */ + public static Response registerService(String jsonPath, boolean createOrUpdate) throws IOException { + + String serviceInfo = getServiceModel(jsonPath); + + WebClient client = initializeClient(); + + client.type(BusConstant.APPLICATION_JSON_HEADER); + + client.accept(BusConstant.APPLICATION_JSON_HEADER); + + client.path(BusConstant.BUS_SERVICE_URL); + + client.query(BusConstant.CREATE_OR_UPDATE, createOrUpdate); + + LOGGER.info("Connecting bus address : " + busPath + BusConstant.BUS_SERVICE_URL); + + return client.invoke(BusConstant.POST_METHOD, serviceInfo); + + } + + /** + * get the service's model. and return it as a string ;
+ * + * @param jsonPath + * @return + * @since + */ + private static String getServiceModel(String jsonPath) { + + String serviceInfo = ""; + + try { + LOGGER.info("begin to read file micro service json " + jsonPath); + + FileInputStream busFile = new FileInputStream(jsonPath); + + int size = busFile.available(); + + byte[] buffer = new byte[size]; + + busFile.read(buffer); + + busFile.close(); + + serviceInfo = new String(buffer); + LOGGER.info("finished to read micro service json file. "); + } catch (Exception ex) { + LOGGER.error("Read the micro service json file error :", ex); + } + return serviceInfo; + } + + /** + * initialize the bus ip and port.
+ * + * @return + * @throws IOException + * @since + */ + private static String getBusAddress() throws IOException { + + LOGGER.info("begin to get the bus baseurl."); + FileInputStream busFile = null; + String url = BusConstant.MICROSERVICE_DEFAULT; + + String filePath = SystemEnvVariablesFactory.getInstance().getAppRoot() + BusConstant.BUS_CONFIGURE_FILE; + LOGGER.info("bus base url file:" + filePath); + + Properties properties = new Properties(); + + try { + busFile = new FileInputStream(filePath); + properties.load(busFile); + url = properties.getProperty(BusConstant.BUS_ADDRESS_KEY); + } catch (IOException e) { + if (busFile != null) { + busFile.close(); + } + LOGGER.error("Read the bus url failed: ", e); + } + + LOGGER.info("initialize the bus baseurl is: " + url); + return BusConstant.HTTP_HEAD + url; + } + + /** + * get the bus's client's address. and initialize the web client.
+ * + * @return + * @throws IOException + * @since + */ + private static WebClient initializeClient() throws IOException { + + final List providers = new ArrayList(); + + JacksonJsonProvider jacksonJsonProvider = new JacksonJsonProvider(); + + providers.add(jacksonJsonProvider); + + if (busPath == null) { + busPath = getBusAddress(); + } + + return WebClient.create(busPath, providers); + } +} diff --git a/wso2/common-util/src/main/java/org/openo/baseservice/bus/util/RegisterServiceListener.java b/wso2/common-util/src/main/java/org/openo/baseservice/bus/util/RegisterServiceListener.java new file mode 100644 index 0000000..c4e1417 --- /dev/null +++ b/wso2/common-util/src/main/java/org/openo/baseservice/bus/util/RegisterServiceListener.java @@ -0,0 +1,70 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.baseservice.bus.util; + +import java.io.File; +import java.io.IOException; + +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; + +import org.openo.baseservice.util.impl.SystemEnvVariablesFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Initialize the service register listener.
+ *

+ *

+ * + * @author + * @version + */ +public class RegisterServiceListener implements ServletContextListener { + + private static final Logger LOGGER = LoggerFactory.getLogger(RegisterServiceListener.class); + + @Override + public void contextInitialized(ServletContextEvent sce) { + + String servicePath = SystemEnvVariablesFactory.getInstance().getAppRoot() + BusConstant.MICROSERVICE_PATH; + LOGGER.info("microservices json file path is" + servicePath); + + File file = new File(servicePath); + + File[] fileList = file.listFiles(); + + for (File tempFile : fileList) { + String fileName = tempFile.getName(); + if (fileName.substring(fileName.lastIndexOf('.') + 1).equalsIgnoreCase(BusConstant.JSON)) { + LOGGER.info("begin to initialize the service file" + tempFile.getAbsolutePath()); + + try { + RegisterService.registerService(tempFile.getAbsolutePath(), true); + } catch (IOException e) { + LOGGER.error("Faile to register the service file :" + tempFile.getPath() + ", exception:" + e); + } + } + } + } + + @Override + public void contextDestroyed(ServletContextEvent sce) { + // TODO Auto-generated method stub + + } +} diff --git a/wso2/common-util/src/main/java/org/openo/baseservice/encrypt/cbb/CipherCreator.java b/wso2/common-util/src/main/java/org/openo/baseservice/encrypt/cbb/CipherCreator.java new file mode 100644 index 0000000..d964cbc --- /dev/null +++ b/wso2/common-util/src/main/java/org/openo/baseservice/encrypt/cbb/CipherCreator.java @@ -0,0 +1,95 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.baseservice.encrypt.cbb; + +import org.openo.baseservice.encrypt.cbb.impl.AesCipherFactory; +import org.openo.baseservice.encrypt.cbb.inf.AbstractCipher; +import org.openo.baseservice.encrypt.cbb.inf.AbstractCipherFactory; + +/** + * Helps create cipher instances from factory.
+ *

+ * Creates the cipher instances using cipher factory. By default it uses AesCipherFactory. + * Can be changed through spring. + *

+ * + * @author + * @version 08-Jun-2016 + */ +public final class CipherCreator { + + private static CipherCreator instance = new CipherCreator(); + + private AbstractCipherFactory factory = new AesCipherFactory(); + + /** + * Constructor
+ *

+ * private + *

+ * + * @since + */ + private CipherCreator() { + + } + + /** + * Singleton instance. + *
+ * + * @return + * @since + */ + public static CipherCreator instance() { + return instance; + } + + /** + * Creates cipher with default key. + *
+ * + * @return cipher instance with default key. + * @since + */ + public AbstractCipher create() { + return factory.createCipherManager(); + } + + /** + * Creates cipher instance with a key. + *
+ * + * @param key the key to be used for encryption and decryption. + * @return cipher instance with specified key. + * @since + */ + public AbstractCipher create(final String key) { + return factory.createCipherManager(key); + } + + /** + * Sets the cipher factory instance. + *
+ * + * @param factory cipher factory. + * @since + */ + public void setFactory(final AbstractCipherFactory factory) { + this.factory = factory; + } + +} diff --git a/wso2/common-util/src/main/java/org/openo/baseservice/encrypt/cbb/impl/AesCipher.java b/wso2/common-util/src/main/java/org/openo/baseservice/encrypt/cbb/impl/AesCipher.java new file mode 100644 index 0000000..f117269 --- /dev/null +++ b/wso2/common-util/src/main/java/org/openo/baseservice/encrypt/cbb/impl/AesCipher.java @@ -0,0 +1,132 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.baseservice.encrypt.cbb.impl; + +import java.security.NoSuchAlgorithmException; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.KeySpec; + +import javax.crypto.Cipher; +import javax.crypto.SecretKey; +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.PBEKeySpec; +import javax.crypto.spec.SecretKeySpec; +import javax.xml.bind.DatatypeConverter; + +import org.openo.baseservice.encrypt.cbb.inf.AbstractCipher; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * CipherManager implement
+ *

+ *

+ * + * @author + * @version 31-May-2016 + */ +public class AesCipher implements AbstractCipher { + + private static final Logger LOG = LoggerFactory.getLogger(AesCipher.class); + + private static final byte[] DEFAULT_IV = {2, 1, 4, 8, 0, 3, 2, 0, 7, 9, 2, 8, 5, 11, 6, 1}; + + private static final IvParameterSpec IV_PARAMETER_SPEC = new IvParameterSpec(DEFAULT_IV); + + protected final SecretKey secretKey; + + /** + * Constructor
+ *

+ * Creates default key. + *

+ * + * @since + */ + public AesCipher() { + super(); + secretKey = createSecretKey("default"); + } + + /** + * + * Constructor
+ *

+ *

+ * Creates key. + * @param key + * @since + */ + public AesCipher(final String key) { + super(); + secretKey = createSecretKey(key); + } + + private SecretKey createSecretKey(final String key) { + SecretKey secretKey = null; + try { + final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); + final KeySpec keySpec = new PBEKeySpec(key.toCharArray(), DEFAULT_IV, 30000, 128); + + secretKey = keyFactory.generateSecret(keySpec); + return new SecretKeySpec(secretKey.getEncoded(), "AES"); + } catch(InvalidKeySpecException e) { + LOG.error("Invalid KeySpec ", e); + } catch(NoSuchAlgorithmException e) { + LOG.error("Algorithm do not support: ", e); + } + return null; + } + + @Override + public String encrypt(final String plain) { + try { + final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); + cipher.init(Cipher.ENCRYPT_MODE, secretKey, IV_PARAMETER_SPEC); + final byte[] encryptToBytes = cipher.doFinal(plain.getBytes()); + return DatatypeConverter.printBase64Binary(encryptToBytes); + } catch(final Exception e) { + LOG.error("Encrypt the plain error:", e); + return null; + } + } + + @Override + public String decrypt(final String encrypted) { + + if(encrypted == null || encrypted.length() == 0) { + return null; + } + + if(secretKey == null) { + return null; + } + + try { + final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); + cipher.init(Cipher.DECRYPT_MODE, secretKey, IV_PARAMETER_SPEC); + final byte[] tempBytes = DatatypeConverter.parseBase64Binary(encrypted); + final byte[] decrypTobytes = cipher.doFinal(tempBytes); + return new String(decrypTobytes); + } catch(final Exception e) { + LOG.error("decrypt the plain error:", e); + return null; + } + } + +} diff --git a/wso2/common-util/src/main/java/org/openo/baseservice/encrypt/cbb/impl/AesCipherFactory.java b/wso2/common-util/src/main/java/org/openo/baseservice/encrypt/cbb/impl/AesCipherFactory.java new file mode 100644 index 0000000..95e7336 --- /dev/null +++ b/wso2/common-util/src/main/java/org/openo/baseservice/encrypt/cbb/impl/AesCipherFactory.java @@ -0,0 +1,54 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.baseservice.encrypt.cbb.impl; + +import org.openo.baseservice.encrypt.cbb.inf.AbstractCipher; +import org.openo.baseservice.encrypt.cbb.inf.AbstractCipherFactory; + +/** + * Factory class to create CipherManager instances.
+ *

+ *

+ * + * @author + * @version 03-Jun-2016 + */ +public class AesCipherFactory implements AbstractCipherFactory { + + /** + * Creates new CipherManager instance.
+ * + * @return new cipher manager instance. + * @since + */ + @Override + public AbstractCipher createCipherManager() { + return new AesCipher(); + } + + /** + * Creates new CipherManager instance.
+ * + * @param key new cipher manager instance. + * @return + * @since + */ + @Override + public AbstractCipher createCipherManager(final String key) { + return new AesCipher(key); + } + +} diff --git a/wso2/common-util/src/main/java/org/openo/baseservice/encrypt/cbb/inf/AbstractCipher.java b/wso2/common-util/src/main/java/org/openo/baseservice/encrypt/cbb/inf/AbstractCipher.java new file mode 100644 index 0000000..608dd82 --- /dev/null +++ b/wso2/common-util/src/main/java/org/openo/baseservice/encrypt/cbb/inf/AbstractCipher.java @@ -0,0 +1,50 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.baseservice.encrypt.cbb.inf; + +/** + * Cipher Manager, provides the encrypt/decrypt interface + *
+ *

+ * It provides bi-directional encryption api. + *

+ * + * @author + * @version 31-May-2016 + */ +public interface AbstractCipher { + + /** + * Encrypt a string. + *
+ * + * @param plain string to be encrypted. + * @return encrypted string. + * @since + */ + String encrypt(String plain); + + /** + * Decrypt a string. + *
+ * + * @param encrypted String is encrypted by AES 128 + * @return plain after decrypt + * @since + */ + String decrypt(String encrypted); + +} diff --git a/wso2/common-util/src/main/java/org/openo/baseservice/encrypt/cbb/inf/AbstractCipherFactory.java b/wso2/common-util/src/main/java/org/openo/baseservice/encrypt/cbb/inf/AbstractCipherFactory.java new file mode 100644 index 0000000..e820250 --- /dev/null +++ b/wso2/common-util/src/main/java/org/openo/baseservice/encrypt/cbb/inf/AbstractCipherFactory.java @@ -0,0 +1,45 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.baseservice.encrypt.cbb.inf; + +/** + * Factory class to create CipherManager instances.
+ *

+ *

+ * + * @author + * @version 03-Jun-2016 + */ +public interface AbstractCipherFactory { + + /** + * Creates new CipherManager instance.
+ * + * @return new cipher manager instance. + * @since + */ + AbstractCipher createCipherManager(); + + /** + * Creates new CipherManager instance.
+ * + * @param key new cipher manager instance. + * @return + * @since + */ + AbstractCipher createCipherManager(final String key); + +} diff --git a/wso2/common-util/src/main/java/org/openo/baseservice/encrypt/cbb/sha/Sha256.java b/wso2/common-util/src/main/java/org/openo/baseservice/encrypt/cbb/sha/Sha256.java new file mode 100644 index 0000000..bbead3e --- /dev/null +++ b/wso2/common-util/src/main/java/org/openo/baseservice/encrypt/cbb/sha/Sha256.java @@ -0,0 +1,110 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.baseservice.encrypt.cbb.sha; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.nio.charset.StandardCharsets; +import java.security.InvalidKeyException; +import java.security.Key; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import javax.xml.bind.DatatypeConverter; + +/** + * Utility to generate SHA256 digest and HMAC.
+ *

+ *

+ * + * @author + * @version 03-Jun-2016 + */ +public final class Sha256 { + + private static final Logger LOGGER = LoggerFactory.getLogger(Sha256.class); + + private Sha256() { + + } + + /** + * Generates SHA256 digest.
+ * + * @param data: The data to be digested. + * @return Hex encoded digested data. + * @since + */ + public static String digest(final String data) { + final byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8); + MessageDigest md = null; + try { + md = MessageDigest.getInstance("SHA-256"); + } catch(final NoSuchAlgorithmException e) { + LOGGER.error("No SHA-256 support ", e); + return ""; + } + final byte[] digest = md.digest(dataBytes); + return DatatypeConverter.printHexBinary(digest); + } + + /** + * Generates hmac signature using data and key.
+ * + * @param data: The data to be signed. + * @param key: The signing key. + * @return Hex encoded HMAC signature. + * @throws InvalidKeyException if the key is invalid. + * @since + */ + public static String mac(final String data, final Key key) throws InvalidKeyException { + final byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8); + Mac mac = null; + try { + mac = Mac.getInstance("HmacSHA256"); + mac.init(key); + } catch(final NoSuchAlgorithmException e) { + LOGGER.error("SHA mac not supported", e); + return ""; + } + final byte[] digest = mac.doFinal(dataBytes); + return DatatypeConverter.printHexBinary(digest); + + } + + /** + * Generates hmac with data and secret. + *
+ * + * @param data: The data to be signed. + * @param secret: The signing key. + * @return Hex encoded HMAC signature. + * @since + */ + public static String mac(final String data, final byte[] secret) { + final Key key = new SecretKeySpec(secret, "HmacSHA256"); + try { + return mac(data, key); + } catch(final InvalidKeyException e) { + LOGGER.error("Invalid key: ", e); + return ""; + } + } + +} diff --git a/wso2/common-util/src/main/java/org/openo/baseservice/util/RestUtils.java b/wso2/common-util/src/main/java/org/openo/baseservice/util/RestUtils.java new file mode 100644 index 0000000..2661d69 --- /dev/null +++ b/wso2/common-util/src/main/java/org/openo/baseservice/util/RestUtils.java @@ -0,0 +1,82 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.baseservice.util; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; + +import javax.servlet.http.HttpServletRequest; + +/** + * Utility functions for ROA.
+ *

+ *

+ * + * @author + * @version 31-May-2016 + */ +public final class RestUtils { + + private static final Logger LOGGER = LoggerFactory.getLogger(RestUtils.class); + + private RestUtils() { + + } + + /** + * To get body from http request
+ * + * @param request : request object. + * @return Request body as string. + * @since + */ + public static String getRequestBody(final HttpServletRequest request) { + String body = null; + final StringBuilder stringBuilder = new StringBuilder(); + BufferedReader bufferedReader = null; + + try { + final InputStream inputStream = request.getInputStream(); + if(inputStream != null) { + bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); + final char[] charBuffer = new char[128]; + int bytesRead = -1; + while((bytesRead = bufferedReader.read(charBuffer)) > 0) { + stringBuilder.append(charBuffer, 0, bytesRead); + } + } + } catch(final IOException ex) { + LOGGER.error("read inputStream buffer catch exception:", ex); + } finally { + if(bufferedReader != null) { + try { + bufferedReader.close(); + } catch(final IOException ex) { + LOGGER.error("close buffer catch exception:", ex); + } + } + } + + body = stringBuilder.toString(); + return body; + } + +} diff --git a/wso2/common-util/src/main/java/org/openo/baseservice/util/impl/SystemEnvVariablesDefImpl.java b/wso2/common-util/src/main/java/org/openo/baseservice/util/impl/SystemEnvVariablesDefImpl.java new file mode 100644 index 0000000..0ac707b --- /dev/null +++ b/wso2/common-util/src/main/java/org/openo/baseservice/util/impl/SystemEnvVariablesDefImpl.java @@ -0,0 +1,68 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.baseservice.util.impl; + +import org.openo.baseservice.util.inf.SystemEnvVariables; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.IOException; + +/** + * System environment variable helper implementation.
+ *

+ *

+ * + * @author + * @version 24-Jun-2016 + */ +public class SystemEnvVariablesDefImpl implements SystemEnvVariables { + + private static final Logger LOG = LoggerFactory.getLogger(SystemEnvVariablesDefImpl.class); + + @Override + public String getAppRoot() { + String appRoot = null; + appRoot = System.getProperty("catalina.base"); + if(appRoot != null) { + appRoot = getCanonicalPath(appRoot); + } + return appRoot; + } + + /** + * Gets the canonical path
+ * + * @param inPath input path + * @return the canonical path. + * @since + */ + private String getCanonicalPath(final String inPath) { + String path = null; + try { + if(inPath != null) { + final File file = new File(inPath); + path = file.getCanonicalPath(); + } + } catch(final IOException e) { + LOG.error("file.getCanonicalPath() IOException:", e); + } + return path; + } + +} diff --git a/wso2/common-util/src/main/java/org/openo/baseservice/util/impl/SystemEnvVariablesFactory.java b/wso2/common-util/src/main/java/org/openo/baseservice/util/impl/SystemEnvVariablesFactory.java new file mode 100644 index 0000000..e75c997 --- /dev/null +++ b/wso2/common-util/src/main/java/org/openo/baseservice/util/impl/SystemEnvVariablesFactory.java @@ -0,0 +1,55 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.baseservice.util.impl; + +import org.openo.baseservice.util.inf.SystemEnvVariables; + +/** + * SystemEnvVariables factory class + *
+ *

+ *

+ * + * @author + * @version + */ +public class SystemEnvVariablesFactory { + + private static SystemEnvVariables systemEnvVariablesInstance = new SystemEnvVariablesDefImpl(); + + /** + * + * Constructor
+ *

+ *

+ * + * @since + */ + private SystemEnvVariablesFactory() { + + } + /** + * get the SystemEnvVariables instance + *
+ * + * @return SystemEnvVariables instance + * @since + */ + public static SystemEnvVariables getInstance() { + return systemEnvVariablesInstance; + } +} diff --git a/wso2/common-util/src/main/java/org/openo/baseservice/util/inf/SystemEnvVariables.java b/wso2/common-util/src/main/java/org/openo/baseservice/util/inf/SystemEnvVariables.java new file mode 100644 index 0000000..cf0c182 --- /dev/null +++ b/wso2/common-util/src/main/java/org/openo/baseservice/util/inf/SystemEnvVariables.java @@ -0,0 +1,35 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.baseservice.util.inf; + +/** + * Dependency the system env
+ *

+ *

+ * + * @author + * @version 31-May-2016 + */ +public interface SystemEnvVariables { + + /** + * Get application root path
+ * + * @return application root path. + * @since + */ + String getAppRoot(); +} diff --git a/wso2/common-util/src/test/java/org/openo/baseservice/bus/util/TestRegisterService.java b/wso2/common-util/src/test/java/org/openo/baseservice/bus/util/TestRegisterService.java new file mode 100644 index 0000000..88f5ddd --- /dev/null +++ b/wso2/common-util/src/test/java/org/openo/baseservice/bus/util/TestRegisterService.java @@ -0,0 +1,66 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.baseservice.bus.util; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; + +import javax.ws.rs.core.Response; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.openo.baseservice.util.impl.SystemEnvVariablesDefImpl; + +import junit.framework.Assert; +import mockit.Mock; +import mockit.MockUp; + +public class TestRegisterService { + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + + } + + @Test + public void testregisterServce() throws IOException { + + File file = new File(""); + Response res = null; + + final String path = file.getAbsolutePath(); + + new MockUp() { + @Mock + public String getAppRoot() { + return path; + } + }; + + try { + res = RegisterService.registerService(path, true); + } catch(Exception e) { + Assert.assertNotNull(e); + } + + } +} + diff --git a/wso2/common-util/src/test/java/org/openo/baseservice/bus/util/TestRegisterServiceListener.java b/wso2/common-util/src/test/java/org/openo/baseservice/bus/util/TestRegisterServiceListener.java new file mode 100644 index 0000000..429d986 --- /dev/null +++ b/wso2/common-util/src/test/java/org/openo/baseservice/bus/util/TestRegisterServiceListener.java @@ -0,0 +1,60 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.baseservice.bus.util; + +import java.io.File; + +import javax.servlet.ServletContextEvent; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import mockit.Mock; +import mockit.MockUp; + +public class TestRegisterServiceListener { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + + } + + @Test + public void testRegisterServiceListener() { + + RegisterServiceListener impl = new RegisterServiceListener(); + + ServletContextEvent sce = null; + + new MockUp() { + @Mock + public File[] listFiles() { + File file = new File(""); + File[] filelist = new File[]{file}; + return filelist; + } + + }; + + impl.contextInitialized(sce); + } + +} diff --git a/wso2/common-util/src/test/java/org/openo/baseservice/encrypt/cbb/impl/AesCipherTest.java b/wso2/common-util/src/test/java/org/openo/baseservice/encrypt/cbb/impl/AesCipherTest.java new file mode 100644 index 0000000..c66e36a --- /dev/null +++ b/wso2/common-util/src/test/java/org/openo/baseservice/encrypt/cbb/impl/AesCipherTest.java @@ -0,0 +1,210 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.baseservice.encrypt.cbb.impl; + +import java.security.NoSuchAlgorithmException; +import java.security.spec.InvalidKeySpecException; + +import javax.crypto.Cipher; +import javax.crypto.SecretKeyFactory; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.openo.baseservice.encrypt.cbb.CipherCreator; +import org.openo.baseservice.encrypt.cbb.inf.AbstractCipher; + +import junit.framework.Assert; +import mockit.Mocked; +import mockit.NonStrictExpectations; + +/** + *
+ *

+ *

+ * + * @author + * @version 02-Jun-2016 + */ +public class AesCipherTest { + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception { + CipherCreator.instance().setFactory(new AesCipherFactory()); + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @Before + public void setUp() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @After + public void tearDown() throws Exception { + } + + /** + * Test method for + * {@link org.openo.baseservice.encrypt.cbb.impl.AesCipher#encrypt(java.lang.String)}. + */ + @Test + public void testEncrypt() { + final AbstractCipher cipherManager = CipherCreator.instance().create(); + final String encrypted = cipherManager.encrypt("test-encrypt"); + final String decrypted = cipherManager.decrypt(encrypted); + + Assert.assertEquals("test-encrypt", decrypted); + } + + @Test + public void testEncryptException() throws Exception { + new NonStrictExpectations() { + + @Mocked + Cipher cipher; + + { + cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); + result = new InvalidKeySpecException(); + } + }; + final AbstractCipher cipherManager = CipherCreator.instance().create(); + final String encrypted = cipherManager.encrypt("test-encrypt"); + + Assert.assertEquals(null, encrypted); + } + + /** + * Test method for + * {@link org.openo.baseservice.encrypt.cbb.impl.AesCipher#decrypt(java.lang.String)}. + */ + @Test + public void testDecrypt() { + final AbstractCipher cipherManager = CipherCreator.instance().create(); + final String encrypted = cipherManager.encrypt("test-encrypt"); + final String decrypted = cipherManager.decrypt(encrypted); + + Assert.assertEquals("test-encrypt", decrypted); + } + + @Test + public void testDecryptNull() { + final AbstractCipher cipherManager = CipherCreator.instance().create(); + String decrypted = cipherManager.decrypt(null); + Assert.assertEquals(null, decrypted); + + decrypted = cipherManager.decrypt(""); + + Assert.assertEquals(null, decrypted); + } + + /** + * Test method for + * {@link + * org.openo.baseservice.encrypt.cbb.impl.AesCipher#CipherManagerImpl(java.lang.String)} + * . + */ + @Test + public void testCipherManagerImplString() { + final AbstractCipher cipherManager = CipherCreator.instance().create("secret-key"); + final String encrypted = cipherManager.encrypt("test-encrypt"); + final String decrypted = cipherManager.decrypt(encrypted); + + Assert.assertEquals("test-encrypt", decrypted); + } + + /** + *
+ * + * @since + */ + @Test + public void testCipherManagerImplStringDiffKey() { + final String encrypted = CipherCreator.instance().create("secret-key").encrypt("test-encrypt"); + final String decrypted = CipherCreator.instance().create("wrong-key").decrypt(encrypted); + + Assert.assertNotSame("test-encrypt", decrypted); + + final String decrypt = CipherCreator.instance().create("secret-key").decrypt(encrypted); + Assert.assertEquals("test-encrypt", decrypt); + } + + @Test + public void testCreateSecretKeyNoSuchAlgorithmException() throws Exception { + new NonStrictExpectations() { + + @Mocked + SecretKeyFactory keyFactory; + + { + keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); + result = new NoSuchAlgorithmException(); + } + }; + + final AbstractCipher cipherManager = CipherCreator.instance().create("secret-key"); + final String encrypted = cipherManager.encrypt("test-encrypt"); + Assert.assertEquals(encrypted, null); + + } + + @Test + public void testCreateSecretKeyInvalidKeySpecException() throws Exception { + new NonStrictExpectations() { + + @Mocked + SecretKeyFactory keyFactory; + + { + keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); + result = new InvalidKeySpecException(); + } + }; + + final AbstractCipher cipherManager = CipherCreator.instance().create("secret-key"); + final String decrypted = cipherManager.decrypt("test-encrypt"); + Assert.assertEquals(decrypted, null); + + } +} diff --git a/wso2/common-util/src/test/java/org/openo/baseservice/encrypt/cbb/sha/Sha256Test.java b/wso2/common-util/src/test/java/org/openo/baseservice/encrypt/cbb/sha/Sha256Test.java new file mode 100644 index 0000000..f7eaf23 --- /dev/null +++ b/wso2/common-util/src/test/java/org/openo/baseservice/encrypt/cbb/sha/Sha256Test.java @@ -0,0 +1,193 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.baseservice.encrypt.cbb.sha; + +import static org.junit.Assert.fail; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; + +import java.security.InvalidKeyException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; + +import mockit.Mocked; +import mockit.NonStrictExpectations; +import mockit.integration.junit4.JMockit; + +/** + *
+ *

+ *

+ * + * @author + * @version 03-Jun-2016 + */ +@RunWith(JMockit.class) +public class Sha256Test { + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @Before + public void setUp() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @After + public void tearDown() throws Exception { + } + + /** + * Test method for {@link org.openo.baseservice.encrypt.cbb.sha.Sha256#digest(java.lang.String)} + * . + */ + @Test + public void testDigest() { + String plain = ""; + String expected = "E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855"; + Assert.assertEquals(expected, Sha256.digest(plain)); + + expected = "D7A8FBB307D7809469CA9ABCB0082E4F8D5651E46D3CDB762D02D0BF37C9E592"; + plain = "The quick brown fox jumps over the lazy dog"; + Assert.assertEquals(expected, Sha256.digest(plain)); + } + + @Test + public void testDigestException() throws Exception { + new NonStrictExpectations() { + + @Mocked + MessageDigest md; + + { + md = MessageDigest.getInstance("SHA-256"); + result = new NoSuchAlgorithmException(); + } + }; + final String plain = ""; + final String expected = ""; + Assert.assertEquals(expected, Sha256.digest(plain)); + + } + + /** + * Test method for + * {@link org.openo.baseservice.encrypt.cbb.sha.Sha256#mac(java.lang.String, java.security.Key)} + * . + * + * @throws InvalidKeyException + */ + @Test + public void testMacStringKey() { + final String expected = "F7BC83F430538424B13298E6AA6FB143EF4D59A14946175997479DBC2D1A3CD8"; + final String plain = "The quick brown fox jumps over the lazy dog"; + try { + Assert.assertEquals(expected, Sha256.mac(plain, new SecretKeySpec("key".getBytes(), "HmacSHA256"))); + } catch(final InvalidKeyException e) { + e.printStackTrace(); + fail("testMacStringKey failed" + e.getMessage()); + } + try { + Assert.assertEquals(expected, Sha256.mac(plain, new SecretKeySpec("key".getBytes(), "AES"))); + } catch(final InvalidKeyException e) { + e.printStackTrace(); + fail("testMacStringKey failed" + e.getMessage()); + } + + } + + @Test + public void testMacStringKeyException() throws Exception { + new NonStrictExpectations() { + + @Mocked + Mac mac; + + { + mac = Mac.getInstance("HmacSHA256"); + result = new NoSuchAlgorithmException(); + } + }; + Sha256.mac("dummy", new SecretKeySpec("key".getBytes(), "AES")); + } + + /** + * Test method for + * {@link org.openo.baseservice.encrypt.cbb.sha.Sha256#mac(java.lang.String, byte[])}. + */ + @Test + public void testMacStringByteArray() { + final String expected = "F7BC83F430538424B13298E6AA6FB143EF4D59A14946175997479DBC2D1A3CD8"; + final String plain = "The quick brown fox jumps over the lazy dog"; + Assert.assertEquals(expected, Sha256.mac(plain, "key".getBytes())); + } + + @Test + public void testMacStringByteArrayInvalidKeyException() throws Exception { + final String key = "key"; + new NonStrictExpectations() { + + @Mocked + Mac mac; + + { + mac = Mac.getInstance("HmacSHA256"); + result = new InvalidKeyException(); + } + }; + final String expected = ""; + final String plain = "The quick brown fox jumps over the lazy dog"; + Assert.assertEquals(expected, Sha256.mac(plain, key.getBytes())); + } + +} diff --git a/wso2/common-util/src/test/java/org/openo/baseservice/util/RestUtilsTest.java b/wso2/common-util/src/test/java/org/openo/baseservice/util/RestUtilsTest.java new file mode 100644 index 0000000..56b6eee --- /dev/null +++ b/wso2/common-util/src/test/java/org/openo/baseservice/util/RestUtilsTest.java @@ -0,0 +1,190 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.baseservice.util; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; + +import java.io.ByteArrayInputStream; +import java.io.IOException; + +import javax.servlet.ServletInputStream; +import javax.servlet.http.HttpServletRequest; + +import junit.framework.Assert; +import mockit.Expectations; +import mockit.Mocked; +import mockit.integration.junit4.JMockit; + +/** + *
+ *

+ *

+ * + * @author + * @version 08-Jun-2016 + */ +@RunWith(JMockit.class) +public class RestUtilsTest { + + @Mocked + HttpServletRequest mockHttpServletRequest; + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @Before + public void setUp() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @After + public void tearDown() throws Exception { + } + + /** + * Test method for + * {@link org.openo.baseservice.util.RestUtils#getRequestBody(javax.servlet.http.HttpServletRequest)} + * . + * + * @throws IOException + */ + @Test + public void testGetRequestBody() throws IOException { + final String dummy = "this is a dummy data to test request body"; + final ServletInputStream inputStream = new ServletInputStream() { + + final ByteArrayInputStream stream = new ByteArrayInputStream(dummy.getBytes()); + + @Override + public int read() throws IOException { + return stream.read(); + } + + }; + + new Expectations() { + + { + mockHttpServletRequest.getInputStream(); + returns(inputStream); + } + }; + final String body = RestUtils.getRequestBody(mockHttpServletRequest); + + Assert.assertEquals(dummy, body); + } + + @Test + public void testGetRequestBodyNull() throws IOException { + final ServletInputStream inputStream = null; + new Expectations() { + + { + mockHttpServletRequest.getInputStream(); + returns(inputStream); + } + }; + final String body = RestUtils.getRequestBody(mockHttpServletRequest); + + Assert.assertEquals("", body); + } + + @Test + public void testGetRequestBodyIOException() throws IOException { + final ServletInputStream inputStream = new ServletInputStream() { + + @Override + public int read() throws IOException { + throw new IOException(); + } + + }; + + new Expectations() { + + { + mockHttpServletRequest.getInputStream(); + returns(inputStream); + } + }; + final String body = RestUtils.getRequestBody(mockHttpServletRequest); + + Assert.assertEquals("", body); + } + + @Test + public void testGetRequestBodyCloseIOException() throws IOException { + final ServletInputStream inputStream = new ServletInputStream() { + + final ByteArrayInputStream stream = new ByteArrayInputStream("dummy".getBytes()); + + @Override + public int read() throws IOException { + return stream.read(); + } + + @Override + public void close() throws IOException { + throw new IOException(); + } + }; + + new Expectations() { + + { + mockHttpServletRequest.getInputStream(); + returns(inputStream); + } + }; + final String body = RestUtils.getRequestBody(mockHttpServletRequest); + + Assert.assertEquals("dummy", body); + } + +} diff --git a/wso2/common-util/src/test/java/org/openo/baseservice/util/impl/SystemEnvVariablesDefImplTest.java b/wso2/common-util/src/test/java/org/openo/baseservice/util/impl/SystemEnvVariablesDefImplTest.java new file mode 100644 index 0000000..83414a2 --- /dev/null +++ b/wso2/common-util/src/test/java/org/openo/baseservice/util/impl/SystemEnvVariablesDefImplTest.java @@ -0,0 +1,113 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.baseservice.util.impl; + +import java.io.File; +import java.io.IOException; + +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.openo.baseservice.util.inf.SystemEnvVariables; + +import junit.framework.Assert; +import mockit.Mocked; +import mockit.NonStrictExpectations; +import mockit.integration.junit4.JMockit; +import net.jcip.annotations.NotThreadSafe; + +/** + *
+ *

+ *

+ * + * @author + * @version 08-Jun-2016 + */ +@RunWith(JMockit.class) +@NotThreadSafe +public class SystemEnvVariablesDefImplTest { + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @Before + public void setUp() throws Exception { + } + + @Test + public void testGetAppRootException() throws Exception { + new NonStrictExpectations() { + + @Mocked + File file; + + { + file = new File("."); + file.getCanonicalPath(); + result = new IOException(); + } + + }; + final SystemEnvVariables envVars =new SystemEnvVariablesDefImpl(); + System.setProperty("catalina.base", "."); + final String actual = envVars.getAppRoot(); + Assert.assertEquals(null, actual); + } + + + /** + * Test method for + * {@link org.openo.baseservice.util.impl.SystemEnvVariablesDefImpl#getAppRoot()}. + * + * @throws Exception + */ + @Test + public void testGetAppRoot() throws Exception { + final SystemEnvVariables envVars = new SystemEnvVariablesDefImpl(); + final File file = new File("."); + final String expected = file.getCanonicalPath(); + System.setProperty("catalina.base", "."); + final String actual = envVars.getAppRoot(); + Assert.assertEquals(expected, actual); + } + +} diff --git a/wso2/dropwizard-ioc-container/pom.xml b/wso2/dropwizard-ioc-container/pom.xml new file mode 100644 index 0000000..6223c7f --- /dev/null +++ b/wso2/dropwizard-ioc-container/pom.xml @@ -0,0 +1,80 @@ + + + + 4.0.0 + + org.openo.common-services.common-utilities + common-setting + 1.1.0-SNAPSHOT + + dropwizard-ioc-container + common-services-common-utilities/dropwizard-ioc-container + + + + + + io.dropwizard + dropwizard-core + 0.8.0 + provided + + + + org.reflections + reflections + 0.9.10 + + + com.google.guava + guava + + + + + junit + junit + test + 4.8.2 + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + always + -XX:-UseSplitVerifier + ${maven.test.skip} + ${maven.test.failure.ignore} + + ${excludesFile} + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5 + + 1.8 + 1.8 + 1.8 + 1.8 + + + + + + + diff --git a/wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/annotation/BaseService.java b/wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/annotation/BaseService.java new file mode 100644 index 0000000..ac0bb47 --- /dev/null +++ b/wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/annotation/BaseService.java @@ -0,0 +1,34 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.dropwizard.ioc.annotation; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * basic services for identification + * @author hu.rui + * + */ +@Target({ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface BaseService { + +} diff --git a/wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/annotation/Lazy.java b/wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/annotation/Lazy.java new file mode 100644 index 0000000..40ce5af --- /dev/null +++ b/wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/annotation/Lazy.java @@ -0,0 +1,34 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.dropwizard.ioc.annotation; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * lazy loading of related services + * @author hu.rui + * + */ +@Target({ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface Lazy { + +} diff --git a/wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/annotation/PostBaseService.java b/wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/annotation/PostBaseService.java new file mode 100644 index 0000000..a1a6d77 --- /dev/null +++ b/wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/annotation/PostBaseService.java @@ -0,0 +1,34 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.dropwizard.ioc.annotation; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * load on after basic services + * @author hu.rui + * + */ +@Target({ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface PostBaseService { + +} diff --git a/wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/annotation/PreBaseService.java b/wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/annotation/PreBaseService.java new file mode 100644 index 0000000..f579b9e --- /dev/null +++ b/wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/annotation/PreBaseService.java @@ -0,0 +1,34 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.dropwizard.ioc.annotation; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * prior to basic service loading + * @author hu.rui + * + */ +@Target({ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface PreBaseService { + +} diff --git a/wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/annotation/PreLoad.java b/wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/annotation/PreLoad.java new file mode 100644 index 0000000..3131e8b --- /dev/null +++ b/wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/annotation/PreLoad.java @@ -0,0 +1,34 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.dropwizard.ioc.annotation; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * load before general service + * @author hu.rui + * + */ +@Target({ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface PreLoad { + +} diff --git a/wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/annotation/PreServiceLoad.java b/wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/annotation/PreServiceLoad.java new file mode 100644 index 0000000..e0e3043 --- /dev/null +++ b/wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/annotation/PreServiceLoad.java @@ -0,0 +1,35 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.dropwizard.ioc.annotation; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * + * load before general service,after PreLoad + * @author hu.rui + * + */ +@Target({ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface PreServiceLoad { + +} diff --git a/wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/bundle/AutoConfigBundle.java b/wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/bundle/AutoConfigBundle.java new file mode 100644 index 0000000..4cb4008 --- /dev/null +++ b/wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/bundle/AutoConfigBundle.java @@ -0,0 +1,430 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.dropwizard.ioc.bundle; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Field; +import java.util.Arrays; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +import javax.ws.rs.Path; +import javax.ws.rs.ext.Provider; + +import org.eclipse.jetty.util.component.LifeCycle; +import org.glassfish.hk2.api.ServiceLocator; +import org.glassfish.hk2.api.ServiceLocatorFactory; +import org.glassfish.hk2.utilities.ServiceLocatorUtilities; +import org.glassfish.hk2.utilities.binding.AbstractBinder; +import org.glassfish.jersey.servlet.ServletProperties; +import org.jvnet.hk2.annotations.Service; +import org.openo.dropwizard.ioc.annotation.BaseService; +import org.openo.dropwizard.ioc.annotation.Lazy; +import org.openo.dropwizard.ioc.annotation.PostBaseService; +import org.openo.dropwizard.ioc.annotation.PreBaseService; +import org.openo.dropwizard.ioc.annotation.PreLoad; +import org.openo.dropwizard.ioc.annotation.PreServiceLoad; +import org.openo.dropwizard.ioc.utils.ServiceBinder; +import org.openo.dropwizard.ioc.utils.ServiceLocatorHolder; +import org.reflections.Reflections; +import org.reflections.scanners.SubTypesScanner; +import org.reflections.scanners.TypeAnnotationsScanner; +import org.reflections.util.ClasspathHelper; +import org.reflections.util.ConfigurationBuilder; +import org.reflections.util.FilterBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.codahale.metrics.health.HealthCheck; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.collect.Lists; + +import io.dropwizard.Configuration; +import io.dropwizard.ConfiguredBundle; +import io.dropwizard.configuration.ConfigurationSourceProvider; +import io.dropwizard.lifecycle.Managed; +import io.dropwizard.lifecycle.ServerLifecycleListener; +import io.dropwizard.servlets.tasks.Task; +import io.dropwizard.setup.Bootstrap; +import io.dropwizard.setup.Environment; + +/** + * complete the integration of hK2 container and dropwizard + * + * @author hu.rui + * + */ + +public class AutoConfigBundle implements ConfiguredBundle { + + private static final Logger LOG = LoggerFactory.getLogger(AutoConfigBundle.class); + + private ServiceLocator locator; + private Reflections reflections; + private Set> services; + + private Bootstrap bootstrap; + + + AutoConfigBundle(final String packageName) { + this(Lists.newArrayList(packageName)); + } + + AutoConfigBundle(List packageNames) { + FilterBuilder filterBuilder = new FilterBuilder(); + + packageNames.stream().forEach(packageName -> { + filterBuilder.include(FilterBuilder.prefix(packageName)); + }); + ConfigurationBuilder reflectionCfg = new ConfigurationBuilder(); + + packageNames.stream().forEach(packageName -> { + reflectionCfg.addUrls(ClasspathHelper.forPackage(packageName)); + }); + + reflectionCfg.filterInputsBy(filterBuilder).setScanners(new SubTypesScanner(), + new TypeAnnotationsScanner()); + reflections = new Reflections(reflectionCfg); + + locator = ServiceLocatorFactory.getInstance().create("dw-hk2"); + + ServiceLocatorHolder.setLocator(locator); + + } + + public static AutoConfigBundleBuider newBuilder() { + return new AutoConfigBundleBuider(); + } + + @Override + public void initialize(final Bootstrap bootstrap) { + + this.bootstrap = bootstrap; + registerPreLoadService(); + + LOG.debug("Intialzing auto config bundle."); + } + + private void registerPreLoadService() { + + registerService(PreLoad.class); + + } + + + @Override + public void run(final T configuration, final Environment environment) throws Exception { + + registerConfigurationProvider(configuration, environment); + + + registerEnvironment(environment); + registerObjectMapper(environment); + + environment.getApplicationContext().getServletContext() + .setAttribute(ServletProperties.SERVICE_LOCATOR, locator); + + registerService(PreBaseService.class); + registerService(BaseService.class); + registerService(PostBaseService.class); + this.registerService(PreServiceLoad.class); + + + registerServices(); + + // registerManaged(environment); + registerLifecycle(environment); + registerServerLifecycleListeners(environment); + registerJettyLifeCycleListener(environment); + registerTasks(environment); + registerHealthChecks(environment); + registerProviders(environment); + registerResources(environment); + + environment.lifecycle().manage(new ServiceLocatorManaged(locator)); + + } + + + + private void registerProviders(Environment environment) { + reflections.getSubTypesOf(Provider.class).stream().filter(services::contains) + .forEach(providerKlass -> { + try { + environment.jersey().register(locator.getService(providerKlass)); + } catch (Exception e) { + LOG.warn("", e); + } + + LOG.info("Registering Dropwizard Provider, class name : {}", providerKlass.getName()); + + }); + + } + + private void registerTasks(Environment environment) { + reflections.getSubTypesOf(Task.class).stream().filter(services::contains).forEach(taskKlass -> { + try { + environment.admin().addTask(locator.getService(taskKlass)); + } catch (Exception e) { + LOG.warn("", e); + } + LOG.info("Registering Dropwizard Task, class name : {}", taskKlass.getName()); + }); + + } + + private void registerJettyLifeCycleListener(Environment environment) { + reflections.getSubTypesOf(LifeCycle.Listener.class).stream().filter(services::contains) + .forEach(lifecycleListenerKlass -> { + + try { + environment.lifecycle() + .addLifeCycleListener(locator.getService(lifecycleListenerKlass)); + } catch (Exception e) { + LOG.warn("", e); + } + LOG.info("Registering Dropwizard lifecycleListener, class name : {}", + lifecycleListenerKlass.getName()); + }); + + } + + private void registerServerLifecycleListeners(Environment environment) { + + reflections.getSubTypesOf(ServerLifecycleListener.class).stream().filter(services::contains) + .forEach(serverLifecycleListenerKlass -> { + try { + environment.lifecycle() + .addServerLifecycleListener(locator.getService(serverLifecycleListenerKlass)); + } catch (Exception e) { + LOG.warn("", e); + } + LOG.info("Registering Dropwizard serverLifecycleListener, class name : {}", + serverLifecycleListenerKlass.getName()); + }); + + } + + private void registerLifecycle(Environment environment) { + reflections.getSubTypesOf(LifeCycle.class).stream().filter(services::contains) + .forEach(lifeCycleKlass -> { + try { + environment.lifecycle().manage(locator.getService(lifeCycleKlass)); + } catch (Exception e) { + LOG.warn("", e); + } + LOG.info("Registering Dropwizard LifeCycle, class name : {}", lifeCycleKlass.getName()); + }); + } + + /* + * private void registerManaged(Environment environment) { + * + * reflections.getSubTypesOf(Managed.class).stream().filter(services::contains) + * .forEach(managedKlass -> { try { + * environment.lifecycle().manage(locator.getService(managedKlass)); } catch (Exception e) { + * LOG.warn("", e); } LOG.info("Registering Dropwizard managed, class name : {}", + * managedKlass.getName()); }); + * + * } + */ + + private void registerObjectMapper(Environment environment) { + + final ObjectMapper objectMapper = environment.getObjectMapper(); + + ServiceLocatorUtilities.bind(locator, new AbstractBinder() { + @Override + protected void configure() { + bind(objectMapper).to(ObjectMapper.class); + + LOG.info("Registering Dropwizard objectMapper, class name : {}", + objectMapper.getClass().getName()); + } + }); + + } + + private void registerEnvironment(final Environment environment) { + + ServiceLocatorUtilities.bind(locator, new AbstractBinder() { + @Override + protected void configure() { + bind(environment).to(Environment.class); + + LOG.info("Registering Dropwizard environment, class name : {}", + environment.getClass().getName()); + } + }); + + } + + private void registerConfigurationProvider(final T configuration, final Environment environment) { + + ServiceLocatorUtilities.bind(locator, new AbstractBinder() { + @Override + protected void configure() { + bind(configuration); + LOG.info("Registering Dropwizard Configuration class name:{}", + configuration.getClass().getName()); + if (configuration instanceof Configuration) { + bind((Configuration) configuration).to(Configuration.class); + LOG.info("Registering Dropwizard Configuration class name:{}", + Configuration.class.getName()); + } + + } + }); + + registerSubConfigure(configuration, environment); + + } + + private void registerSubConfigure(final T configuration, final Environment environment) { + final List subDeclaredFields = + Arrays.asList(configuration.getClass().getDeclaredFields()); + List parentDeclaredFields = Arrays.asList(Configuration.class.getDeclaredFields()); + + List filtersubDeclaredFields = subDeclaredFields.stream() + .filter(subDeclaredField -> !subDeclaredField.getType().isPrimitive()) + .filter(subDeclaredField -> !subDeclaredField.getType().equals(String.class)) + .filter(subDeclaredField -> !parentDeclaredFields.contains(subDeclaredField)) + .collect(Collectors.toList()); + + ServiceLocatorUtilities.bind(locator, new AbstractBinder() { + @Override + protected void configure() { + filtersubDeclaredFields.forEach(subField -> { + subField.setAccessible(true); + try { + Object subConfig = subField.get(configuration); + if (subConfig != null) { + bind(subConfig); + LOG.info("Registering Dropwizard Sub Configuration class name {}", + subConfig.getClass().getName()); + } + + } catch (Exception e) { + LOG.error("bind sub config:{} fail", subField); + } + }); + } + }); + + } + + private void registerServices() { + services = this.reflections.getTypesAnnotatedWith(Service.class, true); + if (!services.isEmpty()) { + ServiceLocatorUtilities.bind(locator, new ServiceBinder(services)); + + services.forEach(s -> { + LOG.info("Registering Dropwizard service, class name : {}", s.getName()); + }); + + services.stream().filter(serviceClazz -> (serviceClazz.getAnnotation(Lazy.class) == null)) + .peek(serviceClazz -> LOG.info("active service, class name : {}", serviceClazz.getName())) + .forEach(serviceClazz -> { + try { + long startTime = System.currentTimeMillis(); + locator.getService(serviceClazz); + LOG.info("active service, class name : {},cost time:{}", serviceClazz.getName(), + (System.currentTimeMillis() - startTime)); + } catch (Exception e) { + LOG.warn("", e); + } + + }); + + } else { + LOG.warn("Registering Dropwizard service is empty"); + + } + + } + + private void registerResources(final Environment environment) { + reflections.getTypesAnnotatedWith(Path.class).stream().forEach(resourceClass -> { + + LOG.info("begin Registering Dropwizard resource, class name : {}", resourceClass.getName()); + try { + Object resourceObject = locator.getService(resourceClass); + if (resourceObject != null) { + environment.jersey().register(resourceObject); + LOG.info("Registering Dropwizard resource, class name : {}", resourceClass.getName()); + } else { + LOG.warn(resourceClass.getName() + " not use Service annotation"); + } + } catch (Exception e) { + LOG.error("", e); + } + + + }); + } + + private void registerHealthChecks(final Environment env) { + + reflections.getSubTypesOf(HealthCheck.class).stream().filter(services::contains) + .forEach(healthCheckKlass -> { + try { + env.healthChecks().register(healthCheckKlass.getName(), + locator.getService(healthCheckKlass)); + } catch (Exception e) { + LOG.warn("", e); + } + LOG.info("Registering Dropwizard healthCheck, class name : {}", + healthCheckKlass.getName()); + }); + + } + + + + private void registerService(Class annotationClazz) { + + Set> services = this.reflections.getTypesAnnotatedWith(annotationClazz, true); + if (!services.isEmpty()) { + ServiceLocatorUtilities.bind(locator, new ServiceBinder(services)); + + services.forEach(s -> { + LOG.info("{} Registering service, class name : {}", annotationClazz.getName(), + s.getName()); + }); + + services.stream().filter(serviceClazz -> (serviceClazz.getAnnotation(Lazy.class) == null)) + .peek(serviceClazz -> LOG.info("active service, class name : {}", serviceClazz.getName())) + .forEach(serviceClazz -> { + try { + long startTime = System.currentTimeMillis(); + locator.getService(serviceClazz); + LOG.info("active service, class name : {},cost time:{}", serviceClazz.getName(), + (System.currentTimeMillis() - startTime)); + } catch (Exception e) { + LOG.warn("", e); + } + + }); + + } else { + LOG.warn("Registering {} service is empty", annotationClazz.getName()); + + } + + } +} diff --git a/wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/bundle/AutoConfigBundleBuider.java b/wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/bundle/AutoConfigBundleBuider.java new file mode 100644 index 0000000..5e2cbc0 --- /dev/null +++ b/wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/bundle/AutoConfigBundleBuider.java @@ -0,0 +1,42 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.dropwizard.ioc.bundle; + +import java.util.ArrayList; +import java.util.List; + +import io.dropwizard.Configuration; + +public class AutoConfigBundleBuider { + + private static final String DEFAULT_PACKAGE_NAME="org.openo"; + + private List packageNames=new ArrayList<>(); + + public AutoConfigBundleBuider(){ + packageNames.add( DEFAULT_PACKAGE_NAME); + } + + public AutoConfigBundleBuider addPackageName(String packageName) { + this.packageNames.add(packageName); + return this; + } + + + public AutoConfigBundle build() { + return new AutoConfigBundle(packageNames); + } +} diff --git a/wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/bundle/IOCApplication.java b/wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/bundle/IOCApplication.java new file mode 100644 index 0000000..9465b8e --- /dev/null +++ b/wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/bundle/IOCApplication.java @@ -0,0 +1,42 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.dropwizard.ioc.bundle; + +import io.dropwizard.Application; +import io.dropwizard.Configuration; +import io.dropwizard.setup.Bootstrap; +import io.dropwizard.setup.Environment; + +/** + * complete IOC container startup + * + * @author hu.rui2 + * + */ +public abstract class IOCApplication extends Application { + + + @Override + public void initialize(Bootstrap bootstrap) { + super.initialize(bootstrap); + bootstrap.addBundle(new AutoConfigBundleBuider().build()); + } + + @Override + public void run(T configuration, Environment environment) throws Exception { + + } +} diff --git a/wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/bundle/ServiceLocatorManaged.java b/wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/bundle/ServiceLocatorManaged.java new file mode 100644 index 0000000..4d33021 --- /dev/null +++ b/wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/bundle/ServiceLocatorManaged.java @@ -0,0 +1,51 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.dropwizard.ioc.bundle; + +import org.glassfish.hk2.api.ServiceLocator; + +import io.dropwizard.lifecycle.Managed; + +/** + * Life cycle management for IOC containers + * @author hu.rui + * + */ +public class ServiceLocatorManaged implements Managed{ + + + + private ServiceLocator locator; + + + + public ServiceLocatorManaged(ServiceLocator locator) { + super(); + this.locator = locator; + } + + @Override + public void start() throws Exception { + + + } + + @Override + public void stop() throws Exception { + locator.shutdown(); + } + +} diff --git a/wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/utils/ServiceBinder.java b/wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/utils/ServiceBinder.java new file mode 100644 index 0000000..9ad984f --- /dev/null +++ b/wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/utils/ServiceBinder.java @@ -0,0 +1,52 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.dropwizard.ioc.utils; + +import java.util.Set; + +import org.glassfish.hk2.utilities.binding.AbstractBinder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * @author hu.rui + * + */ +public class ServiceBinder extends AbstractBinder { + + private static final Logger LOG = LoggerFactory.getLogger(ServiceBinder.class); + + final Set> klasses; + + public ServiceBinder(Set> services) { + this.klasses = services; + } + + @Override + protected void configure() { + for (Class klass : this.klasses) { + + try{ + LOG.info("start active class:"+klass.getName()); + addActiveDescriptor(klass); + }catch(Exception e){ + LOG.info("active class error:"+klass.getName(),e); + } + + + } + } +} diff --git a/wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/utils/ServiceLocatorHolder.java b/wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/utils/ServiceLocatorHolder.java new file mode 100644 index 0000000..46dcd4b --- /dev/null +++ b/wso2/dropwizard-ioc-container/src/main/java/org/openo/dropwizard/ioc/utils/ServiceLocatorHolder.java @@ -0,0 +1,36 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.dropwizard.ioc.utils; + +import org.glassfish.hk2.api.ServiceLocator; + +/** + * @author hu.rui + * + */ +public class ServiceLocatorHolder { + + private static ServiceLocator locator; + + public static ServiceLocator getLocator() { + return locator; + } + + public static void setLocator(ServiceLocator locator) { + ServiceLocatorHolder.locator = locator; + } + +} diff --git a/wso2/dropwizard-ioc-container/src/test/java/org/openo/dropwizard/ioc/test/service/IOCBundleTest.java b/wso2/dropwizard-ioc-container/src/test/java/org/openo/dropwizard/ioc/test/service/IOCBundleTest.java new file mode 100644 index 0000000..b0cac65 --- /dev/null +++ b/wso2/dropwizard-ioc-container/src/test/java/org/openo/dropwizard/ioc/test/service/IOCBundleTest.java @@ -0,0 +1,49 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.dropwizard.ioc.test.service; + +import org.glassfish.hk2.api.ServiceLocator; +import org.junit.Before; +import org.junit.Test; +import org.openo.dropwizard.ioc.test.service.app.ExampleApp; +import org.openo.dropwizard.ioc.utils.ServiceLocatorHolder; + +import junit.framework.Assert; + +public class IOCBundleTest { + + + + @Before + public void setUp() throws Exception { + ExampleApp.main(null); + } + + @Test + public void test() { + + ServiceLocator locator = ServiceLocatorHolder.getLocator(); + + TestService testService = locator.getService(TestService.class); + + Assert.assertNotNull(testService); + + Assert.assertEquals(TestService.HELLO, testService.sayHello()); + + Assert.assertEquals(PreTestService.HELLO, testService.sayHelloToPreTestService()); + } + +} diff --git a/wso2/dropwizard-ioc-container/src/test/java/org/openo/dropwizard/ioc/test/service/PreTestService.java b/wso2/dropwizard-ioc-container/src/test/java/org/openo/dropwizard/ioc/test/service/PreTestService.java new file mode 100644 index 0000000..51cc386 --- /dev/null +++ b/wso2/dropwizard-ioc-container/src/test/java/org/openo/dropwizard/ioc/test/service/PreTestService.java @@ -0,0 +1,33 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.dropwizard.ioc.test.service; + +import org.openo.dropwizard.ioc.annotation.PreServiceLoad; + +/** + * @author hu.rui + * + */ +@PreServiceLoad +public class PreTestService { + + public static final String HELLO = "hello Pre Service"; + + public String sayHello(){ + return HELLO; + } + +} diff --git a/wso2/dropwizard-ioc-container/src/test/java/org/openo/dropwizard/ioc/test/service/TestService.java b/wso2/dropwizard-ioc-container/src/test/java/org/openo/dropwizard/ioc/test/service/TestService.java new file mode 100644 index 0000000..3d0f945 --- /dev/null +++ b/wso2/dropwizard-ioc-container/src/test/java/org/openo/dropwizard/ioc/test/service/TestService.java @@ -0,0 +1,41 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.dropwizard.ioc.test.service; + +import javax.inject.Inject; + +import org.jvnet.hk2.annotations.Service; + +/** + * @author hu.rui + * + */ +@Service +public class TestService { + + @Inject + private PreTestService preTestService; + + public static final String HELLO = "hello Service"; + + public String sayHello(){ + return HELLO; + } + + public String sayHelloToPreTestService(){ + return preTestService.sayHello(); + } +} diff --git a/wso2/dropwizard-ioc-container/src/test/java/org/openo/dropwizard/ioc/test/service/app/ExampleApp.java b/wso2/dropwizard-ioc-container/src/test/java/org/openo/dropwizard/ioc/test/service/app/ExampleApp.java new file mode 100644 index 0000000..1e1f3ea --- /dev/null +++ b/wso2/dropwizard-ioc-container/src/test/java/org/openo/dropwizard/ioc/test/service/app/ExampleApp.java @@ -0,0 +1,35 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.dropwizard.ioc.test.service.app; + +import org.openo.dropwizard.ioc.bundle.IOCApplication; +import org.openo.dropwizard.ioc.test.service.conf.TestConfiguration; + +public class ExampleApp extends IOCApplication{ + + private static final String CONFIGURATION_FILE = "example.yml"; + + public static void main(String[] args) throws Exception { + + String configFile = ExampleApp.class.getClassLoader().getResource(CONFIGURATION_FILE).getFile(); + + args = new String[]{"server",configFile}; + + new ExampleApp().run(args); + } + + +} diff --git a/wso2/dropwizard-ioc-container/src/test/java/org/openo/dropwizard/ioc/test/service/conf/TestConfiguration.java b/wso2/dropwizard-ioc-container/src/test/java/org/openo/dropwizard/ioc/test/service/conf/TestConfiguration.java new file mode 100644 index 0000000..82c30cd --- /dev/null +++ b/wso2/dropwizard-ioc-container/src/test/java/org/openo/dropwizard/ioc/test/service/conf/TestConfiguration.java @@ -0,0 +1,26 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.dropwizard.ioc.test.service.conf; + +import io.dropwizard.Configuration; + +/** + * @author hu.rui + * + */ +public class TestConfiguration extends Configuration { + +} diff --git a/wso2/dropwizard-ioc-container/src/test/resources/example.yml b/wso2/dropwizard-ioc-container/src/test/resources/example.yml new file mode 100644 index 0000000..c3ef0f0 --- /dev/null +++ b/wso2/dropwizard-ioc-container/src/test/resources/example.yml @@ -0,0 +1,8 @@ +server: + type: simple + rootPath: '/service/*' + applicationContextPath: / + connector: + type: http + port: 45673 + \ No newline at end of file diff --git a/wso2/logging-sdk/pom.xml b/wso2/logging-sdk/pom.xml new file mode 100644 index 0000000..c616c74 --- /dev/null +++ b/wso2/logging-sdk/pom.xml @@ -0,0 +1,85 @@ + + + + 4.0.0 + + org.openo.common-services.common-utilities + common-setting + 1.1.0-SNAPSHOT + + logging-sdk + common-services-common-utilities/logging-sdk + + + + + + + com.fasterxml.jackson.core + jackson-core + 2.7.3 + + + + com.fasterxml.jackson.core + jackson-databind + 2.7.3 + + + + com.fasterxml.jackson.core + jackson-annotations + 2.7.3 + + + ch.qos.logback + logback-classic + 1.1.3 + + + ch.qos.logback + logback-core + 1.1.3 + + + ch.qos.logback + logback-access + 1.1.3 + + + net.logstash.logback + logstash-logback-encoder + 4.8 + + + + + + maven-compiler-plugin + + + maven-enforcer-plugin + + + + org.apache.maven.plugins + maven-source-plugin + + + attach-sources + + jar + + + + + + + diff --git a/wso2/logging-sdk/src/main/java/org/openo/log/api/LogMessage.java b/wso2/logging-sdk/src/main/java/org/openo/log/api/LogMessage.java new file mode 100644 index 0000000..4a21584 --- /dev/null +++ b/wso2/logging-sdk/src/main/java/org/openo/log/api/LogMessage.java @@ -0,0 +1,132 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.log.api; + +import java.io.Serializable; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import org.slf4j.Logger; + +import org.openo.log.impl.Facitility; +import org.slf4j.LoggerFactory; + + +/** + * + * @author Huabing Zhao + * + */ + +public class LogMessage implements Serializable { + private static final Logger LOGGER = LoggerFactory.getLogger(LogMessage.class.getName()); + + protected long id = -1; + + + protected String detail = null; + + protected String hostname = ""; + + + + private String logType = ""; + + + protected HashMap extendedFields = null; + + private HashMap localeMap = null; + + + + private static final long serialVersionUID = 200408041651009L; + + public String getDetail() { + return detail; + } + + + public long getId() { + return id; + } + + public String getHostname() { + return hostname; + } + + + + public LogMessage() {} + + + + public String getLogType() { + return logType; + } + + public void setLogType(String logType) { + this.logType = logType; + } + + public HashMap getExtendedFields() { + return extendedFields; + } + + public void setExtendedFields(HashMap extendedFields) { + this.extendedFields = extendedFields; + } + + public HashMap getLocaleMap() { + return this.localeMap; + } + + public void setLocalMap(HashMap localeMap) { + this.localeMap = localeMap; + } + + protected void set(String condName, Object condValue) { + if (condValue != null && !"".equals(condValue)) { + if (localeMap == null) { + localeMap = new HashMap(); + } + localeMap.put(condName, condValue.toString()); + + } + } + + + protected void setLocale(String condName, String condValue) { + + if (condValue != null && !"".equals(condValue)) { + if (localeMap == null) { + localeMap = new HashMap(); + } + + + + Map mapJson = Facitility.readJson2Map(condValue); + for (Entry entry : mapJson.entrySet()) { + String key = entry.getKey(); + + String value = entry.getValue().replace("\"", "\'"); + localeMap.put(condName + "_" + key, value); + } + } + + } + + +} diff --git a/wso2/logging-sdk/src/main/java/org/openo/log/api/LogService.java b/wso2/logging-sdk/src/main/java/org/openo/log/api/LogService.java new file mode 100644 index 0000000..a25e10a --- /dev/null +++ b/wso2/logging-sdk/src/main/java/org/openo/log/api/LogService.java @@ -0,0 +1,140 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.log.api; + +import org.openo.log.impl.InsertLogHandler; +import org.openo.log.impl.LogConst; +import org.openo.log.impl.LogIdTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class LogService { + + private static final Logger LOGGER = LoggerFactory.getLogger(LogService.class.getName()); + + + public static final String OPERLOG_SUCCESS = "log_success"; + + public static final String OPERLOG_ERROR = "log_fail"; + + + public static final String OPERLOG_RANK_NORMAL = "operlog_rank_normal"; + + public static final String OPERLOG_RANK_NOTICE = "operlog_rank_notice"; + + public static final String OPERLOG_RANK_IMPORTANT = "operlog_rank_important"; + + public static final String OPERLOG_RANK_VERYIMPORTANT = " operlog_rank_veryimportant"; + + + public static final String SYSLOG_RANK_INFORM = "syslog_rank_inform"; + + public static final String SYSLOG_RANK_NOTICE = "syslog_rank_notice"; + + + public static final String SYSLOG_RANK_WARN = "syslog_rank_warn"; + + public static final String SYSLOG_RANK_ERROR = "syslog_rank_error"; + + + public static final String SYSLOG_RANK_ALERT = "syslog_rank_alert"; + + + public static final String SYSLOG_RANK_EMERG = "syslog_rank_emerg"; + + + public static final String CONNECT_TYPE_WEB = "WEB"; + + public static final String CONNECT_TYPE_TELNET = "TELNET"; + + public static final String CONNECT_TYPE_SSH = "SSH"; + + public static final String CONNECT_TYPE_EM = "EM"; + + public static final short LOG_DISPLAY_NOT = 0; + + public static final short LOG_DISPLAY = 1; + + public static final int LOG_ROOT_LINK_ID = -1; + + private static final int LOG_NO_LINK_ID = 0; + + private static LogService recordLogHandler = null; + + public static LogService getInstance() { + if (recordLogHandler == null) { + recordLogHandler = new LogService(); + } + return recordLogHandler; + } + + public long recordOperLog(OperLogMessage logMessage) { + // TODO Auto-generated method stub + LOGGER.info("receive a insert operLog message"); + InsertLogHandler insertLogHandler = new InsertLogHandler(); + if (insertLogHandler.checkCmdLog((OperLogMessage) logMessage)) { + + long id = + LogIdTool.getRandomID(LogConst.CMD_LOG_FLAG, logMessage.getLogStartDate().getTime()); + logMessage.setId(id); + insertLogHandler.insertLog(logMessage, LogConst.AUDITLOG_OPERATION, LogConst.OPERLOG_TYPE); + + return logMessage.getId(); + } + + return 0; + } + + public long recordSecLog(SecLogMessage logMessage) { + // TODO Auto-generated method stub + //LOGGER.info("receive a insert sec log message"); + InsertLogHandler insertLogHandler = new InsertLogHandler(); + if (insertLogHandler.checkSecLog((SecLogMessage) logMessage)) { + + long id = LogIdTool.getRandomID(LogConst.SECRET_LOG_FLAG, logMessage.getLogDate().getTime()); + logMessage.setId(id); + + insertLogHandler.insertLog(logMessage, LogConst.AUDITLOG_SECURITY, LogConst.SERLOG_TYPE); + + return logMessage.getId(); + } + return 0; + } + + + + public long recordSysLog(SysLogMessage logMessage) { + //LOGGER.info("receive a insert sys log message"); + InsertLogHandler insertLogHandler = new InsertLogHandler(); + if (insertLogHandler.checkSysLog((SysLogMessage) logMessage)) { + + long id = + LogIdTool.getRandomID(LogConst.SYS_LOG_FLAG, logMessage.getLogStartDate().getTime()); + logMessage.setId(id); + insertLogHandler.insertLog(logMessage, LogConst.AUDITLOG_SYSTEM, LogConst.SYSLOG_TYPE); + return logMessage.getId(); + } + return 0; + } + + public static void main(String[] args) + { + LogService service = new LogService(); + OperLogMessage logMessage = new OperLogMessage(); + + service.recordOperLog(logMessage ); + } +} diff --git a/wso2/logging-sdk/src/main/java/org/openo/log/api/OperLogMessage.java b/wso2/logging-sdk/src/main/java/org/openo/log/api/OperLogMessage.java new file mode 100644 index 0000000..567cfd0 --- /dev/null +++ b/wso2/logging-sdk/src/main/java/org/openo/log/api/OperLogMessage.java @@ -0,0 +1,286 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.log.api; + +import java.util.Date; + +import org.openo.log.impl.Facitility; +import org.openo.log.impl.LogConst; + + + +public class OperLogMessage extends LogMessage { + private static final long serialVersionUID = 200408041704009L; + + + public OperLogMessage() { + super(); + this.setLogType(LogConst.OPERLOG_TYPE); + } + + + public OperLogMessage(String userName, String operation, String descriptionInfo, String hostname, + String operateResult, String rank, Date logStartDate, Date logEndDate, String detail) { + super(); + this.setLogType(LogConst.OPERLOG_TYPE); + + this.userName = userName; + this.set("userName", userName); + + this.descriptionInfo = descriptionInfo; + this.setLocale("descriptionInfo", descriptionInfo); + + this.operation = operation; + this.setLocale("operation", operation); + + this.logStartDate = logStartDate; + this.set("logStartDate", Facitility.dateFormat(logStartDate)); + + this.logEndDate = logEndDate; + this.set("logEndDate", Facitility.dateFormat(logEndDate)); + + this.hostname = hostname; + this.set("hostname", hostname); + + this.operateResult = operateResult; + this.set("operateResult", operateResult); + + this.rank = rank; + this.set("rank", rank); + + this.detail = detail; + this.setLocale("detail", detail); + } + + + protected String userName = ""; + + + protected String operation = null; + + + protected String descriptionInfo = null; + + + private String operationType = "other"; + + protected String failReason = null; + + + protected String operateResult = LogService.OPERLOG_SUCCESS; + + + protected String connectMode = LogService.CONNECT_TYPE_WEB; + + + protected String[] resourceIP; + + + protected Date logStartDate = null; + + + protected Date logEndDate = null; + + + protected long linkId = -100; + + protected int isDisplay = LogService.LOG_DISPLAY; + + protected String mac = ""; + + /** + * name(id)|name(id) + */ + private String[] operateResource = null; + + + protected String rank = LogService.OPERLOG_RANK_NORMAL; + + public String getMac() { + return mac; + } + + public OperLogMessage setMac(String mac) { + this.set("mac", mac); + this.mac = mac; + return this; + } + + + public String getUserName() { + return userName; + } + + public OperLogMessage setUserName(String name) { + this.userName = name; + this.set("userName", name); + return this; + } + + public String getFailReason() { + return failReason; + } + + public OperLogMessage setFailReason(String reason) { + this.setLocale("failReason", reason); + this.failReason = reason; + return this; + } + + public String getConnectMode() { + return connectMode; + + } + + public OperLogMessage setConnectMode(String mode) { + this.set("connectMode", mode); + this.connectMode = mode; + return this; + } + + public long getLinkId() { + return linkId; + } + + public OperLogMessage setLinkId(long linkId) { + this.set("linkId", linkId); + this.linkId = linkId; + return this; + } + + public String getOperateResult() { + return operateResult; + } + + public OperLogMessage setOperateResult(String operateResult) { + this.set("operateResult", operateResult); + this.operateResult = operateResult; + return this; + } + + public String getRank() { + return rank; + } + + public OperLogMessage setRank(String rank) { + this.set("rank", rank); + this.rank = rank; + return this; + } + + public String getDescriptionInfo() { + return descriptionInfo; + } + + public OperLogMessage setDescriptionInfo(String desc) { + this.setLocale("descriptionInfo", desc); + descriptionInfo = desc; + return this; + } + + public String getOperation() { + return operation; + } + + public OperLogMessage setOperation(String operation) { + this.setLocale("operation", operation); + this.operation = operation; + return this; + } + + public String[] getResourceIP() { + return resourceIP; + } + + public OperLogMessage setResourceIP(String[] resourceIP) { + this.set("resourceIP", resourceIP); + this.resourceIP = resourceIP; + return this; + } + + public Date getLogStartDate() { + return logStartDate; + } + + public OperLogMessage setLogStartDate(Date logStartDate) { + this.set("logStartDate", Facitility.dateFormat(logStartDate)); + this.logStartDate = logStartDate; + return this; + } + + public Date getLogEndDate() { + return logEndDate; + } + + public OperLogMessage setLogEndDate(Date logEndDate) { + this.set("logEndDate", Facitility.dateFormat(logEndDate)); + this.logEndDate = logEndDate; + return this; + } + + public int getIsDisplay() { + return isDisplay; + } + + public OperLogMessage setIsDisplay(int isDisplay) { + this.set("isDisplay", isDisplay); + this.isDisplay = isDisplay; + return this; + } + + public String[] getOperateResource() { + return operateResource; + } + + public OperLogMessage setOperateResource(String[] operateResource) { + this.set("operateResource", operateResource); + this.operateResource = operateResource; + return this; + } + + public String getOperationType() { + return operationType; + } + + public OperLogMessage setOperationType(String operationType) { + + this.operationType = operationType; + return this; + } + + + + public OperLogMessage setHostname(String hostname) { + this.set("hostname", hostname); + this.hostname = hostname; + return this; + } + + + public LogMessage setId(long id) { + this.set("id", id); + this.id = id; + return this; + } + + + public LogMessage setDetail(String detail) { + this.detail = detail; + this.setLocale("detail", detail); + return this; + } + +} diff --git a/wso2/logging-sdk/src/main/java/org/openo/log/api/SecLogMessage.java b/wso2/logging-sdk/src/main/java/org/openo/log/api/SecLogMessage.java new file mode 100644 index 0000000..7eafbf7 --- /dev/null +++ b/wso2/logging-sdk/src/main/java/org/openo/log/api/SecLogMessage.java @@ -0,0 +1,146 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.log.api; + +import java.util.Date; + +import org.openo.log.impl.Facitility; +import org.openo.log.impl.LogConst; + +public class SecLogMessage extends LogMessage { + + private static final long serialVersionUID = 201603100924009L; + + + public SecLogMessage() { + super(); + this.setLogType(LogConst.SERLOG_TYPE); + } + + + public SecLogMessage(String userName, String hostname, String detail, String logName, + Date logDate) { + super(); + this.setLogType(LogConst.SERLOG_TYPE); + + this.userName = userName; + this.set("userName", userName); + + this.hostname = hostname; + this.set("hostname", hostname); + + this.logName = logName; + this.setLocale("logName", logName); + + this.detail = detail; + this.setLocale("detail", detail); + + this.logDate = logDate; + this.set("logDate", Facitility.dateFormat(logDate)); + } + + protected String userName = ""; + + + protected String logName = null; + + + protected String connectMode = ""; + + + protected String systemID = ""; + + protected String mac = ""; + + public String getMac() { + return mac; + } + + public SecLogMessage setMac(String mac) { + this.set("mac", mac); + this.mac = mac; + return this; + } + + + protected Date logDate = null; + + + public String getUserName() { + + return userName; + } + + + public SecLogMessage setUserName(String userName) { + this.set("userName", userName); + this.userName = userName; + return this; + } + + + public String getConnectMode() { + return connectMode; + } + + + public SecLogMessage setConnectMode(String connectMode) { + this.set("connectMode", connectMode); + this.connectMode = connectMode; + return this; + } + + public String getLogName() { + return logName; + } + + public SecLogMessage setLogName(String logName) { + this.setLocale("logName", logName); + this.logName = logName; + return this; + } + + public Date getLogDate() { + return logDate; + } + + public SecLogMessage setLogDate(Date logDate) { + this.set("logDate", Facitility.dateFormat(logDate)); + this.logDate = logDate; + return this; + } + + public SecLogMessage setHostname(String hostname) { + this.set("hostname", hostname); + this.hostname = hostname; + return this; + } + + + public SecLogMessage setId(long id) { + this.set("id", id); + this.id = id; + return this; + } + + + public SecLogMessage setDetail(String detail) { + this.detail = detail; + this.setLocale("detail", detail); + return this; + } + +} diff --git a/wso2/logging-sdk/src/main/java/org/openo/log/api/SysLogMessage.java b/wso2/logging-sdk/src/main/java/org/openo/log/api/SysLogMessage.java new file mode 100644 index 0000000..5b1a6d9 --- /dev/null +++ b/wso2/logging-sdk/src/main/java/org/openo/log/api/SysLogMessage.java @@ -0,0 +1,180 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.log.api; + +import java.util.Date; + +import org.openo.log.impl.Facitility; +import org.openo.log.impl.LogConst; + + +public class SysLogMessage extends LogMessage { + private static final long serialVersionUID = 200408041707009L; + + + protected String rank = LogService.SYSLOG_RANK_INFORM; + + protected String source = null; + + protected String sourceId = ""; + + protected String logName = null; + + + protected Date logStartDate = null; + + protected Date logEndDate = null; + + protected int isDisplay = LogService.LOG_DISPLAY; + + protected long linkId = -100; + + + public SysLogMessage() { + super(); + this.setLogType(LogConst.SYSLOG_TYPE); + } + + + public SysLogMessage(String logName, String hostname, String rank, String detail, + Date logStartDate, Date logEndDate) { + super(); + this.setLogType(LogConst.SYSLOG_TYPE); + + this.logName = logName; + this.set("logName", logName); + + this.rank = rank; + this.set("rank", rank); + + this.hostname = hostname; + this.set("hostname", hostname); + + this.detail = detail; + this.set("detail", detail); + + this.logStartDate = logStartDate; + this.set("logStartDate", Facitility.dateFormat(logStartDate)); + + this.logEndDate = logEndDate; + this.set("logEndDate", Facitility.dateFormat(logEndDate)); + } + + public Date getLogStartDate() { + return logStartDate; + } + + public SysLogMessage setLogStartDate(Date logStartDate) { + this.set("logStartDate", Facitility.dateFormat(logStartDate)); + this.logStartDate = logStartDate; + return this; + } + + public Date getLogEndDate() { + return logEndDate; + } + + public SysLogMessage setLogEndDate(Date logEndDate) { + this.set("logEndDate", Facitility.dateFormat(logEndDate)); + this.logEndDate = logEndDate; + return this; + } + + public String getRank() { + return rank; + } + + public SysLogMessage setRank(String rank) { + this.set("rank", rank); + this.rank = rank; + return this; + } + + public String getLogName() { + return logName; + } + + public SysLogMessage setLogName(String logName) { + this.setLocale("logName", logName); + this.logName = logName; + return this; + } + + + public final String getSource() { + return source; + } + + + public SysLogMessage setSource(String source) { + this.setLocale("source", source); + this.source = source; + return this; + } + + public int getIsDisplay() { + return isDisplay; + } + + public SysLogMessage setIsDisplay(int isDisplay) { + this.set("isDisplay", isDisplay); + this.isDisplay = isDisplay; + return this; + } + + public long getLinkId() { + return linkId; + } + + public String getSourceId() { + return sourceId; + } + + public SysLogMessage setSourceId(String sourceId) { + this.set("sourceId", sourceId); + this.sourceId = sourceId; + return this; + } + + public SysLogMessage setLinkId(long linkId) { + this.set("linkId", linkId); + this.linkId = linkId; + return this; + } + + public SysLogMessage setHostname(String hostname) { + this.set("hostname", hostname); + this.hostname = hostname; + return this; + } + + + public SysLogMessage setId(long id) { + this.set("id", id); + this.id = id; + return this; + } + + + public SysLogMessage setDetail(String detail) { + this.detail = detail; + this.setLocale("detail", detail); + return this; + } + + + +} diff --git a/wso2/logging-sdk/src/main/java/org/openo/log/impl/Facitility.java b/wso2/logging-sdk/src/main/java/org/openo/log/impl/Facitility.java new file mode 100644 index 0000000..82445bb --- /dev/null +++ b/wso2/logging-sdk/src/main/java/org/openo/log/impl/Facitility.java @@ -0,0 +1,137 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.log.impl; + +import java.io.IOException; +import java.io.StringWriter; +import java.io.Writer; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class Facitility { + private static final Logger LOGGER = LoggerFactory.getLogger(Facitility.class.getName()); + + private Facitility() { + + } + + public static String oToJ(Object o) { + ObjectMapper om = new ObjectMapper(); + Writer w = new StringWriter(); + String json = null; + try { + + om.setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")); + om.writeValue(w, o); + json = w.toString(); + w.close(); + } catch (IOException e) { + LOGGER.error("IOException", e); + } + return json; + } + + public static Map readJson2Map(String json) { + ObjectMapper objectMapper = new ObjectMapper(); + try { + Map maps = objectMapper.readValue(json, Map.class); + return maps; + } catch (Exception e) { + LOGGER.error("IOException", e); + return null; + } + } + + public static String hashMapToJson(HashMap map) { + String string = "{"; + for (Iterator it = map.entrySet().iterator(); it.hasNext();) { + Entry e = (Entry) it.next(); + string += "\"" + e.getKey() + "\":"; + string += "\"" + e.getValue() + "\","; + } + string = string.substring(0, string.lastIndexOf(",")); + string += "}"; + return string; + } + + public static String dateFormat(Date date) { + SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); + return time.format(date); + } + + public static String checkRequiredParam(HashMap checkParamsMap) { + StringBuilder errMsg = new StringBuilder(); + java.util.Iterator hashMapIt = checkParamsMap.keySet().iterator(); + int count = 0; + while (hashMapIt.hasNext()) { + String key = hashMapIt.next(); + Object value = checkParamsMap.get(key); + if (value == null || "".equals(value)) { + errMsg.append(key); + count++; + if (count < checkParamsMap.size() - 1) { + errMsg.append(" and "); + } + } + + } + if (count > 0) { + errMsg.append(" can't be null or \"\"!\n "); + } + return errMsg.toString(); + } + + public static String checkRequiredJsonParam(String jsonParam, String key) { + return ""; +// StringBuilder errMsg = new StringBuilder(); +// try { +// ObjectMapper mapper = new ObjectMapper(); +// JsonNode jsonValue; +// +// +// jsonValue = mapper.readTree(jsonParam.toString()); +// Iterator> elements = jsonValue.fields(); +// while (elements.hasNext()) { +// Entry node = elements.next(); +// String childValue = node.getValue().asText(); +// if (childValue == null || "".equals(childValue)) { +// errMsg.append( +// "Both Chinese and English descriptions of this field cannot be empty: " + key + "/n"); +// break; +// } +// } +// +// return errMsg.toString(); +// } catch (JsonProcessingException e) { +// // TODO Auto-generated catch block +// LOGGER.error("JsonProcessingException" , e); +// return errMsg.toString(); +// } catch (IOException e) { +// // TODO Auto-generated catch block +// LOGGER.error("IOException" , e); +// return errMsg.toString(); +// } + } +} diff --git a/wso2/logging-sdk/src/main/java/org/openo/log/impl/InsertLogHandler.java b/wso2/logging-sdk/src/main/java/org/openo/log/impl/InsertLogHandler.java new file mode 100644 index 0000000..ea5570f --- /dev/null +++ b/wso2/logging-sdk/src/main/java/org/openo/log/impl/InsertLogHandler.java @@ -0,0 +1,265 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.log.impl; + +import java.util.HashMap; +import org.slf4j.Logger; + +import org.openo.log.api.LogMessage; +import org.openo.log.api.LogService; +import org.openo.log.api.OperLogMessage; +import org.openo.log.api.SecLogMessage; +import org.openo.log.api.SysLogMessage; +import org.slf4j.LoggerFactory; + + + +public class InsertLogHandler { + private static final Logger LOGGER = LoggerFactory.getLogger(InsertLogHandler.class.getName()); + + public void insertLog(LogMessage msg, String logIndex, String logType) { + String logJson = Facitility.hashMapToJson(msg.getLocaleMap()); + msg.setLocalMap(null); + + if (msg.getExtendedFields() != null) { + String exendedFieldsJson = Facitility.oToJ(msg.getExtendedFields()); + logJson = logJson.substring(0, logJson.lastIndexOf("}")) + "," + + exendedFieldsJson.substring(1) + "\n"; + msg.setExtendedFields(null); + } + LOGGER.info(logJson, logIndex, logType); + + + } + + public boolean checkCmdLog(OperLogMessage msg) { + StringBuilder errMsg = new StringBuilder(); + boolean errFlag = false; + HashMap checkParamsMap = new HashMap<>(); + checkParamsMap.put("userName", msg.getUserName()); + checkParamsMap.put("operation", msg.getOperation()); + checkParamsMap.put("descriptionInfo", msg.getDescriptionInfo()); + checkParamsMap.put("hostname", msg.getHostname()); + checkParamsMap.put("detail", msg.getDetail()); + checkParamsMap.put("logStartDate", msg.getLogStartDate()); + checkParamsMap.put("logEndDate", msg.getLogEndDate()); + errMsg.append(Facitility.checkRequiredParam(checkParamsMap)); + + + errMsg.append(checkCmdRank(msg.getRank())); + errMsg.append(checkConnectMode(msg.getConnectMode())); + errMsg.append(checkOperateResult(msg.getOperateResult())); + errMsg.append(checkIsDisplay(msg.getIsDisplay())); + + if (msg.getOperation() != null && !("").equals(msg.getOperation())) { + errMsg.append(Facitility.checkRequiredJsonParam(msg.getOperation(), "operation")); + } + if (msg.getDescriptionInfo() != null && !("").equals(msg.getDescriptionInfo())) { + errMsg.append(Facitility.checkRequiredJsonParam(msg.getDescriptionInfo(), "descriptionInfo")); + } + if (msg.getDetail() != null && !("").equals(msg.getDetail())) { + errMsg.append(Facitility.checkRequiredJsonParam(msg.getDetail(), "detail")); + } + if (msg.getFailReason() != null && !("").equals(msg.getFailReason())) { + errMsg.append(Facitility.checkRequiredJsonParam(msg.getFailReason(), "failReason")); + } + if (!"".equals(errMsg.toString())) { + LOGGER.warn(errMsg.toString()); + printCmdLog(msg); + errFlag = true; + } + return !errFlag; + } + + private String checkIsDisplay(int isDisplay) { + StringBuilder errMsg = new StringBuilder(); + if (isDisplay != LogService.LOG_DISPLAY && isDisplay != LogService.LOG_DISPLAY_NOT) { + errMsg.append("isDisplay must be 'LogService.LOG_DISPLAY'"); + errMsg.append(" or 'LogService.LOG_DISPLAY_NOT'\n"); + + } + return errMsg.toString(); + } + + private String checkOperateResult(String operateResult) { + StringBuilder errMsg = new StringBuilder(); + if ((operateResult != LogService.OPERLOG_SUCCESS) + && (operateResult != LogService.OPERLOG_ERROR)) { + errMsg.append("operateResult must be ' LogService.OPERLOG_ERROR'"); + errMsg.append(" or 'LogService.OPERLOG_SUCCESS'\n"); + + } + return errMsg.toString(); + } + + private String checkConnectMode(String connectMode) { + StringBuilder errMsg = new StringBuilder(); + if (!(connectMode.equals(LogService.CONNECT_TYPE_WEB) + || connectMode.equals(LogService.CONNECT_TYPE_TELNET) + || connectMode.equals(LogService.CONNECT_TYPE_SSH) + || connectMode.equals(LogService.CONNECT_TYPE_EM))) { + errMsg.append("connectMode must be 'LogService.CONNECT_TYPE_WEB'"); + errMsg.append(" or 'LogService.CONNECT_TYPE_TELNET'"); + errMsg.append(" or 'LogService.CONNECT_TYPE_SSH'"); + errMsg.append(" or 'LogService.CONNECT_TYPE_EM'\n"); + + } + + return errMsg.toString(); + } + + private String checkCmdRank(String rank) { + StringBuilder errMsg = new StringBuilder(); + boolean isExist = false; + String[] ranks = {LogService.OPERLOG_RANK_NOTICE, LogService.OPERLOG_RANK_NORMAL, + LogService.OPERLOG_RANK_IMPORTANT, LogService.OPERLOG_RANK_VERYIMPORTANT}; + for (int i = 0; i < ranks.length; i++) { + if (rank.equalsIgnoreCase(ranks[i])) { + isExist = true; + break; + } + } + if (!isExist) { + errMsg.append("rank must be 'LogService.OPERLOG_RANK_NORMAL'"); + errMsg.append(" or 'LogService.OPERLOG_RANK_NOTICE'"); + errMsg.append(" or 'LogService.OPERLOG_RANK_IMPORTANT'"); + errMsg.append(" or 'LogService.OPERLOG_RANK_VERYIMPORTANT'\n"); + + } + + return errMsg.toString(); + } + + public void printCmdLog(OperLogMessage msg) { + LOGGER.warn("CMD Log Error Detail msg"); + LOGGER.warn("UserName :" + msg.getUserName()); + LOGGER.warn("operation :" + msg.getOperation()); + LOGGER.warn("hostname :" + msg.getHostname()); + LOGGER.warn("descriptionInfo :" + msg.getDescriptionInfo()); + LOGGER.warn("operateResult :" + msg.getOperateResult()); + LOGGER.warn("FailReason :" + msg.getFailReason()); + LOGGER.warn("detail :" + msg.getDetail()); + LOGGER.warn("ConnectMode:" + msg.getConnectMode()); + LOGGER.warn("OperateResource :" + msg.getOperateResource()); + LOGGER.warn("logStartDate :" + msg.getOperateResource()); + LOGGER.warn("logEndDate :" + msg.getLogEndDate()); + LOGGER.warn("Rank :" + msg.getRank()); + } + + /** + * 检查日志�数是�符��求 + * + * @return true + */ + public boolean checkSecLog(SecLogMessage msg) { + StringBuilder errMsg = new StringBuilder(); + boolean errFlag = false; + HashMap checkParamsMap = new HashMap<>(); + checkParamsMap.put("userName", msg.getUserName()); + checkParamsMap.put("logName", msg.getLogName()); + checkParamsMap.put("hostname", msg.getHostname()); + checkParamsMap.put("detail", msg.getDetail()); + checkParamsMap.put("logDate", msg.getLogDate()); + errMsg.append(Facitility.checkRequiredParam(checkParamsMap)); + errMsg.append(checkConnectMode(msg.getConnectMode())); + + if (msg.getLogName() != null && !("").equals(msg.getLogName())) { + errMsg.append(Facitility.checkRequiredJsonParam(msg.getLogName(), "logName")); + } + if (msg.getDetail() != null && !("").equals(msg.getDetail())) { + errMsg.append(Facitility.checkRequiredJsonParam(msg.getDetail(), "detail")); + } + if (!"".equals(errMsg.toString())) { + LOGGER.warn(errMsg.toString()); + this.printSecLog(msg); + errFlag = true; + } + return !errFlag; + } + + public void printSecLog(SecLogMessage secLog) { + LOGGER.warn("SCRT Log Error Detail msg"); + LOGGER.warn("logDate :" + secLog.getLogDate()); + LOGGER.warn("logName :" + secLog.getLogName()); + LOGGER.warn("userName :" + secLog.getUserName()); + LOGGER.warn("hostname :" + secLog.getHostname()); + LOGGER.warn("connectMode:" + secLog.getConnectMode()); + LOGGER.warn("detail :" + secLog.getDetail()); + } + + public boolean checkSysLog(SysLogMessage msg) { + StringBuilder errMsg = new StringBuilder(); + boolean errFlag = false; + HashMap checkParamsMap = new HashMap<>(); + + checkParamsMap.put("logName", msg.getLogName()); + checkParamsMap.put("logStartDate", msg.getLogStartDate()); + checkParamsMap.put("logEndDate", msg.getLogEndDate()); + checkParamsMap.put("hostname", msg.getHostname()); + checkParamsMap.put("detail", msg.getDetail()); + errMsg.append(Facitility.checkRequiredParam(checkParamsMap)); + errMsg.append(checkSysRank(msg.getRank())); + if (msg.getLogName() != null && !("").equals(msg.getLogName())) { + errMsg.append(Facitility.checkRequiredJsonParam(msg.getLogName(), "logName")); + } + if (msg.getDetail() != null && !("").equals(msg.getDetail())) { + errMsg.append(Facitility.checkRequiredJsonParam(msg.getDetail(), "detail")); + } + if (!"".equals(errMsg.toString())) { + LOGGER.warn(errMsg.toString()); + printSysLog(msg); + errFlag = true; + } + return !errFlag; + } + + private String checkSysRank(String rank) { + StringBuilder errMsg = new StringBuilder(); + boolean isExist = false; + String[] ranks = {LogService.SYSLOG_RANK_INFORM, LogService.SYSLOG_RANK_NOTICE, + LogService.SYSLOG_RANK_WARN, LogService.SYSLOG_RANK_ERROR, LogService.SYSLOG_RANK_ALERT, + LogService.SYSLOG_RANK_EMERG}; + for (int i = 0; i < ranks.length; i++) { + if (rank.equalsIgnoreCase(ranks[i])) { + isExist = true; + break; + } + } + if (!isExist) { + errMsg.append("rank must be 'LogService.SYSLOG_INFORM'"); + errMsg.append(" or 'LogService.SYSLOG_NOTICE'"); + errMsg.append(" or 'LogService.SYSLOG_WARN'"); + errMsg.append(" or 'LogService.SYSLOG_ERROR'"); + errMsg.append(" or 'LogService.SYSLOG_ALTERT'"); + errMsg.append(" or 'LogService.SYSLOG_EMERG'\n"); + + } + + return errMsg.toString(); + } + + public void printSysLog(SysLogMessage msg) { + LOGGER.warn("System Log Error Detail msg"); + LOGGER.warn("logName :" + msg.getLogName()); + LOGGER.warn("rank :" + msg.getRank()); + LOGGER.warn("source :" + msg.getSource()); + LOGGER.warn("logStartDate :" + msg.getLogStartDate()); + LOGGER.warn("logEndDate :" + msg.getLogEndDate()); + LOGGER.warn("detail :" + msg.getDetail()); + } + +} + diff --git a/wso2/logging-sdk/src/main/java/org/openo/log/impl/LogConst.java b/wso2/logging-sdk/src/main/java/org/openo/log/impl/LogConst.java new file mode 100644 index 0000000..1e45313 --- /dev/null +++ b/wso2/logging-sdk/src/main/java/org/openo/log/impl/LogConst.java @@ -0,0 +1,37 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.log.impl; + +public class LogConst { + private LogConst() { + + } + + public final static int CMD_LOG_FLAG = 1; + public final static int SYS_LOG_FLAG = 2; + public final static int SECRET_LOG_FLAG = 3; + + public final static String AUDITLOG_OPERATION = "auditlog_operation"; + public final static String AUDITLOG_SECURITY = "auditlog_security"; + public final static String AUDITLOG_SYSTEM = "auditlog_system"; + + public final static String OPERLOG_TYPE = "operlog"; + public final static String SERLOG_TYPE = "seclog"; + public final static String SYSLOG_TYPE = "syslog"; + + + +} diff --git a/wso2/logging-sdk/src/main/java/org/openo/log/impl/LogIdTool.java b/wso2/logging-sdk/src/main/java/org/openo/log/impl/LogIdTool.java new file mode 100644 index 0000000..4dea43b --- /dev/null +++ b/wso2/logging-sdk/src/main/java/org/openo/log/impl/LogIdTool.java @@ -0,0 +1,67 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.log.impl; + +import java.util.Date; +import java.util.Random; + + + +public class LogIdTool { + private static Random cmdRand = new Random(); + + private static Random sysRand = new Random(); + + private static Random secRand = new Random(); + + private LogIdTool() { + + } + + public static long getRandomID(int logType, long startDate) { + String strCtime = "" + startDate; + if (strCtime.length() > 13) { + strCtime = strCtime.substring(strCtime.length() - 13); + } + int seed1; + if (logType == LogConst.CMD_LOG_FLAG) { + seed1 = cmdRand.nextInt(100000); + } else if (logType == LogConst.SYS_LOG_FLAG) { + seed1 = sysRand.nextInt(100000); + } else if (logType == LogConst.SECRET_LOG_FLAG) { + seed1 = secRand.nextInt(100000); + } else { + return 0; + } + String seed2 = "" + seed1; + int shouldFillLen = 5 - seed2.length(); + for (int i = 0; i < shouldFillLen; i++) { + seed2 = "0" + seed2; + } + return Long.parseLong(strCtime + seed2); + } + + public static long transTimeCond2ID(Date time, boolean isStart) { + long timeLong = time.getTime(); + if (isStart) { + timeLong = timeLong * 100000; + } else { + timeLong = timeLong * 100000 + 99999; + } + return timeLong; + + } +} diff --git a/wso2/logging-sdk/src/main/java/org/openo/log/test/TestLogback2Logstash.java b/wso2/logging-sdk/src/main/java/org/openo/log/test/TestLogback2Logstash.java new file mode 100644 index 0000000..ed4993a --- /dev/null +++ b/wso2/logging-sdk/src/main/java/org/openo/log/test/TestLogback2Logstash.java @@ -0,0 +1,58 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.log.test; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Date; + +import org.openo.log.api.LogService; +import org.openo.log.api.SysLogMessage; +import org.slf4j.LoggerFactory; + +import ch.qos.logback.classic.LoggerContext; +import ch.qos.logback.classic.joran.JoranConfigurator; +import ch.qos.logback.core.joran.spi.JoranException; + +/** + * @author Huabing Zhao + * + */ +public class TestLogback2Logstash { + + /** + * @param args + * @throws JoranException + * @throws IOException + * @throws InterruptedException + */ + public static void main(String[] args) throws JoranException, IOException, InterruptedException { + LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); + loggerContext.reset(); + JoranConfigurator configurator = new JoranConfigurator(); + InputStream configStream = TestLogback2Logstash.class.getResourceAsStream("logback.xml"); + configurator.setContext(loggerContext); + configurator.doConfigure(configStream); // loads logback file + configStream.close(); + + for (int i = 0; i < 10; i++) { + SysLogMessage sysLogMessage = new SysLogMessage("a sys log example", "www.open-o.org", + LogService.SYSLOG_RANK_WARN, "logdetails", new Date(), new Date()); + LogService.getInstance().recordSysLog(sysLogMessage); + } + loggerContext.stop(); + } +} diff --git a/wso2/logging-sdk/src/main/java/org/openo/log/test/logback.xml b/wso2/logging-sdk/src/main/java/org/openo/log/test/logback.xml new file mode 100644 index 0000000..4c41c2a --- /dev/null +++ b/wso2/logging-sdk/src/main/java/org/openo/log/test/logback.xml @@ -0,0 +1,22 @@ + + + + 127.0.0.1:4560 + + + + + + + + %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + \ No newline at end of file diff --git a/wso2/pom.xml b/wso2/pom.xml new file mode 100644 index 0000000..668c863 --- /dev/null +++ b/wso2/pom.xml @@ -0,0 +1,332 @@ + + + + 4.0.0 + + + org.openo.oparent + oparent + 1.1.0-SNAPSHOT + ../oparent + + + org.openo.common-services.common-utilities + common-setting + pom + common-services-common-utilities + + + UTF-8 + false + false + ${project.artifactId}-${project.version} + ${basedir}/target + 1.6.1 + + + ${project.artifactId}-${project.version} + ${basedir}/../release/pkgzip + **/*$* + + UTF-8 + https://nexus.open-o.org/content + UTF-8 + UTF-8 + + + + scm:git:ssh://git.open-o.org:29418/common-services-common-utilities.git + scm:git:ssh://git.open-o.org:29418/common-services-common-utilities.git + HEAD + https://wiki.open-o.orgiew/Common_Services + + + + baseservice-i18n + common-util + dropwizard-ioc-container + logging-sdk + rest-client + wso2bpel-ext + + + + + + commons-io + commons-io + 2.4 + + + org.apache.commons + org.apache.commons.lang + 2.6.0 + + + org.apache.commons + org.apache.commons.logging + 1.1.1 + + + org.apache.commons + org.apache.commons.codec + 1.9.0 + + + + org.slf4j + slf4j-api + ${slf4j.version} + + + org.slf4j + slf4j-log4j12 + ${slf4j.version} + + + log4j + log4j + 1.2.16 + + + org.mybatis + mybatis-spring + 1.2.0 + + + org.mybatis + mybatis + 3.2.7 + + + org.apache.commons + commons-lang3 + 3.1 + + + org.codehaus.jackson + jackson-mapper-asl + 1.9.2 + + + net.sf.json-lib + json-lib + 2.4 + jdk15 + + + org.eclipse.jetty.aggregate + jetty-all + 8.1.16.v20140903 + + + org.eclipse.jetty.orbit + javax.servlet + 3.0.0.v201112011016 + provided + + + redis.clients + jedis + 2.8.0 + + + org.apache.commons + commons-dbcp2 + 2.0.1 + + + org.codehaus.jackson + jackson-mapper-asl + 1.9.2 + + + + + + + + ${resources.dir} + + + ${project.build.directory}/generated-resources + + + ${basedir}/src/main/java + + **/*.java + + + + ${basedir}/src/main/resources + + + + + ${basedir}/src/test/java + + **/*.java + + + + ${basedir}/src/test/resources + + + + + + org.apache.maven.plugins + maven-antrun-plugin + 1.6 + + + ant-contrib + ant-contrib + 1.0b3 + + + ant + ant + + + + + com.google.js + closure-compiler + 1.0.0 + + + com.google.closure-stylesheets + closure-stylesheets + 20140426 + + + + + org.apache.maven.plugins + maven-clean-plugin + 2.4.1 + + + org.apache.maven.plugins + maven-release-plugin + 2.5.2 + + + **/*.java + + true + + + + + + + + + org.apache.maven.plugins + maven-release-plugin + + + + + + org.apache.maven.plugins + maven-deploy-plugin + 2.7 + + 2 + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.6.1 + + true + ${javadoc.loc}/javadoc.css + ${javadoc.loc}/overview.html + org.apache.*,*.impl + true + true + false + false + protected + 1.5 + gb2312 + UTF-8 + gb2312 + 256M + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.3 + + 1.7 + 1.7 + + + + org.apache.maven.plugins + maven-jar-plugin + 2.3.1 + + ${bundle.name} + ${release.dir} + + + + + maven-clean-plugin + + false + + + ${release.dir} + + ${bundle.name}.${project.packaging} + + + + + + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.6.1 + + true + true + public + + + + + + diff --git a/wso2/rest-client/.gitignore b/wso2/rest-client/.gitignore new file mode 100644 index 0000000..b83d222 --- /dev/null +++ b/wso2/rest-client/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/wso2/rest-client/pom.xml b/wso2/rest-client/pom.xml new file mode 100644 index 0000000..de54805 --- /dev/null +++ b/wso2/rest-client/pom.xml @@ -0,0 +1,88 @@ + + + + 4.0.0 + + org.openo.common-services.common-utilities + common-setting + 1.1.0-SNAPSHOT + + commonlib-restclient + + + + + org.openo.common-services.common-utilities + commonlib-cbb + 1.1.0-SNAPSHOT + + + org.eclipse.jetty.aggregate + jetty-all + + + junit + junit + test + 4.8.2 + + + com.googlecode.jmockit + jmockit + test + 1.1 + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + always + -XX:-UseSplitVerifier + ${maven.test.skip} + ${maven.test.failure.ignore} + + ${excludesFile} + + + + + org.codehaus.mojo + cobertura-maven-plugin + 2.6 + + + xml + html + + + + + package + + cobertura + + + + + + +common-services-common-utilities/rest-client diff --git a/wso2/rest-client/src/main/java/org/openo/baseservice/remoteservice/exception/ExceptionArgs.java b/wso2/rest-client/src/main/java/org/openo/baseservice/remoteservice/exception/ExceptionArgs.java new file mode 100644 index 0000000..6c92f23 --- /dev/null +++ b/wso2/rest-client/src/main/java/org/openo/baseservice/remoteservice/exception/ExceptionArgs.java @@ -0,0 +1,110 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.baseservice.remoteservice.exception; + +/** + * ROA exception handling parameters. + *
+ *

+ *

+ * + * @author + * @version 28-May-2016 + */ +public class ExceptionArgs { + + /** + * Exception descriptions. + */ + private String[] descArgs = null; + + /** + * Exception reasons. + */ + private String[] reasonArgs = null; + + /** + * Exception detals. + */ + private String[] detailArgs = null; + + /** + * Exception advices. + */ + private String[] adviceArgs = null; + + /** + * Constructor
+ *

+ *

+ * + * @since + */ + public ExceptionArgs() { + // default constructor. + } + + /** + * Constructor
+ *

+ *

+ * + * @since + * @param descArgs: descriptions. + * @param reasonArgs: reasons. + * @param detailArgs: details. + * @param adviceArgs: advices. + */ + public ExceptionArgs(final String[] descArgs, final String[] reasonArgs, final String[] detailArgs, + final String[] adviceArgs) { + this.descArgs = descArgs; + this.reasonArgs = reasonArgs; + this.detailArgs = detailArgs; + this.adviceArgs = adviceArgs; + } + + public String[] getDescArgs() { + return descArgs; + } + + public void setDescArgs(final String[] descArgs) { + this.descArgs = descArgs; + } + + public String[] getReasonArgs() { + return reasonArgs; + } + + public void setReasonArgs(final String[] reasonArgs) { + this.reasonArgs = reasonArgs; + } + + public String[] getDetailArgs() { + return detailArgs; + } + + public void setDetailArgs(final String[] detailArgs) { + this.detailArgs = detailArgs; + } + + public String[] getAdviceArgs() { + return adviceArgs; + } + + public void setAdviceArgs(final String[] adviceArgs) { + this.adviceArgs = adviceArgs; + } +} diff --git a/wso2/rest-client/src/main/java/org/openo/baseservice/remoteservice/exception/ServiceException.java b/wso2/rest-client/src/main/java/org/openo/baseservice/remoteservice/exception/ServiceException.java new file mode 100644 index 0000000..378fe9f --- /dev/null +++ b/wso2/rest-client/src/main/java/org/openo/baseservice/remoteservice/exception/ServiceException.java @@ -0,0 +1,269 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.baseservice.remoteservice.exception; + +import java.text.MessageFormat; + +/** + * The base class for all common exception.
+ *

+ *

+ * + * @author + * @version 28-May-2016 + */ +public class ServiceException extends Exception { + + /** + * default exception id. + */ + public static final String DEFAULT_ID = "framwork.remote.SystemError"; + + /** + * Serial number. + */ + private static final long serialVersionUID = 5703294364555144738L; + + /** + * Exception id. + */ + private String id = DEFAULT_ID; + + private Object[] args = null; + + private int httpCode = 500; + + private ExceptionArgs exceptionArgs = null; + + /** + * The default constructor
+ *

+ * This method is only used as deserialized, in other cases, use parameterized constructor. + *

+ * + * @since + */ + public ServiceException() { + super(""); + } + + /** + * Constructor
+ *

+ *

+ * + * @since + * @param id: details. + * @param cause: reason. + */ + public ServiceException(final String id, final Throwable cause) { + super(cause); + this.setId(id); + } + + /** + * Constructor
+ *

+ *

+ * + * @since + * @param message: details. + */ + public ServiceException(final String message) { + super(message); + } + + /** + * Constructor
+ *

+ *

+ * + * @since + * @param id: exception id. + * @param message: details. + */ + public ServiceException(final String id, final String message) { + super(message); + this.setId(id); + } + + /** + * Constructor
+ *

+ *

+ * + * @since + * @param id: exception id. + * @param httpCode: http status code. + */ + public ServiceException(final String id, final int httpCode) { + super(); + this.setId(id); + this.setHttpCode(httpCode); + } + + /** + * Constructor
+ *

+ * the exception include the httpcode and message. + *

+ * + * @since + * @param httpCode http code. + * @param message details. + */ + public ServiceException(final int httpCode, final String message) { + super(message); + this.setHttpCode(httpCode); + } + + /** + * Constructor
+ *

+ *

+ * + * @since + * @param id: exception id. + * @param httpCode: http code. + * @param exceptionArgs: Exception handling frame parameters. + */ + public ServiceException(final String id, final int httpCode, final ExceptionArgs exceptionArgs) { + super(); + this.setId(id); + this.setHttpCode(httpCode); + this.setExceptionArgs(exceptionArgs); + } + + /** + * Constructor
+ *

+ * Have a placeholder exception, use args formatted message. + *

+ * + * @since + * @param id: exception id. + * @param message: details. + * @param args: Placeholders for parameters + */ + public ServiceException(final String id, final String message, final Object... args) { + super(MessageFormat.format(message, args)); + this.setId(id); + this.args = args; + } + + /** + * Constructor
+ *

+ * Have a placeholder exception, use args formatted message + *

+ * + * @since + * @param id: exception id. + * @param message: details. + * @param cause: reason. + * @param args: placeholder for parameters + */ + public ServiceException(final String id, final String message, final Throwable cause, final Object... args) { + super(MessageFormat.format(message, args), cause); + this.setId(id); + this.args = args; + } + + /** + * Constructor
+ *

+ *

+ * + * @since + * @param id: exception id. + * @param message: details. + * @param cause: reason. + */ + public ServiceException(final String id, final String message, final Throwable cause) { + super(message, cause); + this.setId(id); + } + + /** + * Constructor
+ *

+ *

+ * + * @since + * @param cause: reason. + */ + public ServiceException(final Throwable cause) { + super(cause); + } + + /** + * Get exceptoin id.
+ * + * @return + * @since + */ + public String getId() { + if(id == null || id.isEmpty()) { + return DEFAULT_ID; + } + return id; + } + + public void setId(final String id) { + this.id = id; + } + + public int getHttpCode() { + return this.httpCode; + } + + public void setHttpCode(final int httpCode) { + this.httpCode = httpCode; + } + + /** + * Obtain the ROA exception handling framework parameters
+ * + * @return exception args. + * @since + */ + public ExceptionArgs getExceptionArgs() { + return exceptionArgs; + } + + public void setExceptionArgs(final ExceptionArgs exceptionArgs) { + this.exceptionArgs = exceptionArgs; + } + + /** + * Gets the parameter information
+ * + * @return parameter list. + * @since + */ + protected Object[] getArgs() { + if(args == null || args.length == 0 || DEFAULT_ID.equals(getId())) { + return new Object[] {}; + } + return args; + } + + @Override + public String toString() { + return "exception.id: " + getId() + "; " + super.toString(); + } + +} diff --git a/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/ReaderHelper.java b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/ReaderHelper.java new file mode 100644 index 0000000..85e4f56 --- /dev/null +++ b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/ReaderHelper.java @@ -0,0 +1,61 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.baseservice.roa.util; + +import org.apache.commons.io.LineIterator; + +import java.io.Reader; + +/** + * Helper for read line.
+ *

+ *

+ * + * @author + * @version 31-May-2016 + */ +public class ReaderHelper { + + private LineIterator ite = null; + + /** + * Constructor
+ *

+ *

+ * + * @since + * @param reader + */ + public ReaderHelper(final Reader reader) { + if(reader != null) { + ite = new LineIterator(reader); + } + + } + + /** + * Gets the next line.
+ * + * @return line if present else null. + * @since + */ + public String getLine() { + if(ite != null && ite.hasNext()) { + return ite.nextLine(); + } + return null; + } +} diff --git a/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/DefaultAsyncCallback.java b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/DefaultAsyncCallback.java new file mode 100644 index 0000000..81adeb6 --- /dev/null +++ b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/DefaultAsyncCallback.java @@ -0,0 +1,37 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.baseservice.roa.util.restclient; + +/** + * Restful Asynchronous call back implentation.
+ *

+ *

+ * + * @author + * @version 28-May-2016 + */ +public class DefaultAsyncCallback implements RestfulAsyncCallback { + + @Override + public void callback(final RestfulResponse response) { + // default implementation. + } + + @Override + public void handleExcepion(final Throwable e) { + // default implementation + } +} diff --git a/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/HttpBaseRest.java b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/HttpBaseRest.java new file mode 100644 index 0000000..3e64937 --- /dev/null +++ b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/HttpBaseRest.java @@ -0,0 +1,273 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.baseservice.roa.util.restclient; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; + +import org.eclipse.jetty.client.Address; +import org.eclipse.jetty.client.HttpClient; +import org.eclipse.jetty.client.HttpExchange; +import org.eclipse.jetty.http.HttpMethods; +import org.openo.baseservice.remoteservice.exception.ServiceException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + *
+ *

+ *

+ * + * @author + * @version Aug 9, 2016 + */ +public abstract class HttpBaseRest implements Restful { + + private static final Logger LOG = LoggerFactory.getLogger(HttpRest.class); + + final AtomicInteger requestId = new AtomicInteger(0); + + protected HttpClient client = null; + + private static final String LOCAL_HOST = "127.0.0.1"; + + static final String HTTP_PATCH = "PATCH"; + + String defaultIP = LOCAL_HOST; + + int defaultPort = -10000; + + int defaultTimeout = 30000; + + final String procenameRouteID = "RouteID-" + System.currentTimeMillis() + "-"; + + /** + * Constructor
+ *

+ *

+ * + * @since + */ + public HttpBaseRest() { + super(); + } + + protected void createHttpClient() { + client = new HttpClient(); + } + + protected RestHttpContentExchange createRestHttpContentExchange(final RestfulAsyncCallback callback) { + final RestHttpContentExchange exchange = new RestHttpContentExchange(true, callback); + exchange.setScheme("http"); + return exchange; + } + + private String encodeParams(final RestfulParametes restParametes) throws ServiceException { + final Map parm = restParametes.getParamMap(); + String value = null; + boolean bHasParma = false; + final StringBuilder builder = new StringBuilder(); + try { + for(final String key : parm.keySet()) { + value = parm.get(key); + if(value == null) { + value = ""; + } + String str; + if(bHasParma) { + str = String.format("&%s=%s", URLEncoder.encode(key, RestfulClientConst.ENCODING), + URLEncoder.encode(value, RestfulClientConst.ENCODING)); + } else { + bHasParma = true; + str = String.format("%s=%s", URLEncoder.encode(key, RestfulClientConst.ENCODING), + URLEncoder.encode(value, RestfulClientConst.ENCODING)); + } + builder.append(str); + } + } catch(final UnsupportedEncodingException ex) { + LOG.error("unsupported encoding: ", ex); + throw new ServiceException("Broken VM does not support UTF-8"); + } + return builder.toString(); + } + + private void processHeader(final RestHttpContentExchange contentExchange, final Map headerMap) { + for(final String key : headerMap.keySet()) { + final String value = headerMap.get(key); + contentExchange.addRequestHeader(key, value); + } + + } + + private void setContentExchangeParams(final RestHttpContentExchange contentExchange) { + final String contentType = contentExchange.getRequestFields().getStringField("Content-Type"); + if(null == contentType || contentType.isEmpty()) { + // application/json;charset=utf-8 + contentExchange.setRequestContentType(RestfulClientConst.APPLICATION_FORM_URLENCODED); + } + final String encoding = contentExchange.getRequestFields().getStringField("Accept-Encoding"); + if(null == encoding || encoding.isEmpty()) { + // compress,gzip + contentExchange.setRequestHeader("Accept-Encoding", "*/*"); + } + contentExchange.setVersion(11); + } + + /** + *
+ * + * @param method + * @param servicePath + * @param restParametes + * @param options + * @param callback + * @return + * @throws ServiceException + * @since + */ + protected RestfulResponse sendHttpRequest(final String method, final String servicePath, + final RestfulParametes restParametes, final RestfulOptions options, final RestfulAsyncCallback callback) + throws ServiceException { + final RestHttpContentExchange contentExchange = createRestHttpContentExchange(callback); + if(null == restParametes) { + return new RestfulResponse(); + } + final String requestTrace = this.getReuqestIdString(); + restParametes.putHttpContextHeader(RestfulClientConst.REQUEST_ID, requestTrace); + + RestfulResponse rsp = null; + try { + contentExchange.setMethod(method); + final String str = encodeParams(restParametes); + final StringBuilder builder = new StringBuilder(); + builder.append(servicePath); + if(str.length() > 0 && (method.equals(HttpMethods.GET) || method.equals(HttpMethods.DELETE) + || method.equals(HttpMethods.HEAD))) { + builder.append('?'); + builder.append(str); + } + setDefaultUrl(contentExchange, options, builder); + processHeader(contentExchange, restParametes.getHeaderMap()); + setContentExchangeParams(contentExchange); + + setPostPutParam(method, restParametes, contentExchange, str); + setTimeout(options, contentExchange); + + client.send(contentExchange); + rsp = callbackExecute(callback, contentExchange); + } catch(final Exception e) { + LOG.error("request reply message have exception:status is " + + RestHttpContentExchange.toState(contentExchange.getStatus())); + throw new ServiceException(e); + } + return rsp; + } + + private void setDefaultUrl(final RestHttpContentExchange contentExchange, final RestfulOptions options, + final StringBuilder url) { + // server + if(url.toString().startsWith("http")) { + contentExchange.setURL(url.toString()); + } else { + String host = defaultIP; + int iPort = defaultPort; + if(options != null) { + host = options.getHost(); + if(host.isEmpty()) { + host = defaultIP; + } + iPort = options.getPort(); + if(iPort == 0) { + iPort = defaultPort; + } + } + // Integer.getInteger(".http.client.maxThread",30) + contentExchange.setAddress(new Address(host, iPort)); + contentExchange.setRequestURI(url.toString()); + } + } + + private String getReuqestIdString() { + if(this.requestId.get() == 0x7FFFFFFF) { + this.requestId.set(1); + } + final int reqId = this.requestId.getAndIncrement(); + final StringBuilder builder = new StringBuilder(this.procenameRouteID); + // time + final SimpleDateFormat dateFormate = new SimpleDateFormat("yyMMdd"); + final SimpleDateFormat timeFormate = new SimpleDateFormat("HHmmss"); + final Date date = Calendar.getInstance().getTime(); + builder.append(dateFormate.format(date) + timeFormate.format(date)); + builder.append('-'); + builder.append(reqId); + return builder.toString(); + } + + private void setPostPutParam(final String method, final RestfulParametes restParametes, + final RestHttpContentExchange contentExchange, final String str) throws UnsupportedEncodingException { + if(HttpMethods.POST.equals(method) || HttpMethods.PUT.equals(method) || HTTP_PATCH.equals(method)) { + ByteArrayInputStream buff; + final String tmpRaw = restParametes.getRawData(); + if(tmpRaw == null) { + buff = new ByteArrayInputStream(str.getBytes(RestfulClientConst.ENCODING)); + } else { + buff = new ByteArrayInputStream(tmpRaw.getBytes(RestfulClientConst.ENCODING)); + } + final int len = buff.available(); + contentExchange.setRequestContentSource(buff); + contentExchange.setRequestHeader("content-length", String.valueOf(len)); + } + } + + private void setTimeout(final RestfulOptions options, final RestHttpContentExchange contentExchange) { + if(options != null) { + final long timeout = options.getRestTimeout(); + if(timeout != 0) { + contentExchange.setTimeout(timeout); + } else { + contentExchange.setTimeout(defaultTimeout); + } + } else { + contentExchange.setTimeout(defaultTimeout); + } + } + + private RestfulResponse callbackExecute(final RestfulAsyncCallback callback, + final RestHttpContentExchange contentExchange) throws InterruptedException, IOException, ServiceException { + if(callback == null) { + final int exchangeState = contentExchange.waitForDone(); + if(exchangeState == HttpExchange.STATUS_COMPLETED) { + return contentExchange.getResponse(); + } else if(exchangeState == HttpExchange.STATUS_EXCEPTED) { + throw new ServiceException( + "request is exception: " + RestHttpContentExchange.toState(HttpExchange.STATUS_EXCEPTED)); + } else if(exchangeState == HttpExchange.STATUS_EXPIRED) { + throw new ServiceException( + "request is expierd: " + RestHttpContentExchange.toState(HttpExchange.STATUS_EXPIRED)); + } + } + return null; + } + +} diff --git a/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/HttpRest.java b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/HttpRest.java new file mode 100644 index 0000000..047f20e --- /dev/null +++ b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/HttpRest.java @@ -0,0 +1,254 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.baseservice.roa.util.restclient; + +import org.eclipse.jetty.client.HttpClient; +import org.eclipse.jetty.http.HttpMethods; +import org.eclipse.jetty.util.thread.QueuedThreadPool; +import org.openo.baseservice.remoteservice.exception.ServiceException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + *
+ *

+ *

+ * + * @author + * @version Aug 9, 2016 + */ +public class HttpRest extends HttpBaseRest { + + private static final Logger LOG = LoggerFactory.getLogger(HttpRest.class); + + /** + * Initializing Rest options.
+ * + * @param options: rest options. + * @throws ServiceException + * @since + */ + public void initHttpRest(final RestfulOptions option) throws ServiceException { + if(option == null) { + client = null; + throw new ServiceException("option is null."); + } + createHttpClient(); + try { + int iValue; + iValue = option.getIntOption(RestfulClientConst.MAX_CONN_PER_ADDR_KEY_NAME); + // max 200 concurrent,connections to every address + client.setMaxConnectionsPerAddress(iValue); + + iValue = option.getIntOption(RestfulClientConst.THREAD_KEY_NAME); + // max threads + client.setThreadPool(new QueuedThreadPool(iValue)); + iValue = option.getIntOption(RestfulClientConst.CONN_TIMEOUT_KEY_NAME); + client.setConnectTimeout(iValue); + iValue = option.getRestTimeout(); + defaultTimeout = iValue; + client.setTimeout(iValue); + + iValue = option.getIntOption(RestfulClientConst.IDLE_TIMEOUT_KEY_NAME); + client.setIdleTimeout(iValue); + iValue = option.getIntOption(RestfulClientConst.MAX_RESPONSE_HEADER_SIZE); + client.setResponseHeaderSize(iValue); + iValue = option.getIntOption(RestfulClientConst.MAX_REQUEST_HEADER_SIZE); + client.setRequestHeaderSize(iValue); + // HttpClient.CONNECTOR_SOCKET + client.setConnectorType(HttpClient.CONNECTOR_SELECT_CHANNEL); + client.start(); + defaultIP = option.getStringOption(RestfulClientConst.HOST_KEY_NAME); + defaultPort = option.getIntOption(RestfulClientConst.PORT_KEY_NAME); + } catch(final Exception e) { + LOG.error("start httpclient error", e); + client = null; + throw new ServiceException("http client init failed."); + } + } + + @Override + public RestfulResponse get(final String servicePath, final RestfulParametes restParametes) throws ServiceException { + return this.sendHttpRequest(HttpMethods.GET, servicePath, restParametes, null, null); + } + + @Override + public RestfulResponse get(final String servicePath, final RestfulParametes restParametes, + final RestfulOptions option) throws ServiceException { + return this.sendHttpRequest(HttpMethods.GET, servicePath, restParametes, option, null); + } + + @Override + public RestfulResponse head(final String servicePath, final RestfulParametes restParametes) + throws ServiceException { + return this.sendHttpRequest(HttpMethods.HEAD, servicePath, restParametes, null, null); + } + + @Override + public RestfulResponse head(final String servicePath, final RestfulParametes restParametes, + final RestfulOptions option) throws ServiceException { + return this.sendHttpRequest(HttpMethods.HEAD, servicePath, restParametes, option, null); + } + + @Override + public void asyncGet(final String servicePath, final RestfulParametes restParametes, + final RestfulAsyncCallback callback) throws ServiceException { + if(callback == null) { + this.sendHttpRequest(HttpMethods.GET, servicePath, restParametes, null, new DefaultAsyncCallback()); + } else { + this.sendHttpRequest(HttpMethods.GET, servicePath, restParametes, null, callback); + } + } + + @Override + public void asyncGet(final String servicePath, final RestfulParametes restParametes, final RestfulOptions option, + final RestfulAsyncCallback callback) throws ServiceException { + if(callback == null) { + this.sendHttpRequest(HttpMethods.GET, servicePath, restParametes, option, new DefaultAsyncCallback()); + } else { + this.sendHttpRequest(HttpMethods.GET, servicePath, restParametes, option, callback); + } + } + + @Override + public RestfulResponse put(final String servicePath, final RestfulParametes restParametes) throws ServiceException { + return this.sendHttpRequest(HttpMethods.PUT, servicePath, restParametes, null, null); + } + + @Override + public RestfulResponse put(final String servicePath, final RestfulParametes restParametes, + final RestfulOptions option) throws ServiceException { + return this.sendHttpRequest(HttpMethods.PUT, servicePath, restParametes, option, null); + } + + @Override + public void asyncPut(final String servicePath, final RestfulParametes restParametes, + final RestfulAsyncCallback callback) throws ServiceException { + if(callback == null) { + this.sendHttpRequest(HttpMethods.PUT, servicePath, restParametes, null, new DefaultAsyncCallback()); + } else { + this.sendHttpRequest(HttpMethods.PUT, servicePath, restParametes, null, callback); + } + } + + @Override + public void asyncPut(final String servicePath, final RestfulParametes restParametes, final RestfulOptions option, + final RestfulAsyncCallback callback) throws ServiceException { + if(callback == null) { + this.sendHttpRequest(HttpMethods.PUT, servicePath, restParametes, option, new DefaultAsyncCallback()); + } else { + this.sendHttpRequest(HttpMethods.PUT, servicePath, restParametes, option, callback); + } + } + + @Override + public RestfulResponse post(final String servicePath, final RestfulParametes restParametes) + throws ServiceException { + return this.sendHttpRequest(HttpMethods.POST, servicePath, restParametes, null, null); + } + + @Override + public RestfulResponse post(final String servicePath, final RestfulParametes restParametes, + final RestfulOptions option) throws ServiceException { + return this.sendHttpRequest(HttpMethods.POST, servicePath, restParametes, option, null); + } + + @Override + public void asyncPost(final String servicePath, final RestfulParametes restParametes, + final RestfulAsyncCallback callback) throws ServiceException { + if(callback == null) { + this.sendHttpRequest(HttpMethods.POST, servicePath, restParametes, null, new DefaultAsyncCallback()); + } else { + this.sendHttpRequest(HttpMethods.POST, servicePath, restParametes, null, callback); + } + } + + @Override + public void asyncPost(final String servicePath, final RestfulParametes restParametes, final RestfulOptions option, + final RestfulAsyncCallback callback) throws ServiceException { + if(callback == null) { + this.sendHttpRequest(HttpMethods.POST, servicePath, restParametes, option, new DefaultAsyncCallback()); + } else { + this.sendHttpRequest(HttpMethods.POST, servicePath, restParametes, option, callback); + } + } + + @Override + public RestfulResponse delete(final String servicePath, final RestfulParametes restParametes) + throws ServiceException { + return this.sendHttpRequest(HttpMethods.DELETE, servicePath, restParametes, null, null); + } + + @Override + public RestfulResponse delete(final String servicePath, final RestfulParametes restParametes, + final RestfulOptions option) throws ServiceException { + return this.sendHttpRequest(HttpMethods.DELETE, servicePath, restParametes, option, null); + } + + @Override + public void asyncDelete(final String servicePath, final RestfulParametes restParametes, + final RestfulAsyncCallback callback) throws ServiceException { + if(callback == null) { + this.sendHttpRequest(HttpMethods.DELETE, servicePath, restParametes, null, new DefaultAsyncCallback()); + } else { + this.sendHttpRequest(HttpMethods.DELETE, servicePath, restParametes, null, callback); + } + } + + @Override + public void asyncDelete(final String servicePath, final RestfulParametes restParametes, final RestfulOptions option, + final RestfulAsyncCallback callback) throws ServiceException { + if(callback == null) { + this.sendHttpRequest(HttpMethods.DELETE, servicePath, restParametes, option, new DefaultAsyncCallback()); + } else { + this.sendHttpRequest(HttpMethods.DELETE, servicePath, restParametes, option, callback); + } + } + + @Override + public RestfulResponse patch(final String servicePath, final RestfulParametes restParametes) + throws ServiceException { + return this.sendHttpRequest(HTTP_PATCH, servicePath, restParametes, null, null); + } + + @Override + public RestfulResponse patch(final String servicePath, final RestfulParametes restParametes, + final RestfulOptions option) throws ServiceException { + return this.sendHttpRequest(HTTP_PATCH, servicePath, restParametes, option, null); + } + + @Override + public void asyncPatch(final String servicePath, final RestfulParametes restParametes, + final RestfulAsyncCallback callback) throws ServiceException { + if(callback == null) { + this.sendHttpRequest(HTTP_PATCH, servicePath, restParametes, null, new DefaultAsyncCallback()); + } else { + this.sendHttpRequest(HTTP_PATCH, servicePath, restParametes, null, callback); + } + } + + @Override + public void asyncPatch(final String servicePath, final RestfulParametes restParametes, final RestfulOptions option, + final RestfulAsyncCallback callback) throws ServiceException { + if(callback == null) { + this.sendHttpRequest(HTTP_PATCH, servicePath, restParametes, option, new DefaultAsyncCallback()); + } else { + this.sendHttpRequest(HTTP_PATCH, servicePath, restParametes, option, callback); + } + } + +} diff --git a/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestHttpContentExchange.java b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestHttpContentExchange.java new file mode 100644 index 0000000..99328a7 --- /dev/null +++ b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestHttpContentExchange.java @@ -0,0 +1,234 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.baseservice.roa.util.restclient; + +import org.openo.baseservice.remoteservice.exception.ServiceException; + +import org.apache.commons.lang.StringUtils; +import org.eclipse.jetty.client.ContentExchange; +import org.eclipse.jetty.client.HttpDestination; +import org.eclipse.jetty.http.HttpFields; +import org.eclipse.jetty.http.HttpHeaders; +import org.eclipse.jetty.io.Buffer; +import org.eclipse.jetty.util.StringUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.charset.Charset; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Map; +import java.util.zip.GZIPInputStream; + +/** + * ContentExchange implementation classe to provide access to response. + *
+ *

+ *

+ * + * @author + * @version 28-May-2016 + */ +public class RestHttpContentExchange extends ContentExchange { + + private static final Logger LOGGER = LoggerFactory.getLogger(RestHttpContentExchange.class); + + private boolean gzip = false; + + private RestfulAsyncCallback callback = null; + + /** + * Constructor
+ *

+ *

+ * + * @since + * @param cacheFields whether to cache response header. + * @param asyncCallback callback method. + */ + RestHttpContentExchange(final boolean cacheFields, final RestfulAsyncCallback asyncCallback) { + super(cacheFields); + this.callback = asyncCallback; + } + + /** + * Extract message. + *
+ * + * @param data GZipped data. + * @return Uncompressed data. + * @throws IOException + * @since + */ + public String decompressGzipToStr(final byte[] data) throws IOException { + if(data == null) { + return ""; + } + ByteArrayInputStream input = null; + GZIPInputStream gzis = null; + InputStreamReader reader = null; + final StringBuilder out = new StringBuilder(); + try { + input = new ByteArrayInputStream(data); + gzis = new GZIPInputStream(input); + reader = new InputStreamReader(gzis, Charset.forName(RestfulClientConst.ENCODING)); + final char[] buff = new char[1024]; + for(int n; (n = reader.read(buff)) != -1;) { + out.append(new String(buff, 0, n)); + } + } finally { + if(reader != null) { + try { + reader.close(); + } catch(final IOException e) { + LOGGER.error("decompress Gzip reader exception:", e); + } + } + if(gzis != null) { + try { + gzis.close(); + } catch(final IOException e) { + LOGGER.error("decompress Gzip exception:", e); + } + } + if(input != null) { + try { + input.close(); + } catch(final IOException e) { + LOGGER.error("decompress Gzip input exception:", e); + } + } + } + return out.toString(); + + } + + /** + * View response headers Content-Encoding values if you need to extract data.
+ * + * @param name buffer + * @param value value + * @throws IOException + * @since + */ + @Override + protected synchronized void onResponseHeader(final Buffer name, final Buffer value) throws IOException { + super.onResponseHeader(name, value); + final int header = HttpHeaders.CACHE.getOrdinal(name); + if(header == HttpHeaders.CONTENT_ENCODING_ORDINAL) { + final String encoding = StringUtil.asciiToLowerCase(value.toString()); + gzip = encoding != null && StringUtils.contains(encoding, "gzip"); + } + + } + + @Override + protected void onResponseComplete() throws IOException { + if(LOGGER.isInfoEnabled()) { + LOGGER.info("Response has Complete:" + "path:" + this.getRequestURI().replace("\n", "0x0A")); + } + super.onResponseComplete(); + if(callback != null) { + final RestfulResponse rsp = getResponse(); + callback.callback(rsp); + } + } + + @Override + protected void onRequestCommitted() throws IOException { + if(LOGGER.isInfoEnabled()) { + LOGGER.info("Request Header has been send:" + "path:" + this.getRequestURI().replace("\n", "0x0A")); + } + super.onRequestCommitted(); + } + + @Override + protected void onRequestComplete() throws IOException { + if(LOGGER.isInfoEnabled()) { + LOGGER.info("Request has bend send complete:" + "path:" + this.getRequestURI().replace("\n", "0x0A")); + } + super.onRequestComplete(); + } + + @Override + protected void onException(final Throwable x) { + LOGGER.warn("onException:", x); + super.onException(x); + if(callback != null) { + callback.handleExcepion(x); + } + } + + @Override + protected void onConnectionFailed(final Throwable x) { + LOGGER.warn("onConnectionFailed:", x); + super.onConnectionFailed(x); + if(callback != null) { + callback.handleExcepion(x); + } + + } + + @Override + protected void expire(final HttpDestination destination) { + super.expire(destination); + if(callback != null) { + callback.handleExcepion(new ServiceException("request is expired, status:" + toState(getStatus()))); + } + } + + public boolean isGzip() { + return gzip; + } + + /** + * Get the response as RestfulResponse. + *
+ * + * @return response object. + * @throws IOException + * @since + */ + public RestfulResponse getResponse() throws IOException { + final RestfulResponse rsp = new RestfulResponse(); + rsp.setStatus(this.getResponseStatus()); + if(isGzip()) { + final String responseString = decompressGzipToStr(getResponseContentBytes()); + rsp.setResponseJson(responseString); + } else { + rsp.setResponseJson(this.getResponseContent()); + } + + final HttpFields field = this.getResponseFields(); + if(field != null) { + final Map header = new HashMap<>(); + + final Enumeration names = field.getFieldNames(); + for(final Enumeration e = names; e.hasMoreElements();) { + final String fieldName = e.nextElement(); + final String fieldValue = field.getStringField(fieldName); + header.put(fieldName, fieldValue); + } + + rsp.setRespHeaderMap(header); + } + return rsp; + } + +} diff --git a/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/Restful.java b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/Restful.java new file mode 100644 index 0000000..8527e68 --- /dev/null +++ b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/Restful.java @@ -0,0 +1,298 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.baseservice.roa.util.restclient; + +import org.openo.baseservice.remoteservice.exception.ServiceException; + +/** + * ReSTful method interface.
+ *

+ *

+ * + * @author + * @version 28-May-2016 + */ +public interface Restful { + + /** + * Http GET method.
+ * + * @param servicePath: request path. + * @param restParametes: query parameters. + * @return response. + * @throws ServiceException + * @since + */ + RestfulResponse get(String servicePath, RestfulParametes restParametes) throws ServiceException; + + /** + * Http HEAD method.
+ * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @param options: request options. + * @return response. + * @throws ServiceException + * @since + */ + RestfulResponse head(String servicePath, RestfulParametes restParametes, RestfulOptions options) + throws ServiceException; + + /** + * Http HEAD method.
+ * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @return response. + * @throws ServiceException + * @since + */ + RestfulResponse head(String servicePath, RestfulParametes restParametes) throws ServiceException; + + /** + * Http GET method.
+ * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @param options: request options. + * @return response. + * @throws ServiceException + * @since + */ + RestfulResponse get(String servicePath, RestfulParametes restParametes, RestfulOptions options) + throws ServiceException; + + /** + * Asynchronouse GET request.
+ * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @param callback: response callback method. + * @throws ServiceException + * @since + */ + void asyncGet(String servicePath, RestfulParametes restParametes, RestfulAsyncCallback callback) + throws ServiceException; + + /** + * Asynchronouse GET request.
+ * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @param options: request options. + * @param callback: response callback method. + * @throws ServiceException + * @since + */ + void asyncGet(String servicePath, RestfulParametes restParametes, RestfulOptions options, + RestfulAsyncCallback callback) throws ServiceException; + + /** + * Http PUT method.
+ * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @return response. + * @throws ServiceException + * @since + */ + RestfulResponse put(String servicePath, RestfulParametes restParametes) throws ServiceException; + + /** + * Http PUT method.
+ * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @param options: request options. + * @return response. + * @throws ServiceException + * @since + */ + RestfulResponse put(String servicePath, RestfulParametes restParametes, RestfulOptions options) + throws ServiceException; + + /** + * Asynchronouse PUT request.
+ * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @param callback: response callback method. + * @throws ServiceException + * @since + */ + void asyncPut(String servicePath, RestfulParametes restParametes, RestfulAsyncCallback callback) + throws ServiceException; + + /** + * Asynchronouse PUT request.
+ * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @param options: request options. + * @param callback: response callback method. + * @throws ServiceException + * @since + */ + void asyncPut(String servicePath, RestfulParametes restParametes, RestfulOptions options, + RestfulAsyncCallback callback) throws ServiceException; + + /** + * Http POST method.
+ * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @return response. + * @throws ServiceException + * @since + */ + RestfulResponse post(String servicePath, RestfulParametes restParametes) throws ServiceException; + + /** + * Http POST method.
+ * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @param options: request options. + * @return response. + * @throws ServiceException + * @since + */ + RestfulResponse post(String servicePath, RestfulParametes restParametes, RestfulOptions options) + throws ServiceException; + + /** + * Asynchronouse POST request.
+ * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @param callback: response callback method. + * @throws ServiceException + * @since + */ + void asyncPost(String servicePath, RestfulParametes restParametes, RestfulAsyncCallback callback) + throws ServiceException; + + /** + * Asynchronouse POST request.
+ * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @param options: request options. + * @param callback: response callback method. + * @throws ServiceException + * @since + */ + void asyncPost(String servicePath, RestfulParametes restParametes, RestfulOptions options, + RestfulAsyncCallback callback) throws ServiceException; + + /** + * Http DELETE method.
+ * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @return response. + * @throws ServiceException + * @since + */ + RestfulResponse delete(String servicePath, RestfulParametes restParametes) throws ServiceException; + + /** + * Http DELETE method.
+ * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @param options: request options. + * @return response. + * @throws ServiceException + * @since + */ + RestfulResponse delete(String servicePath, RestfulParametes restParametes, RestfulOptions options) + throws ServiceException; + + /** + * Asynchronouse DELETE request.
+ * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @param callback: response callback method. + * @throws ServiceException + * @since + */ + void asyncDelete(String servicePath, RestfulParametes restParametes, RestfulAsyncCallback callback) + throws ServiceException; + + /** + * Asynchronouse DELETE request.
+ * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @param options: request options. + * @param callback: response callback method. + * @throws ServiceException + * @since + */ + void asyncDelete(String servicePath, RestfulParametes restParametes, RestfulOptions options, + RestfulAsyncCallback callback) throws ServiceException; + + /** + * Http PATCH method.
+ * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @return response. + * @throws ServiceException + * @since + */ + RestfulResponse patch(String servicePath, RestfulParametes restParametes) throws ServiceException; + + /** + * Http PATCH method.
+ * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @param options: request options. + * @return response. + * @throws ServiceException + * @since + */ + RestfulResponse patch(String servicePath, RestfulParametes restParametes, RestfulOptions options) + throws ServiceException; + + /** + * Asynchronouse PATCH request.
+ * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @param callback: response callback method. + * @throws ServiceException + * @since + */ + void asyncPatch(String servicePath, RestfulParametes restParametes, RestfulAsyncCallback callback) + throws ServiceException; + + /** + * Asynchronouse PATCH request.
+ * + * @param servicePath: request path. + * @param restParametes: request parameters. + * @param options: request options. + * @param callback: response callback method. + * @throws ServiceException + * @since + */ + void asyncPatch(String servicePath, RestfulParametes restParametes, RestfulOptions options, + RestfulAsyncCallback callback) throws ServiceException; +} diff --git a/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulAsyncCallback.java b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulAsyncCallback.java new file mode 100644 index 0000000..bf461c9 --- /dev/null +++ b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulAsyncCallback.java @@ -0,0 +1,43 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.baseservice.roa.util.restclient; + +/** + * Callback interface for ReST calls.
+ *

+ *

+ * + * @author + * @version 28-May-2016 + */ +public interface RestfulAsyncCallback { + + /** + * Response callback.
+ * + * @param response: response of ReST call. + * @since + */ + void callback(RestfulResponse response); + + /** + * Exceptoin callback.
+ * + * @param e: ReST call exception. + * @since + */ + void handleExcepion(Throwable e); +} diff --git a/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulClientConst.java b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulClientConst.java new file mode 100644 index 0000000..3741c20 --- /dev/null +++ b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulClientConst.java @@ -0,0 +1,63 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.baseservice.roa.util.restclient; + +/** + * Constants for ReST client.
+ *

+ *

+ * + * @author + * @version 28-May-2016 + */ +public class RestfulClientConst { + + /** -- json Ecode -- **/ + public static final String APPLICATION_FORM_JSON_EBCIDED = "application/json"; + + /** + * urlencode + */ + public static final String APPLICATION_FORM_URLENCODED = "application/x-www-form-urlencoded; charset=UTF-8"; + + public static final String ENCODING = "UTF-8"; + + public static final String SERVER_KEY_NAME = "defaultServer"; + + public static final String HOST_KEY_NAME = "host"; + + public static final String PORT_KEY_NAME = "port"; + + public static final String CONN_TIMEOUT_KEY_NAME = "ConnectTimeout"; + + public static final String THREAD_KEY_NAME = "thread"; + + public static final String IDLE_TIMEOUT_KEY_NAME = "idletimeout"; + + public static final String TIMEOUT_KEY_NAME = "timeout"; + + public static final String MAX_CONN_PER_ADDR_KEY_NAME = "maxConnectionPerAddr"; + + public static final String REQUEST_ID = "x-request-id"; + + public static final String MAX_RESPONSE_HEADER_SIZE = "responseHeaderSize"; + + public static final String MAX_REQUEST_HEADER_SIZE = "requestHeaderSize"; + + private RestfulClientConst() { + + } +} diff --git a/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulConfigure.java b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulConfigure.java new file mode 100644 index 0000000..3ce6859 --- /dev/null +++ b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulConfigure.java @@ -0,0 +1,162 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.baseservice.roa.util.restclient; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +import org.openo.baseservice.roa.util.ReaderHelper; +import org.openo.baseservice.util.impl.SystemEnvVariablesFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import net.sf.json.JSONObject; + +/** + * Rest client options.
+ *

+ *

+ * + * @author + * @version 28-May-2016 + */ +public class RestfulConfigure { + + private static final Logger LOG = LoggerFactory.getLogger(RestfulConfigure.class); + + private RestfulOptions options = null; + + /** + * Constructor
+ *

+ * Use the default path initialization http Rest options. + *

+ * + * @since + */ + public RestfulConfigure() { + final String config = "/etc/conf/restclient.json"; + final String approot = SystemEnvVariablesFactory.getInstance().getAppRoot(); + final StringBuilder extendSetting = new StringBuilder(); + + if(approot != null) { + extendSetting.append(approot); + extendSetting.append(config); + } else { + extendSetting.append(System.getProperty("user.dir")); + extendSetting.append(config); + } + + final String configfile = extendSetting.toString(); + initRestConf(configfile); + } + + /** + * Constructor
+ *

+ * Use the specified file to initialize http Rest options. + *

+ * + * @since + * @param configfile + */ + public RestfulConfigure(final String configfile) { + initRestConf(configfile); + } + + public RestfulOptions getOptions() { + return options; + } + + private void initRestConf(final String configfile) { + options = getDefaultOptions(); + + final JSONObject obj = loadJsonFromFile(configfile); + if(obj != null) { + if(obj.has(RestfulClientConst.SERVER_KEY_NAME)) { + final JSONObject server = obj.getJSONObject(RestfulClientConst.SERVER_KEY_NAME); + setStringOption(server, RestfulClientConst.HOST_KEY_NAME); + setIntOption(server, RestfulClientConst.PORT_KEY_NAME); + } + setIntOption(obj, RestfulClientConst.CONN_TIMEOUT_KEY_NAME); + setIntOption(obj, RestfulClientConst.THREAD_KEY_NAME); + setIntOption(obj, RestfulClientConst.IDLE_TIMEOUT_KEY_NAME); + setIntOption(obj, RestfulClientConst.TIMEOUT_KEY_NAME); + setIntOption(obj, RestfulClientConst.MAX_CONN_PER_ADDR_KEY_NAME); + setIntOption(obj, RestfulClientConst.MAX_RESPONSE_HEADER_SIZE); + setIntOption(obj, RestfulClientConst.MAX_REQUEST_HEADER_SIZE); + } else { + LOG.error("failed to load json from " + configfile); + } + } + + private void setStringOption(final JSONObject json, final String key) { + if(json.has(key)) { + options.setOption(key, json.getString(key)); + } + } + + private void setIntOption(final JSONObject json, final String key) { + if(json.has(key)) { + options.setOption(key, json.getInt(key)); + } + } + + private RestfulOptions getDefaultOptions() { + options = new RestfulOptions(); + options.setOption(RestfulClientConst.CONN_TIMEOUT_KEY_NAME, 3000); + options.setOption(RestfulClientConst.THREAD_KEY_NAME, 200); + options.setOption(RestfulClientConst.IDLE_TIMEOUT_KEY_NAME, 30000); + options.setOption(RestfulClientConst.TIMEOUT_KEY_NAME, 30000); + options.setOption(RestfulClientConst.MAX_CONN_PER_ADDR_KEY_NAME, 50); + options.setOption(RestfulClientConst.MAX_RESPONSE_HEADER_SIZE, 20 * 1024); + options.setOption(RestfulClientConst.MAX_REQUEST_HEADER_SIZE, 20 * 1024); + return options; + } + + private JSONObject loadJsonFromFile(final String filePath) { + final File file = new File(filePath); + if((!file.exists()) || (!file.isFile())) { + LOG.error(filePath + "isn't exist."); + return null; + } + BufferedReader reader = null; + final StringBuilder jsonstr = new StringBuilder(); + JSONObject jo = null; + try { + reader = new BufferedReader(new FileReader(file)); + final ReaderHelper rHelpper = new ReaderHelper(reader); + String tempString = null; + while((tempString = rHelpper.getLine()) != null) { + jsonstr.append(tempString); + } + jo = JSONObject.fromObject(jsonstr.toString()); + } catch(final IOException e) { + LOG.error("load file exception:" + e); + } finally { + if(reader != null) { + try { + reader.close(); + } catch(final IOException e) { + LOG.error("close error.", e); + } + } + } + return jo; + } +} diff --git a/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulFactory.java b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulFactory.java new file mode 100644 index 0000000..5b94374 --- /dev/null +++ b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulFactory.java @@ -0,0 +1,95 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.baseservice.roa.util.restclient; + +import org.openo.baseservice.remoteservice.exception.ServiceException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.HashMap; +import java.util.Map; + +/** + * RestFul instance factory.
+ *

+ *

+ * + * @author + * @version 28-May-2016 + */ +public class RestfulFactory { + + /** + * https protocol. + */ + public static final String PROTO_HTTPS = "https"; + + /** + * http protocol. + */ + public static final String PROTO_HTTP = "http"; + + private static final Logger LOG = LoggerFactory.getLogger(RestfulFactory.class); + + private static final Map INSTANCES = new HashMap<>(2); + + private RestfulFactory() { + + } + + /** + * Get RESTful instance. This method returns a singleton instance. + *
+ * + * @param protocol protocol. currently only support 'http'. + * @return restful instance. + * @since + */ + public static synchronized Restful getRestInstance(final String protocol) { + Restful rest = INSTANCES.get(protocol); + if(rest != null) { + return rest; + } + if(PROTO_HTTP.equals(protocol)) { + rest = createHttpRest(); + INSTANCES.put(protocol, rest); + } + return rest; + } + + private static Restful createHttpRest() { + final HttpRest rest = new HttpRest(); + setRestOption(rest, null); + return rest; + } + + private static void setRestOption(final HttpRest rest, final String restoptionfile) { + try { + RestfulConfigure config; + if(restoptionfile == null || restoptionfile.isEmpty()) { + config = new RestfulConfigure(); + } else { + config = new RestfulConfigure(restoptionfile); + } + + final RestfulOptions option = config.getOptions(); + rest.initHttpRest(option); + } catch(final ServiceException e) { + LOG.error("init http client exception: ", e); + } + } +} diff --git a/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulOptions.java b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulOptions.java new file mode 100644 index 0000000..6e5812f --- /dev/null +++ b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulOptions.java @@ -0,0 +1,170 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.baseservice.roa.util.restclient; + +import java.util.HashMap; +import java.util.Map; + +/** + * Options for Rest communication.
+ *

+ *

+ * + * @author + * @version 28-May-2016 + */ +public class RestfulOptions { + + public static final String REST_OPTIONS_NAME_TIMEOUT = "timeout"; + + public static final int REST_OPTIONS_TIMEOUT_MAXTIMEOUT = 1800000; + + private final Map optionsMap = new HashMap<>(); + + /** + * Get port.
+ * + * @return port. + * @since + */ + public int getPort() { + final Object obj = this.getOption(RestfulClientConst.PORT_KEY_NAME); + if(null == obj) { + return 0; + } + return ((Integer)obj).intValue(); + } + + /** + * Set port.
+ * + * @param port port to set. + * @return + * @since + */ + public boolean setPort(final int port) { + this.setOption(RestfulClientConst.PORT_KEY_NAME, port); + return true; + } + + /** + * Get host.
+ * + * @return the host. + * @since + */ + public String getHost() { + final Object obj = this.getOption(RestfulClientConst.HOST_KEY_NAME); + if(null == obj) { + return ""; + } + return (String)obj; + } + + /** + * Set host.
+ * + * @param host host to set. + * @return + * @since + */ + public boolean setHost(final String host) { + this.setOption(RestfulClientConst.HOST_KEY_NAME, host); + return true; + } + + /** + * Set rest time-out.
+ * + * @param timeout time-out to set in seconds. + * @return + * @since + */ + public boolean setRestTimeout(final int timeout) { + if(0 < timeout && REST_OPTIONS_TIMEOUT_MAXTIMEOUT >= timeout) { + this.setOption(REST_OPTIONS_NAME_TIMEOUT, timeout); + return true; + } + return false; + } + + /** + * Get time-out.
+ * + * @return time-out in seconds. + * @since + */ + public int getRestTimeout() { + final Object obj = this.getOption(REST_OPTIONS_NAME_TIMEOUT); + if(null == obj) { + return 0; + } + return ((Integer)obj).intValue(); + } + + /** + * Get specified option.
+ * + * @param optionName option name. + * @return option + * @since + */ + public Object getOption(final String optionName) { + return optionsMap.get(optionName); + } + + /** + * Get option value as integer.
+ * + * @param optionName option name. + * @return option value as int. + * @since + */ + public int getIntOption(final String optionName) { + final Object obj = this.getOption(optionName); + if(null == obj) { + return 0; + } + return ((Integer)obj).intValue(); + } + + /** + * Get option value as string.
+ * + * @param optionName option name. + * @return option value as string. + * @since + */ + public String getStringOption(final String optionName) { + final Object obj = this.getOption(optionName); + if(null == obj) { + return ""; + } + return (String)obj; + } + + /** + * Set option.
+ * + * @param option option name. + * @param optionsValue option value. + * @return + * @since + */ + public Object setOption(final String option, final Object optionsValue) { + return optionsMap.put(option, optionsValue); + } +} diff --git a/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulParametes.java b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulParametes.java new file mode 100644 index 0000000..aea8753 --- /dev/null +++ b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulParametes.java @@ -0,0 +1,155 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.baseservice.roa.util.restclient; + +import java.util.HashMap; +import java.util.Map; + +/** + *
+ *

+ *

+ * + * @author + * @version Aug 9, 2016 + */ +public class RestfulParametes { + + private Map paramMap = new HashMap<>(); + + private Map headerMap = new HashMap<>(); + + private String rawData = null; + + /** + *
+ * + * @param key + * @return + * @since + */ + public String get(final String key) { + return paramMap.get(key); + } + + /** + *
+ * + * @param data + * @since + */ + public void setRawData(final String data) { + this.rawData = data; + } + + /** + *
+ * + * @return + * @since + */ + public String getRawData() { + return this.rawData; + } + + /** + *
+ * + * @param key + * @param value + * @return + * @since + */ + public String put(final String key, final String value) { + return paramMap.put(key, value); + } + + /** + *
+ * + * @param key + * @param value + * @return + * @since + */ + public String putHttpContextHeader(final String key, final String value) { + return headerMap.put(key, value); + } + + /** + *
+ * + * @param key + * @param value + * @return + * @since + */ + public String putHttpContextHeader(final String key, final int value) { + return this.putHttpContextHeader(key, String.valueOf(value)); + } + + /** + *
+ * + * @param key + * @return + * @since + */ + public String getHttpContextHeader(final String key) { + return headerMap.get(key); + } + + /** + *
+ * + * @return + * @since + */ + public Map getParamMap() { + return paramMap; + } + + /** + *
+ * + * @param paramMap + * @since + */ + public void setParamMap(final Map paramMap) { + this.paramMap = paramMap; + } + + /** + *
+ * + * @return + * @since + */ + public Map getHeaderMap() { + return this.headerMap; + } + + /** + *
+ * + * @param headerMap + * @since + */ + public void setHeaderMap(final Map headerMap) { + this.headerMap = headerMap; + } +} diff --git a/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulResponse.java b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulResponse.java new file mode 100644 index 0000000..25105b7 --- /dev/null +++ b/wso2/rest-client/src/main/java/org/openo/baseservice/roa/util/restclient/RestfulResponse.java @@ -0,0 +1,144 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.baseservice.roa.util.restclient; + +import java.util.Map; + +/** + * Response for RestFul requests.
+ *

+ *

+ * + * @author + * @version 28-May-2016 + */ +public class RestfulResponse { + + private String responseContent; + + private int status = -1; + + private Map respHeaderMap = null; + + /** + *
+ * + * @return + * @since + */ + public int getStatus() { + return status; + } + + /** + *
+ * + * @param status + * @since + */ + public void setStatus(final int status) { + this.status = status; + } + + /** + *
+ * + * @return + * @since + */ + public Map getRespHeaderMap() { + return respHeaderMap; + } + + /** + *
+ * + * @param header + * @since + */ + public void setRespHeaderMap(final Map header) { + this.respHeaderMap = header; + } + + /** + * Get response header value as integer.
+ * + * @param key header param name. + * @return header param value as integer. (-1 if error) + * @since + */ + public int getRespHeaderInt(final String key) { + if(respHeaderMap != null) { + final String result = respHeaderMap.get(key); + if(result != null) { + return Integer.parseInt(result); + } + } + return -1; + } + + /** + * Get response header value as long.
+ * + * @param key header param name. + * @return value as long. -1 if no value. + * @since + */ + public long getRespHeaderLong(final String key) { + if(respHeaderMap != null) { + final String result = respHeaderMap.get(key); + if(result != null) { + return Long.parseLong(result); + } + } + return -1; + } + + /** + * Get http header as string.
+ * + * @param key header name. + * @return header value. + * @since + */ + public String getRespHeaderStr(final String key) { + if(respHeaderMap != null) { + return respHeaderMap.get(key); + } + return null; + } + + /** + *
+ * + * @return + * @since + */ + public String getResponseContent() { + return responseContent; + } + + /** + *
+ * + * @param responseString + * @since + */ + public void setResponseJson(final String responseString) { + this.responseContent = responseString; + } +} diff --git a/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/ReaderHelperTest.java b/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/ReaderHelperTest.java new file mode 100644 index 0000000..9922476 --- /dev/null +++ b/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/ReaderHelperTest.java @@ -0,0 +1,116 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.baseservice.roa.util; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.io.Reader; +import java.io.StringReader; + +import junit.framework.Assert; + +/** + *
+ *

+ *

+ * + * @author + * @version 12-Jun-2016 + */ +public class ReaderHelperTest { + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @Before + public void setUp() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @After + public void tearDown() throws Exception { + } + + /** + * Test method for {@link org.openo.baseservice.util.inf.ReaderHelper#getLine()}. + */ + @Test + public void testGetLine() { + final String message = "hello.. how are you?"; + final Reader reader = new StringReader(message); + final ReaderHelper helper = new ReaderHelper(reader); + final String actual = helper.getLine(); + Assert.assertEquals(message, actual); + } + + /** + * Test method for {@link org.openo.baseservice.util.inf.ReaderHelper#getLine()}. + */ + @Test + public void testGetLineMultiLine() { + final String line1 = "hello.. how are you?"; + final String line2 = "I am fine."; + final Reader reader = new StringReader(line1 + System.lineSeparator() + line2); + final ReaderHelper helper = new ReaderHelper(reader); + String actual = helper.getLine(); + Assert.assertEquals(line1, actual); + actual = helper.getLine(); + Assert.assertEquals(line2, actual); + actual = helper.getLine(); + Assert.assertEquals(null, actual); + } + + @Test + public void testGetLineNull() { + final ReaderHelper helper = new ReaderHelper(null); + final String actual = helper.getLine(); + Assert.assertEquals(null, actual); + + } + +} diff --git a/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/TestServiceUtil.java b/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/TestServiceUtil.java new file mode 100644 index 0000000..d99d562 --- /dev/null +++ b/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/TestServiceUtil.java @@ -0,0 +1,92 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.baseservice.roa.util; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + *
+ *

+ *

+ * + * @author + * @version 13-Jun-2016 + */ +public class TestServiceUtil { + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @Before + public void setUp() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @After + public void tearDown() throws Exception { + } + + /** + *
+ * + * @since + */ + @Test + public void testGetServiceHost() { + } + + /** + *
+ * + * @since + */ + @Test + public void testGetServicePort() { + } +} diff --git a/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestHttpRest.java b/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestHttpRest.java new file mode 100644 index 0000000..47d4ac8 --- /dev/null +++ b/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestHttpRest.java @@ -0,0 +1,1179 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.baseservice.roa.util.restclient; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.lang.reflect.Field; +import java.net.URLEncoder; + +import org.eclipse.jetty.client.HttpClient; +import org.eclipse.jetty.client.HttpExchange; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.openo.baseservice.remoteservice.exception.ServiceException; + +import mockit.Mock; +import mockit.MockUp; +import mockit.Mocked; +import mockit.NonStrictExpectations; +import mockit.integration.junit4.JMockit; + +/** + *
+ *

+ *

+ * + * @author + * @version 13-Jun-2016 + */ +@RunWith(JMockit.class) +public class TestHttpRest { + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @Before + public void setUp() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @After + public void tearDown() throws Exception { + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + public void testInitHttpRest() throws Exception { + final RestfulOptions options = new RestfulOptions(); + new MockUp() { + + @Mock + public void doStart() { + System.out.println("started"); + } + }; + final HttpRest httpRest = new HttpRest(); + httpRest.initHttpRest(options); + final Field httpClient = HttpBaseRest.class.getDeclaredField("client"); + httpClient.setAccessible(true); + Assert.assertNotNull(httpClient.get(httpRest)); + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + public void testInitHttpRestExcpetion() throws Exception { + final RestfulOptions options = new RestfulOptions(); + new MockUp() { + + @Mock + public void doStart() throws Exception { + throw new Exception(); + } + }; + final HttpRest httpRest = new HttpRest(); + thrown.expect(ServiceException.class); + thrown.expectMessage("http client init failed."); + httpRest.initHttpRest(options); + final Field httpClient = HttpRest.class.getDeclaredField("client"); + httpClient.setAccessible(true); + Assert.assertNull(httpClient.get(httpRest)); + System.out.println("finished"); + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + public void testInitHttpRestNull() throws Exception { + final HttpRest httpRest = new HttpRest(); + thrown.expect(ServiceException.class); + thrown.expectMessage("option is null."); + httpRest.initHttpRest(null); + } + + /** + *
+ * + * @throws NoSuchFieldException + * @throws Exception + * @since + */ + @Test + public void testCreateRestHttpContentExchange() throws NoSuchFieldException, Exception { + final HttpBaseRest httpRest = new HttpRest(); + final RestfulAsyncCallback callback = new RestfulAsyncCallback() { + + @Override + public void callback(final RestfulResponse response) { + + } + + @Override + public void handleExcepion(final Throwable e) { + + } + + }; + final RestHttpContentExchange exchange = httpRest.createRestHttpContentExchange(callback); + assertNotNull(exchange); + final Field callbackField = RestHttpContentExchange.class.getDeclaredField("callback"); + assertNotNull(callbackField); + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + public void testGetStringRestfulParametes() throws Exception { + final RestfulOptions options = new RestfulOptions(); + + final HttpRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone"); + return HttpExchange.STATUS_COMPLETED; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_COMPLETED); + return response; + } + + }; + final RestfulParametes parametes = new RestfulParametes(); + parametes.put("id", "1234"); + parametes.put("name", "some-name"); + parametes.put("address", null); + parametes.putHttpContextHeader("Content-Type", "application/json"); + parametes.putHttpContextHeader("Accept-Encoding", "*/*"); + final RestfulResponse response = httpRest.get("path/to/service", parametes); + assertEquals(HttpExchange.STATUS_COMPLETED, response.getStatus()); + + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + public void testGetStringRestfulParametesRestfulOptions() throws Exception { + final RestfulOptions options = new RestfulOptions(); + + final HttpRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone"); + return HttpExchange.STATUS_COMPLETED; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_COMPLETED); + return response; + } + + }; + final RestfulResponse response = httpRest.get("path/to/service", new RestfulParametes(), options); + assertEquals(HttpExchange.STATUS_COMPLETED, response.getStatus()); + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + public void testGetStringRestfulParametesEncodeError() throws Exception { + final RestfulOptions options = new RestfulOptions(); + + final HttpRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone"); + return HttpExchange.STATUS_COMPLETED; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_COMPLETED); + return response; + } + + }; + + new NonStrictExpectations() { + + @Mocked + URLEncoder encoder; + + { + URLEncoder.encode(anyString, RestfulClientConst.ENCODING); + result = new UnsupportedEncodingException(); + } + + }; + + thrown.expect(ServiceException.class); + thrown.expectMessage("Broken VM does not support"); + + final RestfulParametes parametes = new RestfulParametes(); + parametes.put("id", "1234"); + parametes.put("name", "some-name"); + parametes.put("address", null); + parametes.putHttpContextHeader("Content-Type", "application/json"); + parametes.putHttpContextHeader("Accept-Encoding", "*/*"); + final RestfulResponse response = httpRest.get("path/to/service", parametes); + assertEquals(HttpExchange.STATUS_COMPLETED, response.getStatus()); + + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + public void testHeadStringRestfulParametes() throws Exception { + final RestfulOptions options = new RestfulOptions(); + + final HttpRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone"); + return HttpExchange.STATUS_COMPLETED; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_COMPLETED); + return response; + } + + }; + final RestfulParametes parametes = new RestfulParametes(); + parametes.put("id", "1234"); + parametes.put("name", "some-name"); + parametes.put("address", null); + parametes.putHttpContextHeader("Content-Type", ""); + parametes.putHttpContextHeader("Accept-Encoding", ""); + final RestfulResponse response = httpRest.head("path/to/service", parametes); + assertEquals(HttpExchange.STATUS_COMPLETED, response.getStatus()); + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + public void testHeadStringRestfulParametesRestfulOptions() throws Exception { + final RestfulOptions options = new RestfulOptions(); + + final HttpRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone"); + return HttpExchange.STATUS_COMPLETED; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_COMPLETED); + return response; + } + + }; + final RestfulParametes parametes = new RestfulParametes(); + parametes.put("id", "1234"); + parametes.put("name", "some-name"); + parametes.put("address", null); + parametes.putHttpContextHeader("Content-Type", ""); + parametes.putHttpContextHeader("Accept-Encoding", ""); + final RestfulResponse response = httpRest.head("path/to/service", parametes, options); + assertEquals(HttpExchange.STATUS_COMPLETED, response.getStatus()); + } + + /** + *
+ * + * @param options + * @return + * @throws ServiceException + * @since + */ + private HttpRest getHttpRest(final RestfulOptions options) throws ServiceException { + final HttpRest httpRest = new HttpRest(); + { + new MockUp() { + + @Mock + public void doStart() { + System.out.println("started"); + } + + @Mock + public void send(final HttpExchange exchange) throws IOException { + System.out.println("send"); + } + }; + httpRest.initHttpRest(options); + + } + return httpRest; + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + public void testAsyncGetStringRestfulParametesRestfulAsyncCallback() throws Exception { + final RestfulOptions options = new RestfulOptions(); + + final HttpRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone"); + return HttpExchange.STATUS_COMPLETED; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_COMPLETED); + return response; + } + + }; + + final RestfulAsyncCallback callback = new RestfulAsyncCallback() { + + @Override + public void callback(final RestfulResponse response) { + System.out.println("callback called."); + + } + + @Override + public void handleExcepion(final Throwable e) { + + System.out.println("handleExcepion called."); + } + + }; + httpRest.asyncGet("path/to/service", new RestfulParametes(), callback); + httpRest.asyncGet("path/to/service", new RestfulParametes(), null); + } + + /** + *
+ * + * @throws ServiceException + * @since + */ + @Test + public void testAsyncGetStringRestfulParametesRestfulOptionsRestfulAsyncCallback() throws ServiceException { + final RestfulOptions options = new RestfulOptions(); + + final HttpRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone"); + return HttpExchange.STATUS_COMPLETED; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_COMPLETED); + return response; + } + + }; + + final RestfulAsyncCallback callback = new RestfulAsyncCallback() { + + @Override + public void callback(final RestfulResponse response) { + System.out.println("callback called."); + + } + + @Override + public void handleExcepion(final Throwable e) { + + System.out.println("handleExcepion called."); + } + + }; + httpRest.asyncGet("path/to/service", new RestfulParametes(), new RestfulOptions(), callback); + httpRest.asyncGet("path/to/service", new RestfulParametes(), new RestfulOptions(), null); + } + + /** + *
+ * + * @throws ServiceException + * @since + */ + @Test + public void testPutStringRestfulParametes() throws ServiceException { + final RestfulOptions options = new RestfulOptions(); + + final HttpRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone"); + return HttpExchange.STATUS_COMPLETED; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_COMPLETED); + return response; + } + + }; + final RestfulParametes parametes = new RestfulParametes(); + parametes.put("id", "1234"); + parametes.put("name", "some-name"); + parametes.put("address", null); + parametes.putHttpContextHeader("Content-Type", ""); + parametes.putHttpContextHeader("Accept-Encoding", ""); + final RestfulResponse response = httpRest.put("path/to/service", parametes); + assertEquals(HttpExchange.STATUS_COMPLETED, response.getStatus()); + } + + /** + *
+ * + * @throws ServiceException + * @since + */ + @Test + public void testPutStringRestfulParametesRestfulOptions() throws ServiceException { + + final RestfulOptions options = new RestfulOptions(); + + final HttpRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone"); + return HttpExchange.STATUS_COMPLETED; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_COMPLETED); + return response; + } + + }; + final RestfulParametes parametes = new RestfulParametes(); + parametes.put("id", "1234"); + parametes.put("name", "some-name"); + parametes.put("address", null); + parametes.putHttpContextHeader("Content-Type", ""); + parametes.putHttpContextHeader("Accept-Encoding", ""); + final RestfulResponse response = httpRest.put("path/to/service", parametes, null); + assertEquals(HttpExchange.STATUS_COMPLETED, response.getStatus()); + } + + /** + *
+ * + * @throws ServiceException + * @since + */ + @Test + public void testAsyncPutStringRestfulParametesRestfulAsyncCallback() throws ServiceException { + final RestfulOptions options = new RestfulOptions(); + + final HttpRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone"); + return HttpExchange.STATUS_COMPLETED; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_COMPLETED); + return response; + } + + }; + + final RestfulAsyncCallback callback = new RestfulAsyncCallback() { + + @Override + public void callback(final RestfulResponse response) { + System.out.println("callback called."); + + } + + @Override + public void handleExcepion(final Throwable e) { + + System.out.println("handleExcepion called."); + } + + }; + httpRest.asyncPut("path/to/service", new RestfulParametes(), callback); + httpRest.asyncPut("path/to/service", new RestfulParametes(), null); + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + public void testAsyncPutStringRestfulParametesRestfulOptionsRestfulAsyncCallback() throws Exception { + final RestfulOptions options = new RestfulOptions(); + + final HttpRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone"); + return HttpExchange.STATUS_COMPLETED; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_COMPLETED); + return response; + } + + }; + + final RestfulAsyncCallback callback = new RestfulAsyncCallback() { + + @Override + public void callback(final RestfulResponse response) { + System.out.println("callback called."); + + } + + @Override + public void handleExcepion(final Throwable e) { + + System.out.println("handleExcepion called."); + } + + }; + httpRest.asyncPut("path/to/service", new RestfulParametes(), new RestfulOptions(), callback); + httpRest.asyncPut("path/to/service", new RestfulParametes(), new RestfulOptions(), null); + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + public void testPostStringRestfulParametes() throws Exception { + final RestfulOptions options = new RestfulOptions(); + + final HttpBaseRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone"); + return HttpExchange.STATUS_EXPIRED; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_EXPIRED); + return response; + } + + }; + final RestfulParametes parameters = new RestfulParametes(); + parameters.put("id", "1234"); + parameters.put("name", "some-name"); + parameters.put("address", null); + parameters.putHttpContextHeader("Content-Type", ""); + parameters.putHttpContextHeader("Accept-Encoding", ""); + + thrown.expect(ServiceException.class); + thrown.expectMessage("request is expierd"); + final RestfulResponse response = httpRest.post("http://localhost:80/path/to/service", parameters); + assertEquals(HttpExchange.STATUS_EXPIRED, response.getStatus()); + } + + /** + *
+ * + * @throws ServiceException + * @since + */ + @Test + public void testPostStringRestfulParametesRestfulOptions() throws ServiceException { + final RestfulOptions options = new RestfulOptions(); + + final HttpBaseRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone" + HttpExchange.STATUS_EXCEPTED); + return HttpExchange.STATUS_EXCEPTED; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_COMPLETED); + return response; + } + + }; + final RestfulParametes parameters = new RestfulParametes(); + parameters.put("id", "1234"); + parameters.put("name", "some-name"); + parameters.put("address", null); + parameters.setRawData("{ \"data\"=\"sample JSON data\""); + parameters.putHttpContextHeader("Content-Type", ""); + parameters.putHttpContextHeader("Accept-Encoding", ""); + thrown.expect(ServiceException.class); + thrown.expectMessage("request is exception"); + final RestfulResponse response = httpRest.post("path/to/service", parameters, null); + assertEquals(HttpExchange.STATUS_COMPLETED, response.getStatus()); + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + public void testAsyncPostStringRestfulParametesRestfulAsyncCallback() throws Exception { + final RestfulOptions options = new RestfulOptions(); + options.setRestTimeout(10); + + final HttpBaseRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone:" + HttpExchange.STATUS_EXCEPTED); + return 99; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_EXCEPTED); + return response; + } + + }; + + final RestfulAsyncCallback callback = new RestfulAsyncCallback() { + + @Override + public void callback(final RestfulResponse response) { + System.out.println("callback called."); + + } + + @Override + public void handleExcepion(final Throwable e) { + + System.out.println("handleExcepion called."); + } + + }; + httpRest.asyncPost("path/to/service", new RestfulParametes(), options, callback); + httpRest.asyncPost("path/to/service", new RestfulParametes(), options, null); + } + + /** + *
+ * + * @throws ServiceException + * @since + */ + @Test + public void testAsyncPostStringRestfulParametesRestfulOptionsRestfulAsyncCallback() throws ServiceException { + final RestfulOptions options = new RestfulOptions(); + options.setRestTimeout(10); + + final HttpBaseRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone:" + HttpExchange.STATUS_COMPLETED); + return HttpExchange.STATUS_COMPLETED; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_COMPLETED); + return response; + } + + }; + + final RestfulAsyncCallback callback = new RestfulAsyncCallback() { + + @Override + public void callback(final RestfulResponse response) { + System.out.println("callback called."); + + } + + @Override + public void handleExcepion(final Throwable e) { + + System.out.println("handleExcepion called."); + } + + }; + httpRest.asyncPost("path/to/service", new RestfulParametes(), options, callback); + httpRest.asyncPost("path/to/service", new RestfulParametes(), options, null); + } + + /** + *
+ * + * @throws ServiceException + * @since + */ + @Test + public void testDeleteStringRestfulParametes() throws ServiceException { + final RestfulOptions options = new RestfulOptions(); + + final HttpBaseRest httpRest = getHttpRest(options); + + final RestfulResponse response = httpRest.delete("path/to/service", null); + assertEquals(-1, response.getStatus()); + } + + /** + *
+ * + * @throws ServiceException + * @since + */ + @Test + public void testDeleteStringRestfulParametesRestfulOptions() throws ServiceException { + final RestfulOptions options = new RestfulOptions(); + + final HttpBaseRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone" + HttpExchange.STATUS_COMPLETED); + return HttpExchange.STATUS_COMPLETED; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_COMPLETED); + return response; + } + + }; + final RestfulParametes parameters = new RestfulParametes(); + parameters.put("id", "1234"); + parameters.put("name", "some-name"); + parameters.put("address", null); + parameters.setRawData("{ \"data\"=\"sample JSON data\""); + parameters.putHttpContextHeader("Content-Type", ""); + parameters.putHttpContextHeader("Accept-Encoding", ""); + final RestfulResponse response = httpRest.delete("path/to/service", parameters, options); + assertEquals(HttpExchange.STATUS_COMPLETED, response.getStatus()); + } + + /** + *
+ * + * @throws ServiceException + * @since + */ + @Test + public void testAsyncDeleteStringRestfulParametesRestfulAsyncCallback() throws ServiceException { + final RestfulOptions options = new RestfulOptions(); + options.setRestTimeout(10); + + final HttpBaseRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone:" + HttpExchange.STATUS_COMPLETED); + return HttpExchange.STATUS_COMPLETED; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_COMPLETED); + return response; + } + + }; + + final RestfulAsyncCallback callback = new RestfulAsyncCallback() { + + @Override + public void callback(final RestfulResponse response) { + System.out.println("callback called."); + + } + + @Override + public void handleExcepion(final Throwable e) { + + System.out.println("handleExcepion called."); + } + + }; + httpRest.asyncDelete("path/to/service", new RestfulParametes(), callback); + httpRest.asyncDelete("path/to/service", new RestfulParametes(), null); + } + + /** + *
+ * + * @throws ServiceException + * @since + */ + @Test + public void testAsyncDeleteStringRestfulParametesRestfulOptionsRestfulAsyncCallback() throws ServiceException { + final RestfulOptions options = new RestfulOptions(); + options.setRestTimeout(10); + + final HttpBaseRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone:" + HttpExchange.STATUS_COMPLETED); + return HttpExchange.STATUS_COMPLETED; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_COMPLETED); + return response; + } + + }; + + final RestfulAsyncCallback callback = new RestfulAsyncCallback() { + + @Override + public void callback(final RestfulResponse response) { + System.out.println("callback called."); + + } + + @Override + public void handleExcepion(final Throwable e) { + + System.out.println("handleExcepion called."); + } + + }; + httpRest.asyncDelete("path/to/service", new RestfulParametes(), options, callback); + httpRest.asyncDelete("path/to/service", new RestfulParametes(), options, null); + } + + /** + *
+ * + * @throws ServiceException + * @since + */ + @Test + public void testPatchStringRestfulParametes() throws ServiceException { + final RestfulOptions options = new RestfulOptions(); + + final HttpBaseRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone" + HttpExchange.STATUS_COMPLETED); + return HttpExchange.STATUS_COMPLETED; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_COMPLETED); + return response; + } + + }; + final RestfulParametes parameters = new RestfulParametes(); + parameters.put("id", "1234"); + parameters.put("name", "some-name"); + parameters.put("address", null); + parameters.setRawData("{ \"data\"=\"sample JSON data\""); + parameters.putHttpContextHeader("Content-Type", ""); + parameters.putHttpContextHeader("Accept-Encoding", ""); + final RestfulResponse response = httpRest.patch("path/to/service", parameters); + assertEquals(HttpExchange.STATUS_COMPLETED, response.getStatus()); + } + + /** + *
+ * + * @throws ServiceException + * @since + */ + @Test + public void testPatchStringRestfulParametesRestfulOptions() throws ServiceException { + final RestfulOptions options = new RestfulOptions(); + + final HttpBaseRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone" + HttpExchange.STATUS_COMPLETED); + return HttpExchange.STATUS_COMPLETED; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_COMPLETED); + return response; + } + + }; + final RestfulParametes parameters = new RestfulParametes(); + parameters.put("id", "1234"); + parameters.put("name", "some-name"); + parameters.put("address", null); + parameters.setRawData("{ \"data\"=\"sample JSON data\""); + parameters.putHttpContextHeader("Content-Type", ""); + parameters.putHttpContextHeader("Accept-Encoding", ""); + final RestfulResponse response = httpRest.patch("path/to/service", parameters, options); + assertEquals(HttpExchange.STATUS_COMPLETED, response.getStatus()); + } + + /** + *
+ * + * @throws ServiceException + * @since + */ + @Test + public void testAsyncPatchStringRestfulParametesRestfulAsyncCallback() throws ServiceException { + final RestfulOptions options = new RestfulOptions(); + options.setRestTimeout(10); + + final HttpBaseRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone:" + HttpExchange.STATUS_COMPLETED); + return HttpExchange.STATUS_COMPLETED; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_COMPLETED); + return response; + } + + }; + + final RestfulAsyncCallback callback = new RestfulAsyncCallback() { + + @Override + public void callback(final RestfulResponse response) { + System.out.println("callback called."); + + } + + @Override + public void handleExcepion(final Throwable e) { + + System.out.println("handleExcepion called."); + } + + }; + httpRest.asyncPatch("path/to/service", new RestfulParametes(), callback); + httpRest.asyncPatch("path/to/service", new RestfulParametes(), null); + } + + /** + *
+ * + * @throws ServiceException + * @since + */ + @Test + public void testAsyncPatchStringRestfulParametesRestfulOptionsRestfulAsyncCallback() throws ServiceException { + final RestfulOptions options = new RestfulOptions(); + options.setRestTimeout(10); + + final HttpBaseRest httpRest = getHttpRest(options); + new MockUp() { + + @Mock + public int waitForDone() { + System.out.println("waitForDone:" + HttpExchange.STATUS_COMPLETED); + return HttpExchange.STATUS_COMPLETED; + } + + @Mock + public RestfulResponse getResponse() throws IOException { + final RestfulResponse response = new RestfulResponse(); + response.setStatus(HttpExchange.STATUS_COMPLETED); + return response; + } + + }; + + final RestfulAsyncCallback callback = new RestfulAsyncCallback() { + + @Override + public void callback(final RestfulResponse response) { + System.out.println("callback called."); + + } + + @Override + public void handleExcepion(final Throwable e) { + + System.out.println("handleExcepion called."); + } + + }; + httpRest.asyncPatch("path/to/service", new RestfulParametes(), options, callback); + httpRest.asyncPatch("path/to/service", new RestfulParametes(), options, null); + } + +} diff --git a/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestHttpContentExchange.java b/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestHttpContentExchange.java new file mode 100644 index 0000000..dbd1b1e --- /dev/null +++ b/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestHttpContentExchange.java @@ -0,0 +1,592 @@ +/* + * Copyright 2016-2017 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.baseservice.roa.util.restclient; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.zip.GZIPInputStream; + +import org.apache.log4j.Level; +import org.apache.log4j.LogManager; +import org.eclipse.jetty.client.Address; +import org.eclipse.jetty.client.CachedExchange; +import org.eclipse.jetty.client.HttpDestination; +import org.eclipse.jetty.client.HttpExchange; +import org.eclipse.jetty.http.HttpFields; +import org.eclipse.jetty.http.HttpHeaders; +import org.eclipse.jetty.io.Buffer; +import org.eclipse.jetty.io.ByteArrayBuffer; +import org.eclipse.jetty.util.StringUtil; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.openo.baseservice.remoteservice.exception.ServiceException; + +import mockit.Mock; +import mockit.MockUp; +import mockit.Mocked; +import mockit.integration.junit4.JMockit; + +/** + *
+ *

+ *

+ * + * @author + * @version 20-Jun-2016 + */ +@RunWith(JMockit.class) +public class TestRestHttpContentExchange { + + @Mocked + HttpDestination mockedDest; + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @Before + public void setUp() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @After + public void tearDown() throws Exception { + LogManager.getLogger(RestHttpContentExchange.class).setLevel(Level.ERROR); + } + + /** + *
+ * + * @throws IOException + * @since + */ + @Test + public void testOnRequestCommitted() throws IOException { + final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null); + final Address address = new Address("localhost", 9999); + exchange.setAddress(address); + exchange.setRequestURI("/the/request/uri"); + exchange.onRequestCommitted(); + + LogManager.getLogger(RestHttpContentExchange.class).setLevel(Level.DEBUG); + exchange.onRequestCommitted(); + } + + /** + *
+ * + * @throws IOException + * @since + */ + @Test + public void testOnRequestComplete() throws IOException { + final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null); + final Address address = new Address("localhost", 9999); + exchange.setAddress(address); + exchange.setRequestURI("/the/request/uri"); + exchange.onRequestComplete(); + + LogManager.getLogger(RestHttpContentExchange.class).setLevel(Level.DEBUG); + exchange.onRequestComplete(); + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + public void testOnResponseComplete() throws Exception { + RestHttpContentExchange exchange = new RestHttpContentExchange(false, null); + final Address address = new Address("localhost", 9999); + exchange.setAddress(address); + exchange.setRequestURI("/the/request/uri"); + exchange.onResponseComplete(); + + LogManager.getLogger(RestHttpContentExchange.class).setLevel(Level.DEBUG); + exchange.onResponseComplete(); + + final AtomicInteger isCallback = new AtomicInteger(0); + final AtomicInteger isException = new AtomicInteger(0); + final RestfulAsyncCallback callback = new RestfulAsyncCallback() { + + @Override + public void callback(final RestfulResponse response) { + isCallback.set(1); + } + + @Override + public void handleExcepion(final Throwable e) { + isException.set(1); + } + + }; + + final Field statusField = HttpExchange.class.getDeclaredField("_status"); + statusField.setAccessible(true); + exchange = new RestHttpContentExchange(false, callback); + statusField.set(exchange, new AtomicInteger(200)); + exchange.setAddress(new Address("localhost", 9999)); + exchange.setRequestURI("/the/request/uri"); + exchange.onResponseComplete(); + assertEquals(1, isCallback.get()); + assertEquals(0, isException.get()); + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + @Ignore + public void testDecompressGzipToStr() throws Exception { + final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null); + final Address address = new Address("localhost", 9999); + exchange.setAddress(address); + exchange.setRequestURI("/the/request/uri"); + + final InputStream stream = ClassLoader.getSystemResourceAsStream("sample.txt.gz"); + final byte[] binaryData = new byte[1024]; + stream.read(binaryData); + final String expected = "sample data."; + + final String actual = exchange.decompressGzipToStr(binaryData); + + System.out.println("actual: '" + actual + "'"); + System.out.println("expected: '" + expected + "'"); + assertEquals(actual, expected); + + new MockUp() { + + @Mock + public int read() throws Exception { + throw new IOException(); + } + + @Mock + public int read(final byte abyte0[], final int i, final int j) { + + return -1; + } + + }; + + thrown.expect(IOException.class); + exchange.decompressGzipToStr(binaryData); + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + @Ignore + public void testDecompressGzipToStrException() throws Exception { + final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null); + final Address address = new Address("localhost", 9999); + exchange.setAddress(address); + exchange.setRequestURI("/the/request/uri"); + + final InputStream stream = ClassLoader.getSystemResourceAsStream("sample.txt.gz"); + final byte[] binaryData = new byte[1024]; + stream.read(binaryData); + final String expected = "sample data."; + + new MockUp() { + + @Mock + public void close() throws IOException { + throw new IOException(); + } + + }; + + new MockUp() { + + @Mock + public void close() throws IOException { + throw new IOException(); + } + + }; + + new MockUp() { + + @Mock + public void close() throws IOException { + throw new IOException(); + } + + }; + + final String actual = exchange.decompressGzipToStr(binaryData); + + System.out.println("actual: '" + actual + "'"); + System.out.println("expected: '" + expected + "'"); + assertEquals(actual, expected); + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + public void testDecompressGzipToStrNull() throws Exception { + final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null); + final Address address = new Address("localhost", 9999); + exchange.setAddress(address); + exchange.setRequestURI("/the/request/uri"); + final String expected = ""; + final String actual = exchange.decompressGzipToStr(null); + + System.out.println("actual: '" + actual + "'"); + System.out.println("expected: '" + expected + "'"); + assertEquals(actual, expected); + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + public void testOnResponseHeaderBufferBuffer() throws Exception { + final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null); + final Address address = new Address("localhost", 9999); + exchange.setAddress(address); + exchange.setRequestURI("/the/request/uri"); + + final Buffer name = new ByteArrayBuffer("key"); + final Buffer value = new ByteArrayBuffer("value"); + exchange.onResponseHeader(name, value); + + new MockUp() { + + @Mock + public int getOrdinal(final Buffer buffer) { + return HttpHeaders.CONTENT_ENCODING_ORDINAL; + } + + }; + exchange.onResponseHeader(name, value); + + new MockUp() { + + @Mock + public String asciiToLowerCase(final String s) { + return "gzip"; + } + + }; + exchange.onResponseHeader(name, value); + + } + + /** + *
+ * + * @since + */ + @Test + public void testOnExceptionThrowable() { + final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null); + final Address address = new Address("localhost", 9999); + exchange.setAddress(address); + exchange.setRequestURI("/the/request/uri"); + exchange.onException(new Exception()); + } + + /** + *
+ * + * @since + */ + @Test + public void testOnExceptionThrowableWithCallback() { + final AtomicInteger isCallback = new AtomicInteger(0); + final AtomicInteger isException = new AtomicInteger(0); + final RestfulAsyncCallback callback = new RestfulAsyncCallback() { + + @Override + public void callback(final RestfulResponse response) { + isCallback.set(1); + } + + @Override + public void handleExcepion(final Throwable e) { + isException.set(1); + } + + }; + final RestHttpContentExchange exchange = new RestHttpContentExchange(true, callback); + final Address address = new Address("localhost", 9999); + exchange.setAddress(address); + exchange.setRequestURI("/the/request/uri"); + exchange.onException(new Exception()); + assertEquals(0, isCallback.get()); + assertEquals(1, isException.get()); + } + + /** + *
+ * + * @since + */ + @Test + public void testOnConnectionFailedThrowable() { + final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null); + final Address address = new Address("localhost", 9999); + exchange.setAddress(address); + exchange.setRequestURI("/the/request/uri"); + exchange.onConnectionFailed(new Exception()); + } + + /** + *
+ * + * @since + */ + @Test + public void testOnConnectionFailedThrowableException() { + final AtomicInteger isCallback = new AtomicInteger(0); + final AtomicInteger isException = new AtomicInteger(0); + final RestfulAsyncCallback callback = new RestfulAsyncCallback() { + + @Override + public void callback(final RestfulResponse response) { + isCallback.set(1); + } + + @Override + public void handleExcepion(final Throwable e) { + isException.set(1); + } + + }; + final RestHttpContentExchange exchange = new RestHttpContentExchange(true, callback); + final Address address = new Address("localhost", 9999); + exchange.setAddress(address); + exchange.setRequestURI("/the/request/uri"); + exchange.onConnectionFailed(new Exception()); + assertEquals(0, isCallback.get()); + assertEquals(1, isException.get()); + } + + /** + *
+ * + * @since + */ + @Test + public void testExpireHttpDestination() { + final RestHttpContentExchange exchange = new RestHttpContentExchange(true, null); + final Address address = new Address("localhost", 9999); + exchange.setAddress(address); + exchange.setRequestURI("/the/request/uri"); + exchange.expire(mockedDest); + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + public void testExpireHttpDestinationException() throws Exception { + final AtomicInteger isCallback = new AtomicInteger(0); + final AtomicInteger isException = new AtomicInteger(0); + final List thrSet = new ArrayList(); + final RestfulAsyncCallback callback = new RestfulAsyncCallback() { + + @Override + public void callback(final RestfulResponse response) { + isCallback.set(1); + } + + @Override + public void handleExcepion(final Throwable e) { + isException.set(1); + thrSet.add(e); + } + + }; + final RestHttpContentExchange exchange = new RestHttpContentExchange(true, callback); + final Address address = new Address("localhost", 9999); + exchange.setAddress(address); + exchange.setRequestURI("/the/request/uri"); + exchange.expire(mockedDest); + assertEquals(0, isCallback.get()); + assertEquals(1, isException.get()); + assertEquals(1, thrSet.size()); + final Throwable t = thrSet.get(0); + assertEquals(ServiceException.class, t.getClass()); + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + public void testIsGzip() throws Exception { + final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null); + final Address address = new Address("localhost", 9999); + exchange.setAddress(address); + exchange.setRequestURI("/the/request/uri"); + + final Buffer name = new ByteArrayBuffer("key"); + final Buffer value = new ByteArrayBuffer("value"); + + new MockUp() { + + @Mock + public int getOrdinal(final Buffer buffer) { + return HttpHeaders.CONTENT_ENCODING_ORDINAL; + } + + }; + exchange.onResponseHeader(name, value); + assertFalse(exchange.isGzip()); + + new MockUp() { + + @Mock + public String asciiToLowerCase(final String s) { + return "gzip"; + } + + }; + exchange.onResponseHeader(name, value); + assertTrue(exchange.isGzip()); + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + public void testGetResponse() throws Exception { + final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null); + final Address address = new Address("localhost", 9999); + exchange.setAddress(address); + exchange.setRequestURI("/the/request/uri"); + + final Field statusField = HttpExchange.class.getDeclaredField("_status"); + statusField.setAccessible(true); + statusField.set(exchange, new AtomicInteger(200)); + + RestfulResponse response = exchange.getResponse(); + assertEquals(0, response.getStatus()); + + final HttpFields fields = new HttpFields(); + final Field headerFields = CachedExchange.class.getDeclaredField("_responseFields"); + headerFields.setAccessible(true); + headerFields.set(exchange, fields); + response = exchange.getResponse(); + assertEquals(0, response.getStatus()); + fields.add("Content-Type", "application/json"); + fields.add("Content-Encode", "UTF-8"); + response = exchange.getResponse(); + assertEquals(0, response.getStatus()); + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + public void testGetResponseGzip() throws Exception { + final RestHttpContentExchange exchange = new RestHttpContentExchange(false, null); + final Address address = new Address("localhost", 9999); + exchange.setAddress(address); + exchange.setRequestURI("/the/request/uri"); + new MockUp() { + + @Mock + public boolean isGzip() { + return true; + } + }; + final Field statusField = HttpExchange.class.getDeclaredField("_status"); + statusField.setAccessible(true); + statusField.set(exchange, new AtomicInteger(200)); + + final RestfulResponse response = exchange.getResponse(); + assertEquals(0, response.getStatus()); + } +} diff --git a/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulConfigure.java b/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulConfigure.java new file mode 100644 index 0000000..7cc7b1e --- /dev/null +++ b/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulConfigure.java @@ -0,0 +1,238 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.baseservice.roa.util.restclient; + +import static org.junit.Assert.assertEquals; + +import org.openo.baseservice.util.impl.SystemEnvVariablesDefImpl; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; + +import net.sf.json.JSONObject; + +import java.io.File; +import java.io.IOException; +import java.net.URL; + +import mockit.Mock; +import mockit.MockUp; +import mockit.integration.junit4.JMockit; + +/** + *
+ *

+ *

+ * + * @author + * @version 20-Jun-2016 + */ +@RunWith(JMockit.class) +public class TestRestfulConfigure { + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception { + setAppRoot(); + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @Before + public void setUp() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @After + public void tearDown() throws Exception { + } + + private static void setAppRoot() { + final URL resource = ClassLoader.getSystemResource("etc/conf/restclient.json"); + final String urlPath = resource.getPath().replace("etc/conf/restclient.json", ""); + + try { + final String path = new File(urlPath).getCanonicalPath(); + System.out.println("path: " + path); + + System.setProperty("catalina.base", path); + System.out.println("approot:" + System.getProperty("catalina.base")); + } catch(final IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + + /** + *
+ * @throws Exception + * @since + */ + @Test + public final void testRestfulConfigure() throws Exception { + final RestfulConfigure configure = new RestfulConfigure(); + final RestfulOptions options = configure.getOptions(); + assertEquals("127.0.0.1", options.getHost()); + assertEquals(8080, options.getPort()); + assertEquals(1000, options.getIntOption("ConnectTimeout")); + assertEquals(10, options.getIntOption("thread")); + assertEquals(500000, options.getIntOption("idletimeout")); + assertEquals(10000, options.getIntOption("timeout")); + + } + + /** + *
+ * @throws Exception + * @since + */ + @Test + public final void testRestfulConfigureAppRootNull() throws Exception { + new MockUp() { + + @Mock + public String getAppRoot() { + return null; + } + + }; + final RestfulConfigure configure = new RestfulConfigure(); + final RestfulOptions options = configure.getOptions(); + + assertEquals("", options.getHost()); + assertEquals(0, options.getPort()); + assertEquals(3000, options.getIntOption("ConnectTimeout")); + assertEquals(200, options.getIntOption("thread")); + assertEquals(30000, options.getIntOption("idletimeout")); + assertEquals(30000, options.getIntOption("timeout")); + + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + public final void testRestfulConfigureDefault() throws Exception { + + { + + new MockUp() { + + @Mock + public boolean isFile() { + return false; + } + }; + final RestfulConfigure configure = new RestfulConfigure(); + final RestfulOptions options = configure.getOptions(); + assertEquals("", options.getHost()); + assertEquals(0, options.getPort()); + assertEquals(3000, options.getIntOption("ConnectTimeout")); + assertEquals(200, options.getIntOption("thread")); + assertEquals(30000, options.getIntOption("idletimeout")); + assertEquals(30000, options.getIntOption("timeout")); + } + + } + + /** + *
+ * + * @throws Exception + * @since + */ + @Test + public final void testRestfulConfigureException() throws Exception { + + new MockUp() { + + @Mock + JSONObject fromObject(final Object object) throws IOException { + throw new IOException(); + } + }; + + final RestfulConfigure configure = new RestfulConfigure(); + final RestfulOptions options = configure.getOptions(); + assertEquals("", options.getHost()); + assertEquals(0, options.getPort()); + assertEquals(3000, options.getIntOption("ConnectTimeout")); + assertEquals(200, options.getIntOption("thread")); + assertEquals(30000, options.getIntOption("idletimeout")); + assertEquals(30000, options.getIntOption("timeout")); + + } + + /** + * + * @since + */ + @Test + public final void testRestfulConfigureString() { + final String configFile = "rest-client-test.json"; + final String appRoot = System.getProperty("catalina.base"); + final RestfulConfigure configure = new RestfulConfigure(appRoot + File.separator + configFile); + final RestfulOptions options = configure.getOptions(); + assertEquals("10.10.10.10", options.getHost()); + assertEquals(443, options.getPort()); + assertEquals(10, options.getIntOption("ConnectTimeout")); + assertEquals(100, options.getIntOption("thread")); + assertEquals(30, options.getIntOption("idletimeout")); + assertEquals(60, options.getIntOption("timeout")); + } + + /** + *
+ * + * @since + */ + @Test + public final void testGetOptions() { + } +} \ No newline at end of file diff --git a/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulFactory.java b/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulFactory.java new file mode 100644 index 0000000..5678732 --- /dev/null +++ b/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulFactory.java @@ -0,0 +1,109 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.baseservice.roa.util.restclient; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import org.openo.baseservice.remoteservice.exception.ServiceException; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; + +import mockit.Mock; +import mockit.MockUp; +import mockit.integration.junit4.JMockit; + +/** + *
+ *

+ *

+ * + * @author + * @version 21-Jun-2016 + */ +@RunWith(JMockit.class) +public class TestRestfulFactory { + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @Before + public void setUp() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @After + public void tearDown() throws Exception { + } + + /** + *
+ * + * @since + */ + @Test + public void testGetRestInstance() { + Restful instance = RestfulFactory.getRestInstance("https"); + assertNull(instance); + new MockUp() { + + @Mock + public void initHttpRest(final RestfulOptions option) throws ServiceException { + throw new ServiceException(); + } + + }; + instance = RestfulFactory.getRestInstance("http"); + assertNotNull(instance); + + instance = RestfulFactory.getRestInstance("http"); + assertNotNull(instance); + } +} diff --git a/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulOptions.java b/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulOptions.java new file mode 100644 index 0000000..b91bbef --- /dev/null +++ b/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulOptions.java @@ -0,0 +1,288 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.baseservice.roa.util.restclient; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; + +import java.util.ArrayList; +import java.util.List; + +import mockit.integration.junit4.JMockit; + +/** + *
+ *

+ *

+ * + * @author + * @version 20-Jun-2016 + */ +@RunWith(JMockit.class) +public class TestRestfulOptions { + + @Rule + final public ExpectedException thrown = ExpectedException.none(); + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @Before + public void setUp() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @After + public void tearDown() throws Exception { + } + + /** + *
+ * + * @since + */ + @Test + public void testGetPort() { + final RestfulOptions options = new RestfulOptions(); + final int port = 9091; + assertEquals(0, options.getPort()); + options.setPort(port); + assertEquals(port, options.getPort()); + } + + /** + *
+ * + * @since + */ + @Test + public void testSetPort() { + final RestfulOptions options = new RestfulOptions(); + final int port = 9091; + assertTrue(options.setPort(port)); + assertEquals(port, options.getPort()); + } + + /** + *
+ * + * @since + */ + @Test + public void testGetHost() { + final RestfulOptions options = new RestfulOptions(); + final String host = "localhost"; + assertEquals("", options.getHost()); + options.setHost(host); + assertEquals(host, options.getHost()); + } + + /** + *
+ * + * @since + */ + @Test + public void testSetHost() { + final RestfulOptions options = new RestfulOptions(); + final String host = "localhost"; + assertTrue(options.setHost(host)); + assertEquals(host, options.getHost()); + } + + /** + *
+ * + * @since + */ + @Test + public void testSetRestTimeout() { + final RestfulOptions options = new RestfulOptions(); + int timeout = 0; + assertFalse(options.setRestTimeout(timeout)); + assertEquals(0, options.getRestTimeout()); + + timeout = 1; + assertTrue(options.setRestTimeout(timeout)); + assertEquals(timeout, options.getRestTimeout()); + + timeout = 10; + assertTrue(options.setRestTimeout(timeout)); + assertEquals(timeout, options.getRestTimeout()); + + timeout = RestfulOptions.REST_OPTIONS_TIMEOUT_MAXTIMEOUT - 1; + assertTrue(options.setRestTimeout(timeout)); + assertEquals(timeout, options.getRestTimeout()); + + timeout = RestfulOptions.REST_OPTIONS_TIMEOUT_MAXTIMEOUT; + assertTrue(options.setRestTimeout(timeout)); + assertEquals(timeout, options.getRestTimeout()); + + timeout = RestfulOptions.REST_OPTIONS_TIMEOUT_MAXTIMEOUT + 1; + assertFalse(options.setRestTimeout(timeout)); + } + + /** + *
+ * + * @since + */ + @Test + public void testGetRestTimeout() { + final RestfulOptions options = new RestfulOptions(); + int timeout = 0; + assertEquals(0, options.getRestTimeout()); + + timeout = 1; + assertTrue(options.setRestTimeout(timeout)); + assertEquals(timeout, options.getRestTimeout()); + } + + /** + *
+ * + * @since + */ + @Test + public void testGetOption() { + final RestfulOptions options = new RestfulOptions(); + assertNull(options.getOption("invalid")); + + options.setHost("localhost"); + Object obj = options.getOption(RestfulClientConst.HOST_KEY_NAME); + assertNotNull(obj); + assertTrue(obj instanceof String); + assertEquals("localhost", obj); + + final List list = new ArrayList(); + list.add("data"); + options.setOption("list", list); + obj = options.getOption("list"); + assertNotNull(obj); + assertTrue(obj instanceof List); + assertSame(list, obj); + } + + /** + *
+ * + * @since + */ + @Test + public void testGetIntOption() { + final RestfulOptions options = new RestfulOptions(); + + assertEquals(0, options.getIntOption("count")); + + options.setOption("count", 1); + assertEquals(1, options.getIntOption("count")); + + thrown.expect(RuntimeException.class); + + options.setOption("string-count", "two"); + final int value = options.getIntOption("string-count"); + assertEquals(2, value); + + } + + /** + *
+ * + * @since + */ + @Test + public void testGetStringOption() { + final RestfulOptions options = new RestfulOptions(); + + assertEquals("", options.getStringOption("count")); + + options.setOption("string-count", "one"); + assertEquals("one", options.getStringOption("string-count")); + + thrown.expect(RuntimeException.class); + + options.setOption("count", 2); + final String value = options.getStringOption("count"); + assertEquals(2, value); + } + + /** + *
+ * + * @since + */ + @Test + public void testSetOption() { + final RestfulOptions options = new RestfulOptions(); + assertNull(options.getOption("invalid")); + + options.setHost("localhost"); + Object obj = options.getOption(RestfulClientConst.HOST_KEY_NAME); + assertNotNull(obj); + assertTrue(obj instanceof String); + assertEquals("localhost", obj); + + final List list = new ArrayList(); + list.add("data"); + options.setOption("list", list); + obj = options.getOption("list"); + assertNotNull(obj); + assertTrue(obj instanceof List); + assertSame(list, obj); + } +} diff --git a/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulParametes.java b/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulParametes.java new file mode 100644 index 0000000..fbe9430 --- /dev/null +++ b/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulParametes.java @@ -0,0 +1,229 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.baseservice.roa.util.restclient; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; + +/** + *
+ *

+ *

+ * + * @author + * @version 21-Jun-2016 + */ +public class TestRestfulParametes { + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @Before + public void setUp() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @After + public void tearDown() throws Exception { + } + + /** + *
+ * + * @since + */ + @Test + public void testGet() { + final RestfulParametes params = new RestfulParametes(); + assertNull(params.get("param")); + final Map paramMap = new HashMap(); + params.setParamMap(paramMap); + paramMap.put("param", "value"); + assertEquals("value", params.get("param")); + } + + /** + *
+ * + * @since + */ + @Test + public void testSetRawData() { + final RestfulParametes params = new RestfulParametes(); + final String data = "Sample data."; + params.setRawData(data); + assertEquals(data, params.getRawData()); + } + + /** + *
+ * + * @since + */ + @Test + public void testGetRawData() { + final RestfulParametes params = new RestfulParametes(); + assertNull(params.getRawData()); + final String data = "Sample data."; + params.setRawData(data); + assertEquals(data, params.getRawData()); + } + + /** + *
+ * + * @since + */ + @Test + public void testPut() { + final RestfulParametes params = new RestfulParametes(); + params.put("somekey", "somevalue"); + params.put("otherkey", "othervalue"); + assertEquals("somevalue", params.get("somekey")); + assertEquals("othervalue", params.get("otherkey")); + } + + /** + *
+ * + * @since + */ + @Test + public void testPutHttpContextHeaderStringString() { + final RestfulParametes params = new RestfulParametes(); + params.putHttpContextHeader("Context-Encoding", "UTF-8"); + assertEquals("UTF-8", params.getHttpContextHeader("Context-Encoding")); + } + + /** + *
+ * + * @since + */ + @Test + public void testPutHttpContextHeaderStringInt() { + final RestfulParametes params = new RestfulParametes(); + params.putHttpContextHeader("Expire-At", 1000); + assertEquals("1000", params.getHttpContextHeader("Expire-At")); + } + + /** + *
+ * + * @since + */ + @Test + public void testGetHttpContextHeader() { + final RestfulParametes params = new RestfulParametes(); + params.putHttpContextHeader("Expire-At", 1000); + params.putHttpContextHeader("Context-Encoding", "UTF-8"); + assertEquals("1000", params.getHttpContextHeader("Expire-At")); + assertEquals("UTF-8", params.getHttpContextHeader("Context-Encoding")); + } + + /** + *
+ * + * @since + */ + @Test + public void testGetParamMap() { + final RestfulParametes params = new RestfulParametes(); + params.put("key", "value"); + final Map map = params.getParamMap(); + assertEquals("value", map.get("key")); + } + + /** + *
+ * + * @since + */ + @Test + public void testSetParamMap() { + final RestfulParametes params = new RestfulParametes(); + final Map map = new HashMap(); + map.put("key", "value"); + params.setParamMap(map); + assertEquals("value", params.get("key")); + + } + + /** + *
+ * + * @since + */ + @Test + public void testGetHeaderMap() { + final RestfulParametes params = new RestfulParametes(); + params.putHttpContextHeader("key", "value"); + final Map map = params.getHeaderMap(); + assertEquals("value", map.get("key")); + } + + /** + *
+ * + * @since + */ + @Test + public void testSetHeaderMap() { + final RestfulParametes params = new RestfulParametes(); + final Map map = new HashMap(); + map.put("key", "value"); + params.setHeaderMap(map); + assertEquals("value", params.getHttpContextHeader("key")); + } +} diff --git a/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulResponse.java b/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulResponse.java new file mode 100644 index 0000000..19fc7d5 --- /dev/null +++ b/wso2/rest-client/src/test/java/org/openo/baseservice/roa/util/restclient/TestRestfulResponse.java @@ -0,0 +1,273 @@ +/* + * Copyright 2016 Huawei Technologies Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openo.baseservice.roa.util.restclient; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import java.util.HashMap; +import java.util.Map; + +/** + *
+ *

+ *

+ * + * @author + * @version 20-Jun-2016 + */ +public class TestRestfulResponse { + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @Before + public void setUp() throws Exception { + } + + /** + *
+ * + * @throws java.lang.Exception + * @since + */ + @After + public void tearDown() throws Exception { + } + + /** + *
+ * + * @since + */ + @Test + public void testGetStatus() { + final RestfulResponse response = new RestfulResponse(); + int actual = response.getStatus(); + int expected = -1; + + assertEquals(expected, actual); + expected = 202; + response.setStatus(expected); + actual = response.getStatus(); + assertEquals(expected, actual); + } + + /** + *
+ * + * @since + */ + @Test + public void testSetStatus() { + final RestfulResponse response = new RestfulResponse(); + final int expected = 10; + response.setStatus(expected); + final int actual = response.getStatus(); + assertEquals(expected, actual); + } + + /** + *
+ * + * @since + */ + @Test + public void testGetRespHeaderMap() { + final RestfulResponse response = new RestfulResponse(); + Map expected = response.getRespHeaderMap(); + assertNull(expected); + expected = new HashMap(); + expected.put("key", "value"); + response.setRespHeaderMap(expected); + final Map actual = response.getRespHeaderMap(); + assertNotNull(actual); + assertSame(actual, expected); + + } + + /** + *
+ * + * @since + */ + @Test + public void testSetRespHeaderMap() { + final RestfulResponse response = new RestfulResponse(); + response.setRespHeaderMap(null); + Map expected = response.getRespHeaderMap(); + assertNull(expected); + expected = new HashMap(); + expected.put("key", "value"); + response.setRespHeaderMap(expected); + final Map actual = response.getRespHeaderMap(); + assertNotNull(actual); + assertSame(actual, expected); + } + + /** + *
+ * + * @since + */ + @Test + public void testGetRespHeaderInt() { + final RestfulResponse response = new RestfulResponse(); + response.setRespHeaderMap(null); + int actual = response.getRespHeaderInt("somekey"); + assertEquals(-1, actual); + final Map headers = new HashMap(); + headers.put("key", "value"); + headers.put("count", "1"); + response.setRespHeaderMap(headers); + actual = response.getRespHeaderInt("somekey"); + assertEquals(-1, actual); + + actual = response.getRespHeaderInt("count"); + assertEquals(1, actual); + + thrown.expect(RuntimeException.class); + actual = response.getRespHeaderInt("key"); + assertEquals(1, actual); + + } + + /** + *
+ * + * @since + */ + @Test + public void testGetRespHeaderLong() { + final RestfulResponse response = new RestfulResponse(); + response.setRespHeaderMap(null); + long actual = response.getRespHeaderLong("somekey"); + assertEquals(-1, actual); + final Map headers = new HashMap(); + headers.put("key", "value"); + headers.put("count", "1"); + headers.put("max", "" + Long.MAX_VALUE); + headers.put("max++", Long.MAX_VALUE + 1 + ""); + response.setRespHeaderMap(headers); + actual = response.getRespHeaderLong("somekey"); + assertEquals(-1, actual); + + actual = response.getRespHeaderLong("count"); + assertEquals(1, actual); + + actual = response.getRespHeaderLong("max"); + assertEquals(Long.MAX_VALUE, actual); + + actual = response.getRespHeaderLong("max++"); + assertTrue(actual < 0); + + thrown.expect(RuntimeException.class); + actual = response.getRespHeaderLong("key"); + assertEquals(1, actual); + } + + /** + *
+ * + * @since + */ + @Test + public void testGetRespHeaderStr() { + final RestfulResponse response = new RestfulResponse(); + response.setRespHeaderMap(null); + String actual = response.getRespHeaderStr("somekey"); + assertEquals(null, actual); + final Map headers = new HashMap(); + headers.put("key", "value"); + headers.put("count", "1"); + headers.put("max", "" + Long.MAX_VALUE); + response.setRespHeaderMap(headers); + actual = response.getRespHeaderStr("somekey"); + assertEquals(null, actual); + + actual = response.getRespHeaderStr("key"); + assertEquals("value", actual); + + } + + /** + *
+ * + * @since + */ + @Test + public void testGetResponseContent() { + final RestfulResponse response = new RestfulResponse(); + assertEquals(null, response.getResponseContent()); + + final String content = "{ \"content\" = \"The response content\" }"; + response.setResponseJson(content); + assertEquals(content, response.getResponseContent()); + } + + /** + *
+ * + * @since + */ + @Test + public void testSetResponseJson() { + final RestfulResponse response = new RestfulResponse(); + assertEquals(null, response.getResponseContent()); + + final String content = "{ \"content\" = \"The response content\" }"; + response.setResponseJson(content); + assertEquals(content, response.getResponseContent()); + } +} diff --git a/wso2/rest-client/src/test/resources/etc/conf/restclient.json b/wso2/rest-client/src/test/resources/etc/conf/restclient.json new file mode 100644 index 0000000..1ab1aaf --- /dev/null +++ b/wso2/rest-client/src/test/resources/etc/conf/restclient.json @@ -0,0 +1,11 @@ +{ + "defaultServer": + { + "host":"127.0.0.1", + "port":"8080", + }, + "ConnectTimeout":"1000", + "thread":"10", + "idletimeout":"500000", + "timeout":"10000" +} \ No newline at end of file diff --git a/wso2/rest-client/src/test/resources/rest-client-test.json b/wso2/rest-client/src/test/resources/rest-client-test.json new file mode 100644 index 0000000..0bdd9cd --- /dev/null +++ b/wso2/rest-client/src/test/resources/rest-client-test.json @@ -0,0 +1,11 @@ +{ + "defaultServer": + { + "host":"10.10.10.10", + "port":"443", + }, + "ConnectTimeout":"10", + "thread":"100", + "idletimeout":"30", + "timeout":"60", +} \ No newline at end of file diff --git a/wso2/wso2bpel-ext/pom.xml b/wso2/wso2bpel-ext/pom.xml new file mode 100644 index 0000000..e432cbe --- /dev/null +++ b/wso2/wso2bpel-ext/pom.xml @@ -0,0 +1,45 @@ + + + + + org.openo.common-services.common-utilities.wso2bpel-ext + wso2bpelparent + 1.1.0-SNAPSHOT + wso2bpel-parent/wso2bpelparent + + + 4.0.0 + wso2bpel-root + common-services-common-utilities/wso2bpel-ext + pom + + + wso2bpel-parent + wso2bpel-core + + + + + + com.mycila + license-maven-plugin + + + + diff --git a/wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/pom.xml b/wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/pom.xml new file mode 100644 index 0000000..3f81980 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/pom.xml @@ -0,0 +1,181 @@ + + + + 4.0.0 + + + org.openo.common-services.common-utilities.wso2bpel-ext + wso2bpel-core-parent + 1.1.0-SNAPSHOT + + + BPEL4RESTLight + common-services-common-utilities/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight + + jar + + + 4.4.1 + + + + + wso2-nexus + http://dist.wso2.org/maven2 + + true + + + false + + + + + + + bpel4rest + + + + com.mycila + license-maven-plugin + + + ** + + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + false + + ** + + + + + + + + + + commons-codec + commons-codec + 1.3 + compile + + + commons-httpclient + commons-httpclient + 3.0-rc4 + + + commons-logging + commons-logging + 1.0.3 + + + org.apache.httpcomponents + httpcore + ${httpclient.version} + + + + + org.wso2.bpel + ode-bpel-api + 1.3.5-wso2v4 + + + + org.wso2.bpel + ode-bpel-obj + 1.3.5-wso2v4 + + + + org.wso2.bpel + ode-bpel-runtime + 1.3.5-wso2v4 + + + + + com.googlecode.json-simple + json-simple + 1.1.1 + + + diff --git a/wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/extensions/bpel4restlight/Bpel4RestLightExtensionBundle.java b/wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/extensions/bpel4restlight/Bpel4RestLightExtensionBundle.java new file mode 100644 index 0000000..88ac53e --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/extensions/bpel4restlight/Bpel4RestLightExtensionBundle.java @@ -0,0 +1,48 @@ +/** + * Copyright 2011 IAAS University of Stuttgart
+ *
+ * + * @author uwe.breitenbuecher@iaas.uni-stuttgart.de + * + */ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.unistuttgart.iaas.bpel.extensions.bpel4restlight; + +import org.apache.ode.bpel.runtime.extension.AbstractExtensionBundle; + + +public class Bpel4RestLightExtensionBundle extends AbstractExtensionBundle { + + public static final String NAMESPACE = "http://iaas.uni-stuttgart.de/bpel/extensions/bpel4restlight"; + + + /** {@inheritDoc} */ + @Override + public String getNamespaceURI() { + return NAMESPACE; + } + + /** {@inheritDoc} */ + @Override + public void registerExtensionActivities() { + super.registerExtensionOperation("logNodes", EPRDemoOperation.class); + super.registerExtensionOperation("PUT", Bpel4RestLightOperation.class); + super.registerExtensionOperation("GET", Bpel4RestLightOperation.class); + super.registerExtensionOperation("POST", Bpel4RestLightOperation.class); + super.registerExtensionOperation("DELETE", Bpel4RestLightOperation.class); + } +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/extensions/bpel4restlight/Bpel4RestLightOperation.java b/wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/extensions/bpel4restlight/Bpel4RestLightOperation.java new file mode 100644 index 0000000..2335f49 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/extensions/bpel4restlight/Bpel4RestLightOperation.java @@ -0,0 +1,147 @@ +package de.unistuttgart.iaas.bpel.extensions.bpel4restlight; + +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; +import java.util.Properties; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.ode.bpel.common.FaultException; +import org.apache.ode.bpel.runtime.extension.AbstractSyncExtensionOperation; +import org.apache.ode.bpel.runtime.extension.ExtensionContext; +import org.opentosca.bpel4restlight.rest.HighLevelRestApi; +import org.opentosca.bpel4restlight.rest.HttpMethod; +import org.opentosca.bpel4restlight.rest.HttpResponseMessage; +/** + * + * Copyright 2011 IAAS University of Stuttgart
+ *
+ * + * This class provides 4 BPEL4RestLight ExtensionActivity-operations which + * correspond to the 4 typical REST-Operations GET, PUT, POST and Delete. + * + * @author uwe.breitenbuecher@iaas.uni-stuttgart.de + * + */ +import org.w3c.dom.Element; + +import de.unistuttgart.iaas.bpel.extensions.bpel4restlight.util.Bpel4RestLightUtil; +import de.unistuttgart.iaas.bpel.util.BPELVariableInjectionUtil; +import de.unistuttgart.iaas.bpel.util.BpelUtil; + + +public class Bpel4RestLightOperation extends AbstractSyncExtensionOperation { + protected static final Log log = LogFactory.getLog(Bpel4RestLightOperation.class); + private static final String EXT_PROPERTIES = "wso2bps-ext.properties"; // extra properties setting + private static final String MSB_URL = "MSB_URL"; // http://msb:port, ext property msb url, if exist replace the request url + + + public static String wrapper = "temporary-simple-type-wrapper"; + private static String msbUrl = null; + + static { + + try { + File file = new File(EXT_PROPERTIES); + if(file.exists()) { + Properties p=new Properties(); + InputStream inputStream = new FileInputStream(file); + p.load(inputStream); + inputStream.close(); + msbUrl = p.getProperty(MSB_URL); + } + + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + private void processResponseMessage(HttpResponseMessage responseMessage, ExtensionContext context, Element element) throws FaultException { + // Write responsePayload to designated variable + String responsePayloadVariableName = Bpel4RestLightUtil.getMethodAttributeValue(element, MethodAttribute.RESPONSEPAYLOADVARIABLE); + String statusCodeVariableName = Bpel4RestLightUtil.getMethodAttributeValue(element, MethodAttribute.STATUSCODEVARIABLE); + + if (responsePayloadVariableName != null && !responsePayloadVariableName.equals("")) { + BpelUtil.writeResponsePayloadToVariable(context, responseMessage.getResponseBody(), responsePayloadVariableName, Bpel4RestLightOperation.wrapper); + } + + if (statusCodeVariableName != null && !statusCodeVariableName.equals("")) { + String StatusCode = "" + responseMessage.getStatusCode(); // int can not be casted to String + + BpelUtil.writeResponsePayloadToVariable(context, StatusCode, statusCodeVariableName, Bpel4RestLightOperation.wrapper); + + } + } + + /** {@inheritDoc} */ + @Override + protected void runSync(ExtensionContext context, Element element) throws FaultException { + element = BPELVariableInjectionUtil.replaceExtensionVariables(context, element); + log.debug("LocalName of edited element: " + element.getLocalName()); + String httpMethod = element.getLocalName(); + + // Extract requestUri + String requestUri = getRequestUrl(element); + + HttpResponseMessage responseMessage = null; + String acceptHeader = Bpel4RestLightUtil.extractAcceptHeader(context, element); + String contentTypeHeader = Bpel4RestLightUtil.extractContentTypeHeader(context, element); + String requestPayload = Bpel4RestLightUtil.extractRequestPayload(context, element); + + // Execute corresponding HttpMethod via the HighLevelRestApi + switch (HttpMethod.valueOf(httpMethod)) { + + case PUT: { + responseMessage = HighLevelRestApi.Put(requestUri, requestPayload, acceptHeader, contentTypeHeader); + break; + } + + case POST: { + responseMessage = HighLevelRestApi.Post(requestUri, requestPayload, acceptHeader, contentTypeHeader); + break; + } + + case GET: { + responseMessage = HighLevelRestApi.Get(requestUri, acceptHeader, contentTypeHeader); + break; + } + + case DELETE: { + responseMessage = HighLevelRestApi.Delete(requestUri, acceptHeader, contentTypeHeader); + break; + } + } + + processResponseMessage(responseMessage, context, element); + // Bpel4RestLightOperation.wrapper = null; + } + + + /** + * getRequestUrl + * get request url from element, if exists msbUrl property, then replace the ip and port + * @param element + * @return + */ + private String getRequestUrl(Element element) { + String requestUri = Bpel4RestLightUtil.getMethodAttributeValue(element, MethodAttribute.REQUESTURI); + log.debug("original url:" + requestUri); + if(msbUrl == null || "".equals(msbUrl) || "http://msb:port".equals(msbUrl)) { + return requestUri; + } else { + requestUri = requestUri.substring(requestUri.indexOf("//") + 2); + int index = requestUri.indexOf("/"); + if(index == -1) { + + } else { + requestUri = requestUri.substring(index); + } + requestUri = msbUrl + requestUri; + log.debug("changed url:" + requestUri); + return requestUri; + } + } +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/extensions/bpel4restlight/EPRDemoOperation.java b/wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/extensions/bpel4restlight/EPRDemoOperation.java new file mode 100644 index 0000000..fd7b4b3 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/extensions/bpel4restlight/EPRDemoOperation.java @@ -0,0 +1,74 @@ +/** + * + * Copyright 2011 IAAS University of Stuttgart
+ *
+ * + * THIS CLASS IS USED FOR TEST PURPOSES! + * + * @author uwe.breitenbuecher@iaas.uni-stuttgart.de + * + */ +package de.unistuttgart.iaas.bpel.extensions.bpel4restlight; + +import java.net.HttpURLConnection; +import java.net.URL; + +import org.apache.ode.bpel.common.FaultException; +import org.apache.ode.bpel.o.OPartnerLink; +import org.apache.ode.bpel.runtime.PartnerLinkInstance; +import org.apache.ode.bpel.runtime.extension.AbstractSyncExtensionOperation; +import org.apache.ode.bpel.runtime.extension.ExtensionContext; +import org.w3c.dom.Element; + +import de.unistuttgart.iaas.xml.DomXmlConverter; + + +public class EPRDemoOperation extends AbstractSyncExtensionOperation { + + /** {@inheritDoc} */ + @Override + protected void runSync(ExtensionContext context, Element element) throws FaultException { + System.out.println("bin hier"); + try { + for (OPartnerLink l : context.getInternalInstance().getProcessModel().allPartnerLinks) { + + PartnerLinkInstance pli = context.getPartnerLinkInstance(l); + + Element epr = context.getInternalInstance().fetchPartnerRoleEndpointReferenceData(pli); + System.out.println("EPR|||"); + System.out.println(DomXmlConverter.nodeToString(epr, null)); + + System.out.println(epr.getChildNodes().item(0).getChildNodes().item(1).getNodeName()); + System.out.println(epr.getChildNodes().item(0).getChildNodes().item(1).getTextContent()); + System.out.println(".."); + System.out.println(epr.getChildNodes().item(0).getChildNodes().item(1).getChildNodes().item(0).getTextContent()); + + epr.getChildNodes().item(0).getChildNodes().item(1).getChildNodes().item(0).setTextContent("http://localhost:8084/FRP/rrr"); + + System.out.println(epr.getChildNodes().item(0).getChildNodes().item(1).getChildNodes().item(0).getTextContent()); + + System.out.println(context.getDUDir().toString()); + + } + + } catch (Exception e) { + e.printStackTrace(); + } + + System.out.println("ich bin hiiiiiiiiiier!!"); + + try { + URL url = new URL("http://localhost:8084/FRP/rrr"); + + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("PUT"); + + int responseCode = connection.getResponseCode(); + System.out.println(responseCode); + + } catch (Exception e) { + e.printStackTrace(); + } + } + +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/extensions/bpel4restlight/MethodAttribute.java b/wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/extensions/bpel4restlight/MethodAttribute.java new file mode 100644 index 0000000..ce80c16 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/extensions/bpel4restlight/MethodAttribute.java @@ -0,0 +1,17 @@ +/** + * + * Copyright 2011 IAAS University of Stuttgart
+ *
+ * + * This enum is used to decouple DOM-Attribute names from their + * String-representation within a certain library (for portability issues) + * + * @author uwe.breitenbuecher@iaas.uni-stuttgart.de + * + */ +package de.unistuttgart.iaas.bpel.extensions.bpel4restlight; + + +public enum MethodAttribute { + REQUESTURI, REQUESTPAYLOADVARIABLE, RESPONSEPAYLOADVARIABLE, STATUSCODEVARIABLE, ACCEPTHEADER, CONTENTTYPE; +} \ No newline at end of file diff --git a/wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/extensions/bpel4restlight/util/Bpel4RestLightUtil.java b/wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/extensions/bpel4restlight/util/Bpel4RestLightUtil.java new file mode 100644 index 0000000..1c9d7d1 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/extensions/bpel4restlight/util/Bpel4RestLightUtil.java @@ -0,0 +1,113 @@ +/** + * Copyright 2011 IAAS University of Stuttgart
+ *
+ * + * @author uwe.breitenbuecher@iaas.uni-stuttgart.de + * + */ +package de.unistuttgart.iaas.bpel.extensions.bpel4restlight.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.ode.bpel.common.FaultException; +import org.apache.ode.bpel.runtime.extension.ExtensionContext; +import org.w3c.dom.Element; +import org.w3c.dom.Node; + +import de.unistuttgart.iaas.bpel.extensions.bpel4restlight.Bpel4RestLightOperation; +import de.unistuttgart.iaas.bpel.extensions.bpel4restlight.MethodAttribute; +import de.unistuttgart.iaas.xml.DomXmlConverter; + + +public class Bpel4RestLightUtil { + protected static final Log log = LogFactory.getLog(Bpel4RestLightUtil.class); + /** + * This function extracts the requestPayload specified in the passed + * element. This requestPayload is either the content contained in a special + * BPEL-Variable which is referenced by name by a special attribute of the + * passed element or the content contained in the first child node of the + * passed element + * + * @param context ExtensionContext + * @param element Element from which the requestPayload has to be extracted + * @return RequestPayload as String + * @throws FaultException + */ + public static String extractRequestPayload(ExtensionContext context, Element element) throws FaultException { + + String requestPayload = ""; + + String requestPayloadVariableName = getMethodAttributeValue(element, MethodAttribute.REQUESTPAYLOADVARIABLE); + + if (requestPayloadVariableName != null && requestPayloadVariableName != "") { + Node requestVariableNode = context.readVariable(requestPayloadVariableName); + if (requestVariableNode.getLocalName().equals("temporary-simple-type-wrapper")) { + Bpel4RestLightOperation.wrapper = "temporary-simple-type-wrapper"; + requestPayload = DomXmlConverter.nodeToString(requestVariableNode, "temporary-simple-type-wrapper"); + } else { + requestPayload = DomXmlConverter.nodeToString(requestVariableNode, null); + } + log.debug("The pure request variable as String: \n" + DomXmlConverter.nodeToString(requestVariableNode, null) + "\n"); + } + + return requestPayload; + } + + public static String extractAcceptHeader(ExtensionContext context, Element element) throws FaultException { + return getMethodAttributeValue(element, MethodAttribute.ACCEPTHEADER); + } + + public static String extractContentTypeHeader(ExtensionContext context, Element element) throws FaultException { + return getMethodAttributeValue(element, MethodAttribute.CONTENTTYPE); + } + + /** + * This function extracts special predefined attributes (see + * {@link MethodAttribute}) from a passed DOM-Element + * + * @param element Element containing the requested Attribute-Value + * @param methodAttribute Attribute whose content has to be returned + * @return Value / Content of the attribute + */ + public static String getMethodAttributeValue(Element element, MethodAttribute methodAttribute) { + + String result = ""; + + switch (methodAttribute) { + + case REQUESTURI: + result = element.getAttribute("uri"); + + if (result == null || "".equals(result)) { + result = element.getAttribute("requestUri"); + } + break; + case REQUESTPAYLOADVARIABLE: + result = element.getAttribute("request"); + + if (result == null || "".equals(result)) { + result = element.getAttribute("requestPayload"); + } + break; + case RESPONSEPAYLOADVARIABLE: + result = element.getAttribute("response"); + + if (result == null || "".equals(result)) { + result = element.getAttribute("responsePayload"); + } + break; + case STATUSCODEVARIABLE: + result = element.getAttribute("statusCode"); + break; + case ACCEPTHEADER: + result = element.getAttribute("accept"); + break; + case CONTENTTYPE: + result = element.getAttribute("contentType"); + break; + } + + return result; + } + +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/util/BPELVariableInjectionUtil.java b/wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/util/BPELVariableInjectionUtil.java new file mode 100644 index 0000000..2298bf1 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/util/BPELVariableInjectionUtil.java @@ -0,0 +1,149 @@ +/** + * Copyright 2011 + * + * @author Uwe Breitenbuecher + * + * This class provides some methods for BPEL-Variable-Injection + */ + package de.unistuttgart.iaas.bpel.util; + +import java.io.IOException; +import java.io.StringReader; +import java.io.StringWriter; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.apache.ode.bpel.common.FaultException; +import org.apache.ode.bpel.runtime.extension.ExtensionContext; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + + +public class BPELVariableInjectionUtil { + + /** + * This method serializes a Node into a String + * + * @param node + * @return String representation of the node + */ + public static String nodeToString(Node node) { + try { + + if (node != null && node.getLocalName().equals("temporary-simple-type-wrapper")) { + // this is a temporary hack for string variables and the likes, + // as you may see ODE wrappes simpletypes in wrapper-elements, + // but this isn't great here + return node.getTextContent(); + } + + // Create transformer + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + + // Transform Node into a String representation by regarding some + // formatting rules + StringWriter stringWriter = new StringWriter(); + transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3"); + transformer.transform(new DOMSource(node), new StreamResult(stringWriter)); + + // Return build string + return stringWriter.toString(); + } catch (Exception e) { + e.printStackTrace(); + } + + // If any error occurs, return empty string + return ""; + } + + /** + * This method executes the BPEL-Variable-Injection. It replaces referenced + * BPEL-Variables with corresponding content + * + * @param context ExtensionContext of process + * @param element DOM-Representation of the BPEL-Code in which the + * Variable-Injection has to be done + * @return modified BPEL-Code as DOM-Representation + */ + public static Element replaceExtensionVariables(ExtensionContext context, Element element) { + + try { + String BPELCodeAsString; + + // Transform BPEL-Code (DOM-Representation) into a String + BPELCodeAsString = nodeToString(element); + + // Find and replace referenced BPEL-Variables + int startIndex = BPELCodeAsString.indexOf("$bpelvar["); + if (startIndex != -1) { + while (startIndex != -1) { + int endIndex = startIndex; + while (BPELCodeAsString.charAt(endIndex) != ']') { + endIndex++; + } + + // Extract name of referenced variable + String variableName = BPELCodeAsString.substring(startIndex + 9, endIndex); + + // Extract content of referenced variable + Node variableContent = context.readVariable(variableName); + + System.out.println("Replacing variable " + variableName + "(" + variableContent.getNamespaceURI() + " " + variableContent.getLocalName() + ") with content: \n"); + System.out.println("NodeValue(): " + variableContent.getNodeValue() + "\n"); + System.out.println("TextContent(): " + variableContent.getTextContent()); + System.out.println("The full bpel script (before change) as string: \n" + BPELCodeAsString + "\n"); + + // Replace variable-reference with corresponding content + BPELCodeAsString = BPELCodeAsString.replace("$bpelvar[" + variableName + "]", nodeToString(variableContent)); + + System.out.println("The full bpel script as string: \n" + BPELCodeAsString + "\n"); + startIndex = BPELCodeAsString.indexOf("$bpelvar["); + } + + // Transform modified code (String) into DOM-Representation + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setNamespaceAware(true); + DocumentBuilder builder = factory.newDocumentBuilder(); + + InputSource inputSource = new InputSource(); + inputSource.setCharacterStream(new StringReader(BPELCodeAsString)); + Document newDocument = builder.parse(inputSource); + + // Return first child (because Document root is not needed) + return (Element) newDocument.getFirstChild(); + + } else { + + // If no referenced variables are found, return original code + return element; + } + } catch (ParserConfigurationException e) { + e.printStackTrace(); + } catch (SAXException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (FaultException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return null; + } + +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/util/BpelUtil.java b/wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/util/BpelUtil.java new file mode 100644 index 0000000..33c0d54 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/bpel/util/BpelUtil.java @@ -0,0 +1,102 @@ +/** + * Copyright 2011 IAAS University of Stuttgart
+ *
+ * + * @author uwe.breitenbuecher@iaas.uni-stuttgart.de + * + */ +package de.unistuttgart.iaas.bpel.util; + +import java.io.IOException; +import java.io.StringReader; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.apache.ode.bpel.common.FaultException; +import org.apache.ode.bpel.evar.ExternalVariableModuleException; +import org.apache.ode.bpel.o.OScope.Variable; +import org.apache.ode.bpel.runtime.extension.ExtensionContext; +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + + +public class BpelUtil { + + /** + * This function writes a passed content to a specified processVariable + * (referenced by name). The content will be converted into its + * DOM-Representation for overwriting the processVariableContent (therefore + * it has to be XML-serializable, e.g. for complex data types there have to + * be JAX-B Annotations within the corresponding Class) + * + * @param context ExtensionContext needed to access the processVariable + * @param content New content for the specified processVariable + * @param processVariableName Variable whose content has to be overwritten + * @throws FaultException + */ + public static void writeContentToBPELVariable(ExtensionContext context, Object content, String processVariableName, String wrapper) throws FaultException { + // check the node + System.out.println("The content object: " + content + "\n"); + // small hack for test + Node hackNode = null; + System.out.println("Trying to parse string to dom: " + ((String) content) + "\n"); + + if (wrapper != null) { + // a hack for simple type wrapper + content = "<" + wrapper + ">" + (String) content + ""; + } + try { + hackNode = stringToDom((String) content); + } catch (ParserConfigurationException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } catch (SAXException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } catch (IOException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + + Variable bpelVariable = context.getVisibleVariables().get(processVariableName); + if (hackNode == null) { + System.out.println("hackNode is null! \n"); + } + if (bpelVariable == null) { + System.out.println("bpelVariable is null! \n"); + } + try { + // replaced responseAsNode to hackNode + context.writeVariable(bpelVariable, hackNode); + } catch (ExternalVariableModuleException e) { + e.printStackTrace(); + } + + } + + /** + * This function writes a String to a BPEL Variable of type XSD-String + * + * @param context ExtensionContext + * @param responsePayload ResponsePayload as String + * @param processVariableName Name of the target BPEL variable + * @throws FaultException + */ + public static void writeResponsePayloadToVariable(ExtensionContext context, Object responsePayload, String processVariableName, String wrapper) throws FaultException { + BpelUtil.writeContentToBPELVariable(context, responsePayload, processVariableName, wrapper); + } + + private static Node stringToDom(String xmlString) throws ParserConfigurationException, SAXException, IOException { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setNamespaceAware(true); + DocumentBuilder builder = factory.newDocumentBuilder(); + InputSource is = new InputSource(new StringReader(xmlString)); + Document d = builder.parse(is); + return d.getFirstChild(); + } + +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/xml/DomXmlConverter.java b/wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/xml/DomXmlConverter.java new file mode 100644 index 0000000..cbce6e8 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/xml/DomXmlConverter.java @@ -0,0 +1,179 @@ +/** + * + * Copyright 2011 IAAS University of Stuttgart
+ *
+ * + * @author uwe.breitenbuecher@iaas.uni-stuttgart.de + * + */ +package de.unistuttgart.iaas.xml; + +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.List; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Marshaller; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Result; +import javax.xml.transform.Source; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + + +public class DomXmlConverter { + + // Single instance of transformer + private static Transformer xmlTransformer; + + + /** + * Converts a Node to its String-representation + * + * @param node Node which has to be converted + * @return String representation of the passed node + */ + public static String nodeToString(Node node, String wrapperElement) { + try { + System.out.println("\n\n\n"); + System.out.println("check if node got a namespace: " + node.getNamespaceURI()); + if (wrapperElement != null) { + // this hack is need as ODE wrapps simpletypes in such elements + return node.getTextContent(); + } + + Source source = new DOMSource(node); + + StringWriter writer = new StringWriter(); + Result result = new StreamResult(writer); + + Transformer transformer = DomXmlConverter.getTransformer(); + transformer.transform(source, result); + + return writer.toString(); + } catch (Exception e) { + e.printStackTrace(); + } + return "Parsing error"; + } + + /** + * Singleton implementation of transformer access + * + * @return Transformer + * @throws Exception + */ + private static synchronized Transformer getTransformer() throws Exception { + if (DomXmlConverter.xmlTransformer == null) { + DomXmlConverter.xmlTransformer = TransformerFactory.newInstance().newTransformer(); + DomXmlConverter.xmlTransformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); + DomXmlConverter.xmlTransformer.setOutputProperty(OutputKeys.INDENT, "yes"); + DomXmlConverter.xmlTransformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); + } + return DomXmlConverter.xmlTransformer; + } + + /** + * This method converts a NodeList into a List of Strings. Each string + * represents the TextContent of each Node contained in the NodeList + * + * @param nodeList which contains the Nodes + * @return List of TextContents of each node + */ + public static List convertNodeListToStringList(NodeList nodeList) { + List resultList = new ArrayList(); + + for (int i = 0; i < nodeList.getLength(); i++) { + resultList.add(nodeList.item(i).getTextContent()); + } + + return resultList; + } + + /** + * This method converts a NodeList into a List of Nodes + * + * @param nodeList + * @return List of Nodes + */ + public static List convertNodeListToList(NodeList nodeList) { + List resultList = new ArrayList(nodeList.getLength()); + for (int i = 0; i < nodeList.getLength(); i++) { + resultList.add(nodeList.item(i)); + } + return resultList; + } + + + /** + * Helper-Class for converting an Object into its DOM-Representation. The + * SerializingContainer is a Wrapper to enable the serialization of any + * object via JAXB. + */ + @XmlRootElement + private static class SerializingContainer { + + Object object; + + + public Object getObject() { + return this.object; + } + + public void setObject(Object object) { + this.object = object; + } + + } + + + /** + * This methods converts an Object into its DOM-Representation + * + * @param object which have to be converted + * @return DOM-Representation of the object + */ + public static Node convertObjectToDom(Object object) { + try { + + // Create new SerializingContainer and pack the object, which has to + // be serialized, into it. This has to be done, because JAXB + // only marshalls objects of classes annotated with the + // @XmlRootElement-Annotation. + SerializingContainer container = new SerializingContainer(); + container.setObject(object); + + // Create empty Document + Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); + + // Create JAXBContext and bind classes + Class[] classesToBeBound = new Class[] {SerializingContainer.class, container.getObject().getClass()}; + JAXBContext jaxbContext = JAXBContext.newInstance(classesToBeBound, null); + + Marshaller marshaller = jaxbContext.createMarshaller(); + + // Set some properties + marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); + marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); + + // Marshall container into document. + marshaller.marshal(container, document); + + // Extract only the contained information in the serialized + // DOM-Representation of the SerializingContainer + return document.getFirstChild().getFirstChild(); + + } catch (Exception e) { + return null; + } + } + +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/xml/XPathEvaluator.java b/wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/xml/XPathEvaluator.java new file mode 100644 index 0000000..0ae6b2c --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/de/unistuttgart/iaas/xml/XPathEvaluator.java @@ -0,0 +1,34 @@ +/** + * + * Copyright 2011 IAAS University of Stuttgart
+ *
+ * + * @author uwe.breitenbuecher@iaas.uni-stuttgart.de + * + */ +package de.unistuttgart.iaas.xml; + +import javax.xml.namespace.QName; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathFactory; + + +public class XPathEvaluator { + + public static XPath xpath = XPathFactory.newInstance().newXPath(); + + + @SuppressWarnings("unchecked") + public static t evaluate(String expression, Object source, QName returnType) { + + Object resultAsObject = null; + try { + resultAsObject = xpath.evaluate(expression, source, returnType); + + } catch (Exception e) { + e.printStackTrace(); + } + return (t) resultAsObject; + } + +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/org/opentosca/bpel4restlight/rest/HighLevelRestApi.java b/wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/org/opentosca/bpel4restlight/rest/HighLevelRestApi.java new file mode 100644 index 0000000..ec10959 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/org/opentosca/bpel4restlight/rest/HighLevelRestApi.java @@ -0,0 +1,178 @@ +/******************************************************************************* + * Copyright (c) 2012-2013 University of Stuttgart. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and the Apache License 2.0 which both accompany this distribution, + * and are available at http://www.eclipse.org/legal/epl-v10.html + * and http://www.apache.org/licenses/LICENSE-2.0 + *******************************************************************************/ +/* + * Modifications Copyright 2016-2017 ZTE Corporation. + */ +/** + * This class wraps HTTP-Method functionality and thereby abstracts from low + * level code to simplify the usage. + */ +package org.opentosca.bpel4restlight.rest; + +import org.apache.commons.httpclient.HttpMethodBase; +import org.apache.commons.httpclient.NameValuePair; +import org.apache.commons.httpclient.methods.DeleteMethod; +import org.apache.commons.httpclient.methods.GetMethod; +import org.apache.commons.httpclient.methods.PostMethod; +import org.apache.commons.httpclient.methods.PutMethod; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.http.HttpHeaders; + + +public class HighLevelRestApi { + protected static final Log log = LogFactory.getLog(HighLevelRestApi.class); + /** + * This method implements the HTTP Put Method + * + * @param uri + * Resource URI + * @param requestPayload + * Content which has to be put into the Resource + * @return ResponseCode of HTTP Interaction + */ + @SuppressWarnings("deprecation") + public static HttpResponseMessage Put(String uri, String requestPayload, String acceptHeaderValue, String contentTypeHeader) { + + PutMethod method = new PutMethod(uri); + // requestPayload = "" + + // requestPayload; + + HighLevelRestApi.setHeader(method, acceptHeaderValue, contentTypeHeader); + method.setRequestBody(requestPayload); + + HttpResponseMessage responseMessage = LowLevelRestApi.executeHttpMethod(method); + + // kill ", ""); + responseMessage.setResponseBody(temp); + } + } + +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/org/opentosca/bpel4restlight/rest/HttpMethod.java b/wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/org/opentosca/bpel4restlight/rest/HttpMethod.java new file mode 100644 index 0000000..209cca3 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/org/opentosca/bpel4restlight/rest/HttpMethod.java @@ -0,0 +1,20 @@ +/******************************************************************************* + * Copyright (c) 2012-2013 University of Stuttgart. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and the Apache License 2.0 which both accompany this distribution, + * and are available at http://www.eclipse.org/legal/epl-v10.html + * and http://www.apache.org/licenses/LICENSE-2.0 + *******************************************************************************/ +/* + * Modifications Copyright 2016-2017 ZTE Corporation. + */ +/** + * This enum is intended to simplify identifying different HTTP-methods + */ +package org.opentosca.bpel4restlight.rest; + + +public enum HttpMethod { + PUT, POST, GET, DELETE +} \ No newline at end of file diff --git a/wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/org/opentosca/bpel4restlight/rest/HttpResponseMessage.java b/wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/org/opentosca/bpel4restlight/rest/HttpResponseMessage.java new file mode 100644 index 0000000..07198d8 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/org/opentosca/bpel4restlight/rest/HttpResponseMessage.java @@ -0,0 +1,53 @@ +/******************************************************************************* + * Copyright (c) 2012-2013 University of Stuttgart. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and the Apache License 2.0 which both accompany this distribution, + * and are available at http://www.eclipse.org/legal/epl-v10.html + * and http://www.apache.org/licenses/LICENSE-2.0 + *******************************************************************************/ +/* + * Modifications Copyright 2016-2017 ZTE Corporation. + */ +/** + * This enum is intended to simplify identifying different HTTP-methods + */ +package org.opentosca.bpel4restlight.rest; + +/** + */ +public class HttpResponseMessage { + + private int statusCode; + private String responseBody; + + + /** + * @return the statusCode + */ + public int getStatusCode() { + return this.statusCode; + } + + /** + * @param statusCode the statusCode to set + */ + protected void setStatusCode(int statusCode) { + this.statusCode = statusCode; + } + + /** + * @return the responseBody + */ + public String getResponseBody() { + return this.responseBody; + } + + /** + * @param responseBody the responseBody to set + */ + protected void setResponseBody(String responseBody) { + this.responseBody = responseBody; + } + +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/org/opentosca/bpel4restlight/rest/LowLevelRestApi.java b/wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/org/opentosca/bpel4restlight/rest/LowLevelRestApi.java new file mode 100644 index 0000000..c522ca9 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/org/opentosca/bpel4restlight/rest/LowLevelRestApi.java @@ -0,0 +1,182 @@ +/******************************************************************************* + * Copyright (c) 2012-2013 University of Stuttgart. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and the Apache License 2.0 which both accompany this distribution, + * and are available at http://www.eclipse.org/legal/epl-v10.html + * and http://www.apache.org/licenses/LICENSE-2.0 + *******************************************************************************/ +/* + * Modifications Copyright 2016-2017 ZTE Corporation. + */ + /** + * This static-class eases HTTP-method execution by self-managed fault-handling + * and automated Response-information processing + */ +package org.opentosca.bpel4restlight.rest; + +import java.io.IOException; +import java.util.Map; +import java.util.Set; + +import org.apache.commons.httpclient.Header; +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.HttpMethod; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; + + +public class LowLevelRestApi { + + protected static final Log log = LogFactory.getLog(LowLevelRestApi.class); + // Local HttpClient used for every communication (Singleton implementation) +// private static HttpClient httpClient = new HttpClient(); + + /** + * Executes a passed HttpMethod (Method type is either PUT, POST, GET or + * DELETE) and returns a HttpResponseMessage + * + * @param method Method to execute + * @return HttpResponseMessage which contains all information about the + * execution + */ + public static HttpResponseMessage executeHttpMethod(HttpMethod method) { + + HttpResponseMessage responseMessage = null; + + try { + log.debug("Method invocation on URI: \n"); + log.debug(method.getURI().toString()); + + // Execute Request + HttpClient httpClient = new HttpClient(); + httpClient.executeMethod(method); + responseMessage = LowLevelRestApi.extractResponseInformation(method); + + } catch (Exception e) { + log.error("call rest error:", e); + } finally { + // Release Connection anyway + method.releaseConnection(); + } + + // Extract response information and return + return responseMessage; + } + + /** + * Extracts the response information from an executed HttpMethod + * + * @param method Executed Method + * @return Packaged response information + */ + private static HttpResponseMessage extractResponseInformation(HttpMethod method) { + // Create and return HttpResponseMethod + HttpResponseMessage responseMessage = new HttpResponseMessage(); + responseMessage.setStatusCode(method.getStatusCode()); + try { + responseMessage.setResponseBody(getResponseBody(method)); + } catch (Exception e) { + log.error(e); + } + return responseMessage; + + } + + /** + * getResponseBody + * + * get response body info, if response body is a json object, then translate json object to xml + * if the rest request failed, i.e. the response body is a 404 error page, then response the body with header + * @param method + * @return + * @throws ParseException + */ + private static String getResponseBody(HttpMethod method) throws ParseException + { + String result = null; + try { + result = method.getResponseBodyAsString(); + log.debug("result:"); + log.debug(result); + } catch (IOException e) { + log.error(e); + } + + Header header = method.getRequestHeader("Accept"); + if ("application/json".equals(header.getValue())) { + StringBuilder sb = new StringBuilder(); + sb.append(""); + sb.append(""); + if(result != null && !"".equals(result)) { + /** + if(result.startsWith("")) { + sb.append(""); + } else { + Object json = new JSONParser().parse(result); + json2Xml(sb, "obj", json); + } + */ + + try { + Object json = new JSONParser().parse(result); + json2Xml(sb, "obj", json); + } catch (Exception e) { + log.error(e); + sb.append(""); + } + } + sb.append(""); + + log.debug("responseBody:"); + log.debug(sb.toString()); + return sb.toString(); + } + return result; + } + + + @SuppressWarnings("unchecked") + public static void json2Xml(StringBuilder sb, String key, Object jsonObject) { + if(jsonObject == null) { + sb.append("empty"); + return; + } + + if(jsonObject instanceof JSONArray) { + JSONArray array = (JSONArray) jsonObject; + sb.append("<").append(key).append("s").append(">"); + for(int i=0, len=array.size(); i"); + + return; + } else if(jsonObject instanceof JSONObject) { + sb.append("<").append(key).append(">"); + JSONObject json = (JSONObject) jsonObject; + for(Map.Entry entry : (Set>)json.entrySet()) { + json2Xml(sb, entry.getKey(), entry.getValue()); + } + sb.append(""); + return; + } else { + sb.append("<").append(key).append(">"); + sb.append(""); + sb.append(""); + + return; + } + } + +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/distribution/pom.xml b/wso2/wso2bpel-ext/wso2bpel-core/distribution/pom.xml new file mode 100644 index 0000000..fd6c48c --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/distribution/pom.xml @@ -0,0 +1,34 @@ + + + + + org.openo.common-services.common-utilities.wso2bpel-ext + wso2bpel-core-parent + 1.1.0-SNAPSHOT + + + 4.0.0 + distribution + common-services-common-utilities/wso2bpel-ext/wso2bpel-core/distribution + pom + + + standalone + + diff --git a/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/pom.xml b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/pom.xml new file mode 100644 index 0000000..1ec096d --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/pom.xml @@ -0,0 +1,401 @@ + + + + + org.openo.common-services.common-utilities.wso2bpel-ext + distribution + 1.1.0-SNAPSHOT + + + 4.0.0 + standalone + common-services-common-utilities/wso2bpel-ext/wso2bpel-core/distribution/standalone + pom + + + openo-commonservice-commonutilities-wso2bpel-ext + linux64 + win64 + target/assembly/${linux64id} + target/assembly/${win64id} + target/version + + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-jar-${linux64id} + + copy + + prepare-package + + + + org.openo.common-services.common-utilities.wso2bpel-ext + wso2bpel-mgr + jar + true + ${linux64outputdir}/wso2bps-ext + wso2bpel-service.jar + + + + + + copy-jar-${win64id} + + copy + + prepare-package + + + + org.openo.common-services.common-utilities.wso2bpel-ext + wso2bpel-mgr + jar + true + ${win64outputdir}/wso2bps-ext + wso2bpel-service.jar + + + + + + unzip-wso2bps-${linux64id} + + unpack + + generate-resources + + + + com.wso2 + wso2bps + zip + true + target/assembly/wso2bps + + + + + + unzip-wso2bps-${win64id} + + unpack + + generate-resources + + + + com.wso2 + wso2bps + zip + true + target/assembly/wso2bps + + + + + + + + maven-resources-plugin + + + copy-resources-${linux64id} + process-resources + + copy-resources + + + ${linux64outputdir} + + + src/main/assembly/ + false + + **/* + + + **/*.bat + + + + true + + + + copy-resources-${win64id} + process-resources + + copy-resources + + + ${win64outputdir} + + + src/main/assembly/ + false + + **/* + + + **/*.sh + + + + true + + + + copy-ext-resources-${linux64id} + process-resources + + copy-resources + + + ${linux64outputdir}/wso2bps + + + target/assembly/wso2bps/wso2bps-3.5.0 + false + + **/*.bat + + + + true + + + + copy-ext-resources-${win64id} + process-resources + + copy-resources + + + ${win64outputdir}/wso2bps + + + target/assembly/wso2bps/wso2bps-3.5.0 + false + + **/*.sh + + + + true + + + + + copy-config-resources-linux + process-resources + + copy-resources + + + ${linux64outputdir}/wso2bps/repository/conf + + + src/main/assembly/wso2bps/repository/conf/carbon + false + + **/* + + + + true + + + + copy-config-resources-win + process-resources + + copy-resources + + + ${win64outputdir}/wso2bps/repository/conf + + + src/main/assembly/wso2bps/repository/conf/carbon + false + + **/* + + + + true + + + + copy-bpel4rest-resources-linux + process-resources + + copy-resources + + + ${linux64outputdir}/wso2bps/repository/components/lib + + + ../../BPEL4RESTLight/target + false + + **/bpel4rest.jar + + + + true + + + + copy-bpel4rest-resources-win + process-resources + + copy-resources + + + ${win64outputdir}/wso2bps/repository/components/lib + + + ../../BPEL4RESTLight/target + false + + **/bpel4rest.jar + + + + true + + + + + + org.apache.maven.plugins + maven-antrun-plugin + + + distribution + package + + run + + + + + + + + + + + + + + + + + + + + + + + + + + + + org.openo.common-services.common-utilities.wso2bpel-ext + wso2bpel-mgr + ${project.version} + + + com.wso2 + wso2bps + 3.5.0 + zip + + + diff --git a/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/initDB.sh b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/initDB.sh new file mode 100644 index 0000000..eacbaf2 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/initDB.sh @@ -0,0 +1,53 @@ +#!/bin/bash +# +# Copyright 2016 ZTE Corporation. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +DIRNAME=`dirname $0` +HOME=`cd $DIRNAME/; pwd` +user=$1 +password=$2 +port=$3 +host=$4 + + +echo "start to change db ip and port" +sed -i "s|localhost|$host|" wso2bps/repository/conf/datasources/bps-datasources.xml +sed -i "s|3306|$port|" wso2bps/repository/conf/datasources/bps-datasources.xml +cat wso2bps/repository/conf/datasources/bps-datasources.xml +echo "end of change db ip and port" +echo "" + +echo "start create wso2 bpel db" +mysql -u$user -p$password -P$port -h$host <$HOME/wso2bps/dbscripts/bps/bpel/create/wso-bpel-mysql-createdb.sql +sql_result=$? +if [ $sql_result != 0 ] ; then + echo "failed to create wso2 bpel database" + exit 1 +fi + + +echo "start create wso2 bpel table" +mysql -u$user -p$password -P$port -h$host -Dwso_bpel <$HOME/wso2bps/dbscripts/bps/bpel/create/mysql.sql +sql_result=$? +if [ $sql_result != 0 ] ; then + echo "failed to create wso2 bpel table" + exit 1 +fi + +echo "init wso2 bpel database success!" +exit 0 + + diff --git a/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/run.bat b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/run.bat new file mode 100644 index 0000000..752c415 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/run.bat @@ -0,0 +1,32 @@ +@REM +@REM Copyright 2016-2017 ZTE Corporation. +@REM +@REM Licensed under the Apache License, Version 2.0 (the "License"); +@REM you may not use this file except in compliance with the License. +@REM You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, software +@REM distributed under the License is distributed on an "AS IS" BASIS, +@REM WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@REM See the License for the specific language governing permissions and +@REM limitations under the License. +@REM + +@echo off +title wso2 + +set RUNHOME=%~dp0 +echo ##RUNHOME %RUNHOME% + + +echo ### Starting wso2bps +start /D %RUNHOME%wso2bps bin\wso2server.bat +cd /D %RUNHOME%wso2bps-ext\bin + +echo ### Starting wso2bps-ext +start startup.bat + +cd /D %RUNHOME% + diff --git a/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/run.sh b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/run.sh new file mode 100644 index 0000000..a57d017 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/run.sh @@ -0,0 +1,32 @@ +# +# Copyright 2016-2017 ZTE Corporation. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + + +DIRNAME=`dirname $0` +RUNHOME=`cd $DIRNAME/; pwd` +echo @RUNHOME@ $RUNHOME + +echo "### Starting wso2bps"; +cd wso2bps +$RUNHOME/wso2bps/bin/wso2server.sh & +cd $RUNHOME + + +echo "\n\n### Starting wso2bps-ext" +cd wso2bps-ext +$RUNHOME/wso2bps-ext/bin/startup.sh & +echo "### Starting wso2 end..."; + diff --git a/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/stop.bat b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/stop.bat new file mode 100644 index 0000000..60ebad4 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/stop.bat @@ -0,0 +1,28 @@ +@REM +@REM Copyright 2016 ZTE Corporation. +@REM +@REM Licensed under the Apache License, Version 2.0 (the "License"); +@REM you may not use this file except in compliance with the License. +@REM You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, software +@REM distributed under the License is distributed on an "AS IS" BASIS, +@REM WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@REM See the License for the specific language governing permissions and +@REM limitations under the License. +@REM + +@echo off +title wso2 + +set RUNHOME=%~dp0 +echo ##RUNHOME %RUNHOME% + + +echo ### Starting wso2bps +start /D %RUNHOME%wso2bps bin\shutdown.bat + +echo ### Starting wso2bps-ext +start /D %RUNHOME%wso2bps-ext bin\shutdown.bat diff --git a/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/stop.sh b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/stop.sh new file mode 100644 index 0000000..29e23f5 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/stop.sh @@ -0,0 +1,30 @@ +# +# Copyright 2016 ZTE Corporation. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +DIRNAME=`dirname $0` +RUNHOME=`cd $DIRNAME/; pwd` +echo @RUNHOME@ $RUNHOME + +echo "### Shutdown wso2bps"; +cd wso2bps +$RUNHOME/wso2bps/bin/shutdown.sh & +cd $RUNHOME + + +echo "\n\n### Shutdown wso2bps-ext" +cd wso2bps-ext +$RUNHOME/wso2bps-ext/bin/shutdown.sh & +echo "### Shutdown wso2 end..."; diff --git a/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps-ext/bin/find_kill_process.bat b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps-ext/bin/find_kill_process.bat new file mode 100644 index 0000000..a4a2f06 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps-ext/bin/find_kill_process.bat @@ -0,0 +1,24 @@ +@REM +@REM Copyright 2016 ZTE Corporation. +@REM +@REM Licensed under the Apache License, Version 2.0 (the "License"); +@REM you may not use this file except in compliance with the License. +@REM You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, software +@REM distributed under the License is distributed on an "AS IS" BASIS, +@REM WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@REM See the License for the specific language governing permissions and +@REM limitations under the License. +@REM + +echo %1 | findstr %2 >NUL +echo ERRORLEVEL=%ERRORLEVEL% +IF ERRORLEVEL 1 goto findend +for /f "tokens=1" %%a in (%1) do ( + echo kill %1 + taskkill /F /pid %%a +) +:findend \ No newline at end of file diff --git a/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps-ext/bin/shutdown.bat b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps-ext/bin/shutdown.bat new file mode 100644 index 0000000..76b2f58 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps-ext/bin/shutdown.bat @@ -0,0 +1,34 @@ +@REM +@REM Copyright 2016 ZTE Corporation. +@REM +@REM Licensed under the Apache License, Version 2.0 (the "License"); +@REM you may not use this file except in compliance with the License. +@REM You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, software +@REM distributed under the License is distributed on an "AS IS" BASIS, +@REM WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@REM See the License for the specific language governing permissions and +@REM limitations under the License. +@REM + +@echo off +title stopping wso2bpel-service + +set HOME=%~dp0 +set Main_Class="org.openo.carbon.bpel.Wso2BpelApplication" + +echo ================== wso2bpel-service info ============================================= +echo HOME=$HOME +echo Main_Class=%Main_Class% +echo =============================================================================== + +echo ### Stopping wso2bpel-service +cd /d %HOME% + +for /f "delims=" %%i in ('"%JAVA_HOME%\bin\jcmd"') do ( + call find_kill_process "%%i" %Main_Class% +) +exit \ No newline at end of file diff --git a/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps-ext/bin/shutdown.sh b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps-ext/bin/shutdown.sh new file mode 100644 index 0000000..6d5d93f --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps-ext/bin/shutdown.sh @@ -0,0 +1,61 @@ +# +# Copyright 2016 ZTE Corporation. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +#!/bin/bash +# +# +# Copyright 2016 [ZTE] and others. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +DIRNAME=`dirname $0` +HOME=`cd $DIRNAME/; pwd` +Main_Class="org.openo.carbon.bpel.Wso2BpelApplication" + +echo ================== wso2bpel-service info ============================================= +echo HOME=$HOME +echo Main_Class=$Main_Class +echo =============================================================================== +cd $HOME; pwd + +echo @WORK_DIR@ $HOME + +function save_service_pid(){ + service_pid=`ps -ef | grep $Main_Class | grep -v grep | awk '{print $2}'` + echo @service_pid@ $service_pid +} + +function kill_service_process(){ + ps -p $service_pid + if [ $? == 0 ]; then + kill -9 $service_pid + fi +} + +save_service_pid; +echo @C_CMD@ kill -9 $service_pid +kill_service_process; diff --git a/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps-ext/bin/startup.bat b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps-ext/bin/startup.bat new file mode 100644 index 0000000..95c0b59 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps-ext/bin/startup.bat @@ -0,0 +1,42 @@ +@REM +@REM Copyright 2016 ZTE Corporation. +@REM +@REM Licensed under the Apache License, Version 2.0 (the "License"); +@REM you may not use this file except in compliance with the License. +@REM You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, software +@REM distributed under the License is distributed on an "AS IS" BASIS, +@REM WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@REM See the License for the specific language governing permissions and +@REM limitations under the License. +@REM + +@echo off +title wso2bpel-service + +set RUNHOME=%~dp0 +echo ### RUNHOME: %RUNHOME% +echo ### Starting wso2bpel-service +set WSO2_EXT_HOME=%RUNHOME%\.. + +set JAVA="%JAVA_HOME%\bin\java.exe" +set port=8312 +set jvm_opts=-Xms50m -Xmx128m +rem set jvm_opts=%jvm_opts% -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,address=%port%,server=y,suspend=n +set jvm_opts=%jvm_opts% -DWSO2_EXT_HOME=%WSO2_EXT_HOME% +set class_path=%RUNHOME%;%WSO2_EXT_HOME%\lib\*;%WSO2_EXT_HOME%\wso2bpel-service.jar +echo ### jvm_opts: %jvm_opts% +echo ### class_path: %class_path% + +%JAVA% -classpath %class_path% %jvm_opts% org.openo.carbon.bpel.Wso2BpelApplication server %WSO2_EXT_HOME%/conf/wso2bpel.yml + +IF ERRORLEVEL 1 goto showerror +exit +:showerror +echo WARNING: Error occurred during startup or Server abnormally stopped by way of killing the process,Please check! +echo After checking, press any key to close +pause +exit \ No newline at end of file diff --git a/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps-ext/bin/startup.sh b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps-ext/bin/startup.sh new file mode 100644 index 0000000..c8ea31a --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps-ext/bin/startup.sh @@ -0,0 +1,36 @@ +# +# Copyright 2016 ZTE Corporation. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +DIRNAME=`dirname $0` +RUNHOME=`cd $DIRNAME/; pwd` +WSO_EXT_HOME=${RUNHOME}/.. +echo @RUNHOME@ $RUNHOME + +echo @JAVA_HOME@ $JAVA_HOME +JAVA="$JAVA_HOME/bin/java" +echo @JAVA@ $JAVA + +JAVA_OPTS="-Xms50m -Xmx128m -Djava.awt.headless=true" +port=8312 +# JAVA_OPTS="$JAVA_OPTS -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,address=$port,server=y,suspend=n" +JAVA_OPTS="$JAVA_OPTS -DWSO2_EXT_HOME=${WSO_EXT_HOME}" +echo @JAVA_OPTS@ $JAVA_OPTS + +class_path="$RUNHOME/:$RUNHOME/../lib/*:$RUNHOME/../wso2bpel-service.jar" +echo @class_path@ $class_path + +"$JAVA" $JAVA_OPTS -classpath "$class_path" org.openo.carbon.bpel.Wso2BpelApplication server "$RUNHOME/../conf/wso2bpel.yml" + diff --git a/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps-ext/conf/wso2bpel.yml b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps-ext/conf/wso2bpel.yml new file mode 100644 index 0000000..b56bb5a --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps-ext/conf/wso2bpel.yml @@ -0,0 +1,73 @@ +# +# Copyright 2016-2017 ZTE Corporation. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +template: Hello, %s! + +# defaultName: ${DW_DEFAULT_NAME:-Stranger} +# the micro service ip +serviceIp: +msbServerAddr: http://127.0.0.1:80 + +wso2Host: localhost +wso2HostPort: 9443 +wso2AuthUserName: admin +wso2AuthPassword: admin +wso2Path: ../wso2bps +wso2UploadFilePath: ../wso2bps/tmp/bpeluploads +wso2SslJksFile: ../wso2bps/repository/resources/security/wso2carbon.jks +wso2SslJksPassword: wso2carbon + + +# use the simple server factory if you only want to run on a single port +#server: +# type: simple +# connector: +# type: http +# port: 8080 +server: + type: simple + rootPath: '/openoapi/wso2bpel/v1/*' + applicationContextPath: / + adminContextPath: /admin + connector: + type: http + port: 8101 + +# Logging settings. +logging: + + # The default level of all loggers. Can be OFF, ERROR, WARN, INFO, DEBUG, TRACE, or ALL. + level: ALL + + # Logger-specific levels. + loggers: + + # Sets the level for 'com.example.app' to DEBUG. + org.openo.carbon.bpel.Wso2BpelApplication: INFO + + appenders: + - type: console + threshold: INFO + timeZone: UTC + logFormat: "%d{yyyy-MM-dd HH:mm:ss SSS} %-5p [%c][%t] - %m%n" + - type: file + threshold: INFO + logFormat: "%d{yyyy-MM-dd HH:mm:ss SSS} %-5p [%c][%t] - %m%n" + currentLogFilename: ./logs/wso2bpel-ext.log + archivedLogFilenamePattern: ./logs/zip/wso2bpel-ext-%d{yyyy-MM-dd}.log.gz + archivedFileCount: 7 + timeZone: UTC + diff --git a/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/bin/find_kill_process.bat b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/bin/find_kill_process.bat new file mode 100644 index 0000000..d89cf27 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/bin/find_kill_process.bat @@ -0,0 +1,23 @@ +@REM +@REM Copyright (C) 2015 ZTE, Inc. and others. All rights reserved. (ZTE) +@REM +@REM Licensed under the Apache License, Version 2.0 (the "License"); +@REM you may not use this file except in compliance with the License. +@REM You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, software +@REM distributed under the License is distributed on an "AS IS" BASIS, +@REM WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@REM See the License for the specific language governing permissions and +@REM limitations under the License. +@REM +echo %1 | findstr %2 >NUL +echo ERRORLEVEL=%ERRORLEVEL% +IF ERRORLEVEL 1 goto findend +for /f "tokens=1" %%a in (%1) do ( + echo kill %1 + taskkill /F /pid %%a +) +:findend \ No newline at end of file diff --git a/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/bin/shutdown.bat b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/bin/shutdown.bat new file mode 100644 index 0000000..d932cb7 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/bin/shutdown.bat @@ -0,0 +1,34 @@ +@REM +@REM Copyright (C) 2015 ZTE, Inc. and others. All rights reserved. (ZTE) +@REM +@REM Licensed under the Apache License, Version 2.0 (the "License"); +@REM you may not use this file except in compliance with the License. +@REM You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, software +@REM distributed under the License is distributed on an "AS IS" BASIS, +@REM WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@REM See the License for the specific language governing permissions and +@REM limitations under the License. +@REM +@echo off +title stopping WSO2 + +set HOME=%~dp0 +set Main_Class="org.wso2.carbon.bootstrap.Bootstrap" + +echo ================== WSO2 info ============================================= +echo HOME=$HOME +echo Main_Class=%Main_Class% +echo =============================================================================== + +echo ### Stopping WSO2 +cd /d %HOME% + +rem set JAVA_HOME=D:\WorkSoftware\jdk1.7.0_60 +for /f "delims=" %%i in ('"%JAVA_HOME%\bin\jcmd"') do ( + call find_kill_process "%%i" %Main_Class% +) +exit diff --git a/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/bin/shutdown.sh b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/bin/shutdown.sh new file mode 100644 index 0000000..06a0950 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/bin/shutdown.sh @@ -0,0 +1,44 @@ +#!/bin/bash +# +# Copyright (C) 2015 ZTE, Inc. and others. All rights reserved. (ZTE) +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +DIRNAME=`dirname $0` +HOME=`cd $DIRNAME/; pwd` +Main_Class="org.wso2.carbon.bootstrap.Bootstrap" + +echo ================== umc-service info ============================================= +echo HOME=$HOME +echo Main_Class=$Main_Class +echo =============================================================================== +cd $HOME; pwd + +echo @WORK_DIR@ $HOME + +function save_service_pid(){ + service_pid=`ps -ef | grep $Main_Class | grep -v grep | awk '{print $2}'` + echo @service_pid@ $service_pid +} + +function kill_service_process(){ + ps -p $service_pid + if [ $? == 0 ]; then + kill -9 $service_pid + fi +} + +save_service_pid; +echo @C_CMD@ kill -9 $service_pid +kill_service_process; \ No newline at end of file diff --git a/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/dbscripts/bps/bpel/create/mysql.sql b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/dbscripts/bps/bpel/create/mysql.sql new file mode 100644 index 0000000..c12bbfb --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/dbscripts/bps/bpel/create/mysql.sql @@ -0,0 +1,170 @@ +-- +-- Licensed to the Apache Software Foundation (ASF) under one +-- or more contributor license agreements. See the NOTICE file +-- distributed with this work for additional information +-- regarding copyright ownership. The ASF licenses this file +-- to you under the Apache License, Version 2.0 (the +-- "License"); you may not use this file except in compliance +-- with the License. You may obtain a copy of the License at +-- +-- http://www.apache.org/licenses/LICENSE-2.0 +-- +-- Unless required by applicable law or agreed to in writing, +-- software distributed under the License is distributed on an +-- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +-- KIND, either express or implied. See the License for the +-- specific language governing permissions and limitations +-- under the License. +-- + +-- +-- BPEL Related SQL Scripts +-- + + +create table ODE_SCHEMA_VERSION (VERSION integer); +insert into ODE_SCHEMA_VERSION values (6); +-- Apache ODE - SimpleScheduler Database Schema +-- +-- MySQL scripts by Maciej Szefler. +-- +-- +DROP TABLE IF EXISTS ODE_JOB; + +CREATE TABLE ODE_JOB ( + jobid CHAR(64) NOT NULL DEFAULT '', + ts BIGINT NOT NULL DEFAULT 0, + nodeid char(64) NULL, + scheduled int NOT NULL DEFAULT 0, + transacted int NOT NULL DEFAULT 0, + + instanceId BIGINT, + mexId varchar(255), + processId varchar(255), + type varchar(255), + channel varchar(255), + correlatorId varchar(255), + correlationKeySet varchar(255), + retryCount int, + inMem int, + detailsExt blob(4096), + + PRIMARY KEY(jobid), + INDEX IDX_ODE_JOB_TS(ts), + INDEX IDX_ODE_JOB_NODEID(nodeid) +) +ENGINE=innodb; + +COMMIT; + +CREATE TABLE TASK_ATTACHMENT (ATTACHMENT_ID BIGINT NOT NULL, MESSAGE_EXCHANGE_ID VARCHAR(255), PRIMARY KEY (ATTACHMENT_ID)) ENGINE=innodb; +CREATE TABLE ODE_ACTIVITY_RECOVERY (ID BIGINT NOT NULL, ACTIONS VARCHAR(255), ACTIVITY_ID BIGINT, CHANNEL VARCHAR(255), DATE_TIME DATETIME, DETAILS TEXT, INSTANCE_ID BIGINT, REASON VARCHAR(255), RETRIES INTEGER, PRIMARY KEY (ID)) ENGINE=innodb; +CREATE TABLE ODE_CORRELATION_SET (CORRELATION_SET_ID BIGINT NOT NULL, CORRELATION_KEY VARCHAR(255), NAME VARCHAR(255), SCOPE_ID BIGINT, PRIMARY KEY (CORRELATION_SET_ID)) ENGINE=innodb; +CREATE TABLE ODE_CORRELATOR (CORRELATOR_ID BIGINT NOT NULL, CORRELATOR_KEY VARCHAR(255), PROC_ID BIGINT, PRIMARY KEY (CORRELATOR_ID)) ENGINE=innodb; +CREATE TABLE ODE_CORSET_PROP (ID BIGINT NOT NULL, CORRSET_ID BIGINT, PROP_KEY VARCHAR(255), PROP_VALUE VARCHAR(255), PRIMARY KEY (ID)) ENGINE=innodb; +CREATE TABLE ODE_EVENT (EVENT_ID BIGINT NOT NULL, DETAIL VARCHAR(255), DATA BLOB, SCOPE_ID BIGINT, TSTAMP DATETIME, TYPE VARCHAR(255), INSTANCE_ID BIGINT, PROCESS_ID BIGINT, PRIMARY KEY (EVENT_ID)) ENGINE=innodb; +CREATE TABLE ODE_FAULT (FAULT_ID BIGINT NOT NULL, ACTIVITY_ID INTEGER, DATA TEXT, MESSAGE VARCHAR(4000), LINE_NUMBER INTEGER, NAME VARCHAR(255), PRIMARY KEY (FAULT_ID)) ENGINE=innodb; +CREATE TABLE ODE_MESSAGE (MESSAGE_ID BIGINT NOT NULL, DATA TEXT, HEADER TEXT, TYPE VARCHAR(255), MESSAGE_EXCHANGE_ID VARCHAR(255), PRIMARY KEY (MESSAGE_ID)) ENGINE=innodb; +CREATE TABLE ODE_MESSAGE_EXCHANGE (MESSAGE_EXCHANGE_ID VARCHAR(255) NOT NULL, CALLEE VARCHAR(255), CHANNEL VARCHAR(255), CORRELATION_ID VARCHAR(255), CORRELATION_KEYS VARCHAR(255), CORRELATION_STATUS VARCHAR(255), CREATE_TIME DATETIME, DIRECTION INTEGER, EPR TEXT, FAULT VARCHAR(255), FAULT_EXPLANATION VARCHAR(255), OPERATION VARCHAR(255), PARTNER_LINK_MODEL_ID INTEGER, PATTERN VARCHAR(255), PIPED_ID VARCHAR(255), PORT_TYPE VARCHAR(255), PROPAGATE_TRANS BIT, STATUS VARCHAR(255), SUBSCRIBER_COUNT INTEGER, CORR_ID BIGINT, PARTNER_LINK_ID BIGINT, PROCESS_ID BIGINT, PROCESS_INSTANCE_ID BIGINT, REQUEST_MESSAGE_ID BIGINT, RESPONSE_MESSAGE_ID BIGINT, PRIMARY KEY (MESSAGE_EXCHANGE_ID)) ENGINE=innodb; +CREATE TABLE ODE_MESSAGE_ROUTE (MESSAGE_ROUTE_ID BIGINT NOT NULL, CORRELATION_KEY VARCHAR(255), GROUP_ID VARCHAR(255), ROUTE_INDEX INTEGER, PROCESS_INSTANCE_ID INTEGER, ROUTE_POLICY VARCHAR(16), CORR_ID BIGINT, PRIMARY KEY (MESSAGE_ROUTE_ID)) ENGINE=innodb; +CREATE TABLE ODE_MEX_PROP (ID BIGINT NOT NULL, MEX_ID VARCHAR(255), PROP_KEY VARCHAR(255), PROP_VALUE VARCHAR(2000), PRIMARY KEY (ID)) ENGINE=innodb; +CREATE TABLE ODE_PARTNER_LINK (PARTNER_LINK_ID BIGINT NOT NULL, MY_EPR TEXT, MY_ROLE_NAME VARCHAR(255), MY_ROLE_SERVICE_NAME VARCHAR(255), MY_SESSION_ID VARCHAR(255), PARTNER_EPR TEXT, PARTNER_LINK_MODEL_ID INTEGER, PARTNER_LINK_NAME VARCHAR(255), PARTNER_ROLE_NAME VARCHAR(255), PARTNER_SESSION_ID VARCHAR(255), SCOPE_ID BIGINT, PRIMARY KEY (PARTNER_LINK_ID)) ENGINE=innodb; +CREATE TABLE ODE_PROCESS (ID BIGINT NOT NULL, GUID VARCHAR(255), PROCESS_ID VARCHAR(255), PROCESS_TYPE VARCHAR(255), VERSION BIGINT, PRIMARY KEY (ID)) ENGINE=innodb; +CREATE TABLE ODE_PROCESS_INSTANCE (ID BIGINT NOT NULL, DATE_CREATED DATETIME, EXECUTION_STATE BLOB, FAULT_ID BIGINT, LAST_ACTIVE_TIME DATETIME, LAST_RECOVERY_DATE DATETIME, PREVIOUS_STATE SMALLINT, SEQUENCE BIGINT, INSTANCE_STATE SMALLINT, INSTANTIATING_CORRELATOR_ID BIGINT, PROCESS_ID BIGINT, ROOT_SCOPE_ID BIGINT, PRIMARY KEY (ID)) ENGINE=innodb; +CREATE TABLE ODE_SCOPE (SCOPE_ID BIGINT NOT NULL, MODEL_ID INTEGER, SCOPE_NAME VARCHAR(255), SCOPE_STATE VARCHAR(255), PROCESS_INSTANCE_ID BIGINT, PARENT_SCOPE_ID BIGINT, PRIMARY KEY (SCOPE_ID)) ENGINE=innodb; +CREATE TABLE ODE_XML_DATA (XML_DATA_ID BIGINT NOT NULL, DATA TEXT, IS_SIMPLE_TYPE BIT, NAME VARCHAR(255), SCOPE_ID BIGINT, PRIMARY KEY (XML_DATA_ID)) ENGINE=innodb; +CREATE TABLE ODE_XML_DATA_PROP (ID BIGINT NOT NULL, XML_DATA_ID BIGINT, PROP_KEY VARCHAR(255), PROP_VALUE VARCHAR(255), PRIMARY KEY (ID)) ENGINE=innodb; +CREATE TABLE OPENJPA_SEQUENCE_TABLE (ID TINYINT NOT NULL, SEQUENCE_VALUE BIGINT, PRIMARY KEY (ID)) ENGINE=innodb; +CREATE TABLE STORE_DU (NAME VARCHAR(255) NOT NULL, DEPLOYDT DATETIME, DEPLOYER VARCHAR(255), DIR VARCHAR(255), PRIMARY KEY (NAME)) ENGINE=innodb; +CREATE TABLE STORE_PROCESS (PID VARCHAR(255) NOT NULL, STATE VARCHAR(255), TYPE VARCHAR(255), VERSION BIGINT, DU VARCHAR(255), PRIMARY KEY (PID)) ENGINE=innodb; +CREATE TABLE STORE_PROCESS_PROP (id BIGINT NOT NULL, PROP_KEY VARCHAR(255), PROP_VAL VARCHAR(255), PRIMARY KEY (id)) ENGINE=innodb; +CREATE TABLE STORE_PROC_TO_PROP (PROCESSCONFDAOIMPL_PID VARCHAR(255), ELEMENT_ID BIGINT) ENGINE=innodb; +CREATE TABLE STORE_VERSIONS (id BIGINT NOT NULL, VERSION BIGINT, PRIMARY KEY (id)) ENGINE=innodb; +CREATE INDEX I_D_TASK_ATTACMENT ON TASK_ATTACHMENT (MESSAGE_EXCHANGE_ID); +CREATE INDEX I_D_CTVRY_INSTANCE ON ODE_ACTIVITY_RECOVERY (INSTANCE_ID); +CREATE INDEX I_D_CR_ST_SCOPE ON ODE_CORRELATION_SET (SCOPE_ID); +CREATE INDEX I_D_CRLTR_PROCESS ON ODE_CORRELATOR (PROC_ID); +CREATE INDEX I_D_CRPRP_CORRSET ON ODE_CORSET_PROP (CORRSET_ID); +CREATE INDEX I_OD_VENT_INSTANCE ON ODE_EVENT (INSTANCE_ID); +CREATE INDEX I_OD_VENT_PROCESS ON ODE_EVENT (PROCESS_ID); +CREATE INDEX I_OD_MSSG_MESSAGEEXCHANGE ON ODE_MESSAGE (MESSAGE_EXCHANGE_ID); +CREATE INDEX I_D_MSHNG_CORRELATOR ON ODE_MESSAGE_EXCHANGE (CORR_ID); +CREATE INDEX I_D_MSHNG_PARTNERLINK ON ODE_MESSAGE_EXCHANGE (PARTNER_LINK_ID); +CREATE INDEX I_D_MSHNG_PROCESS ON ODE_MESSAGE_EXCHANGE (PROCESS_ID); +CREATE INDEX I_D_MSHNG_PROCESSINST ON ODE_MESSAGE_EXCHANGE (PROCESS_INSTANCE_ID); +CREATE INDEX I_D_MSHNG_REQUEST ON ODE_MESSAGE_EXCHANGE (REQUEST_MESSAGE_ID); +CREATE INDEX I_D_MSHNG_RESPONSE ON ODE_MESSAGE_EXCHANGE (RESPONSE_MESSAGE_ID); +CREATE INDEX I_D_MS_RT_CORRELATOR ON ODE_MESSAGE_ROUTE (CORR_ID); +CREATE INDEX I_D_MS_RT_PROCESSINST ON ODE_MESSAGE_ROUTE (PROCESS_INSTANCE_ID); +CREATE INDEX I_D_MXPRP_MEX ON ODE_MEX_PROP (MEX_ID); +CREATE INDEX I_D_PRLNK_SCOPE ON ODE_PARTNER_LINK (SCOPE_ID); +CREATE INDEX I_D_PRTNC_FAULT ON ODE_PROCESS_INSTANCE (FAULT_ID); +CREATE INDEX I_D_PRTNC_INSTANTIATINGCORRELATOR ON ODE_PROCESS_INSTANCE (INSTANTIATING_CORRELATOR_ID); +CREATE INDEX I_D_PRTNC_PROCESS ON ODE_PROCESS_INSTANCE (PROCESS_ID); +CREATE INDEX I_D_PRTNC_ROOTSCOPE ON ODE_PROCESS_INSTANCE (ROOT_SCOPE_ID); +CREATE INDEX I_OD_SCOP_PARENTSCOPE ON ODE_SCOPE (PARENT_SCOPE_ID); +CREATE INDEX I_OD_SCOP_PROCESSINSTANCE ON ODE_SCOPE (PROCESS_INSTANCE_ID); +CREATE INDEX I_D_XM_DT_SCOPE ON ODE_XML_DATA (SCOPE_ID); +CREATE INDEX I_D_XMPRP_XMLDATA ON ODE_XML_DATA_PROP (XML_DATA_ID); +CREATE INDEX I_STR_CSS_DU ON STORE_PROCESS (DU); +CREATE INDEX I_STR_PRP_ELEMENT ON STORE_PROC_TO_PROP (ELEMENT_ID); +CREATE INDEX I_STR_PRP_PROCESSCONFDAOIMPL_PID ON STORE_PROC_TO_PROP (PROCESSCONFDAOIMPL_PID); + + + +-- +-- Human Task Related SQL Scripts +-- + + +CREATE TABLE HT_DEADLINE (id BIGINT NOT NULL, DEADLINE_DATE DATETIME NOT NULL, DEADLINE_NAME VARCHAR(255) NOT NULL, STATUS_TOBE_ACHIEVED VARCHAR(255) NOT NULL, TASK_ID BIGINT, PRIMARY KEY (id)) ENGINE = innodb; +CREATE TABLE HT_DEPLOYMENT_UNIT (id BIGINT NOT NULL, CHECKSUM VARCHAR(255) NOT NULL, DEPLOYED_ON DATETIME, DEPLOY_DIR VARCHAR(255) NOT NULL, NAME VARCHAR(255) NOT NULL, PACKAGE_NAME VARCHAR(255) NOT NULL, STATUS VARCHAR(255) NOT NULL, TENANT_ID BIGINT NOT NULL, VERSION BIGINT NOT NULL, PRIMARY KEY (id)) ENGINE = innodb; +CREATE TABLE HT_EVENT (id BIGINT NOT NULL, EVENT_DETAILS VARCHAR(255), NEW_STATE VARCHAR(255), OLD_STATE VARCHAR(255), EVENT_TIMESTAMP DATETIME NOT NULL, EVENT_TYPE VARCHAR(255) NOT NULL, EVENT_USER VARCHAR(255) NOT NULL, TASK_ID BIGINT, PRIMARY KEY (id)) ENGINE = innodb; +CREATE TABLE HT_GENERIC_HUMAN_ROLE (GHR_ID BIGINT NOT NULL, GHR_TYPE VARCHAR(255), TASK_ID BIGINT, PRIMARY KEY (GHR_ID)) ENGINE = innodb; +CREATE TABLE HT_HUMANROLE_ORGENTITY (HUMANROLE_ID BIGINT, ORGENTITY_ID BIGINT) ENGINE = innodb; +CREATE TABLE HT_JOB (id BIGINT NOT NULL, JOB_DETAILS VARCHAR(4000), JOB_NAME VARCHAR(255), NODEID VARCHAR(255), SCHEDULED VARCHAR(1) NOT NULL, TASKID BIGINT NOT NULL, JOB_TIME BIGINT NOT NULL, TRANSACTED VARCHAR(1) NOT NULL, JOB_TYPE VARCHAR(255) NOT NULL, PRIMARY KEY (id)) ENGINE = innodb; +CREATE TABLE HT_MESSAGE (MESSAGE_ID BIGINT NOT NULL, MESSAGE_DATA LONGTEXT, MESSAGE_HEADER LONGTEXT, MESSAGE_TYPE VARCHAR(255), MESSAGE_NAME VARCHAR(512), TASK_ID BIGINT, PRIMARY KEY (MESSAGE_ID)) ENGINE = innodb; +CREATE TABLE HT_ORG_ENTITY (ORG_ENTITY_ID BIGINT NOT NULL, ORG_ENTITY_NAME VARCHAR(255), ORG_ENTITY_TYPE VARCHAR(255), PRIMARY KEY (ORG_ENTITY_ID)) ENGINE = innodb; +CREATE TABLE HT_PRESENTATION_ELEMENT (id BIGINT NOT NULL, PE_CONTENT VARCHAR(2000), XML_LANG VARCHAR(255), PE_TYPE VARCHAR(31), CONTENT_TYPE VARCHAR(255), TASK_ID BIGINT, PRIMARY KEY (id)) ENGINE = innodb; +CREATE TABLE HT_PRESENTATION_PARAM (id BIGINT NOT NULL, PARAM_NAME VARCHAR(255), PARAM_TYPE VARCHAR(255), PARAM_VALUE VARCHAR(2000), TASK_ID BIGINT, PRIMARY KEY (id)) ENGINE = innodb; +CREATE TABLE HT_TASK (id BIGINT NOT NULL, ACTIVATION_TIME DATETIME, COMPLETE_BY_TIME DATETIME, CREATED_ON DATETIME, ESCALATED VARCHAR(1), EXPIRATION_TIME DATETIME, TASK_NAME VARCHAR(255) NOT NULL, PACKAGE_NAME VARCHAR(255) NOT NULL, PRIORITY INTEGER NOT NULL, SKIPABLE VARCHAR(1), START_BY_TIME DATETIME, STATUS VARCHAR(255) NOT NULL, STATUS_BEFORE_SUSPENSION VARCHAR(255), TASK_DEF_NAME VARCHAR(255) NOT NULL, TASK_VERSION BIGINT NOT NULL, TENANT_ID INTEGER NOT NULL, TASK_TYPE VARCHAR(255) NOT NULL, UPDATED_ON DATETIME, FAILURE_MESSAGE BIGINT, INPUT_MESSAGE BIGINT, OUTPUT_MESSAGE BIGINT, PARENTTASK_ID BIGINT, PRIMARY KEY (id)) ENGINE = innodb; +CREATE TABLE HT_TASK_ATTACHMENT (id BIGINT NOT NULL, ACCESS_TYPE VARCHAR(255), ATTACHED_AT DATETIME, CONTENT_TYPE VARCHAR(255), ATTACHMENT_NAME VARCHAR(255), ATTACHMENT_VALUE VARCHAR(255), TASK_ID BIGINT, ATTACHED_BY BIGINT, PRIMARY KEY (id)) ENGINE = innodb; +CREATE TABLE HT_TASK_COMMENT (id BIGINT NOT NULL, COMMENT_TEXT VARCHAR(4000), COMMENTED_BY VARCHAR(100), COMMENTED_ON DATETIME, MODIFIED_BY VARCHAR(100), MODIFIED_ON DATETIME, TASK_ID BIGINT, PRIMARY KEY (id)) ENGINE = innodb; +CREATE TABLE HT_VERSIONS (id BIGINT NOT NULL, TASK_VERSION BIGINT NOT NULL, PRIMARY KEY (id)) ENGINE = innodb; +CREATE INDEX I_HT_DDLN_TASK ON HT_DEADLINE (TASK_ID); +CREATE INDEX I_HT_VENT_TASK ON HT_EVENT (TASK_ID); +CREATE INDEX I_HT_G_RL_TASK ON HT_GENERIC_HUMAN_ROLE (TASK_ID); +CREATE INDEX I_HT_HTTY_ELEMENT ON HT_HUMANROLE_ORGENTITY (ORGENTITY_ID); +CREATE INDEX I_HT_HTTY_HUMANROLE_ID ON HT_HUMANROLE_ORGENTITY (HUMANROLE_ID); +CREATE INDEX I_HT_MSSG_TASK ON HT_MESSAGE (TASK_ID); +CREATE INDEX I_HT_PMNT_DTYPE ON HT_PRESENTATION_ELEMENT (PE_TYPE); +CREATE INDEX I_HT_PMNT_TASK ON HT_PRESENTATION_ELEMENT (TASK_ID); +CREATE INDEX I_HT_PPRM_TASK ON HT_PRESENTATION_PARAM (TASK_ID); +CREATE INDEX I_HT_TASK_FAILUREMESSAGE ON HT_TASK (FAILURE_MESSAGE); +CREATE INDEX I_HT_TASK_INPUTMESSAGE ON HT_TASK (INPUT_MESSAGE); +CREATE INDEX I_HT_TASK_OUTPUTMESSAGE ON HT_TASK (OUTPUT_MESSAGE); +CREATE INDEX I_HT_TASK_PARENTTASK ON HT_TASK (PARENTTASK_ID); +CREATE INDEX I_HT_TMNT_ATTACHEDBY ON HT_TASK_ATTACHMENT (ATTACHED_BY); +CREATE INDEX I_HT_TMNT_TASK ON HT_TASK_ATTACHMENT (TASK_ID); +CREATE INDEX I_HT_TMNT_TASK1 ON HT_TASK_COMMENT (TASK_ID); + +-- +-- Attachment Management Related SQL Scripts +-- +CREATE TABLE ATTACHMENT ( + id BIGINT NOT NULL AUTO_INCREMENT, + CREATED_TIME TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + ATTACHMENT_NAME VARCHAR(255) NOT NULL, + CREATED_BY VARCHAR(255) NOT NULL, + CONTENT_TYPE VARCHAR(255) NOT NULL, + ATTACHMENT_URL VARCHAR(2048) NOT NULL, + ATTACHMENT_CONTENT BLOB, + PRIMARY KEY (id)); + +-- CREATE INDEX I_ATTACHMENT_URL ON ATTACHMENT (ATTACHMENT_URL); + + +-- +-- B4P Related SQL Scripts +-- +CREATE TABLE HT_COORDINATION_DATA (MESSAGE_ID VARCHAR(255) NOT NULL, PROCESS_INSTANCE_ID VARCHAR(255), PROTOCOL_HANDlER_URL VARCHAR(255) NOT NULL, TASK_ID VARCHAR(255), PRIMARY KEY (MESSAGE_ID)) ENGINE = innodb; diff --git a/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/dbscripts/bps/bpel/create/wso-bpel-mysql-createdb.sql b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/dbscripts/bps/bpel/create/wso-bpel-mysql-createdb.sql new file mode 100644 index 0000000..16dca47 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/dbscripts/bps/bpel/create/wso-bpel-mysql-createdb.sql @@ -0,0 +1,31 @@ +-- +-- Copyright 2016 ZTE Corporation. +-- +-- Licensed under the Apache License, Version 2.0 (the "License"); +-- you may not use this file except in compliance with the License. +-- You may obtain a copy of the License at +-- +-- http://www.apache.org/licenses/LICENSE-2.0 +-- +-- Unless required by applicable law or agreed to in writing, software +-- distributed under the License is distributed on an "AS IS" BASIS, +-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +-- See the License for the specific language governing permissions and +-- limitations under the License. +-- + +/******************drop old database and user***************************/ +use mysql; +drop database IF EXISTS wso_bpel; +delete from user where User='wso_bpel'; +FLUSH PRIVILEGES; + +/******************create new database and user***************************/ +create database wso_bpel CHARACTER SET utf8; + +GRANT ALL PRIVILEGES ON wso_bpel.* TO 'wso_bpel'@'%' IDENTIFIED BY 'wso_bpel' WITH GRANT OPTION; +GRANT ALL PRIVILEGES ON mysql.* TO 'wso_bpel'@'%' IDENTIFIED BY 'wso_bpel' WITH GRANT OPTION; + +GRANT ALL PRIVILEGES ON wso_bpel.* TO 'wso_bpel'@'localhost' IDENTIFIED BY 'wso_bpel' WITH GRANT OPTION; +GRANT ALL PRIVILEGES ON mysql.* TO 'wso_bpel'@'localhost' IDENTIFIED BY 'wso_bpel' WITH GRANT OPTION; +FLUSH PRIVILEGES; \ No newline at end of file diff --git a/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/repository/conf/bps.xml b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/repository/conf/bps.xml new file mode 100644 index 0000000..1e09356 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/repository/conf/bps.xml @@ -0,0 +1,174 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 50 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +   + + + + + + + + + + + + + + + + + diff --git a/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/repository/conf/carbon/bps.xml b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/repository/conf/carbon/bps.xml new file mode 100644 index 0000000..1e09356 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/repository/conf/carbon/bps.xml @@ -0,0 +1,174 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 50 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +   + + + + + + + + + + + + + + + + + diff --git a/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/repository/conf/carbon/carbon.xml b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/repository/conf/carbon/carbon.xml new file mode 100644 index 0000000..6973b7c --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/repository/conf/carbon/carbon.xml @@ -0,0 +1,683 @@ + + + + + + + + + WSO2 Business Process Server + + + BPS + + + 3.5.0 + + + + + + + + + local:/${carbon.context}/services/ + + + + + + + BusinessProcessServer + + + + + + + org.wso2.carbon + + + / + + + + + + + + + 15 + + + + + + + + + 0 + + + + + 9999 + + 11111 + + + + + + 10389 + + 8000 + + + + + + 10500 + + + + + + + org.wso2.carbon.tomcat.jndi.CarbonJavaURLContextFactory + + + + + + + + + java + + + + + + + + + + false + + + false + + + 600 + + + + false + + + + + + + + 30 + + + + + + + + + 15 + + + + + + ${carbon.home}/repository/deployment/server/ + + + 15 + + + ${carbon.home}/repository/conf/axis2/axis2.xml + + + 30000 + + + ${carbon.home}/repository/deployment/client/ + + ${carbon.home}/repository/conf/axis2/axis2_client.xml + + false + + + + + + + + + + admin + Default Administrator Role + + + user + Default User Role + + + + + + + + + + + + ${carbon.home}/repository/resources/security/wso2carbon.jks + + JKS + + wso2carbon + + wso2carbon + + wso2carbon + + + + + + ${carbon.home}/repository/resources/security/client-truststore.jks + + JKS + + wso2carbon + + + + + + + + + + + + + + + + + + + UserManager + + + false + + + + + + + + + + ${carbon.home}/tmp/work + + + + + + true + + + 10 + + + 30 + + + + + + 100 + + + + keystore + certificate + * + + org.wso2.carbon.ui.transports.fileupload.AnyFileUploadExecutor + + + + + jarZip + + org.wso2.carbon.ui.transports.fileupload.JarZipUploadExecutor + + + + dbs + + org.wso2.carbon.ui.transports.fileupload.DBSFileUploadExecutor + + + + tools + + org.wso2.carbon.ui.transports.fileupload.ToolsFileUploadExecutor + + + + toolsAny + + org.wso2.carbon.ui.transports.fileupload.ToolsAnyFileUploadExecutor + + + + + + + info + org.wso2.carbon.core.transports.util.InfoProcessor + + + wsdl + org.wso2.carbon.core.transports.util.Wsdl11Processor + + + wsdl2 + org.wso2.carbon.core.transports.util.Wsdl20Processor + + + xsd + org.wso2.carbon.core.transports.util.XsdProcessor + + + + + + false + false + true + svn + http://svnrepo.example.com/repos/ + username + password + true + + + + + + + + + + + + + + + ${require.carbon.servlet} + + + + + true + + + + + + + default repository + http://dist.wso2.org/p2/carbon/releases/4.4.1-SNAPSHOT + + + + + + + + true + + + + + + true + + diff --git a/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/repository/conf/datasources/activiti-datasources.xml b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/repository/conf/datasources/activiti-datasources.xml new file mode 100644 index 0000000..f95cb87 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/repository/conf/datasources/activiti-datasources.xml @@ -0,0 +1,32 @@ + + + + org.wso2.carbon.ndatasource.rdbms.RDBMSDataSourceReader + + + + + + ACTIVITI_DB + The datasource used for activiti engine + + jdbc/ActivitiDB + + + + jdbc:h2:repository/database/activiti;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;LOCK_TIMEOUT=60000 + wso2carbon + wso2carbon + org.h2.Driver + 50 + 60000 + true + SELECT 1 + 30000 + + + + + + + diff --git a/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/repository/conf/datasources/bps-datasources.xml b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/repository/conf/datasources/bps-datasources.xml new file mode 100644 index 0000000..22f79f7 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/repository/conf/datasources/bps-datasources.xml @@ -0,0 +1,32 @@ + + + + org.wso2.carbon.ndatasource.rdbms.RDBMSDataSourceReader + + + + + BPS_DS + + + bpsds + + + + jdbc:mysql://localhost:3306/wso_bpel + wso_bpel + wso_bpel + com.mysql.jdbc.Driver + true + SELECT 1 + 30000 + false + true + 100 + 20 + 10000 + + + + + diff --git a/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/repository/conf/datasources/master-datasources.xml b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/repository/conf/datasources/master-datasources.xml new file mode 100644 index 0000000..897e335 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/repository/conf/datasources/master-datasources.xml @@ -0,0 +1,68 @@ + + + + org.wso2.carbon.ndatasource.rdbms.RDBMSDataSourceReader + + + + + + WSO2_CARBON_DB + The datasource used for registry and user manager + + jdbc/WSO2CarbonDB + + + + jdbc:h2:repository/database/WSO2CARBON_DB;DB_CLOSE_ON_EXIT=FALSE;LOCK_TIMEOUT=60000 + wso2carbon + wso2carbon + org.h2.Driver + 50 + 60000 + true + SELECT 1 + 30000 + false + + + + + + + + + + diff --git a/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/wso2bps-ext.properties b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/wso2bps-ext.properties new file mode 100644 index 0000000..02d1b6d --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/distribution/standalone/src/main/assembly/wso2bps/wso2bps-ext.properties @@ -0,0 +1 @@ +MSB_URL=http://127.0.0.1:80 \ No newline at end of file diff --git a/wso2/wso2bpel-ext/wso2bpel-core/pom.xml b/wso2/wso2bpel-ext/wso2bpel-core/pom.xml new file mode 100644 index 0000000..144066e --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/pom.xml @@ -0,0 +1,36 @@ + + + + + org.openo.common-services.common-utilities.wso2bpel-ext + wso2bpel-root + 1.1.0-SNAPSHOT + + + 4.0.0 + wso2bpel-core-parent + common-services-common-utilities/wso2bpel-ext/wso2bpel-core + pom + + + BPEL4RESTLight + wso2bpel-mgr + distribution + + diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/pom.xml b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/pom.xml new file mode 100644 index 0000000..5a7eac8 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/pom.xml @@ -0,0 +1,453 @@ + + + + + + org.openo.common-services.common-utilities.wso2bpel-ext + wso2bpel-core-parent + 1.1.0-SNAPSHOT + + + 4.0.0 + wso2bpel-mgr + common-services-common-utilities/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr + jar + + true + + + + + wso2-nexus + http://dist.wso2.org/maven2 + + true + + + false + + + + smartbearsoftware + http://smartbearsoftware.com/repository/maven2/ + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + 1.7 + 1.7 + UTF-8 + + -verbose + -Xlint:unchecked + -Xlint:deprecation + -bootclasspath + ${env.JAVA_HOME}/jre/lib/rt.jar + + + + + org.eclipse.m2e + lifecycle-mapping + + + + + + org.apache.maven.plugins + maven-dependency-plugin + [2.0,) + + copy-dependencies + + + + + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + true + + + + + + org.apache.maven.plugins + maven-shade-plugin + + true + + + *:* + + META-INF/*.SF + META-INF/*.DSA + META-INF/*.RSA + + + + + + + package + + shade + + + + + + org.openo.carbon.bpel.Wso2BpelApplication + + + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-dependencies + package + + copy-dependencies + + + + + io.dropwizard + dropwizard-core + ${dropwizard.version} + true + + + + + + + + + + + + io.dropwizard + dropwizard-core + + + io.dropwizard + dropwizard-assets + + + io.dropwizard + dropwizard-hibernate + + + + org.projectlombok + lombok + + + io.swagger + swagger-jersey2-jaxrs + + + + org.glassfish.jersey.core + jersey-server + + + org.glassfish.jersey.media + jersey-media-multipart + + + org.glassfish.jersey.containers + jersey-container-servlet-core + + + + com.eclipsesource.jaxrs + consumer + + + com.eclipsesource.jaxrs + jersey-all + + + + + + com.google.code.gson + gson + + + + junit + junit + test + + + org.powermock + powermock-module-junit4 + test + + + org.powermock + powermock-api-mockito + test + + + org.apache.ant + ant + test + + + + + + org.apache.ws.commons.axiom.wso2 + axiom + 1.2.11.wso2v4 + + + axion.wso2 + axion + 1.0.0.M3-dev-wso2v1 + + + org.apache.axis2.wso2 + axis2 + 1.6.1.wso2v10 + + + org.apache.axis2.wso2 + axis2-jaxbri + 1.6.1.wso2v10 + + + org.apache.axis2.wso2 + axis2-json + 1.6.1.wso2v10 + + + org.apache.axis2 + axis2-transport-jms + 1.0.0 + + + org.apache.axis2 + axis2-transport-mail + 1.0.0 + + + org.apache.axis2 + axis2-transport-sms + 1.0.0 + + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-log4j12 + + + + + commons-beanutils + commons-beanutils + 1.9.2 + + + commons-codec.wso2 + commons-codec + 1.4.0.wso2v1 + + + commons-collections + commons-collections + 3.2.1 + + + commons-fileupload.wso2 + commons-fileupload + 1.2.2.wso2v1 + + + commons-httpclient.wso2 + commons-httpclient + 3.1.0.wso2v2 + + + commons-io.wso2 + commons-io + 2.0.0.wso2v2 + + + commons-lang + commons-lang + 2.5 + + + org.apache.commons + commons-lang3 + 3.2 + + + commons-logging + commons-logging + 1.0.4 + + + net.sf.ezmorph + ezmorph + 1.0.6 + + + org.apache.httpcomponents.wso2 + httpclient + 4.2.5.wso2v1 + + + org.apache.httpcomponents.wso2 + httpcore + 4.3.0.wso2v1 + + + org.apache.httpcomponents + httpmime + 4.3.1 + + + com.fasterxml.jackson.core + jackson-annotations + 2.5.0 + + + javassist + javassist + 3.3.GA + + + javax.annotation + javax.annotation-api + 1.2 + + + javax.ws.rs + javax.ws.rs-api + 2.0.1 + + + jdom + jdom + 0.7 + + + org.glassfish.jersey.media + jersey-media-jaxb + 2.25 + + + org.glassfish.jersey.media + jersey-media-multipart + 2.22.2 + + + net.sf.json-lib + json-lib + 2.4 + jdk15 + + + log4j + log4j + 1.2.16 + + + com.jgoodies + looks + 2.2.1 + + + org.jvnet.mimepull + mimepull + 1.9.3 + + + org.apache.neethi.wso2 + neethi + 2.0.4.wso2v4 + + + org.wso2.carbon + org.wso2.carbon.bpel.stub + 4.2.1 + + + org.wso2.securevault + org.wso2.securevault + 1.0.0-wso2v2 + + + wsdl4j.wso2 + wsdl4j + 1.6.2.wso2v4 + + + org.apache.xmlbeans + xmlbeans + 2.4.0 + + + org.apache.ws.commons.schema.wso2 + XmlSchema + 1.4.7.wso2v2 + + + + eviware + soapui + 1.7.5 + + + eviware + soapui-xmlbeans + 1.7.5 + + + + diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/Wso2BpelApplication.java b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/Wso2BpelApplication.java new file mode 100644 index 0000000..5cec239 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/Wso2BpelApplication.java @@ -0,0 +1,106 @@ +/** + * Copyright 2016 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.carbon.bpel; + +import io.dropwizard.Application; +import io.dropwizard.assets.AssetsBundle; +import io.dropwizard.configuration.EnvironmentVariableSubstitutor; +import io.dropwizard.configuration.SubstitutingSourceProvider; +import io.dropwizard.server.SimpleServerFactory; +import io.dropwizard.setup.Bootstrap; +import io.dropwizard.setup.Environment; +import io.swagger.jaxrs.config.BeanConfig; +import io.swagger.jaxrs.listing.ApiListingResource; + +import org.glassfish.jersey.media.multipart.MultiPartFeature; +import org.openo.carbon.bpel.common.Config; +import org.openo.carbon.bpel.common.ServiceRegistrer; +import org.openo.carbon.bpel.resources.BpsPackage; +import org.openo.carbon.bpel.resources.BpsProcess; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.annotation.JsonInclude; + + + +public class Wso2BpelApplication extends Application { + private static final Logger LOGGER = LoggerFactory.getLogger(Wso2BpelApplication.class); + private static final String API_RESOURCE = "org.openo.carbon.bpel.resources"; + + public static void main(String[] args) throws Exception { + new Wso2BpelApplication().run(args); + } + + + @Override + public String getName() { + return "hello-wso2bpel"; + } + + @Override + public void initialize(Bootstrap bootstrap) { + bootstrap.setConfigurationSourceProvider(new SubstitutingSourceProvider( + bootstrap.getConfigurationSourceProvider(), new EnvironmentVariableSubstitutor(false))); + // binding jar static resource + bootstrap.addBundle(new AssetsBundle("/api-doc", "/api-doc", "index.html", "api-doc")); + } + + private void initService() { + Thread registerWso2bpelService = new Thread(new ServiceRegistrer()); + registerWso2bpelService.setName("register wso2bpel service to Microservice Bus"); + registerWso2bpelService.start(); + } + + + + @Override + public void run(Wso2BpelConfiguration configuration, Environment environment) { + environment.jersey().register(MultiPartFeature.class); + environment.jersey().register(new BpsPackage()); + environment.jersey().register(new BpsProcess()); + // init Swagger conf + initSwaggerConfig(environment, configuration); + Config.setConfigration(configuration); + initService(); + } + + private void initSwaggerConfig(Environment environment, Wso2BpelConfiguration configuration) { + // register swagger scan class + environment.jersey().register(new ApiListingResource()); + environment.getObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL); + + BeanConfig config = new BeanConfig(); + config.setTitle(configuration.getApiDescription()); + config.setVersion("1.0"); + config.setResourcePackage(API_RESOURCE); + + // read rootPath config from yml + SimpleServerFactory simpleServerFactory = + (SimpleServerFactory) configuration.getServerFactory(); + String basePath = simpleServerFactory.getApplicationContextPath(); + String rootPath = simpleServerFactory.getJerseyRootPath(); + + // set basepath for rest api + rootPath = rootPath.substring(0, rootPath.indexOf("/*")); + basePath = basePath.equals("/") ? rootPath + : (new StringBuilder()).append(basePath).append(rootPath).toString(); + + LOGGER.info("getApplicationContextPath:" + basePath); + config.setBasePath(basePath); + config.setScan(true); + } +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/Wso2BpelConfiguration.java b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/Wso2BpelConfiguration.java new file mode 100644 index 0000000..953a919 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/Wso2BpelConfiguration.java @@ -0,0 +1,200 @@ +/** + * Copyright 2016 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.carbon.bpel; + +import io.dropwizard.Configuration; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.dropwizard.db.DataSourceFactory; +import org.hibernate.validator.constraints.NotEmpty; + +import javax.validation.Valid; +import javax.validation.constraints.NotNull; + +public class Wso2BpelConfiguration extends Configuration { + @NotEmpty + private String template; + @NotEmpty + private String apiDescription = "Wso2bps REST API"; + @NotNull + private DataSourceFactory database = new DataSourceFactory(); + + @NotEmpty + private String msbServerAddr; + + @NotEmpty + private String wso2Host; + + @NotEmpty + private String wso2HostPort; + + @NotEmpty + private String wso2AuthUserName; + + @NotEmpty + private String wso2AuthPassword; + + @NotEmpty + private String wso2Path; + + @NotEmpty + private String wso2UploadFilePath; + + @NotEmpty + private String wso2SslJksFile; + + @NotEmpty + private String wso2SslJksPassword; + + @Valid + private String serviceIp; + + @JsonProperty + public String getTemplate() { + return template; + } + + @JsonProperty + public String getApiDescription() { + return apiDescription; + } + + @JsonProperty("database") + public DataSourceFactory getDataSourceFactory() { + return database; + } + + @JsonProperty + public DataSourceFactory getDatabase() { + return database; + } + + @JsonProperty + public void setDatabase(DataSourceFactory database) { + this.database = database; + } + + @JsonProperty + public String getMsbServerAddr() { + return msbServerAddr; + } + + @JsonProperty + public void setMsbServerAddr(String msbServerAddr) { + this.msbServerAddr = msbServerAddr; + } + + @JsonProperty + public String getWso2Host() { + return wso2Host; + } + + @JsonProperty + public void setWso2Host(String wso2Host) { + this.wso2Host = wso2Host; + } + + @JsonProperty + public String getWso2HostPort() { + return wso2HostPort; + } + + @JsonProperty + public void setWso2HostPort(String wso2HostPort) { + this.wso2HostPort = wso2HostPort; + } + + @JsonProperty + public String getWso2AuthUserName() { + return wso2AuthUserName; + } + + @JsonProperty + public void setWso2AuthUserName(String wso2AuthUserName) { + this.wso2AuthUserName = wso2AuthUserName; + } + + @JsonProperty + public String getWso2AuthPassword() { + return wso2AuthPassword; + } + + @JsonProperty + public void setWso2AuthPassword(String wso2AuthPassword) { + this.wso2AuthPassword = wso2AuthPassword; + } + + @JsonProperty + public String getWso2Path() { + return wso2Path; + } + + @JsonProperty + public void setWso2Path(String wso2Path) { + if (wso2Path.startsWith("/") == false) { + this.wso2Path = System.getProperty("WSO2_EXT_HOME") + "/" + wso2Path; + } else { + this.wso2Path = wso2Path; + } + } + + @JsonProperty + public String getWso2UploadFilePath() { + return wso2UploadFilePath; + } + + @JsonProperty + public void setWso2UploadFilePath(String wso2UploadFilePath) { + if (wso2UploadFilePath.startsWith("/") == false) { + this.wso2UploadFilePath = System.getProperty("WSO2_EXT_HOME") + "/" + wso2UploadFilePath; + } else { + this.wso2UploadFilePath = wso2UploadFilePath; + } + } + + @JsonProperty + public String getWso2SslJksFile() { + return wso2SslJksFile; + } + + @JsonProperty + public void setWso2SslJksFile(String wso2SslJksFile) { + if (wso2SslJksFile.startsWith("/") == false) { + this.wso2SslJksFile = System.getProperty("WSO2_EXT_HOME") + "/" + wso2SslJksFile; + } else { + this.wso2SslJksFile = wso2SslJksFile; + } + } + + @JsonProperty + public String getWso2SslJksPassword() { + return wso2SslJksPassword; + } + + @JsonProperty + public void setWso2SslJksPassword(String wso2SslJksPassword) { + this.wso2SslJksPassword = wso2SslJksPassword; + } + + @JsonProperty + public String getServiceIp() { + return serviceIp; + } + + @JsonProperty + public void setServiceIp(String serviceIp) { + this.serviceIp = serviceIp; + } +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/common/Config.java b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/common/Config.java new file mode 100644 index 0000000..f3e83cf --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/common/Config.java @@ -0,0 +1,30 @@ +/** + * Copyright 2016 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.carbon.bpel.common; + +import org.openo.carbon.bpel.Wso2BpelConfiguration; + +public class Config { + private static Wso2BpelConfiguration configration; + + public static Wso2BpelConfiguration getConfigration() { + return configration; + } + + public static void setConfigration(Wso2BpelConfiguration config) { + configration = config; + } +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/common/ServiceRegistrer.java b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/common/ServiceRegistrer.java new file mode 100644 index 0000000..03d88aa --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/common/ServiceRegistrer.java @@ -0,0 +1,70 @@ +/** + * Copyright 2016 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.carbon.bpel.common; + +import org.openo.carbon.bpel.externalservice.entity.ServiceRegisterEntity; +import org.openo.carbon.bpel.externalservice.msb.MicroserviceBusConsumer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ServiceRegistrer implements Runnable { + private static final Logger LOG = LoggerFactory.getLogger(ServiceRegistrer.class); + private final ServiceRegisterEntity wso2bpelEntity = new ServiceRegisterEntity(); + + public ServiceRegistrer() { + initServiceEntity(); + } + + @Override + public void run() { + LOG.info("start wso2bpelEntity microservice register"); + boolean flag = false; + int retry = 0; + while (!flag && retry < 1000) { + LOG.info("wso2bpel microservice register.retry:" + retry); + retry++; + flag = MicroserviceBusConsumer.registerService(wso2bpelEntity); + if (flag == false) { + LOG.warn("microservice register failed, sleep 30S and try again."); + threadSleep(30000); + } else { + LOG.info("microservice register success!"); + break; + } + } + LOG.info("wso2bpel microservice register end."); + } + + private void threadSleep(int second) { + LOG.info("start sleep ...."); + try { + Thread.sleep(second); + } catch (InterruptedException error) { + LOG.error("thread sleep error.errorMsg:" + error.getMessage()); + } + LOG.info("sleep end ."); + } + + private void initServiceEntity() { + wso2bpelEntity.setServiceName("wso2bpel"); + wso2bpelEntity.setProtocol("REST"); + wso2bpelEntity.setVersion("v1"); + wso2bpelEntity.setUrl("/openoapi/wso2bpel/v1"); + wso2bpelEntity.setSingleNode(Config.getConfigration().getServiceIp(), "8101", 0); + wso2bpelEntity.setVisualRange("1"); + } + +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/externalservice/entity/ServiceNode.java b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/externalservice/entity/ServiceNode.java new file mode 100644 index 0000000..5f0d3bb --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/externalservice/entity/ServiceNode.java @@ -0,0 +1,33 @@ +/** + * Copyright 2016 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.carbon.bpel.externalservice.entity; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@JsonIgnoreProperties(ignoreUnknown = true) +public class ServiceNode { + private String ip; + private String port; + private int ttl; +} + diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/externalservice/entity/ServiceRegisterEntity.java b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/externalservice/entity/ServiceRegisterEntity.java new file mode 100644 index 0000000..3dd336d --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/externalservice/entity/ServiceRegisterEntity.java @@ -0,0 +1,57 @@ +/** + * Copyright 2016 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.carbon.bpel.externalservice.entity; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.ArrayList; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@JsonIgnoreProperties(ignoreUnknown = true) +public class ServiceRegisterEntity { + private String serviceName; + private String version; + private String url; + private String protocol; + private String visualRange; + private ArrayList nodes = new ArrayList(); + + /** + * set service entity. + * + * @param ip node ip. can be null + * @param port service port + * @param ttl service survival time + */ + public void setSingleNode(String ip, String port, int ttl) { + ServiceNode node = new ServiceNode(); + if (ip != null && ip.length() > 0) { + node.setIp(ip); + } else { + node.setIp(null); + } + node.setPort(port); + node.setTtl(ttl); + nodes.add(node); + } + +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/externalservice/msb/MicroserviceBusConsumer.java b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/externalservice/msb/MicroserviceBusConsumer.java new file mode 100644 index 0000000..b5086e8 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/externalservice/msb/MicroserviceBusConsumer.java @@ -0,0 +1,48 @@ +/** + * Copyright 2016 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.carbon.bpel.externalservice.msb; + +import com.eclipsesource.jaxrs.consumer.ConsumerFactory; + +import org.glassfish.jersey.client.ClientConfig; +import org.openo.carbon.bpel.common.Config; +import org.openo.carbon.bpel.externalservice.entity.ServiceRegisterEntity; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + + + +public class MicroserviceBusConsumer { + private static final Logger LOG = LoggerFactory.getLogger(MicroserviceBusConsumer.class); + + /** + * @param entity service entity + * @return register service to msb success return true, else return false. + */ + public static boolean registerService(ServiceRegisterEntity entity) { + ClientConfig config = new ClientConfig(); + try { + MicroserviceBusRest resourceserviceproxy = ConsumerFactory.createConsumer( + Config.getConfigration().getMsbServerAddr(), config, MicroserviceBusRest.class); + resourceserviceproxy.registerServce("false", entity); + } catch (Exception error) { + LOG.error("microservice register failed!" + error.getMessage()); + return false; + } + return true; + } +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/externalservice/msb/MicroserviceBusRest.java b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/externalservice/msb/MicroserviceBusRest.java new file mode 100644 index 0000000..83a6941 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/externalservice/msb/MicroserviceBusRest.java @@ -0,0 +1,39 @@ +/** + * Copyright 2016 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.carbon.bpel.externalservice.msb; + +import javax.ws.rs.Consumes; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; + +import org.openo.carbon.bpel.externalservice.entity.ServiceRegisterEntity; + + + + +@Path("/openoapi/microservices/v1/services") +// @Path("/api/microservices/v1/services") +public interface MicroserviceBusRest { + @Path("") + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public ServiceRegisterEntity registerServce(@QueryParam("createOrUpdate") String createOrUpdate, + ServiceRegisterEntity entity)throws Exception; +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/resources/BpsPackage.java b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/resources/BpsPackage.java new file mode 100644 index 0000000..e11c1eb --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/resources/BpsPackage.java @@ -0,0 +1,632 @@ +/** + * Copyright 2016-2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.carbon.bpel.resources; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.atomic.AtomicLong; + +import javax.activation.DataHandler; +import javax.activation.DataSource; +import javax.activation.FileDataSource; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.QueryParam; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.xml.namespace.QName; + +import org.apache.axiom.om.OMAbstractFactory; +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.OMFactory; +import org.apache.axiom.om.OMNamespace; +import org.apache.axis2.AxisFault; +import org.apache.axis2.addressing.EndpointReference; +import org.apache.axis2.client.Options; +import org.apache.axis2.rpc.client.RPCServiceClient; +import org.apache.axis2.transport.http.HTTPConstants; +import org.apache.axis2.transport.http.HttpTransportProperties; +import org.apache.axis2.transport.http.HttpTransportProperties.Authenticator; +import org.apache.commons.io.FileUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import org.glassfish.jersey.media.multipart.FormDataMultiPart; +import org.glassfish.jersey.media.multipart.FormDataParam; +import org.glassfish.jersey.media.multipart.MultiPartFeature; +import org.glassfish.jersey.media.multipart.file.FileDataBodyPart; +import org.wso2.carbon.bpel.stub.upload.types.UploadedFileItem; +import org.openo.carbon.bpel.common.Config; +import org.openo.carbon.bpel.util.JsonUtil; +import org.openo.carbon.bpel.util.Xml2JsonUtil; + +import com.codahale.metrics.annotation.Timed; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; + +@Path("/") +@Api(tags = {"wso2 bpel api"}) +public class BpsPackage { + + private static final Log log = LogFactory.getLog(BpsPackage.class); + + public static final int STATUS_SUCCESS = 1; + public static final int STATUS_FAIL = 0; + /** + * 无错误 + */ + public static final int ERROR_CODE_NOERROR = 0; + /** + * 不支持的文件类型 + */ + public static final int ERROR_CODE_PACKAGE_UNSUPPORED_FILE = 10001; + /** + * 同名的包正在操作中 + */ + public static final int ERROR_CODE_PACKAGE_STATUS_BUSY = 10002; + /** + * 包名重复 + */ + public static final int ERROR_CODE_PACKAGE_DUPLICATED_NAME = 10003; + /** + * 未获取到包部署的信息 + */ + public static final int ERROR_CODE_PACKAGE_DEPLOY_INFORMATION_IS_LOST = 10004; + /** + * 卸载包失败 + */ + public static final int ERROR_CODE_PACKAGE_UNDEPLOY_FAILED = 10005; + /** + * 包不存在 + */ + public static final int ERROR_CODE_PACKAGE_NOTEXISTS = 10006; + /** + * 服务运行时异常 + */ + public static final int ERROR_CODE_RUNTIME_EXCEPTION = 20001; + /** + * Axis运行时异常 + */ + public static final int ERROR_CODE_RUNTIME_EXCEPTION_AXIS = 20002; + /** + * IO运行时异常 + */ + public static final int ERROR_CODE_RUNTIME_EXCEPTION_IO = 20003; + + public static Set packageNameSet = new HashSet(); + + private Map configMap = null; + + @SuppressWarnings("unused") + private final AtomicLong counter; + + public BpsPackage() { + this.counter = new AtomicLong(); + } + + private synchronized String getConfig(String key) { + if (configMap == null) { + configMap = new HashMap(); + String uploadFilePath = Config.getConfigration().getWso2UploadFilePath(); + String jksFile = Config.getConfigration().getWso2SslJksFile(); + String trustStorePassword = Config.getConfigration().getWso2SslJksPassword(); + String httpUsername = Config.getConfigration().getWso2AuthUserName(); + String httpPassword = Config.getConfigration().getWso2AuthPassword(); + String host = Config.getConfigration().getWso2Host(); + String port = Config.getConfigration().getWso2HostPort(); + configMap.put("uploadFilePath", uploadFilePath); + configMap.put("jksFile", jksFile); + configMap.put("trustStorePassword", trustStorePassword); + configMap.put("httpUsername", httpUsername); + configMap.put("httpPassword", httpPassword); + configMap.put("host", host); + configMap.put("port", port); + } + if (configMap.containsKey(key)) { + return configMap.get(key); + } else { + return ""; + } + } + + public static boolean lockPackageName(String packageName) { + boolean succeed = false; + synchronized (packageNameSet) { + if (!packageNameSet.contains(packageName)) { + packageNameSet.add(packageName); + succeed = true; + } + } + return succeed; + } + + public static boolean unlockPackageName(String packageName) { + boolean succeed = false; + synchronized (packageNameSet) { + if (packageNameSet.contains(packageName)) { + packageNameSet.remove(packageName); + succeed = true; + } + } + return succeed; + } + + @POST + @Path(value = "package") + @Consumes(MediaType.MULTIPART_FORM_DATA) + @Produces(value = MediaType.APPLICATION_JSON) + @ApiOperation(value = "package process", response = Map.class) + @Timed + public Map uploadFile(@FormDataParam("filename") String filename, + @FormDataParam("file") InputStream fileInputStream, + @FormDataParam("file") FormDataContentDisposition fileDetail, + @Context HttpServletRequest request, @Context HttpServletResponse response) + throws IOException { + Map map = new LinkedHashMap(); + String errorMessage = "unkown"; + int errorCode = ERROR_CODE_NOERROR; + + String fileName = fileDetail.getFileName(); + String fullName = getConfig("uploadFilePath") + "/" + fileName; + File file = new File(fullName); + String packageName = null; + try { + if (fileName.endsWith(".zip")) { + packageName = fileName.substring(0, fileName.length() - 4); + } else { + errorCode = ERROR_CODE_PACKAGE_UNSUPPORED_FILE; + throw new Exception("Only support *.zip file."); + } + if (!lockPackageName(packageName)) { + errorCode = ERROR_CODE_PACKAGE_STATUS_BUSY; + throw new Exception("Package " + packageName + " is operating."); + } + FileUtils.copyInputStreamToFile(fileInputStream, file); + System.setProperty("javax.net.ssl.trustStore", "*.keystore"); + System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol"); + System.setProperty("javax.net.ssl.trustStore", getConfig("jksFile")); + System.setProperty("javax.net.ssl.trustStorePassword", getConfig("trustStorePassword")); + + HttpTransportProperties.Authenticator authenticator = + new HttpTransportProperties.Authenticator(); + List auth = new ArrayList(); + auth.add(Authenticator.BASIC); + authenticator.setAuthSchemes(auth); + authenticator.setUsername(getConfig("httpUsername")); + authenticator.setPassword(getConfig("httpPassword")); + authenticator.setPreemptiveAuthentication(true); + + map.putAll(bpsDeployPackage(fileName, fullName, packageName, authenticator)); + map.put("status", STATUS_SUCCESS); + map.put("message", "success"); + return map; + } catch (AxisFault e) { + errorMessage = e.getLocalizedMessage(); + errorCode = ERROR_CODE_RUNTIME_EXCEPTION_AXIS; + log.error(e.getMessage(), e); + e.printStackTrace(); + } catch (IOException e) { + errorMessage = e.getLocalizedMessage(); + errorCode = ERROR_CODE_RUNTIME_EXCEPTION_IO; + log.error(e.getMessage(), e); + e.printStackTrace(); + } catch (Throwable e) { + errorMessage = e.getLocalizedMessage(); + if (e instanceof BpsServiceException) { + errorCode = ((BpsServiceException) e).getErrorCode(); + } else { + errorCode = ERROR_CODE_RUNTIME_EXCEPTION; + } + log.error(e.getMessage(), e); + e.printStackTrace(); + } finally { + if (packageName != null) { + unlockPackageName(packageName); + } + } + map.put("errorCode", errorCode); + map.put("status", STATUS_FAIL); + map.put("message", errorMessage); + return map; + } + + @SuppressWarnings("rawtypes") + private Map bpsDeployPackage(String fileName, String fullName, String packageName, + HttpTransportProperties.Authenticator authenticator) + throws JsonParseException, JsonMappingException, IOException, AxisFault, Exception { + Map map = new HashMap(); + Map deployedPackageInfoMap = getDeployedPackageInfo(authenticator, packageName, ""); + if (deployedPackageInfoMap.get("packageName") != null) { + throw new BpsServiceException(ERROR_CODE_PACKAGE_DUPLICATED_NAME,"Package " + deployedPackageInfoMap.get("packageName") + + " exist, please undeploy it first."); + } + OMElement element = deployPackage(fileName, fullName, authenticator); + System.out.println(Xml2JsonUtil.xml2JSON(element.toString())); + + long timeout = 60 * 1000L; + long timeStart = System.currentTimeMillis(); + while (System.currentTimeMillis() - timeStart < timeout) { + deployedPackageInfoMap = getDeployedPackageInfo(authenticator, packageName, ""); + if (deployedPackageInfoMap.get("packageName") == null) { + Thread.sleep(2000); + } else { + break; + } + } + if (deployedPackageInfoMap.get("packageName") == null) { + throw new BpsServiceException(ERROR_CODE_PACKAGE_DEPLOY_INFORMATION_IS_LOST, + "Package " + packageName + " deploy failed or deploy information is lost."); + } + map.put("packageName", deployedPackageInfoMap.get("packageName")); + map.put("processId", deployedPackageInfoMap.get("pid")); + return map; + } + + private OMElement deployPackage(String fileName, String fullName, + HttpTransportProperties.Authenticator authenticator) throws AxisFault { + String url = + "https://" + getConfig("host") + ":" + getConfig("port") + "/services/BPELUploader?wsdl"; + RPCServiceClient serviceClient = new RPCServiceClient(); + EndpointReference targetEPR = new EndpointReference(url); + Options options = serviceClient.getOptions(); + options.setTo(targetEPR); + options.setAction("urn:uploadService"); + options.setProperty(HTTPConstants.SO_TIMEOUT, new Integer(300000)); + options.setProperty(HTTPConstants.AUTHENTICATE, authenticator); + serviceClient.setOptions(options); + + QName qname = new QName("http://services.deployer.bpel.carbon.wso2.org", "uploadService"); + UploadedFileItem fileItem = new UploadedFileItem(); + fileItem.setFileName(fileName); + fileItem.setFileType("zip"); + + DataSource dataSource = new FileDataSource(fullName); + fileItem.setDataHandler(new DataHandler(dataSource)); + UploadedFileItem[] parameters = new UploadedFileItem[] {fileItem}; + OMElement element = serviceClient.invokeBlocking(qname, parameters); + return element; + } + + @Path(value = "package/{packageName}") + @DELETE + @Produces(value = MediaType.APPLICATION_JSON) + @ApiOperation(value = "delete", response = Map.class) + @Timed + public Map delete(@PathParam("packageName") String packageName, + @Context HttpServletRequest request) { + Map map = new LinkedHashMap(); + String errorMessage = "unkown"; + int errorCode = ERROR_CODE_NOERROR; + try { + if (!lockPackageName(packageName)) { + throw new Exception("Package " + packageName + " is operating."); + } + System.setProperty("javax.net.ssl.trustStore", "*.keystore"); + System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol"); + System.setProperty("javax.net.ssl.trustStore", getConfig("jksFile")); + System.setProperty("javax.net.ssl.trustStorePassword", getConfig("trustStorePassword")); + + HttpTransportProperties.Authenticator authenticator = + new HttpTransportProperties.Authenticator(); + List auth = new ArrayList(); + auth.add(Authenticator.BASIC); + authenticator.setAuthSchemes(auth); + authenticator.setUsername(getConfig("httpUsername")); + authenticator.setPassword(getConfig("httpPassword")); + authenticator.setPreemptiveAuthentication(true); + + map.putAll(bpsUndeployPackage(packageName, authenticator)); + + return map; + } catch (AxisFault e) { + errorMessage = e.getLocalizedMessage(); + errorCode = ERROR_CODE_RUNTIME_EXCEPTION_AXIS; + log.error(e.getMessage(), e); + e.printStackTrace(); + } catch (Throwable e) { + errorMessage = e.getLocalizedMessage(); + if (e instanceof BpsServiceException) { + errorCode = ((BpsServiceException) e).getErrorCode(); + } else { + errorCode = ERROR_CODE_RUNTIME_EXCEPTION; + } + log.error(e.getMessage(), e); + e.printStackTrace(); + } finally { + if (packageName != null) { + unlockPackageName(packageName); + } + } + map.put("errorCode", errorCode); + map.put("status", STATUS_FAIL); + map.put("message", errorMessage); + return map; + } + + @SuppressWarnings({"rawtypes", "unused"}) + private Map bpsUndeployPackage(String packageName, + HttpTransportProperties.Authenticator authenticator) + throws JsonParseException, JsonMappingException, IOException, AxisFault, Exception { + Map map = new HashMap(); + Map deployedPackageInfoMap = getDeployedPackageInfo(authenticator, packageName, ""); + if (deployedPackageInfoMap.get("packageName") == null) { + throw new BpsServiceException(ERROR_CODE_PACKAGE_NOTEXISTS,"Package " + deployedPackageInfoMap.get("packageName") + + " does not exist, please deploy it first."); + } + OMElement element = undeployPackage(authenticator, packageName); + deployedPackageInfoMap = getDeployedPackageInfo(authenticator, packageName, ""); + if (deployedPackageInfoMap.get("packageName") != null) { + throw new BpsServiceException(ERROR_CODE_PACKAGE_UNDEPLOY_FAILED, + "Package " + deployedPackageInfoMap.get("packageName") + " undeploy failed."); + } + map.put("status", STATUS_SUCCESS); + map.put("message", "success"); + + return map; + } + + private OMElement undeployPackage(HttpTransportProperties.Authenticator authenticator, + String packageName) throws AxisFault { + String url = "https://" + getConfig("host") + ":" + getConfig("port") + + "/services/BPELPackageManagementService?wsdl"; + RPCServiceClient serviceClient = new RPCServiceClient(); + EndpointReference targetEPR = new EndpointReference(url); + Options options = serviceClient.getOptions(); + options.setTo(targetEPR); + options.setAction("sch:undeployBPELPackage"); + options.setProperty(HTTPConstants.SO_TIMEOUT, new Integer(300000)); + options.setProperty(HTTPConstants.AUTHENTICATE, authenticator); + serviceClient.setOptions(options); + OMFactory fac = OMAbstractFactory.getOMFactory(); + OMNamespace omNs = fac.createOMNamespace("http://wso2.org/bps/management/schema", "sch"); + OMElement method = fac.createOMElement("undeployBPELPackage", omNs); + OMElement content = fac.createOMElement("package", omNs); + content.addChild(fac.createOMText(content, packageName)); + method.addChild(content); + method.build(); + OMElement res = serviceClient.sendReceive(method); + return res; + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + private Map getFullDeployedPackageInfo(HttpTransportProperties.Authenticator authenticator, + String packageName, String page) throws Exception { + String result; + String jsonTemplate = + "{'listDeployedPackagesPaginated':{'page':'${page}','packageSearchString':'${searchString}'}}"; + Map jsonParamMap = new HashMap(); + jsonParamMap.put("page", page); + jsonParamMap.put("searchString", packageName); + Object params = getParams(jsonTemplate, jsonParamMap); + result = BpsProcess.invokeWsdl("https://" + getConfig("host") + ":" + getConfig("port") + + "/services/BPELPackageManagementService?wsdl", params, authenticator); + Map processMap = JsonUtil.json2Bean(result, Map.class); + return processMap; + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + private Map getDeployedPackageInfo(HttpTransportProperties.Authenticator authenticator, + String packageName, String page) throws Exception { + Map resultMap = new HashMap(); + Map processMap = getFullDeployedPackageInfo(authenticator, packageName, page); + Object packages = ((Map) processMap.get("deployedPackagesPaginated")).get("package"); + Map deployedPackage = null; + if (packages instanceof List) { + for (Iterator iter = ((List) packages).iterator(); iter.hasNext();) { + Map packageMap = (Map) iter.next(); + String deployedPackageName = (String) packageMap.get("name"); + if (deployedPackageName.equals(packageName)) { + deployedPackage = packageMap; + break; + } + } + } else if (packages instanceof Map) { + String deployedPackageName = (String) ((Map) packages).get("name"); + if (deployedPackageName.equals(packageName)) { + deployedPackage = (Map) packages; + } + } + if (deployedPackage != null) { + String fullPackageName = null; + String pid = null; + Object versions = ((Map) deployedPackage.get("versions")).get("version"); + Map lastestVersion = null; + if (versions instanceof List) { + for (Iterator iter = ((List) versions).iterator(); iter.hasNext();) { + Map version = (Map) iter.next(); + if (version.get("isLatest").equals("true")) { + lastestVersion = version; + } + } + } else if (versions instanceof Map) { + lastestVersion = (Map) versions; + } + fullPackageName = (String) ((Map) ((Map) lastestVersion.get("processes")).get("process")) + .get("packageName"); + pid = (String) ((Map) ((Map) lastestVersion.get("processes")).get("process")).get("pid"); + resultMap.put("packageName", fullPackageName); + resultMap.put("pid", pid); + } + return resultMap; +} + + + @SuppressWarnings({"rawtypes", "unchecked"}) + public static Map getParams(String jsonTemplate, Map paramMap) + throws JsonParseException, JsonMappingException, IOException { + String json = jsonTemplate.replaceAll("'", "\""); + for (Iterator iter = paramMap.keySet().iterator(); iter.hasNext();) { + String key = (String) iter.next(); + String value = ""; + if (paramMap.get(key) != null) { + value = paramMap.get(key).toString().replaceAll("\"", "\\\\\""); + } + json = json.replaceAll("\\$\\{" + key + "\\}", value); + } + return JsonUtil.json2Bean(json, Map.class); + } + + @GET + @Path(value = "listPackages") + @Produces(value = MediaType.APPLICATION_JSON) + @ApiOperation(value = "list packages", response = Map.class) + @Timed + public Map listPackages(@QueryParam("page") String page, + @QueryParam("searchString") String searchString, @Context HttpServletRequest request) + throws IOException { + Map map = new LinkedHashMap(); + String errorMessage = "unkown"; + int errorCode = ERROR_CODE_NOERROR; + String packageName = null; + try { + System.setProperty("javax.net.ssl.trustStore", "*.keystore"); + System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol"); + System.setProperty("javax.net.ssl.trustStore", getConfig("jksFile")); + System.setProperty("javax.net.ssl.trustStorePassword", getConfig("trustStorePassword")); + + HttpTransportProperties.Authenticator authenticator = + new HttpTransportProperties.Authenticator(); + List auth = new ArrayList(); + auth.add(Authenticator.BASIC); + authenticator.setAuthSchemes(auth); + authenticator.setUsername(getConfig("httpUsername")); + authenticator.setPassword(getConfig("httpPassword")); + authenticator.setPreemptiveAuthentication(true); + + map.putAll(getFullDeployedPackageInfo(authenticator,searchString,page)); + + map.put("status", STATUS_SUCCESS); + map.put("message", "success"); + return map; + } catch (AxisFault e) { + errorMessage = e.getLocalizedMessage(); + errorCode = ERROR_CODE_RUNTIME_EXCEPTION_AXIS; + log.error(e.getMessage(), e); + e.printStackTrace(); + } catch (IOException e) { + errorMessage = e.getLocalizedMessage(); + errorCode = ERROR_CODE_RUNTIME_EXCEPTION_IO; + log.error(e.getMessage(), e); + e.printStackTrace(); + } catch (Throwable e) { + if (e instanceof BpsServiceException) { + errorCode = ((BpsServiceException) e).getErrorCode(); + } else { + errorCode = ERROR_CODE_RUNTIME_EXCEPTION; + } + errorMessage = e.getLocalizedMessage(); + log.error(e.getMessage(), e); + e.printStackTrace(); + } finally { + if (packageName != null) { + unlockPackageName(packageName); + } + } + map.put("errorCode", errorCode); + map.put("status", STATUS_FAIL); + map.put("message", errorMessage); + return map; + } + + @SuppressWarnings("rawtypes") + public static void main(String[] args) { + try { + + boolean remoteDebug = true; + boolean localDebug = false; + if (remoteDebug) { + Client client = ClientBuilder.newBuilder().register(MultiPartFeature.class).build(); + WebTarget target = client.target("http://localhost:8101/openoapi/wso2bpel/v1/package"); + FileDataBodyPart bodyPart = new FileDataBodyPart("file", + new File("F:\\wso2bps-3.5.1\\wso2bps-3.5.1\\repository\\samples\\bpel\\Alarm.zip")); + FormDataMultiPart formDataMultiPart = new FormDataMultiPart(); + formDataMultiPart.field("fileName", "Alarm.zip").bodyPart(bodyPart); + String result = target.request(MediaType.APPLICATION_JSON) + .post(Entity.entity(formDataMultiPart, formDataMultiPart.getMediaType()), String.class); + System.out.println(result); + } + // + // System.out.println("************************************************************************"); + // + // bodyPart = new FileDataBodyPart("file", new + // File("D:\\temp\\bpel-sample\\AssignDate\\AssignDate.zip")); + // formDataMultiPart = new FormDataMultiPart(); + // formDataMultiPart.field("fileName", + // "AssignDate.zip").bodyPart(bodyPart); + // result = target.request(MediaType.APPLICATION_JSON) + // .post(Entity.entity(formDataMultiPart, + // formDataMultiPart.getMediaType()), String.class); + // System.out.println(result); + // + if (localDebug) { + System.setProperty("javax.net.ssl.trustStore", "*.keystore"); + System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol"); + System.setProperty("javax.net.ssl.trustStore", + "D:\\software\\WSO2\\wso2bps-3.5.1\\repository\\resources\\security\\wso2carbon.jks"); + System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon"); + HttpTransportProperties.Authenticator authenticator = + new HttpTransportProperties.Authenticator(); + List auth = new ArrayList(); + auth.add(Authenticator.BASIC); + authenticator.setAuthSchemes(auth); + authenticator.setUsername("admin"); + authenticator.setPassword("admin"); + authenticator.setPreemptiveAuthentication(true); + // + // String packageName = "RESTProcess"; + // Map deployedPackageInfoMap = + // getDeployedPackageInfo(authenticator, packageName); + + BpsPackage packageTest = new BpsPackage(); + Map map; + // map = packageTest.bpsUndeployPackage("AssignDate", + // authenticator); + // System.out.println(JsonUtil.bean2Json(map)); + map = packageTest.bpsDeployPackage("AssignDate.zip", + "D:\\temp\\bpel-sample\\AssignDate\\AssignDate.zip", "AssignDate", authenticator); + System.out.println(JsonUtil.bean2Json(map)); + map = packageTest.bpsUndeployPackage("AssignDate", authenticator); + System.out.println(JsonUtil.bean2Json(map)); + } + + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/resources/BpsProcess.java b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/resources/BpsProcess.java new file mode 100644 index 0000000..148e309 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/resources/BpsProcess.java @@ -0,0 +1,544 @@ +/** + * Copyright 2016 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.carbon.bpel.resources; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.atomic.AtomicLong; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.Consumes; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.xml.namespace.QName; + +import org.apache.axiom.om.OMAbstractFactory; +import org.apache.axiom.om.OMAttribute; +import org.apache.axiom.om.OMDocument; +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.OMFactory; +import org.apache.axiom.om.OMNamespace; +import org.apache.axiom.om.OMText; +import org.apache.axiom.om.OMXMLBuilderFactory; +import org.apache.axiom.om.OMXMLParserWrapper; +import org.apache.axiom.om.util.StAXParserConfiguration; +import org.apache.axis2.AxisFault; +import org.apache.axis2.addressing.EndpointReference; +import org.apache.axis2.client.Options; +import org.apache.axis2.client.ServiceClient; +import org.apache.axis2.rpc.client.RPCServiceClient; +import org.apache.axis2.transport.http.HTTPConstants; +import org.apache.axis2.transport.http.HttpTransportProperties; +import org.apache.axis2.transport.http.HttpTransportProperties.Authenticator; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.glassfish.jersey.media.multipart.MultiPartFeature; +import org.openo.carbon.bpel.common.Config; +import org.openo.carbon.bpel.util.JsonUtil; +import org.openo.carbon.bpel.util.SoapUtil; +import org.openo.carbon.bpel.util.Xml2JsonUtil; + +import com.codahale.metrics.annotation.Timed; +import com.eviware.soapui.model.iface.MessagePart; +import com.eviware.soapui.model.iface.Request; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.JsonNode; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; + +@Path("/") +@Api(tags = {"wso2 bpel api"}) +public class BpsProcess { + + private static final Log log = LogFactory.getLog(BpsProcess.class); + + public static final int STATUS_SUCCESS = 1; + public static final int STATUS_FAIL = 0; + + private Map configMap = null; + + @SuppressWarnings("unused") + private final AtomicLong counter; + + public BpsProcess() { + this.counter = new AtomicLong(); + } + + private synchronized String getConfig(String key) { + if (configMap == null) { + configMap = new HashMap(); + //Config.getConfigration().getMsbServerAddr(); + /* String uploadFilePath = ConfigManager.getInstance().getProperty("wso2.uploadfile.path"); + String jksFile = ConfigManager.getInstance().getProperty("wso2.ssl.jks.file"); + String trustStorePassword = + ConfigManager.getInstance().getProperty("wso2.ssl.trustStorePassword"); + String httpUsername = + ConfigManager.getInstance().getProperty("wso2.http.authenticator.username"); + String httpPassword = + ConfigManager.getInstance().getProperty("wso2.http.authenticator.password"); + String host = ConfigManager.getInstance().getProperty("wso2.host"); + String port = ConfigManager.getInstance().getProperty("wso2.http.port");*/ + String uploadFilePath = Config.getConfigration().getWso2UploadFilePath(); + String jksFile = Config.getConfigration().getWso2SslJksFile(); + String trustStorePassword = Config.getConfigration().getWso2SslJksPassword(); + String httpUsername = Config.getConfigration().getWso2AuthUserName(); + String httpPassword = Config.getConfigration().getWso2AuthPassword(); + String host = Config.getConfigration().getWso2Host(); + String port = Config.getConfigration().getWso2HostPort(); + configMap.put("uploadFilePath", uploadFilePath); + configMap.put("jksFile", jksFile); + configMap.put("trustStorePassword", trustStorePassword); + configMap.put("httpUsername", httpUsername); + configMap.put("httpPassword", httpPassword); + configMap.put("host", host); + configMap.put("port", port); + } + if (configMap.containsKey(key)) { + return configMap.get(key); + } else { + return ""; + } + } + + @SuppressWarnings("unchecked") + @POST + @Path("process/instance") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(value = MediaType.APPLICATION_JSON) + @ApiOperation(value = "startProcess", response = Map.class) + @Timed + public Map startProcess(JsonNode jsonObj, @Context HttpServletRequest request) { + Map map = new LinkedHashMap(); + String errorMessage = "unkown"; + + Map paramMap = new HashMap(); + try { + paramMap = JsonUtil.json2Bean(jsonObj.toString(), Map.class); + String processId = (String) paramMap.get("processId"); + + Object params = paramMap.get("params"); + + String wsdlUrl = getWsdlUrl(processId); + String response = invokeWsdl(wsdlUrl, params); + + map.put("status", STATUS_SUCCESS); + map.put("message", "success"); + // map.put("wsdl", wsdlUrl); + map.put("response", response); + return map; + } catch (JsonParseException e) { + errorMessage = e.getLocalizedMessage(); + log.error(e.getMessage(), e); + e.printStackTrace(); + } catch (JsonMappingException e) { + errorMessage = e.getLocalizedMessage(); + log.error(e.getMessage(), e); + e.printStackTrace(); + } catch (IOException e) { + errorMessage = e.getLocalizedMessage(); + log.error(e.getMessage(), e); + e.printStackTrace(); + } catch (Exception e) { + errorMessage = e.getLocalizedMessage(); + log.error(e.getMessage(), e); + e.printStackTrace(); + } + + map.put("status", STATUS_FAIL); + map.put("message", errorMessage); + return map; + } + + public static String invokeWsdl(String wsdlUrl, Object params) throws Exception { + return invokeWsdl(wsdlUrl, params, null); + } + + @SuppressWarnings({"unused", "rawtypes"}) + public static String invokeWsdl(String wsdlUrl, Object params, + HttpTransportProperties.Authenticator authenticator) throws Exception { + SoapUtil soapUtil = new SoapUtil(); + Request[] requestTemplates = soapUtil.getRequestTemplate(wsdlUrl); + String requestTemplate = null; + Request invokeRequest = null; + for (Request requestXML : requestTemplates) { + + InputStream is = new ByteArrayInputStream(requestXML.getRequestContent().getBytes()); + OMXMLParserWrapper builder = OMXMLBuilderFactory.createOMBuilder( + OMAbstractFactory.getOMFactory(), StAXParserConfiguration.STANDALONE, is); + OMElement root = builder.getDocumentElement(); + OMDocument omDocument = builder.getDocument(); + Iterator iter = omDocument.getChildren(); + OMElement bodyElement = null; + while (iter.hasNext()) { + OMElement node = (OMElement) iter.next(); + String nodeName = node.getLocalName(); + if (nodeName.equals("Envelope")) { + Iterator envChildren = node.getChildElements(); + while (envChildren.hasNext()) { + Object childNode = envChildren.next(); + if (childNode instanceof OMElement) { + if (((OMElement) childNode).getLocalName().equals("Body")) { + bodyElement = (OMElement) childNode; + } + } + } + } + } + Set paramSet = new HashSet(); + Iterator bodyIter = bodyElement.getChildElements(); + while (bodyIter.hasNext()) { + Object obj = bodyIter.next(); + OMElement requestBody = (OMElement) obj; + paramSet.add(requestBody.getLocalName()); + } + if (params instanceof Map) { + Set paramKeySet = ((Map) params).keySet(); + boolean matched = true; + for (Object key : paramKeySet) { + if (!paramSet.contains(key)) { + matched = false; + continue; + } + } + if (matched) { + invokeRequest = requestXML; + requestTemplate = requestXML.getRequestContent(); + break; + } + } + } + if (requestTemplate == null) { + throw new Exception("Invalid param."); + } + + InputStream is = new ByteArrayInputStream(requestTemplate.getBytes()); + OMXMLParserWrapper builder = OMXMLBuilderFactory + .createOMBuilder(OMAbstractFactory.getOMFactory(), StAXParserConfiguration.STANDALONE, is); + OMElement root = builder.getDocumentElement(); + OMDocument omDocument = builder.getDocument(); + Iterator iter = omDocument.getChildren(); + OMElement bodyElement = null; + while (iter.hasNext()) { + OMElement node = (OMElement) iter.next(); + String nodeName = node.getLocalName(); + if (nodeName.equals("Envelope")) { + Iterator envChildren = node.getChildElements(); + while (envChildren.hasNext()) { + Object childNode = envChildren.next(); + if (childNode instanceof OMElement) { + if (((OMElement) childNode).getLocalName().equals("Body")) { + bodyElement = (OMElement) childNode; + } + } + } + } + } + + Options options = new Options(); + EndpointReference targetEPR = new EndpointReference(wsdlUrl); + options.setTo(targetEPR); + if (authenticator != null) { + options.setProperty(HTTPConstants.AUTHENTICATE, authenticator); + } + ServiceClient sender = new ServiceClient(); + sender.setOptions(options); + OMFactory factory = OMAbstractFactory.getOMFactory(); + OMElement requestBody = null; + Iterator bodyIter = bodyElement.getChildElements(); + while (bodyIter.hasNext()) { + Object obj = bodyIter.next(); + requestBody = (OMElement) obj; + } + + // Iterator requestBodyIter = requestBody.getChildElements(); + setParams(requestBody, params); + + requestBody.build(); + OMElement result = null; + boolean needResponse = false; + try { + MessagePart[] parts = invokeRequest.getResponseParts(); + if (parts != null && parts.length > 0) { + needResponse = true; + } + } catch (RuntimeException e) { + e.printStackTrace(); + } catch (Throwable e) { + e.printStackTrace(); + } + if (needResponse) { + result = sender.sendReceive(requestBody); + return Xml2JsonUtil.xml2JSON(result.toString()); + } else { + sender.sendRobust(requestBody); + return ""; + } + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + private static void setParams(OMElement requestBody, Object params) { + Object currentParams = null; + if (params instanceof Map) { + currentParams = ((Map) params).get((requestBody).getLocalName()); + Object obj = requestBody.getFirstElement(); + if (obj == null) { + if (currentParams instanceof String) { + requestBody.setText((String) currentParams); + } + } else { + Iterator iter = requestBody.getChildElements(); + while (iter.hasNext()) { + OMElement child = iter.next(); + setParams((OMElement) child, currentParams); + } + } + } + } + + @SuppressWarnings("unchecked") + public String getWsdlUrl(String pid) { + log.warn("rest begin..."); + String wsdlUrl = null; + try { + System.setProperty("javax.net.ssl.trustStore", "*.keystore"); + + System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol"); + + System.setProperty("javax.net.ssl.trustStore", getConfig("jksFile")); + System.setProperty("javax.net.ssl.trustStorePassword", getConfig("trustStorePassword")); + + String url = "https://" + getConfig("host") + ":" + getConfig("port") + + "/services/ProcessManagementService?wsdl"; + RPCServiceClient serviceClient = new RPCServiceClient(); + EndpointReference targetEPR = new EndpointReference(url); + Options options = serviceClient.getOptions(); + options.setTo(targetEPR); + // options.setAction("sch:undeployBPELPackage"); + + options.setProperty(HTTPConstants.SO_TIMEOUT, new Integer(300000)); + HttpTransportProperties.Authenticator authenticator = + new HttpTransportProperties.Authenticator(); + List auth = new ArrayList(); + auth.add(Authenticator.BASIC); + authenticator.setAuthSchemes(auth); + authenticator.setUsername(getConfig("httpUsername")); + authenticator.setPassword(getConfig("httpPassword")); + authenticator.setPreemptiveAuthentication(true); + options.setProperty(HTTPConstants.AUTHENTICATE, authenticator); + + serviceClient.setOptions(options); + + OMFactory fac = OMAbstractFactory.getOMFactory(); + OMNamespace omNs = fac.createOMNamespace("http://wso2.org/bps/management/schema", "sch"); + + OMElement method = fac.createOMElement("getProcessInfoIn", omNs); + QName pidQName = QName.valueOf(pid); + OMElement pidElement = fac.createOMElement("pid", omNs); + + pidElement.addChild(fac.createOMText(pidElement, pidQName)); + method.addChild(pidElement); + + method.build(); + + OMElement res = serviceClient.sendReceive(method); + res.getFirstElement().getText(); + + // System.out.println(JsonUtil.bean2Json(parse(res))); + + Iterator iter = res.getChildrenWithLocalName("endpoints"); + if (iter.hasNext()) { + OMElement endPoints = (OMElement) iter.next(); + Iterator endPointIter = endPoints.getChildrenWithLocalName("endpointRef"); + if (endPointIter.hasNext()) { + OMElement endpointRef = (OMElement) endPointIter.next(); + Iterator endpointRefIter = + endpointRef.getChildrenWithLocalName("serviceLocations"); + if (endpointRefIter.hasNext()) { + OMElement serviceLocations = (OMElement) endpointRefIter.next(); + Iterator serviceLocationsIter = + serviceLocations.getChildrenWithLocalName("serviceLocation"); + while (serviceLocationsIter.hasNext()) { + OMElement serviceLocation = (OMElement) serviceLocationsIter.next(); + String sUrl = serviceLocation.getText(); + if (sUrl.endsWith("wsdl")) { + wsdlUrl = sUrl; + break; + } + } + } + } + } + + } catch (AxisFault e) { + log.error(e.getMessage(), e); + e.printStackTrace(); + } catch (Throwable e) { + log.error(e.getMessage(), e); + e.printStackTrace(); + } finally { + log.warn("invoke finally..."); + } + return wsdlUrl; + } + + @SuppressWarnings({"unused", "rawtypes", "unchecked"}) + private Map parse(OMElement node) { + Map resultMap = new HashMap(); + Iterator attrIter = node.getAllAttributes(); + while (attrIter.hasNext()) { + OMAttribute attr = (OMAttribute) attrIter.next(); + resultMap.put(attr.getLocalName(), attr.getAttributeValue()); + } + boolean hasChild = false; + List childList = new ArrayList(); + Iterator childIter = node.getChildren();// getChildElements(); + while (childIter.hasNext()) { + hasChild = true; + Object child = childIter.next(); + if (child instanceof OMText) { + resultMap.put(node.getLocalName(), ((OMText) child).getText()); + } else if (child instanceof OMElement) { + childList.add(parse((OMElement) child)); + resultMap.put(node.getLocalName(), childList); + } + } + return resultMap; + } + + public static void main1(String[] args) { + Client client = ClientBuilder.newBuilder().register(MultiPartFeature.class).build(); + WebTarget target = client.target("http://127.0.0.1:8080/wso2bpel/v1/process/instance"); + String jsonObj = + "{\"processId\":\"{http://ode/bpel/unit-test}HelloWorld2-18\",\"params\": {\"hello\":{\"TestPart\":\"AAA\"}}}"; + Response response = target.request(MediaType.APPLICATION_JSON) + .post(Entity.entity(jsonObj, MediaType.APPLICATION_JSON)); + int responseCode = response.getStatus(); + if (responseCode == 200) { + String excuteRespJson = response.readEntity(String.class); + // context.setExcuteRespJson(excuteRespJson); + // System.out.println("excute responseJson=====" + + // context.getExcuteRespJson()); + System.out.println(excuteRespJson); + } + + System.out.println("************************************************************************"); + jsonObj = + "{\"processId\":\"{http://ode/bpel/unit-test}HelloWorld2-18\",\"params\": {\"hello\":{\"TestPart\":\"AAA\"}}}"; + BpsProcess process = new BpsProcess(); + try { + Map resultMap = process.startProcess(JsonUtil.getJsonNode(jsonObj), null); + System.out.println(JsonUtil.bean2Json(resultMap)); + } catch (JsonProcessingException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + System.out.println("************************************************************************"); + jsonObj = + "{\"processId\":\"{http://ode/bpel/unit-test}HelloXslWorld-3\",\"params\": {\"helloXsl\":{\"TestPart\":{\"content\":\"AAA\"}}}}"; + process = new BpsProcess(); + try { + Map resultMap = process.startProcess(JsonUtil.getJsonNode(jsonObj), null); + System.out.println(JsonUtil.bean2Json(resultMap)); + } catch (JsonProcessingException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + System.out.println("************************************************************************"); + jsonObj = + "{\"processId\":\"{http://wso2.org/bps/samples/While}While-5\",\"params\": {\"WhileRequest\":{\"input\":\"365\"}}}"; + process = new BpsProcess(); + try { + Map resultMap = process.startProcess(JsonUtil.getJsonNode(jsonObj), null); + System.out.println(JsonUtil.bean2Json(resultMap)); + } catch (JsonProcessingException e) { + e.printStackTrace(); + } catch (IOException e) { + } + + } + + @SuppressWarnings("unchecked") + public static void main(String[] args) { + + Map map = new LinkedHashMap(); + String errorMessage = "unkown"; + + Map paramMap = new HashMap(); + try { + String param = + "{\"planInput\":{\"sfc_count\":\"2\",\"nsInstanceId\":\"223\",\"vnfmId\":\"112\",\"instanceId\":\"334\",\"object_context\":\"{\\\"e\\\":{\\\"f\\\":\\\"4\\\"}}\",\"vnf_count\":\"2\",\"serviceTemplateId\":\"?\",\"vl_count\":\"2\",\"containerapiUrl\":\"?\",\"object_additionalParamForVnf\":\"[{\\\"b\\\":1},{\\\"c\\\":{\\\"d\\\":\\\"2\\\"}}}]\",\"object_additionalParamForNs\":\"[{\\\"a\\\":3},{\\\"e\\\":{\\\"f\\\":\\\"4\\\"}}}]\"}}"; + String jsonObj = + "{\"processId\":\"{http://wso2.org/bps/samples/While}While-5\",\"params\":" + param + "}"; + paramMap = JsonUtil.json2Bean(jsonObj.toString(), Map.class); + Object params = paramMap.get("params"); + String wsdlUrl = "http://10.74.151.36:9763/services/initService?wsdl"; + String response = invokeWsdl(wsdlUrl, params); + map.put("status", STATUS_SUCCESS); + map.put("message", "success"); + map.put("response", response); + System.out.println(JsonUtil.bean2Json(map)); + } catch (JsonParseException e) { + errorMessage = e.getLocalizedMessage(); + log.error(e.getMessage(), e); + e.printStackTrace(); + } catch (JsonMappingException e) { + errorMessage = e.getLocalizedMessage(); + log.error(e.getMessage(), e); + e.printStackTrace(); + } catch (IOException e) { + errorMessage = e.getLocalizedMessage(); + log.error(e.getMessage(), e); + e.printStackTrace(); + } catch (Exception e) { + errorMessage = e.getLocalizedMessage(); + log.error(e.getMessage(), e); + e.printStackTrace(); + } + + map.put("status", STATUS_FAIL); + map.put("message", errorMessage); + try { + System.out.println(JsonUtil.bean2Json(map)); + } catch (IOException e) { + errorMessage = e.getLocalizedMessage(); + log.error(e.getMessage(), e); + e.printStackTrace(); + } + + } +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/resources/BpsServiceException.java b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/resources/BpsServiceException.java new file mode 100644 index 0000000..bd05a95 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/resources/BpsServiceException.java @@ -0,0 +1,30 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.carbon.bpel.resources; + +public class BpsServiceException extends Exception { + + int errorCode = 0; + + public int getErrorCode() { + return errorCode; + } + + public BpsServiceException(int errorCode, String message) { + super(message); + this.errorCode = errorCode; + } +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/resources/RestAppConfig.java b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/resources/RestAppConfig.java new file mode 100644 index 0000000..b81fbe9 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/resources/RestAppConfig.java @@ -0,0 +1,37 @@ +/** + * Copyright 2016 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.carbon.bpel.resources; + +import javax.ws.rs.ApplicationPath; + +import org.glassfish.jersey.filter.LoggingFilter; +import org.glassfish.jersey.media.multipart.MultiPartFeature; +import org.glassfish.jersey.server.ResourceConfig; + +import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; + +@ApplicationPath("/v1") +public class RestAppConfig extends ResourceConfig { + + public RestAppConfig() { + packages("org.wso2.carbon.bpel.rest.ext.v1"); + register(JacksonJsonProvider.class); + register(MultiPartFeature.class); + // register(MultiPartResource.class); + register(LoggingFilter.class); + } + +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/util/ClientWsdlLoader.java b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/util/ClientWsdlLoader.java new file mode 100644 index 0000000..70a9588 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/util/ClientWsdlLoader.java @@ -0,0 +1,82 @@ +/** + * Copyright 2016 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.carbon.bpel.util; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.net.URL; +import org.apache.log4j.Logger; + +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.HttpException; +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.httpclient.methods.GetMethod; + +import com.eviware.soapui.impl.wsdl.support.wsdl.WsdlLoader; + +public class ClientWsdlLoader extends WsdlLoader { + private static Logger logger = Logger.getLogger(ClientWsdlLoader.class); + + private boolean isAborted = false; + private HttpClient httpClient; + + public ClientWsdlLoader(String url, HttpClient httpClient) { + super(url); + this.httpClient = httpClient; + } + + public InputStream load(String url) throws Exception { + GetMethod httpGetMethod; + + if (url.startsWith("file")) { + return new URL(url).openStream(); + } + + // Authentication is not being overridden on the method. It needs + // to be present on the supplied HttpClient instance! + httpGetMethod = new GetMethod(url); + httpGetMethod.setDoAuthentication(true); + + try { + int result = httpClient.executeMethod(httpGetMethod); + + if (result != HttpStatus.SC_OK) { + if (result < 200 || result > 299) { + throw new HttpException( + "Received status code '" + result + "' on WSDL HTTP (GET) request: '" + url + "'."); + } else { + logger.warn( + "Received status code '" + result + "' on WSDL HTTP (GET) request: '" + url + "'."); + } + } + + return new ByteArrayInputStream(httpGetMethod.getResponseBody()); + } finally { + httpGetMethod.releaseConnection(); + } + } + + public boolean abort() { + isAborted = true; + return true; + } + + public boolean isAborted() { + return isAborted; + } + + public void close() {} +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/util/JsonUtil.java b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/util/JsonUtil.java new file mode 100644 index 0000000..f2a4d97 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/util/JsonUtil.java @@ -0,0 +1,61 @@ +/** + * Copyright 2016 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.carbon.bpel.util; + +import java.io.IOException; +import java.io.StringWriter; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JavaType; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class JsonUtil { + + @SuppressWarnings("deprecation") + public static String bean2Json(Object obj) throws IOException { + ObjectMapper mapper = new ObjectMapper(); + StringWriter sw = new StringWriter(); + JsonGenerator gen = new JsonFactory().createJsonGenerator(sw); + mapper.writeValue(gen, obj); + gen.close(); + return sw.toString(); + } + + public static T json2Bean(String jsonStr, Class objClass) + throws JsonParseException, JsonMappingException, IOException { + ObjectMapper mapper = new ObjectMapper(); + return mapper.readValue(jsonStr, objClass); + } + + @SuppressWarnings("deprecation") + public static T readJson(String jsonStr, Class collectionClass, Class... elementClasses) + throws Exception { + ObjectMapper mapper = new ObjectMapper(); + JavaType javaType = + mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses); + return mapper.readValue(jsonStr, javaType); + } + + public static JsonNode getJsonNode(String json) throws JsonProcessingException, IOException { + return new ObjectMapper().readTree(json); + } + +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/util/LRULinkedHashMap.java b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/util/LRULinkedHashMap.java new file mode 100644 index 0000000..deb07c6 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/util/LRULinkedHashMap.java @@ -0,0 +1,106 @@ +/** + * Copyright 2016 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.carbon.bpel.util; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +/** + * + * @author bsli + * + * @param + * @param + */ +@SuppressWarnings("serial") +public class LRULinkedHashMap extends LinkedHashMap { + private final int maxCapacity; + + private static final float DEFAULT_LOAD_FACTOR = 0.75f; + + private final Lock lock = new ReentrantLock(); + + public LRULinkedHashMap(int maxCapacity) { + super(maxCapacity, DEFAULT_LOAD_FACTOR, true); + this.maxCapacity = maxCapacity; + } + + @Override + protected boolean removeEldestEntry(java.util.Map.Entry eldest) { + return size() > maxCapacity; + } + + @Override + public boolean containsKey(Object key) { + try { + lock.lock(); + return super.containsKey(key); + } finally { + lock.unlock(); + } + } + + @Override + public V get(Object key) { + try { + lock.lock(); + return super.get(key); + } finally { + lock.unlock(); + } + } + + @Override + public V put(K key, V value) { + try { + lock.lock(); + return super.put(key, value); + } finally { + lock.unlock(); + } + } + + public int size() { + try { + lock.lock(); + return super.size(); + } finally { + lock.unlock(); + } + } + + public void clear() { + try { + lock.lock(); + super.clear(); + } finally { + lock.unlock(); + } + } + + public Collection> getAll() { + try { + lock.lock(); + return new ArrayList>(super.entrySet()); + } finally { + lock.unlock(); + } + } +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/util/SoapUtil.java b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/util/SoapUtil.java new file mode 100644 index 0000000..6f7bf0d --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/util/SoapUtil.java @@ -0,0 +1,156 @@ +/** + * Copyright 2016 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.carbon.bpel.util; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +import javax.naming.ConfigurationException; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.apache.commons.httpclient.HttpClient; +import org.apache.log4j.Logger; + +import com.eviware.soapui.impl.wsdl.WsdlInterface; +import com.eviware.soapui.impl.wsdl.WsdlProject; +import com.eviware.soapui.impl.wsdl.support.wsdl.WsdlLoader; +import com.eviware.soapui.model.iface.Operation; +import com.eviware.soapui.model.iface.Request; + +public class SoapUtil { + private static final Logger log = Logger.getLogger(SoapUtil.class); + + private DocumentBuilderFactory docBuilderFactory; + private Map wsdls = new LRULinkedHashMap(256); + + public SoapUtil() { + docBuilderFactory = DocumentBuilderFactory.newInstance(); + docBuilderFactory.setNamespaceAware(true); + } + + public Request[] getRequestTemplate(String wsdlUrl) + throws UnsupportedOperationException, IOException { + Request[] requests = new Request[0]; + List requestList = new ArrayList(); + Operation operationInst = null; + WsdlInterface[] wsdlInterfaces = getWsdlInterfaces(wsdlUrl, null); + for (WsdlInterface wsdlInterface : wsdlInterfaces) { + Operation opr = wsdlInterface.getOperationAt(0); + if (opr != null) { + operationInst = opr; + String requestTemplate = operationInst.getRequestAt(0).getRequestContent(); + requestList.add(operationInst.getRequestAt(0)); + } + } + requests = requestList.toArray(new Request[0]); + return requests; + } + + /** + * + * @param wsdl + * @param operation + * @param httpClientProps + * @return + * @throws IOException + * @throws UnsupportedOperationException + */ + private Operation getOperation(String wsdl, String operation, Properties httpClientProps) + throws IOException, UnsupportedOperationException { + WsdlInterface[] wsdlInterfaces = getWsdlInterfaces(wsdl, httpClientProps); + for (WsdlInterface wsdlInterface : wsdlInterfaces) { + Operation operationInst = wsdlInterface.getOperationByName(operation); + + if (operationInst != null) { + return operationInst; + } + } + wsdls.remove(wsdl); + wsdlInterfaces = getWsdlInterfaces(wsdl, httpClientProps); + for (WsdlInterface wsdlInterface : wsdlInterfaces) { + Operation operationInst = wsdlInterface.getOperationByName(operation); + if (operationInst != null) { + return operationInst; + } + } + + throw new UnsupportedOperationException( + "Operation '" + operation + "' not supported by WSDL '" + wsdl + "'."); + } + + /** + * + * @param wsdl + * @param httpClientProps + * @return + * @throws IOException + */ + private WsdlInterface[] getWsdlInterfaces(String wsdl, Properties httpClientProps) + throws IOException { + try { + WsdlInterface[] wsdlInterfaces = wsdls.get(wsdl); + if (wsdlInterfaces == null) { + WsdlProject wsdlProject = new WsdlProject(); + WsdlLoader wsdlLoader = createWsdlLoader(wsdl, httpClientProps); + + wsdlInterfaces = wsdlProject.importWsdl(wsdl, true, wsdlLoader); + + wsdls.put(wsdl, wsdlInterfaces); + } + return wsdlInterfaces; + } catch (Exception e) { + e.printStackTrace(); + log.error(e.getMessage()); + throw new RuntimeException("Failed to import WSDL '" + wsdl + "'."); + } + } + + /** + * + * @param wsdl + * @param httpClientProps + * @return + * @throws ConfigurationException + */ + private WsdlLoader createWsdlLoader(String wsdl, Properties httpClientProps) + throws ConfigurationException { + HttpClient httpClient = new HttpClient(); + return new ClientWsdlLoader(wsdl, httpClient); + } + + public static void main(String[] args) { + SoapUtil soapUtil = new SoapUtil(); + + try { + String url = "http://10.74.151.36:9763/services/initService?wsdl"; + Request[] requestXMLs = soapUtil.getRequestTemplate(url); + + for (Request requestXML : requestXMLs) { + String requestJson = Xml2JsonUtil.xml2JSON(requestXML.getRequestContent()); + System.out.println("===================================="); + System.out.println(requestJson); + } + + } catch (UnsupportedOperationException e1) { + e1.printStackTrace(); + } catch (IOException e1) { + e1.printStackTrace(); + } + } +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/util/Xml2JsonUtil.java b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/util/Xml2JsonUtil.java new file mode 100644 index 0000000..7f05a84 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/java/org/openo/carbon/bpel/util/Xml2JsonUtil.java @@ -0,0 +1,141 @@ +/** + * Copyright 2016 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openo.carbon.bpel.util; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.InputStream; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import net.sf.json.JSONObject; + +import org.jdom.Document; +import org.jdom.Element; +import org.jdom.input.SAXBuilder; + +public class Xml2JsonUtil { + /** + * transform xml to json + * + * @param xml xml format string + * @return return json string when success; otherwise return null + */ + public static String xml2JSON(String xml) { + JSONObject obj = new JSONObject(); + try { + InputStream is = new ByteArrayInputStream(xml.getBytes("utf-8")); + SAXBuilder sb = new SAXBuilder(); + Document doc = sb.build(is); + Element root = doc.getRootElement(); + obj.put(root.getName(), iterateElement(root)); + return obj.toString(); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * transform xml file to json string + * + * @param file java.io.File is an effective xml file + * @return return json string when success; otherwise return null + */ + public static String xml2JSON(File file) { + JSONObject obj = new JSONObject(); + try { + SAXBuilder sb = new SAXBuilder(); + Document doc = sb.build(file); + Element root = doc.getRootElement(); + obj.put(root.getName(), iterateElement(root)); + return obj.toString(); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * an iteration function + * + * @param parentElement : org.jdom.Element + * @return java.util.Map + */ + @SuppressWarnings({"unchecked", "rawtypes"}) + private static Map iterateElement(Element parentElement) { + List node = parentElement.getChildren(); + Element element = null; + Map map = new HashMap(); + List list = null; + for (int i = 0; i < node.size(); i++) { + element = (Element) node.get(i); + if (element.getTextTrim().equals("")) { + if (element.getChildren().size() == 0) + continue; + if (map.containsKey(element.getName())) { + Object obj = map.get(element.getName()); + if (obj instanceof Map) { + list = new LinkedList(); + list.add(obj); + list.add(iterateElement(element)); + map.remove(element.getName()); + map.put(element.getName(), list); + } else if (obj instanceof List) { + list = (List) obj; + list.add(iterateElement(element)); + } + } else { + map.put(element.getName(), iterateElement(element)); + } + } else { + map.put(element.getName(), element.getTextTrim()); + } + } + return map; + } + + public static void main(String[] args) { + System.out.println(Xml2JsonUtil.xml2JSON("" + "" + "" + + "MapGuideddddddd" + "true" + "" + + "ddd" + "" + "" + "" + "ccc" + + "ggg" + "" + "aaa" + + "" + "" + "" + "" + "" + "33333333" + + "" + "" + "444" + "" + "")); + + String xml = + " fdsafasdfasdf "; + + System.out.println(Xml2JsonUtil.xml2JSON(xml)); + + xml = + " ? "; + + System.out.println(Xml2JsonUtil.xml2JSON(xml)); + + xml = + ""; + + System.out.println(Xml2JsonUtil.xml2JSON(xml)); + + xml = + " 2 112 {\"e\":{\"f\":\"4\"}} ? 2 ? 223 334 2 [{\"b\":1},{\"c\":{\"d\":\"2\"}}}] [{\"a\":3},{\"e\":{\"f\":\"4\"}}}] "; + + System.out.println(Xml2JsonUtil.xml2JSON(xml)); + } +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/META-INF/MANIFEST.MF b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/META-INF/MANIFEST.MF new file mode 100644 index 0000000..eaf90a9 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Created-By: 1.7.0_72 (Oracle Corporation) + diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/WEB-INF/web.xml b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/WEB-INF/web.xml new file mode 100644 index 0000000..2a5346c --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/WEB-INF/web.xml @@ -0,0 +1,41 @@ + + + + + + ZENAP API-DOC. + + ZENAP API-DOC + + + + + index.html + index.xhtml + index.htm + index.jsp + + + + diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/css/reset.css b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/css/reset.css new file mode 100644 index 0000000..2e11612 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/css/reset.css @@ -0,0 +1,140 @@ +/** + * Copyright 2016 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* http://meyerweb.com/eric/tools/css/reset/ v2.0 | 20110126 */ +html, +body, +div, +span, +applet, +object, +iframe, +h1, +h2, +h3, +h4, +h5, +h6, +p, +blockquote, +pre, +a, +abbr, +acronym, +address, +big, +cite, +code, +del, +dfn, +em, +img, +ins, +kbd, +q, +s, +samp, +small, +strike, +strong, +sub, +sup, +tt, +var, +b, +u, +i, +center, +dl, +dt, +dd, +ol, +ul, +li, +fieldset, +form, +label, +legend, +table, +caption, +tbody, +tfoot, +thead, +tr, +th, +td, +article, +aside, +canvas, +details, +embed, +figure, +figcaption, +footer, +header, +hgroup, +menu, +nav, +output, +ruby, +section, +summary, +time, +mark, +audio, +video { + margin: 0; + padding: 0; + border: 0; + font-size: 100%; + font: inherit; + vertical-align: baseline; +} +/* HTML5 display-role reset for older browsers */ +article, +aside, +details, +figcaption, +figure, +footer, +header, +hgroup, +menu, +nav, +section { + display: block; +} +body { + line-height: 1; +} +ol, +ul { + list-style: none; +} +blockquote, +q { + quotes: none; +} +blockquote:before, +blockquote:after, +q:before, +q:after { + content: ''; + content: none; +} +table { + border-collapse: collapse; + border-spacing: 0; +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/css/screen.css b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/css/screen.css new file mode 100644 index 0000000..2b982c2 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/css/screen.css @@ -0,0 +1,1271 @@ +/** + * Copyright 2016 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* Original style from softwaremaniacs.org (c) Ivan Sagalaev */ +.swagger-section pre code { + display: block; + padding: 0.5em; + background: #F0F0F0; +} +.swagger-section pre code, +.swagger-section pre .subst, +.swagger-section pre .tag .title, +.swagger-section pre .lisp .title, +.swagger-section pre .clojure .built_in, +.swagger-section pre .nginx .title { + color: black; +} +.swagger-section pre .string, +.swagger-section pre .title, +.swagger-section pre .constant, +.swagger-section pre .parent, +.swagger-section pre .tag .value, +.swagger-section pre .rules .value, +.swagger-section pre .rules .value .number, +.swagger-section pre .preprocessor, +.swagger-section pre .ruby .symbol, +.swagger-section pre .ruby .symbol .string, +.swagger-section pre .aggregate, +.swagger-section pre .template_tag, +.swagger-section pre .django .variable, +.swagger-section pre .smalltalk .class, +.swagger-section pre .addition, +.swagger-section pre .flow, +.swagger-section pre .stream, +.swagger-section pre .bash .variable, +.swagger-section pre .apache .tag, +.swagger-section pre .apache .cbracket, +.swagger-section pre .tex .command, +.swagger-section pre .tex .special, +.swagger-section pre .erlang_repl .function_or_atom, +.swagger-section pre .markdown .header { + color: #800; +} +.swagger-section pre .comment, +.swagger-section pre .annotation, +.swagger-section pre .template_comment, +.swagger-section pre .diff .header, +.swagger-section pre .chunk, +.swagger-section pre .markdown .blockquote { + color: #888; +} +.swagger-section pre .number, +.swagger-section pre .date, +.swagger-section pre .regexp, +.swagger-section pre .literal, +.swagger-section pre .smalltalk .symbol, +.swagger-section pre .smalltalk .char, +.swagger-section pre .go .constant, +.swagger-section pre .change, +.swagger-section pre .markdown .bullet, +.swagger-section pre .markdown .link_url { + color: #080; +} +.swagger-section pre .label, +.swagger-section pre .javadoc, +.swagger-section pre .ruby .string, +.swagger-section pre .decorator, +.swagger-section pre .filter .argument, +.swagger-section pre .localvars, +.swagger-section pre .array, +.swagger-section pre .attr_selector, +.swagger-section pre .important, +.swagger-section pre .pseudo, +.swagger-section pre .pi, +.swagger-section pre .doctype, +.swagger-section pre .deletion, +.swagger-section pre .envvar, +.swagger-section pre .shebang, +.swagger-section pre .apache .sqbracket, +.swagger-section pre .nginx .built_in, +.swagger-section pre .tex .formula, +.swagger-section pre .erlang_repl .reserved, +.swagger-section pre .prompt, +.swagger-section pre .markdown .link_label, +.swagger-section pre .vhdl .attribute, +.swagger-section pre .clojure .attribute, +.swagger-section pre .coffeescript .property { + color: #8888ff; +} +.swagger-section pre .keyword, +.swagger-section pre .id, +.swagger-section pre .phpdoc, +.swagger-section pre .title, +.swagger-section pre .built_in, +.swagger-section pre .aggregate, +.swagger-section pre .css .tag, +.swagger-section pre .javadoctag, +.swagger-section pre .phpdoc, +.swagger-section pre .yardoctag, +.swagger-section pre .smalltalk .class, +.swagger-section pre .winutils, +.swagger-section pre .bash .variable, +.swagger-section pre .apache .tag, +.swagger-section pre .go .typename, +.swagger-section pre .tex .command, +.swagger-section pre .markdown .strong, +.swagger-section pre .request, +.swagger-section pre .status { + font-weight: bold; +} +.swagger-section pre .markdown .emphasis { + font-style: italic; +} +.swagger-section pre .nginx .built_in { + font-weight: normal; +} +.swagger-section pre .coffeescript .javascript, +.swagger-section pre .javascript .xml, +.swagger-section pre .tex .formula, +.swagger-section pre .xml .javascript, +.swagger-section pre .xml .vbscript, +.swagger-section pre .xml .css, +.swagger-section pre .xml .cdata { + opacity: 0.5; +} +.swagger-section .swagger-ui-wrap { + line-height: 1; + font-family: "Droid Sans", sans-serif; + max-width: 960px; + margin-left: auto; + margin-right: auto; +} +.swagger-section .swagger-ui-wrap b, +.swagger-section .swagger-ui-wrap strong { + font-family: "Droid Sans", sans-serif; + font-weight: bold; +} +.swagger-section .swagger-ui-wrap q, +.swagger-section .swagger-ui-wrap blockquote { + quotes: none; +} +.swagger-section .swagger-ui-wrap p { + line-height: 1.4em; + padding: 0 0 10px; + color: #333333; +} +.swagger-section .swagger-ui-wrap q:before, +.swagger-section .swagger-ui-wrap q:after, +.swagger-section .swagger-ui-wrap blockquote:before, +.swagger-section .swagger-ui-wrap blockquote:after { + content: none; +} +.swagger-section .swagger-ui-wrap .heading_with_menu h1, +.swagger-section .swagger-ui-wrap .heading_with_menu h2, +.swagger-section .swagger-ui-wrap .heading_with_menu h3, +.swagger-section .swagger-ui-wrap .heading_with_menu h4, +.swagger-section .swagger-ui-wrap .heading_with_menu h5, +.swagger-section .swagger-ui-wrap .heading_with_menu h6 { + display: block; + clear: none; + float: left; + -moz-box-sizing: border-box; + -webkit-box-sizing: border-box; + -ms-box-sizing: border-box; + box-sizing: border-box; + width: 60%; +} +.swagger-section .swagger-ui-wrap table { + border-collapse: collapse; + border-spacing: 0; +} +.swagger-section .swagger-ui-wrap table thead tr th { + padding: 5px; + font-size: 0.9em; + color: #666666; + border-bottom: 1px solid #999999; +} +.swagger-section .swagger-ui-wrap table tbody tr:last-child td { + border-bottom: none; +} +.swagger-section .swagger-ui-wrap table tbody tr.offset { + background-color: #f0f0f0; +} +.swagger-section .swagger-ui-wrap table tbody tr td { + padding: 6px; + font-size: 0.9em; + border-bottom: 1px solid #cccccc; + vertical-align: top; + line-height: 1.3em; +} +.swagger-section .swagger-ui-wrap ol { + margin: 0px 0 10px; + padding: 0 0 0 18px; + list-style-type: decimal; +} +.swagger-section .swagger-ui-wrap ol li { + padding: 5px 0px; + font-size: 0.9em; + color: #333333; +} +.swagger-section .swagger-ui-wrap ol, +.swagger-section .swagger-ui-wrap ul { + list-style: none; +} +.swagger-section .swagger-ui-wrap h1 a, +.swagger-section .swagger-ui-wrap h2 a, +.swagger-section .swagger-ui-wrap h3 a, +.swagger-section .swagger-ui-wrap h4 a, +.swagger-section .swagger-ui-wrap h5 a, +.swagger-section .swagger-ui-wrap h6 a { + text-decoration: none; +} +.swagger-section .swagger-ui-wrap h1 a:hover, +.swagger-section .swagger-ui-wrap h2 a:hover, +.swagger-section .swagger-ui-wrap h3 a:hover, +.swagger-section .swagger-ui-wrap h4 a:hover, +.swagger-section .swagger-ui-wrap h5 a:hover, +.swagger-section .swagger-ui-wrap h6 a:hover { + text-decoration: underline; +} +.swagger-section .swagger-ui-wrap h1 span.divider, +.swagger-section .swagger-ui-wrap h2 span.divider, +.swagger-section .swagger-ui-wrap h3 span.divider, +.swagger-section .swagger-ui-wrap h4 span.divider, +.swagger-section .swagger-ui-wrap h5 span.divider, +.swagger-section .swagger-ui-wrap h6 span.divider { + color: #aaaaaa; +} +.swagger-section .swagger-ui-wrap a { + color: #547f00; +} +.swagger-section .swagger-ui-wrap a img { + border: none; +} +.swagger-section .swagger-ui-wrap article, +.swagger-section .swagger-ui-wrap aside, +.swagger-section .swagger-ui-wrap details, +.swagger-section .swagger-ui-wrap figcaption, +.swagger-section .swagger-ui-wrap figure, +.swagger-section .swagger-ui-wrap footer, +.swagger-section .swagger-ui-wrap header, +.swagger-section .swagger-ui-wrap hgroup, +.swagger-section .swagger-ui-wrap menu, +.swagger-section .swagger-ui-wrap nav, +.swagger-section .swagger-ui-wrap section, +.swagger-section .swagger-ui-wrap summary { + display: block; +} +.swagger-section .swagger-ui-wrap pre { + font-family: "Anonymous Pro", "Menlo", "Consolas", "Bitstream Vera Sans Mono", "Courier New", monospace; + background-color: #fcf6db; + border: 1px solid #e5e0c6; + padding: 10px; +} +.swagger-section .swagger-ui-wrap pre code { + line-height: 1.6em; + background: none; +} +.swagger-section .swagger-ui-wrap .content > .content-type > div > label { + clear: both; + display: block; + color: #0F6AB4; + font-size: 1.1em; + margin: 0; + padding: 15px 0 5px; +} +.swagger-section .swagger-ui-wrap .content pre { + font-size: 12px; + margin-top: 5px; + padding: 5px; +} +.swagger-section .swagger-ui-wrap .icon-btn { + cursor: pointer; +} +.swagger-section .swagger-ui-wrap .info_title { + padding-bottom: 10px; + font-weight: bold; + font-size: 25px; +} +.swagger-section .swagger-ui-wrap p.big, +.swagger-section .swagger-ui-wrap div.big p { + font-size: 1em; + margin-bottom: 10px; +} +.swagger-section .swagger-ui-wrap form.fullwidth ol li.string input, +.swagger-section .swagger-ui-wrap form.fullwidth ol li.url input, +.swagger-section .swagger-ui-wrap form.fullwidth ol li.text textarea, +.swagger-section .swagger-ui-wrap form.fullwidth ol li.numeric input { + width: 500px !important; +} +.swagger-section .swagger-ui-wrap .info_license { + padding-bottom: 5px; +} +.swagger-section .swagger-ui-wrap .info_tos { + padding-bottom: 5px; +} +.swagger-section .swagger-ui-wrap .message-fail { + color: #cc0000; +} +.swagger-section .swagger-ui-wrap .info_url { + padding-bottom: 5px; +} +.swagger-section .swagger-ui-wrap .info_email { + padding-bottom: 5px; +} +.swagger-section .swagger-ui-wrap .info_name { + padding-bottom: 5px; +} +.swagger-section .swagger-ui-wrap .info_description { + padding-bottom: 10px; + font-size: 15px; +} +.swagger-section .swagger-ui-wrap .markdown ol li, +.swagger-section .swagger-ui-wrap .markdown ul li { + padding: 3px 0px; + line-height: 1.4em; + color: #333333; +} +.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.string input, +.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.url input, +.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.numeric input { + display: block; + padding: 4px; + width: auto; + clear: both; +} +.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.string input.title, +.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.url input.title, +.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.numeric input.title { + font-size: 1.3em; +} +.swagger-section .swagger-ui-wrap table.fullwidth { + width: 100%; +} +.swagger-section .swagger-ui-wrap .model-signature { + font-family: "Droid Sans", sans-serif; + font-size: 1em; + line-height: 1.5em; +} +.swagger-section .swagger-ui-wrap .model-signature .signature-nav a { + text-decoration: none; + color: #AAA; +} +.swagger-section .swagger-ui-wrap .model-signature .signature-nav a:hover { + text-decoration: underline; + color: black; +} +.swagger-section .swagger-ui-wrap .model-signature .signature-nav .selected { + color: black; + text-decoration: none; +} +.swagger-section .swagger-ui-wrap .model-signature .propType { + color: #5555aa; +} +.swagger-section .swagger-ui-wrap .model-signature pre:hover { + background-color: #ffffdd; +} +.swagger-section .swagger-ui-wrap .model-signature pre { + font-size: .85em; + line-height: 1.2em; + overflow: auto; + max-height: 200px; + cursor: pointer; +} +.swagger-section .swagger-ui-wrap .model-signature ul.signature-nav { + display: block; + margin: 0; + padding: 0; +} +.swagger-section .swagger-ui-wrap .model-signature ul.signature-nav li:last-child { + padding-right: 0; + border-right: none; +} +.swagger-section .swagger-ui-wrap .model-signature ul.signature-nav li { + float: left; + margin: 0 5px 5px 0; + padding: 2px 5px 2px 0; + border-right: 1px solid #ddd; +} +.swagger-section .swagger-ui-wrap .model-signature .propOpt { + color: #555; +} +.swagger-section .swagger-ui-wrap .model-signature .snippet small { + font-size: 0.75em; +} +.swagger-section .swagger-ui-wrap .model-signature .propOptKey { + font-style: italic; +} +.swagger-section .swagger-ui-wrap .model-signature .description .strong { + font-weight: bold; + color: #000; + font-size: .9em; +} +.swagger-section .swagger-ui-wrap .model-signature .description div { + font-size: 0.9em; + line-height: 1.5em; + margin-left: 1em; +} +.swagger-section .swagger-ui-wrap .model-signature .description .stronger { + font-weight: bold; + color: #000; +} +.swagger-section .swagger-ui-wrap .model-signature .description .propWrap .optionsWrapper { + border-spacing: 0; + position: absolute; + background-color: #ffffff; + border: 1px solid #bbbbbb; + display: none; + font-size: 11px; + max-width: 400px; + line-height: 30px; + color: black; + padding: 5px; + margin-left: 10px; +} +.swagger-section .swagger-ui-wrap .model-signature .description .propWrap .optionsWrapper th { + text-align: center; + background-color: #eeeeee; + border: 1px solid #bbbbbb; + font-size: 11px; + color: #666666; + font-weight: bold; + padding: 5px; + line-height: 15px; +} +.swagger-section .swagger-ui-wrap .model-signature .description .propWrap .optionsWrapper .optionName { + font-weight: bold; +} +.swagger-section .swagger-ui-wrap .model-signature .propName { + font-weight: bold; +} +.swagger-section .swagger-ui-wrap .model-signature .signature-container { + clear: both; +} +.swagger-section .swagger-ui-wrap .body-textarea { + width: 300px; + height: 100px; + border: 1px solid #aaa; +} +.swagger-section .swagger-ui-wrap .markdown p code, +.swagger-section .swagger-ui-wrap .markdown li code { + font-family: "Anonymous Pro", "Menlo", "Consolas", "Bitstream Vera Sans Mono", "Courier New", monospace; + background-color: #f0f0f0; + color: black; + padding: 1px 3px; +} +.swagger-section .swagger-ui-wrap .required { + font-weight: bold; +} +.swagger-section .swagger-ui-wrap input.parameter { + width: 300px; + border: 1px solid #aaa; +} +.swagger-section .swagger-ui-wrap h1 { + color: black; + font-size: 1.5em; + line-height: 1.3em; + padding: 10px 0 10px 0; + font-family: "Droid Sans", sans-serif; + font-weight: bold; +} +.swagger-section .swagger-ui-wrap .heading_with_menu { + float: none; + clear: both; + overflow: hidden; + display: block; +} +.swagger-section .swagger-ui-wrap .heading_with_menu ul { + display: block; + clear: none; + float: right; + -moz-box-sizing: border-box; + -webkit-box-sizing: border-box; + -ms-box-sizing: border-box; + box-sizing: border-box; + margin-top: 10px; +} +.swagger-section .swagger-ui-wrap h2 { + color: black; + font-size: 1.3em; + padding: 10px 0 10px 0; +} +.swagger-section .swagger-ui-wrap h2 a { + color: black; +} +.swagger-section .swagger-ui-wrap h2 span.sub { + font-size: 0.7em; + color: #999999; + font-style: italic; +} +.swagger-section .swagger-ui-wrap h2 span.sub a { + color: #777777; +} +.swagger-section .swagger-ui-wrap span.weak { + color: #666666; +} +.swagger-section .swagger-ui-wrap .message-success { + color: #89BF04; +} +.swagger-section .swagger-ui-wrap caption, +.swagger-section .swagger-ui-wrap th, +.swagger-section .swagger-ui-wrap td { + text-align: left; + font-weight: normal; + vertical-align: middle; +} +.swagger-section .swagger-ui-wrap .code { + font-family: "Anonymous Pro", "Menlo", "Consolas", "Bitstream Vera Sans Mono", "Courier New", monospace; +} +.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.text textarea { + font-family: "Droid Sans", sans-serif; + height: 250px; + padding: 4px; + display: block; + clear: both; +} +.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.select select { + display: block; + clear: both; +} +.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.boolean { + float: none; + clear: both; + overflow: hidden; + display: block; +} +.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.boolean label { + display: block; + float: left; + clear: none; + margin: 0; + padding: 0; +} +.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.boolean input { + display: block; + float: left; + clear: none; + margin: 0 5px 0 0; +} +.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li.required label { + color: black; +} +.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li label { + display: block; + clear: both; + width: auto; + padding: 0 0 3px; + color: #666666; +} +.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li label abbr { + padding-left: 3px; + color: #888888; +} +.swagger-section .swagger-ui-wrap form.formtastic fieldset.inputs ol li p.inline-hints { + margin-left: 0; + font-style: italic; + font-size: 0.9em; + margin: 0; +} +.swagger-section .swagger-ui-wrap form.formtastic fieldset.buttons { + margin: 0; + padding: 0; +} +.swagger-section .swagger-ui-wrap span.blank, +.swagger-section .swagger-ui-wrap span.empty { + color: #888888; + font-style: italic; +} +.swagger-section .swagger-ui-wrap .markdown h3 { + color: #547f00; +} +.swagger-section .swagger-ui-wrap .markdown h4 { + color: #666666; +} +.swagger-section .swagger-ui-wrap .markdown pre { + font-family: "Anonymous Pro", "Menlo", "Consolas", "Bitstream Vera Sans Mono", "Courier New", monospace; + background-color: #fcf6db; + border: 1px solid #e5e0c6; + padding: 10px; + margin: 0 0 10px 0; +} +.swagger-section .swagger-ui-wrap .markdown pre code { + line-height: 1.6em; +} +.swagger-section .swagger-ui-wrap div.gist { + margin: 20px 0 25px 0 !important; +} +.swagger-section .swagger-ui-wrap ul#resources { + font-family: "Droid Sans", sans-serif; + font-size: 0.9em; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource { + border-bottom: 1px solid #dddddd; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource:hover div.heading h2 a, +.swagger-section .swagger-ui-wrap ul#resources li.resource.active div.heading h2 a { + color: black; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource:hover div.heading ul.options li a, +.swagger-section .swagger-ui-wrap ul#resources li.resource.active div.heading ul.options li a { + color: #555555; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource:last-child { + border-bottom: none; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading { + border: 1px solid transparent; + float: none; + clear: both; + overflow: hidden; + display: block; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options { + overflow: hidden; + padding: 0; + display: block; + clear: none; + float: right; + margin: 14px 10px 0 0; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options li { + float: left; + clear: none; + margin: 0; + padding: 2px 10px; + border-right: 1px solid #dddddd; + color: #666666; + font-size: 0.9em; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options li a { + color: #aaaaaa; + text-decoration: none; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options li a:hover { + text-decoration: underline; + color: black; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options li a:hover, +.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options li a:active, +.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options li a.active { + text-decoration: underline; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options li:first-child, +.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options li.first { + padding-left: 0; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options li:last-child, +.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options li.last { + padding-right: 0; + border-right: none; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options:first-child, +.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading ul.options.first { + padding-left: 0; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading h2 { + color: #999999; + padding-left: 0; + display: block; + clear: none; + float: left; + font-family: "Droid Sans", sans-serif; + font-weight: bold; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading h2 a { + color: #999999; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource div.heading h2 a:hover { + color: black; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation { + float: none; + clear: both; + overflow: hidden; + display: block; + margin: 0 0 10px; + padding: 0; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading { + float: none; + clear: both; + overflow: hidden; + display: block; + margin: 0; + padding: 0; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading h3 { + display: block; + clear: none; + float: left; + width: auto; + margin: 0; + padding: 0; + line-height: 1.1em; + color: black; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading h3 span.path { + padding-left: 10px; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading h3 span.path a { + color: black; + text-decoration: none; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading h3 span.path a:hover { + text-decoration: underline; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading h3 span.http_method a { + text-transform: uppercase; + text-decoration: none; + color: white; + display: inline-block; + width: 50px; + font-size: 0.7em; + text-align: center; + padding: 7px 0 4px; + -moz-border-radius: 2px; + -webkit-border-radius: 2px; + -o-border-radius: 2px; + -ms-border-radius: 2px; + -khtml-border-radius: 2px; + border-radius: 2px; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading h3 span { + margin: 0; + padding: 0; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading ul.options { + overflow: hidden; + padding: 0; + display: block; + clear: none; + float: right; + margin: 6px 10px 0 0; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading ul.options li { + float: left; + clear: none; + margin: 0; + padding: 2px 10px; + font-size: 0.9em; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading ul.options li a { + text-decoration: none; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.heading ul.options li.access { + color: black; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.content { + border-top: none; + padding: 10px; + -moz-border-radius-bottomleft: 6px; + -webkit-border-bottom-left-radius: 6px; + -o-border-bottom-left-radius: 6px; + -ms-border-bottom-left-radius: 6px; + -khtml-border-bottom-left-radius: 6px; + border-bottom-left-radius: 6px; + -moz-border-radius-bottomright: 6px; + -webkit-border-bottom-right-radius: 6px; + -o-border-bottom-right-radius: 6px; + -ms-border-bottom-right-radius: 6px; + -khtml-border-bottom-right-radius: 6px; + border-bottom-right-radius: 6px; + margin: 0 0 20px; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.content h4 { + font-size: 1.1em; + margin: 0; + padding: 15px 0 5px; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.content div.sandbox_header { + float: none; + clear: both; + overflow: hidden; + display: block; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.content div.sandbox_header a { + padding: 4px 0 0 10px; + display: inline-block; + font-size: 0.9em; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.content div.sandbox_header input.submit { + display: block; + clear: none; + float: left; + padding: 6px 8px; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.content div.sandbox_header span.response_throbber { + background-image: url('../images/throbber.gif'); + width: 128px; + height: 16px; + display: block; + clear: none; + float: right; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.content form input[type='text'].error { + outline: 2px solid black; + outline-color: #cc0000; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.content div.response div.block pre { + font-family: "Anonymous Pro", "Menlo", "Consolas", "Bitstream Vera Sans Mono", "Courier New", monospace; + padding: 10px; + font-size: 0.9em; + max-height: 400px; + overflow-y: auto; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.put div.heading { + background-color: #f9f2e9; + border: 1px solid #f0e0ca; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.put div.heading h3 span.http_method a { + background-color: #c5862b; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.put div.heading ul.options li { + border-right: 1px solid #dddddd; + border-right-color: #f0e0ca; + color: #c5862b; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.put div.heading ul.options li a { + color: #c5862b; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.put div.content { + background-color: #faf5ee; + border: 1px solid #f0e0ca; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.put div.content h4 { + color: #c5862b; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.put div.content div.sandbox_header a { + color: #dcb67f; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.head div.heading { + background-color: #fcffcd; + border: 1px solid black; + border-color: #ffd20f; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.head div.heading h3 span.http_method a { + text-transform: uppercase; + background-color: #ffd20f; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.head div.heading ul.options li { + border-right: 1px solid #dddddd; + border-right-color: #ffd20f; + color: #ffd20f; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.head div.heading ul.options li a { + color: #ffd20f; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.head div.content { + background-color: #fcffcd; + border: 1px solid black; + border-color: #ffd20f; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.head div.content h4 { + color: #ffd20f; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.head div.content div.sandbox_header a { + color: #6fc992; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.delete div.heading { + background-color: #f5e8e8; + border: 1px solid #e8c6c7; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.delete div.heading h3 span.http_method a { + text-transform: uppercase; + background-color: #a41e22; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.delete div.heading ul.options li { + border-right: 1px solid #dddddd; + border-right-color: #e8c6c7; + color: #a41e22; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.delete div.heading ul.options li a { + color: #a41e22; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.delete div.content { + background-color: #f7eded; + border: 1px solid #e8c6c7; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.delete div.content h4 { + color: #a41e22; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.delete div.content div.sandbox_header a { + color: #c8787a; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.post div.heading { + background-color: #e7f6ec; + border: 1px solid #c3e8d1; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.post div.heading h3 span.http_method a { + background-color: #10a54a; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.post div.heading ul.options li { + border-right: 1px solid #dddddd; + border-right-color: #c3e8d1; + color: #10a54a; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.post div.heading ul.options li a { + color: #10a54a; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.post div.content { + background-color: #ebf7f0; + border: 1px solid #c3e8d1; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.post div.content h4 { + color: #10a54a; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.post div.content div.sandbox_header a { + color: #6fc992; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.patch div.heading { + background-color: #FCE9E3; + border: 1px solid #F5D5C3; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.patch div.heading h3 span.http_method a { + background-color: #D38042; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.patch div.heading ul.options li { + border-right: 1px solid #dddddd; + border-right-color: #f0cecb; + color: #D38042; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.patch div.heading ul.options li a { + color: #D38042; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.patch div.content { + background-color: #faf0ef; + border: 1px solid #f0cecb; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.patch div.content h4 { + color: #D38042; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.patch div.content div.sandbox_header a { + color: #dcb67f; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.get div.heading { + background-color: #e7f0f7; + border: 1px solid #c3d9ec; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.get div.heading h3 span.http_method a { + background-color: #0f6ab4; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.get div.heading ul.options li { + border-right: 1px solid #dddddd; + border-right-color: #c3d9ec; + color: #0f6ab4; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.get div.heading ul.options li a { + color: #0f6ab4; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.get div.content { + background-color: #ebf3f9; + border: 1px solid #c3d9ec; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.get div.content h4 { + color: #0f6ab4; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.get div.content div.sandbox_header a { + color: #6fa5d2; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.options div.heading { + background-color: #e7f0f7; + border: 1px solid #c3d9ec; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.options div.heading h3 span.http_method a { + background-color: #0f6ab4; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.options div.heading ul.options li { + border-right: 1px solid #dddddd; + border-right-color: #c3d9ec; + color: #0f6ab4; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.options div.heading ul.options li a { + color: #0f6ab4; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.options div.content { + background-color: #ebf3f9; + border: 1px solid #c3d9ec; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.options div.content h4 { + color: #0f6ab4; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.options div.content div.sandbox_header a { + color: #6fa5d2; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.get div.content, +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.post div.content, +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.head div.content, +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.put div.content, +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.patch div.content, +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.delete div.content { + border-top: none; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.get div.heading ul.options li:last-child, +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.post div.heading ul.options li:last-child, +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.head div.heading ul.options li:last-child, +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.put div.heading ul.options li:last-child, +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.patch div.heading ul.options li:last-child, +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.delete div.heading ul.options li:last-child, +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.get div.heading ul.options li.last, +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.post div.heading ul.options li.last, +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.head div.heading ul.options li.last, +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.put div.heading ul.options li.last, +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.patch div.heading ul.options li.last, +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation.delete div.heading ul.options li.last { + padding-right: 0; + border-right: none; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations ul.options li a:hover, +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations ul.options li a:active, +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations ul.options li a.active { + text-decoration: underline; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations ul.options li:first-child, +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations ul.options li.first { + padding-left: 0; +} +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations:first-child, +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations.first { + padding-left: 0; +} +.swagger-section .swagger-ui-wrap p#colophon { + margin: 0 15px 40px 15px; + padding: 10px 0; + font-size: 0.8em; + border-top: 1px solid #dddddd; + font-family: "Droid Sans", sans-serif; + color: #999999; + font-style: italic; +} +.swagger-section .swagger-ui-wrap p#colophon a { + text-decoration: none; + color: #547f00; +} +.swagger-section .swagger-ui-wrap h3 { + color: black; + font-size: 1.1em; + padding: 10px 0 10px 0; +} +.swagger-section .swagger-ui-wrap .markdown ol, +.swagger-section .swagger-ui-wrap .markdown ul { + font-family: "Droid Sans", sans-serif; + margin: 5px 0 10px; + padding: 0 0 0 18px; + list-style-type: disc; +} +.swagger-section .swagger-ui-wrap form.form_box { + background-color: #ebf3f9; + border: 1px solid #c3d9ec; + padding: 10px; +} +.swagger-section .swagger-ui-wrap form.form_box label { + color: #0f6ab4 !important; +} +.swagger-section .swagger-ui-wrap form.form_box input[type=submit] { + display: block; + padding: 10px; +} +.swagger-section .swagger-ui-wrap form.form_box p.weak { + font-size: 0.8em; +} +.swagger-section .swagger-ui-wrap form.form_box p { + font-size: 0.9em; + padding: 0 0 15px; + color: #7e7b6d; +} +.swagger-section .swagger-ui-wrap form.form_box p a { + color: #646257; +} +.swagger-section .swagger-ui-wrap form.form_box p strong { + color: black; +} +.swagger-section .title { + font-style: bold; +} +.swagger-section .secondary_form { + display: none; +} +.swagger-section .main_image { + display: block; + margin-left: auto; + margin-right: auto; +} +.swagger-section .oauth_body { + margin-left: 100px; + margin-right: 100px; +} +.swagger-section .oauth_submit { + text-align: center; +} +.swagger-section .api-popup-dialog { + z-index: 10000; + position: absolute; + width: 500px; + background: #FFF; + padding: 20px; + border: 1px solid #ccc; + border-radius: 5px; + display: none; + font-size: 13px; + color: #777; +} +.swagger-section .api-popup-dialog .api-popup-title { + font-size: 24px; + padding: 10px 0; +} +.swagger-section .api-popup-dialog .api-popup-title { + font-size: 24px; + padding: 10px 0; +} +.swagger-section .api-popup-dialog p.error-msg { + padding-left: 5px; + padding-bottom: 5px; +} +.swagger-section .api-popup-dialog button.api-popup-authbtn { + height: 30px; +} +.swagger-section .api-popup-dialog button.api-popup-cancel { + height: 30px; +} +.swagger-section .api-popup-scopes { + padding: 10px 20px; +} +.swagger-section .api-popup-scopes li { + padding: 5px 0; + line-height: 20px; +} +.swagger-section .api-popup-scopes .api-scope-desc { + padding-left: 20px; + font-style: italic; +} +.swagger-section .api-popup-scopes li input { + position: relative; + top: 2px; +} +.swagger-section .api-popup-actions { + padding-top: 10px; +} +.swagger-section .access { + float: right; +} +.swagger-section .auth { + float: right; +} +.swagger-section #api_information_panel { + position: absolute; + background: #FFF; + border: 1px solid #ccc; + border-radius: 5px; + display: none; + font-size: 13px; + max-width: 300px; + line-height: 30px; + color: black; + padding: 5px; +} +.swagger-section #api_information_panel p .api-msg-enabled { + color: green; +} +.swagger-section #api_information_panel p .api-msg-disabled { + color: red; +} +.swagger-section .api-ic { + height: 18px; + vertical-align: middle; + display: inline-block; + background: url(../images/explorer_icons.png) no-repeat; +} +.swagger-section .ic-info { + background-position: 0 0; + width: 18px; + margin-top: -7px; + margin-left: 4px; +} +.swagger-section .ic-warning { + background-position: -60px 0; + width: 18px; + margin-top: -7px; + margin-left: 4px; +} +.swagger-section .ic-error { + background-position: -30px 0; + width: 18px; + margin-top: -7px; + margin-left: 4px; +} +.swagger-section .ic-off { + background-position: -90px 0; + width: 58px; + margin-top: -4px; + cursor: pointer; +} +.swagger-section .ic-on { + background-position: -160px 0; + width: 58px; + margin-top: -4px; + cursor: pointer; +} +.swagger-section #header { + background-color: #89bf04; + padding: 14px; +} +.swagger-section #header a#logo { + font-size: 1.5em; + font-weight: bold; + text-decoration: none; + background: transparent url(../images/logo_small.png) no-repeat left center; + padding: 20px 0 20px 40px; + color: white; +} +.swagger-section #header form#api_selector { + display: block; + clear: none; + float: right; +} +.swagger-section #header form#api_selector .input { + display: block; + clear: none; + float: left; + margin: 0 10px 0 0; +} +.swagger-section #header form#api_selector .input input#input_apiKey { + width: 200px; +} +.swagger-section #header form#api_selector .input input#input_baseUrl { + width: 400px; +} +.swagger-section #header form#api_selector .input a#explore { + display: block; + text-decoration: none; + font-weight: bold; + padding: 6px 8px; + font-size: 0.9em; + color: white; + background-color: #547f00; + -moz-border-radius: 4px; + -webkit-border-radius: 4px; + -o-border-radius: 4px; + -ms-border-radius: 4px; + -khtml-border-radius: 4px; + border-radius: 4px; +} +.swagger-section #header form#api_selector .input a#explore:hover { + background-color: #547f00; +} +.swagger-section #header form#api_selector .input input { + font-size: 0.9em; + padding: 3px; + margin: 0; +} +.swagger-section #content_message { + margin: 10px 15px; + font-style: italic; + color: #999999; +} +.swagger-section #message-bar { + min-height: 30px; + text-align: center; + padding-top: 10px; +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/css/typography.css b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/css/typography.css new file mode 100644 index 0000000..991427a --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/css/typography.css @@ -0,0 +1,41 @@ +/** + * Copyright 2016 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* droid-sans-regular - latin */ +@font-face { + font-family: 'Droid Sans'; + font-style: normal; + font-weight: 400; + src: url('../fonts/droid-sans-v6-latin-regular.eot'); /* IE9 Compat Modes */ + src: local('Droid Sans'), local('DroidSans'), + url('../fonts/droid-sans-v6-latin-regular.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */ + url('../fonts/droid-sans-v6-latin-regular.woff2') format('woff2'), /* Super Modern Browsers */ + url('../fonts/droid-sans-v6-latin-regular.woff') format('woff'), /* Modern Browsers */ + url('../fonts/droid-sans-v6-latin-regular.ttf') format('truetype'), /* Safari, Android, iOS */ + url('../fonts/droid-sans-v6-latin-regular.svg#DroidSans') format('svg'); /* Legacy iOS */ +} +/* droid-sans-700 - latin */ +@font-face { + font-family: 'Droid Sans'; + font-style: normal; + font-weight: 700; + src: url('../fonts/droid-sans-v6-latin-700.eot'); /* IE9 Compat Modes */ + src: local('Droid Sans Bold'), local('DroidSans-Bold'), + url('../fonts/droid-sans-v6-latin-700.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */ + url('../fonts/droid-sans-v6-latin-700.woff2') format('woff2'), /* Super Modern Browsers */ + url('../fonts/droid-sans-v6-latin-700.woff') format('woff'), /* Modern Browsers */ + url('../fonts/droid-sans-v6-latin-700.ttf') format('truetype'), /* Safari, Android, iOS */ + url('../fonts/droid-sans-v6-latin-700.svg#DroidSans') format('svg'); /* Legacy iOS */ +} diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/fonts/droid-sans-v6-latin-700.eot b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/fonts/droid-sans-v6-latin-700.eot new file mode 100644 index 0000000..2250b71 Binary files /dev/null and b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/fonts/droid-sans-v6-latin-700.eot differ diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/fonts/droid-sans-v6-latin-700.svg b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/fonts/droid-sans-v6-latin-700.svg new file mode 100644 index 0000000..a54bbbb --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/fonts/droid-sans-v6-latin-700.svg @@ -0,0 +1,411 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/fonts/droid-sans-v6-latin-700.ttf b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/fonts/droid-sans-v6-latin-700.ttf new file mode 100644 index 0000000..523cb92 Binary files /dev/null and b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/fonts/droid-sans-v6-latin-700.ttf differ diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/fonts/droid-sans-v6-latin-700.woff b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/fonts/droid-sans-v6-latin-700.woff new file mode 100644 index 0000000..67e3e25 Binary files /dev/null and b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/fonts/droid-sans-v6-latin-700.woff differ diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/fonts/droid-sans-v6-latin-700.woff2 b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/fonts/droid-sans-v6-latin-700.woff2 new file mode 100644 index 0000000..1e726a7 Binary files /dev/null and b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/fonts/droid-sans-v6-latin-700.woff2 differ diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/fonts/droid-sans-v6-latin-regular.eot b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/fonts/droid-sans-v6-latin-regular.eot new file mode 100644 index 0000000..ac2698e Binary files /dev/null and b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/fonts/droid-sans-v6-latin-regular.eot differ diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/fonts/droid-sans-v6-latin-regular.svg b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/fonts/droid-sans-v6-latin-regular.svg new file mode 100644 index 0000000..d9f2a21 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/fonts/droid-sans-v6-latin-regular.svg @@ -0,0 +1,403 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/fonts/droid-sans-v6-latin-regular.ttf b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/fonts/droid-sans-v6-latin-regular.ttf new file mode 100644 index 0000000..76aede2 Binary files /dev/null and b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/fonts/droid-sans-v6-latin-regular.ttf differ diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/fonts/droid-sans-v6-latin-regular.woff b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/fonts/droid-sans-v6-latin-regular.woff new file mode 100644 index 0000000..abf1989 Binary files /dev/null and b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/fonts/droid-sans-v6-latin-regular.woff differ diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/fonts/droid-sans-v6-latin-regular.woff2 b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/fonts/droid-sans-v6-latin-regular.woff2 new file mode 100644 index 0000000..9f93f74 Binary files /dev/null and b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/fonts/droid-sans-v6-latin-regular.woff2 differ diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/images/explorer_icons.png b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/images/explorer_icons.png new file mode 100644 index 0000000..ed9d2ff Binary files /dev/null and b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/images/explorer_icons.png differ diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/images/logo_small.png b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/images/logo_small.png new file mode 100644 index 0000000..5496a65 Binary files /dev/null and b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/images/logo_small.png differ diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/images/pet_store_api.png b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/images/pet_store_api.png new file mode 100644 index 0000000..f9f9cd4 Binary files /dev/null and b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/images/pet_store_api.png differ diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/images/throbber.gif b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/images/throbber.gif new file mode 100644 index 0000000..0639388 Binary files /dev/null and b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/images/throbber.gif differ diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/images/wordnik_api.png b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/images/wordnik_api.png new file mode 100644 index 0000000..dca4f14 Binary files /dev/null and b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/images/wordnik_api.png differ diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/index.html b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/index.html new file mode 100644 index 0000000..b195a05 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/index.html @@ -0,0 +1,115 @@ + + + + + Swagger UI + + + + + + + + + + + + + + + + + + + + + + + + + + +
 
+
+ + diff --git a/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/lib/backbone-min.js b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/lib/backbone-min.js new file mode 100644 index 0000000..c66d3a5 --- /dev/null +++ b/wso2/wso2bpel-ext/wso2bpel-core/wso2bpel-mgr/src/main/resources/api-doc/lib/backbone-min.js @@ -0,0 +1,30 @@ +/* + * Copyright 2016 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Backbone.js 1.1.2 + +(function(t,e){if(typeof define==="function"&&define.amd){define(["underscore","jquery","exports"],function(i,r,s){t.Backbone=e(t,s,i,r)})}else if(typeof exports!=="undefined"){var i=require("underscore");e(t,exports,i)}else{t.Backbone=e(t,{},t._,t.jQuery||t.Zepto||t.ender||t.$)}})(this,function(t,e,i,r){var s=t.Backbone;var n=[];var a=n.push;var o=n.slice;var h=n.splice;e.VERSION="1.1.2";e.$=r;e.noConflict=function(){t.Backbone=s;return this};e.emulateHTTP=false;e.emulateJSON=false;var u=e.Events={on:function(t,e,i){if(!c(this,"on",t,[e,i])||!e)return this;this._events||(this._events={});var r=this._events[t]||(this._events[t]=[]);r.push({callback:e,context:i,ctx:i||this});return this},once:function(t,e,r){if(!c(this,"once",t,[e,r])||!e)return this;var s=this;var n=i.once(function(){s.off(t,n);e.apply(this,arguments)});n._callback=e;return this.on(t,n,r)},off:function(t,e,r){var s,n,a,o,h,u,l,f;if(!this._events||!c(this,"off",t,[e,r]))return this;if(!t&&!e&&!r){this._events=void 0;return this}o=t?[t]:i.keys(this._events);for(h=0,u=o.length;h").attr(t);this.setElement(r,false)}else{this.setElement(i.result(this,"el"),false)}}});e.sync=function(t,r,s){var n=T[t];i.defaults(s||(s={}),{emulateHTTP:e.emulateHTTP,emulateJSON:e.emulateJSON});var a={type:n,dataType:"json"};if(!s.url){a.url=i.result(r,"url")||M()}if(s.data==null&&r&&(t==="create"||t==="update"||t==="patch")){a.contentType="application/json";a.data=JSON.stringify(s.attrs||r.toJSON(s))}if(s.emulateJSON){a.contentType="application/x-www-form-urlencoded";a.data=a.data?{model:a.data}:{}}if(s.emulateHTTP&&(n==="PUT"||n==="DELETE"||n==="PATCH")){a.type="POST";if(s.emulateJSON)a.data._method=n;var o=s.beforeSend;s.beforeSend=function(t){t.setRequestHeader("X-HTTP-Method-Override",n);if(o)return o.apply(this,arguments)}}if(a.type!=="GET"&&!s.emulateJSON){a.processData=false}if(a.type==="PATCH"&&k){a.xhr=function(){return new ActiveXObject("Microsoft.XMLHTTP")}}var h=s.xhr=e.ajax(i.extend(a,s));r.trigger("request",r,h,s);return h};var k=typeof window!=="undefined"&&!!window.ActiveXObject&&!(window.XMLHttpRequest&&(new XMLHttpRequest).dispatchEvent);var T={create:"POST",update:"PUT",patch:"PATCH","delete":"DELETE",read:"GET"};e.ajax=function(){return e.$.ajax.apply(e.$,arguments)};var $=e.Router=function(t){t||(t={});if(t.routes)this.routes=t.routes;this._bindRoutes();this.initialize.apply(this,arguments)};var S=/\((.*?)\)/g;var H=/(\(\?)?:\w+/g;var A=/\*\w+/g;var I=/[\-{}\[\]+?.,\\\^$|#\s]/g;i.extend($.prototype,u,{initialize:function(){},route:function(t,r,s){if(!i.isRegExp(t))t=this._routeToRegExp(t);if(i.isFunction(r)){s=r;r=""}if(!s)s=this[r];var n=this;e.history.route(t,function(i){var a=n._extractParameters(t,i);n.execute(s,a);n.trigger.apply(n,["route:"+r].concat(a));n.trigger("route",r,a);e.history.trigger("route",n,r,a)});return this},execute:function(t,e){if(t)t.apply(this,e)},navigate:function(t,i){e.history.navigate(t,i);return this},_bindRoutes:function(){if(!this.routes)return;this.routes=i.result(this,"routes");var t,e=i.keys(this.routes);while((t=e.pop())!=null){this.route(t,this.routes[t])}},_routeToRegExp:function(t){t=t.replace(I,"\\$&").replace(S,"(?:$1)?").replace(H,function(t,e){return e?t:"([^/?]+)"}).replace(A,"([^?]*?)");return new RegExp("^"+t+"(?:\\?([\\s\\S]*))?$")},_extractParameters:function(t,e){var r=t.exec(e).slice(1);return i.map(r,function(t,e){if(e===r.length-1)return t||null;return t?decodeURIComponent(t):null})}});var N=e.History=function(){this.handlers=[];i.bindAll(this,"checkUrl");if(typeof window!=="undefined"){this.location=window.location;this.history=window.history}};var R=/^[#\/]|\s+$/g;var O=/^\/+|\/+$/g;var P=/msie [\w.]+/;var C=/\/$/;var j=/#.*$/;N.started=false;i.extend(N.prototype,u,{interval:50,atRoot:function(){return this.location.pathname.replace(/[^\/]$/,"$&/")===this.root},getHash:function(t){var e=(t||this).location.href.match(/#(.*)$/);return e?e[1]:""},getFragment:function(t,e){if(t==null){if(this._hasPushState||!this._wantsHashChange||e){t=decodeURI(this.location.pathname+this.location.search);var i=this.root.replace(C,"");if(!t.indexOf(i))t=t.slice(i.length)}else{t=this.getHash()}}return t.replace(R,"")},start:function(t){if(N.started)throw new Error("Backbone.history has already been started");N.started=true;this.options=i.extend({root:"/"},this.options,t);this.root=this.options.root;this._wantsHashChange=this.options.hashChange!==false;this._wantsPushState=!!this.options.pushState;this._hasPushState=!!(this.options.pushState&&this.history&&this.history.pushState);var r=this.getFragment();var s=document.documentMode;var n=P.exec(navigator.userAgent.toLowerCase())&&(!s||s<=7);this.root=("/"+this.root+"/").replace(O,"/");if(n&&this._wantsHashChange){var a=e.$('