From 2e16e42d5efbe40ef3f606c22d9494d892394d46 Mon Sep 17 00:00:00 2001 From: lresende Date: Sat, 31 Jan 2009 04:59:18 +0000 Subject: Moving modules that are not part of the main build to contrib folder git-svn-id: http://svn.us.apache.org/repos/asf/tuscany@739505 13f79535-47bb-0310-9956-ffa450edef68 --- .../contrib/modules/binding-atom-abdera/LICENSE | 205 +++ .../binding-atom-abdera/META-INF/MANIFEST.MF | 55 + .../sca/contrib/modules/binding-atom-abdera/NOTICE | 6 + .../modules/binding-atom-abdera/ReceiptToms.gif | Bin 0 -> 14205 bytes .../modules/binding-atom-abdera/ReceiptValue.jpg | Bin 0 -> 21373 bytes .../contrib/modules/binding-atom-abdera/pom.xml | 207 +++ .../sca/binding/atom/collection/Collection.java | 81 + .../binding/atom/collection/MediaCollection.java | 55 + .../binding/atom/collection/NotFoundException.java | 45 + .../binding/atom/provider/AtomBindingInvoker.java | 485 ++++++ .../atom/provider/AtomBindingListenerServlet.java | 871 +++++++++++ .../atom/provider/AtomBindingProviderFactory.java | 74 + .../sca/binding/atom/provider/AtomBindingUtil.java | 164 ++ .../provider/AtomReferenceBindingProvider.java | 183 +++ .../atom/provider/AtomServiceBindingProvider.java | 87 ++ ...che.tuscany.sca.provider.BindingProviderFactory | 19 + .../sca/binding/atom/AtomDeleteTestCase.java | 109 ++ .../tuscany/sca/binding/atom/AtomGetTestCase.java | 107 ++ .../tuscany/sca/binding/atom/AtomPostTestCase.java | 96 ++ .../tuscany/sca/binding/atom/AtomPutTestCase.java | 114 ++ .../sca/binding/atom/AtomTestCaseUtils.java | 96 ++ .../apache/tuscany/sca/binding/atom/Consumer.java | 42 + .../binding/atom/ConsumerProviderAtomTestCase.java | 165 ++ .../sca/binding/atom/ContentNegotiationTest.java | 265 ++++ .../tuscany/sca/binding/atom/CustomerClient.java | 29 + .../sca/binding/atom/CustomerClientImpl.java | 99 ++ .../sca/binding/atom/CustomerCollectionImpl.java | 149 ++ .../sca/binding/atom/MediaCollectionImpl.java | 210 +++ .../sca/binding/atom/MediaCollectionTestCase.java | 287 ++++ .../apache/tuscany/sca/binding/atom/Provider.java | 48 + .../atom/ProviderEntryEntityTagsTestCase.java | 428 ++++++ .../atom/ProviderFeedEntityTagsTestCase.java | 382 +++++ .../atom/ProviderServiceDocumentTestCase.java | 209 +++ .../tuscany/sca/binding/atom/Consumer.composite | 32 + .../tuscany/sca/binding/atom/Provider.composite | 33 + .../sca/binding/atom/ReceiptProvider.composite | 33 + java/sca/contrib/modules/binding-atom/LICENSE | 205 +++ .../modules/binding-atom/META-INF/MANIFEST.MF | 23 + java/sca/contrib/modules/binding-atom/NOTICE | 6 + java/sca/contrib/modules/binding-atom/pom.xml | 62 + .../tuscany/sca/binding/atom/AtomBinding.java | 43 + .../sca/binding/atom/AtomBindingFactory.java | 35 + .../binding/atom/impl/AtomBindingFactoryImpl.java | 36 + .../sca/binding/atom/impl/AtomBindingImpl.java | 117 ++ ...che.tuscany.sca.binding.atom.AtomBindingFactory | 19 + ...ca.contribution.processor.StAXArtifactProcessor | 19 + .../binding/atom/AtomBindingProcessorTestCase.java | 91 ++ .../contrib/modules/binding-corba-runtime/LICENSE | 205 +++ .../binding-corba-runtime/META-INF/MANIFEST.MF | 64 + .../contrib/modules/binding-corba-runtime/NOTICE | 6 + .../contrib/modules/binding-corba-runtime/pom.xml | 130 ++ .../provider/CorbaBindingProviderFactory.java | 70 + .../sca/binding/corba/provider/CorbaInvoker.java | 89 ++ .../provider/CorbaReferenceBindingProvider.java | 100 ++ .../provider/CorbaServiceBindingProvider.java | 92 ++ .../corba/provider/exceptions/CorbaException.java | 34 + .../exceptions/RequestConfigurationException.java | 43 + .../binding/corba/provider/meta/CorbaArray.java | 34 + .../corba/provider/meta/CorbaUnionElement.java | 37 + .../corba/provider/meta/CorbaUnionElementType.java | 28 + .../corba/provider/reference/DynaCorbaRequest.java | 253 ++++ .../provider/reference/DynaCorbaResponse.java | 39 + .../reference/InterfaceInstanceCreator.java | 70 + .../reference/InterfaceMethodInterceptor.java | 65 + .../provider/service/ComponentInvocationProxy.java | 120 ++ .../corba/provider/service/DynaCorbaServant.java | 137 ++ .../provider/service/InvocationException.java | 43 + .../corba/provider/service/InvocationProxy.java | 46 + .../corba/provider/service/OperationTypes.java | 51 + .../corba/provider/types/AnnotationAttributes.java | 46 + .../sca/binding/corba/provider/types/NodeType.java | 28 + .../sca/binding/corba/provider/types/TypeTree.java | 50 + .../corba/provider/types/TypeTreeCreator.java | 497 ++++++ .../binding/corba/provider/types/TypeTreeNode.java | 75 + .../corba/provider/types/UnionAttributes.java | 59 + .../corba/provider/types/util/ArrayTypeHelper.java | 53 + .../provider/types/util/BooleanTypeHelper.java | 39 + .../corba/provider/types/util/ByteTypeHelper.java | 39 + .../corba/provider/types/util/CharTypeHelper.java | 39 + .../provider/types/util/DoubleTypeHelper.java | 39 + .../corba/provider/types/util/EnumTypeHelper.java | 41 + .../corba/provider/types/util/FloatTypeHelper.java | 39 + .../corba/provider/types/util/IntTypeHelper.java | 39 + .../corba/provider/types/util/LongTypeHelper.java | 39 + .../provider/types/util/ReferenceTypeHelper.java | 42 + .../provider/types/util/SequenceTypeHelper.java | 70 + .../corba/provider/types/util/ShortTypeHelper.java | 39 + .../provider/types/util/StringTypeHelper.java | 39 + .../provider/types/util/StructTypeHelper.java | 69 + .../corba/provider/types/util/TypeHelper.java | 47 + .../provider/types/util/TypeHelpersProxy.java | 119 ++ .../corba/provider/types/util/UnionTypeHelper.java | 92 ++ .../binding/corba/provider/types/util/Utils.java | 40 + .../binding/corba/provider/util/MethodFinder.java | 97 ++ .../corba/provider/util/OperationMapper.java | 578 +++++++ ...che.tuscany.sca.provider.BindingProviderFactory | 19 + .../corba/testing/CorbaServantTestCase.java | 564 +++++++ .../binding/corba/testing/CorbaTypesTestCase.java | 841 +++++++++++ .../corba/testing/MappingTestInterface.java | 46 + .../corba/testing/MethodFinderTestCase.java | 70 + .../corba/testing/OperationMappingTestCase.java | 67 + .../sca/binding/corba/testing/TestConstants.java | 87 ++ .../testing/arrays_unions/ArraysUnionsTests.java | 13 + .../arrays_unions/ArraysUnionsTestsHelper.java | 85 ++ .../arrays_unions/ArraysUnionsTestsHolder.java | 38 + .../arrays_unions/ArraysUnionsTestsOperations.java | 16 + .../corba/testing/arrays_unions/InnerUnion.java | 112 ++ .../testing/arrays_unions/InnerUnionHelper.java | 106 ++ .../testing/arrays_unions/InnerUnionHolder.java | 38 + .../corba/testing/arrays_unions/RichUnion.java | 177 +++ .../testing/arrays_unions/RichUnionHelper.java | 157 ++ .../testing/arrays_unions/RichUnionHolder.java | 38 + .../testing/arrays_unions/StringArrayHelper.java | 76 + .../testing/arrays_unions/StringArrayHolder.java | 39 + .../corba/testing/arrays_unions/TestStruct.java | 28 + .../testing/arrays_unions/TestStructHelper.java | 149 ++ .../testing/arrays_unions/TestStructHolder.java | 38 + .../arrays_unions/_ArraysUnionsTestsImplBase.java | 86 ++ .../arrays_unions/_ArraysUnionsTestsStub.java | 100 ++ .../sca/binding/corba/testing/enums/Color.java | 60 + .../binding/corba/testing/enums/ColorHelper.java | 69 + .../binding/corba/testing/enums/ColorHolder.java | 51 + .../binding/corba/testing/enums/EnumManager.java | 30 + .../corba/testing/enums/EnumManagerHelper.java | 98 ++ .../corba/testing/enums/EnumManagerHolder.java | 51 + .../corba/testing/enums/EnumManagerOperations.java | 32 + .../corba/testing/enums/_EnumManagerImplBase.java | 76 + .../corba/testing/enums/_EnumManagerStub.java | 75 + .../sca/binding/corba/testing/exceptions/Calc.java | 30 + .../corba/testing/exceptions/CalcHelper.java | 98 ++ .../corba/testing/exceptions/CalcHolder.java | 51 + .../corba/testing/exceptions/CalcOperations.java | 36 + .../testing/exceptions/CalcPackage/Arguments.java | 41 + .../exceptions/CalcPackage/ArgumentsHelper.java | 94 ++ .../exceptions/CalcPackage/ArgumentsHolder.java | 51 + .../testing/exceptions/CalcPackage/DivByZero.java | 52 + .../exceptions/CalcPackage/DivByZeroHelper.java | 100 ++ .../exceptions/CalcPackage/DivByZeroHolder.java | 51 + .../exceptions/CalcPackage/NotSupported.java | 46 + .../exceptions/CalcPackage/NotSupportedHelper.java | 93 ++ .../exceptions/CalcPackage/NotSupportedHolder.java | 51 + .../corba/testing/exceptions/_CalcImplBase.java | 102 ++ .../corba/testing/exceptions/_CalcStub.java | 106 ++ .../corba/testing/generated/ArraysSetter.java | 30 + .../testing/generated/ArraysSetterHelper.java | 100 ++ .../testing/generated/ArraysSetterHolder.java | 51 + .../testing/generated/ArraysSetterOperations.java | 59 + .../corba/testing/generated/PrimitivesSetter.java | 31 + .../testing/generated/PrimitivesSetterHelper.java | 100 ++ .../testing/generated/PrimitivesSetterHolder.java | 51 + .../generated/PrimitivesSetterOperations.java | 59 + .../corba/testing/generated/RemoteObject.java | 30 + .../testing/generated/RemoteObjectHelper.java | 100 ++ .../testing/generated/RemoteObjectHolder.java | 51 + .../testing/generated/RemoteObjectOperations.java | 30 + .../corba/testing/generated/SimpleStruct.java | 41 + .../testing/generated/SimpleStructHelper.java | 93 ++ .../testing/generated/SimpleStructHolder.java | 51 + .../corba/testing/generated/SomeStruct.java | 51 + .../corba/testing/generated/SomeStructHelper.java | 146 ++ .../corba/testing/generated/SomeStructHolder.java | 51 + .../corba/testing/generated/TestObject.java | 30 + .../corba/testing/generated/TestObjectHelper.java | 99 ++ .../corba/testing/generated/TestObjectHolder.java | 51 + .../testing/generated/TestObjectOperations.java | 44 + .../testing/generated/_ArraysSetterImplBase.java | 232 +++ .../corba/testing/generated/_ArraysSetterStub.java | 343 +++++ .../generated/_PrimitivesSetterImplBase.java | 230 +++ .../testing/generated/_PrimitivesSetterStub.java | 341 +++++ .../testing/generated/_RemoteObjectImplBase.java | 59 + .../corba/testing/generated/_RemoteObjectStub.java | 55 + .../testing/generated/_TestObjectImplBase.java | 149 ++ .../corba/testing/generated/_TestObjectStub.java | 182 +++ .../testing/generated/boolean_listHelper.java | 75 + .../testing/generated/boolean_listHolder.java | 51 + .../corba/testing/generated/char_listHelper.java | 75 + .../corba/testing/generated/char_listHolder.java | 51 + .../corba/testing/generated/double_listHelper.java | 75 + .../corba/testing/generated/double_listHolder.java | 51 + .../corba/testing/generated/float_listHelper.java | 75 + .../corba/testing/generated/float_listHolder.java | 51 + .../corba/testing/generated/long_listHelper.java | 75 + .../corba/testing/generated/long_listHolder.java | 51 + .../testing/generated/long_long_listHelper.java | 75 + .../testing/generated/long_long_listHolder.java | 51 + .../corba/testing/generated/long_seq1Helper.java | 75 + .../corba/testing/generated/long_seq1Holder.java | 51 + .../corba/testing/generated/long_seq2Helper.java | 83 + .../corba/testing/generated/long_seq2Holder.java | 51 + .../corba/testing/generated/long_seq3Helper.java | 89 ++ .../corba/testing/generated/long_seq3Holder.java | 51 + .../corba/testing/generated/octet_listHelper.java | 75 + .../corba/testing/generated/octet_listHolder.java | 51 + .../generated/remote_object_listHelper.java | 80 + .../generated/remote_object_listHolder.java | 51 + .../corba/testing/generated/short_listHelper.java | 75 + .../corba/testing/generated/short_listHolder.java | 51 + .../corba/testing/generated/string_listHelper.java | 77 + .../corba/testing/generated/string_listHolder.java | 51 + .../generated/unsigned_long_listHelper.java | 76 + .../generated/unsigned_long_listHolder.java | 51 + .../generated/unsigned_long_long_listHelper.java | 78 + .../generated/unsigned_long_long_listHolder.java | 51 + .../generated/unsigned_short_listHelper.java | 76 + .../generated/unsigned_short_listHolder.java | 51 + .../corba/testing/generated/wchar_listHelper.java | 75 + .../corba/testing/generated/wchar_listHolder.java | 51 + .../testing/generated/wstring_listHelper.java | 77 + .../testing/generated/wstring_listHolder.java | 51 + .../corba/testing/hierarchy/ArraysTestStruct.java | 45 + .../sca/binding/corba/testing/hierarchy/Calc.java | 30 + .../corba/testing/hierarchy/DummyObject.java | 28 + .../corba/testing/hierarchy/InnerUnion.java | 55 + .../corba/testing/hierarchy/InvalidCorbaArray.java | 38 + .../corba/testing/hierarchy/InvalidEnum1.java | 36 + .../corba/testing/hierarchy/InvalidEnum2.java | 33 + .../corba/testing/hierarchy/InvalidEnum3.java | 33 + .../corba/testing/hierarchy/InvalidStruct1.java | 28 + .../corba/testing/hierarchy/InvalidStruct2.java | 31 + .../corba/testing/hierarchy/InvalidStruct3.java | 36 + .../corba/testing/hierarchy/InvalidUnion1.java | 37 + .../corba/testing/hierarchy/InvalidUnion2.java | 34 + .../corba/testing/hierarchy/InvalidUnion3.java | 35 + .../corba/testing/hierarchy/InvalidUnion4.java | 39 + .../corba/testing/hierarchy/InvalidUnion5.java | 42 + .../corba/testing/hierarchy/NonCorbaException.java | 28 + .../binding/corba/testing/hierarchy/RichUnion.java | 91 ++ .../corba/testing/hierarchy/SimpleStruct.java | 30 + .../corba/testing/hierarchy/SomeStruct.java | 33 + .../corba/testing/references/DummyObject.java | 30 + .../testing/references/DummyObjectHelper.java | 100 ++ .../testing/references/DummyObjectHolder.java | 51 + .../testing/references/DummyObjectOperations.java | 33 + .../corba/testing/references/ObjectManager.java | 30 + .../testing/references/ObjectManagerHelper.java | 100 ++ .../testing/references/ObjectManagerHolder.java | 51 + .../references/ObjectManagerOperations.java | 33 + .../testing/references/_DummyObjectImplBase.java | 84 ++ .../corba/testing/references/_DummyObjectStub.java | 92 ++ .../testing/references/_ObjectManagerImplBase.java | 86 ++ .../testing/references/_ObjectManagerStub.java | 94 ++ .../testing/servants/ArraysSetterServant.java | 89 ++ .../testing/servants/ArraysUnionsServant.java | 42 + .../servants/ArraysUnionsTuscanyServant.java | 43 + .../corba/testing/servants/CalcServant.java | 52 + .../corba/testing/servants/DummyObjectServant.java | 42 + .../corba/testing/servants/EnumManagerServant.java | 33 + .../testing/servants/InvalidTestObjectServant.java | 24 + .../testing/servants/InvalidTypesServant.java | 34 + .../corba/testing/servants/NonCorbaServant.java | 36 + .../testing/servants/ObjectManagerServant.java | 37 + .../testing/servants/PrimitivesSetterServant.java | 89 ++ .../corba/testing/servants/TestObjectServant.java | 71 + .../corba/testing/service/mocks/TestDataType.java | 88 ++ .../corba/testing/service/mocks/TestInterface.java | 139 ++ .../service/mocks/TestInterfaceContract.java | 58 + .../corba/testing/service/mocks/TestOperation.java | 174 +++ .../service/mocks/TestRuntimeComponentService.java | 234 +++ .../testing/service/mocks/TestRuntimeWire.java | 107 ++ .../src/test/resources/arrays_unions.idl | 69 + .../src/test/resources/enums.idl | 44 + .../src/test/resources/exceptions.idl | 58 + .../src/test/resources/general_tests.idl | 124 ++ .../src/test/resources/references.idl | 50 + java/sca/contrib/modules/binding-corba/LICENSE | 205 +++ .../modules/binding-corba/META-INF/MANIFEST.MF | 28 + java/sca/contrib/modules/binding-corba/NOTICE | 6 + java/sca/contrib/modules/binding-corba/pom.xml | 53 + .../tuscany/sca/binding/corba/CorbaBinding.java | 47 + .../sca/binding/corba/CorbaBindingFactory.java | 31 + .../corba/impl/CorbaBindingFactoryImpl.java | 37 + .../sca/binding/corba/impl/CorbaBindingImpl.java | 132 ++ .../binding/corba/impl/CorbaBindingProcessor.java | 133 ++ ...e.tuscany.sca.binding.corba.CorbaBindingFactory | 19 + ...ca.contribution.processor.StAXArtifactProcessor | 19 + .../contrib/modules/binding-ejb-runtime/LICENSE | 205 +++ .../binding-ejb-runtime/META-INF/MANIFEST.MF | 42 + .../sca/contrib/modules/binding-ejb-runtime/NOTICE | 6 + .../contrib/modules/binding-ejb-runtime/pom.xml | 170 +++ .../sca/binding/ejb/corba/ClassLoadingUtil.java | 365 +++++ .../binding/ejb/corba/DynamicStubClassLoader.java | 150 ++ .../sca/binding/ejb/corba/Java2IDLUtil.java | 811 ++++++++++ .../binding/ejb/corba/ObjectInputStreamExt.java | 61 + .../binding/ejb/corba/StubMethodInterceptor.java | 154 ++ .../sca/binding/ejb/corba/UtilInitializer.java | 69 + .../binding/ejb/provider/EJBBindingInvoker.java | 92 ++ .../ejb/provider/EJBBindingProviderFactory.java | 56 + .../EJBBindingReferenceBindingProvider.java | 86 ++ .../tuscany/sca/binding/ejb/util/EJBHandler.java | 338 +++++ .../tuscany/sca/binding/ejb/util/EJBLocator.java | 483 ++++++ .../sca/binding/ejb/util/EJBObjectFactory.java | 209 +++ .../sca/binding/ejb/util/EJBStubHelper.java | 69 + .../sca/binding/ejb/util/InterfaceInfo.java | 117 ++ .../binding/ejb/util/JavaReflectionAdapter.java | 157 ++ .../tuscany/sca/binding/ejb/util/MethodInfo.java | 189 +++ .../sca/binding/ejb/util/NamingEndpoint.java | 124 ++ ...che.tuscany.sca.provider.BindingProviderFactory | 19 + .../binding-ejb-validation-messages.properties | 23 + .../src/test/java/account/BankManagerFacade.java | 33 + .../src/test/java/account/Customer.java | 36 + .../src/test/java/account/CustomerImpl.java | 57 + .../src/test/java/calculator/AddService.java | 27 + .../src/test/java/calculator/AddServiceHome.java | 31 + .../samples/bank/ejb/BankManagerFacade.java | 44 + .../samples/bank/ejb/BankManagerFacadeHome.java | 44 + .../binding/ejb/tests/EJBReferenceTestCase.java | 73 + .../tuscany/sca/binding/ejb/tests/MockServer.java | 151 ++ .../sca/binding/ejb/tests/SocketTracer.java | 138 ++ .../src/test/resources/account/account.composite | 35 + java/sca/contrib/modules/binding-ejb/LICENSE | 205 +++ .../modules/binding-ejb/META-INF/MANIFEST.MF | 27 + java/sca/contrib/modules/binding-ejb/NOTICE | 6 + java/sca/contrib/modules/binding-ejb/pom.xml | 66 + .../apache/tuscany/sca/binding/ejb/EJBBinding.java | 94 ++ .../sca/binding/ejb/EJBBindingException.java | 56 + .../tuscany/sca/binding/ejb/EJBBindingFactory.java | 35 + .../binding/ejb/impl/EJBBindingFactoryImpl.java | 36 + .../sca/binding/ejb/impl/EJBBindingImpl.java | 183 +++ .../sca/binding/ejb/impl/EJBBindingProcessor.java | 184 +++ ...pache.tuscany.sca.binding.ejb.EJBBindingFactory | 19 + ...ca.contribution.processor.StAXArtifactProcessor | 19 + .../binding-ejb-validation-messages.properties | 23 + .../contrib/modules/binding-gdata-runtime/LICENSE | 205 +++ .../binding-gdata-runtime/META-INF/MANIFEST.MF | 48 + .../contrib/modules/binding-gdata-runtime/NOTICE | 6 + .../contrib/modules/binding-gdata-runtime/pom.xml | 169 +++ .../sca/binding/gdata/collection/Collection.java | 79 + .../binding/gdata/collection/MediaCollection.java | 55 + .../gdata/collection/NotFoundException.java | 45 + .../gdata/provider/GdataBindingInvoker.java | 425 ++++++ .../provider/GdataBindingListenerServlet.java | 736 +++++++++ .../provider/GdataBindingProviderFactory.java | 83 + .../binding/gdata/provider/GdataBindingUtil.java | 171 +++ .../provider/GdataReferenceBindingProvider.java | 229 +++ .../provider/GdataServiceBindingProvider.java | 90 ++ ...che.tuscany.sca.provider.BindingProviderFactory | 19 + .../src/main/resources/tuscany-binding-gdata.xsd | 36 + .../apache/tuscany/sca/binding/gdata/Consumer.java | 66 + .../binding/gdata/ConsumerProviderTestCase.java | 153 ++ .../tuscany/sca/binding/gdata/CustomerClient.java | 40 + .../sca/binding/gdata/CustomerClientImpl.java | 123 ++ .../sca/binding/gdata/CustomerCollectionImpl.java | 143 ++ .../gdata/GoogleBloggerServiceTestCase.java | 156 ++ .../gdata/GoogleCalendarServiceTestCase.java | 164 ++ .../gdata/GoogleContactsServiceTestCase.java | 160 ++ .../apache/tuscany/sca/binding/gdata/Provider.java | 48 + .../sca/binding/gdata/StartLocalhostServlet.java | 48 + .../src/test/resources/log4j.properties | 25 + .../tuscany/sca/binding/gdata/Consumer.composite | 32 + .../binding/gdata/ConsumerGoogleBlogger.composite | 32 + .../binding/gdata/ConsumerGoogleCalendar.composite | 32 + .../binding/gdata/ConsumerGoogleContacts.composite | 32 + .../tuscany/sca/binding/gdata/Provider.composite | 33 + java/sca/contrib/modules/binding-gdata/LICENSE | 202 +++ .../modules/binding-gdata/META-INF/MANIFEST.MF | 23 + java/sca/contrib/modules/binding-gdata/NOTICE | 8 + java/sca/contrib/modules/binding-gdata/pom.xml | 60 + .../tuscany/sca/binding/gdata/GdataBinding.java | 78 + .../sca/binding/gdata/GdataBindingFactory.java | 35 + .../gdata/impl/GdataBindingFactoryImpl.java | 36 + .../sca/binding/gdata/impl/GdataBindingImpl.java | 141 ++ .../binding/gdata/xml/GdataBindingProcessor.java | 121 ++ ...e.tuscany.sca.binding.gdata.GdataBindingFactory | 18 + ...ca.contribution.processor.StAXArtifactProcessor | 19 + .../contrib/modules/binding-http-runtime/LICENSE | 205 +++ .../binding-http-runtime/META-INF/MANIFEST.MF | 28 + .../contrib/modules/binding-http-runtime/NOTICE | 6 + .../contrib/modules/binding-http-runtime/pom.xml | 100 ++ .../http/provider/HTTPBindingListenerServlet.java | 516 +++++++ .../http/provider/HTTPBindingProviderFactory.java | 64 + .../http/provider/HTTPGetListenerServlet.java | 94 ++ .../http/provider/HTTPServiceBindingProvider.java | 137 ++ .../http/provider/HTTPServiceListenerServlet.java | 136 ++ .../sca/binding/http/util/HTTPHeadersParser.java | 50 + ...che.tuscany.sca.provider.BindingProviderFactory | 19 + .../http/HTTPBindingCacheTestCaseFIXME.java | 853 +++++++++++ .../sca/binding/http/HTTPBindingTestCase.java | 153 ++ .../sca/binding/http/NotModifiedException.java | 44 + .../binding/http/PreconditionFailedException.java | 44 + .../sca/binding/http/TestBindingCacheImpl.java | 241 +++ .../tuscany/sca/binding/http/TestGetImpl.java | 37 + .../sca/binding/http/TestServiceCacheImpl.java | 61 + .../tuscany/sca/binding/http/TestServiceImpl.java | 61 + .../src/test/resources/content/test.html | 21 + .../src/test/resources/test.composite | 47 + .../src/test/resources/testCache.composite | 33 + java/sca/contrib/modules/binding-http/LICENSE | 205 +++ .../modules/binding-http/META-INF/MANIFEST.MF | 22 + java/sca/contrib/modules/binding-http/NOTICE | 6 + java/sca/contrib/modules/binding-http/pom.xml | 72 + .../tuscany/sca/binding/http/HTTPBinding.java | 31 + .../sca/binding/http/HTTPBindingFactory.java | 35 + .../tuscany/sca/binding/http/HTTPCacheContext.java | 257 ++++ .../tuscany/sca/binding/http/HTTPHeader.java | 51 + .../binding/http/impl/HTTPBindingFactoryImpl.java | 36 + .../sca/binding/http/impl/HTTPBindingImpl.java | 108 ++ ...che.tuscany.sca.binding.http.HTTPBindingFactory | 19 + ...ca.contribution.processor.StAXArtifactProcessor | 19 + .../sca/contrib/modules/binding-jms-policy/LICENSE | 205 +++ java/sca/contrib/modules/binding-jms-policy/NOTICE | 6 + .../sca/contrib/modules/binding-jms-policy/pom.xml | 94 ++ .../jms/policy/JMSBindingDefinitionsProvider.java | 66 + .../token/JMSTokenAuthenticationPolicy.java | 56 + .../JMSTokenAuthenticationPolicyProcessor.java | 112 ++ ...MSTokenAuthenticationPolicyProviderFactory.java | 75 + ...enAuthenticationReferencePolicyInterceptor.java | 89 ++ ...TokenAuthenticationReferencePolicyProvider.java | 90 ++ ...okenAuthenticationServicePolicyInterceptor.java | 89 ++ ...MSTokenAuthenticationServicePolicyProvider.java | 88 ++ .../binding/jms/policy/header/JMSHeaderPolicy.java | 131 ++ .../policy/header/JMSHeaderPolicyProcessor.java | 210 +++ .../header/JMSHeaderPolicyProviderFactory.java | 75 + .../JMSHeaderReferencePolicyInterceptor.java | 130 ++ .../header/JMSHeaderReferencePolicyProvider.java | 95 ++ ...ca.contribution.processor.StAXArtifactProcessor | 20 + ...ache.tuscany.sca.provider.PolicyProviderFactory | 19 + ...che.tuscany.sca.provider.SCADefinitionsProvider | 19 + ...nding-jms-policy-validation-messages.properties | 23 + .../tuscany/sca/binding/jms/policy/definitions.xml | 84 ++ .../jms/policy/PolicyProcessorTestCase.java | 91 ++ .../binding/jms/policy/mock_policy_definitions.xml | 39 + .../contrib/modules/binding-jms-runtime/LICENSE | 205 +++ .../binding-jms-runtime/META-INF/MANIFEST.MF | 47 + .../sca/contrib/modules/binding-jms-runtime/NOTICE | 6 + .../contrib/modules/binding-jms-runtime/pom.xml | 123 ++ .../sca/binding/jms/context/JMSBindingContext.java | 82 + .../jms/headers/HeaderReferenceInterceptor.java | 174 +++ ...OperationSelectorJMSDefaultProviderFactory.java | 68 + ...rationSelectorJMSDefaultServiceInterceptor.java | 167 ++ ...OperationSelectorJMSDefaultServiceProvider.java | 59 + .../jms/provider/AbstractMessageProcessor.java | 117 ++ .../jms/provider/BytesMessageProcessor.java | 75 + .../jms/provider/DefaultJMSBindingListener.java | 266 ++++ .../DefaultJMSResourceFactoryExtensionPoint.java | 30 + .../binding/jms/provider/JMSBindingInvoker.java | 467 ++++++ .../jms/provider/JMSBindingProviderFactory.java | 69 + .../JMSBindingReferenceBindingProvider.java | 170 +++ .../provider/JMSBindingServiceBindingProvider.java | 359 +++++ .../binding/jms/provider/JMSMessageProcessor.java | 55 + .../jms/provider/JMSMessageProcessorUtil.java | 75 + .../binding/jms/provider/JMSResourceFactory.java | 67 + .../provider/JMSResourceFactoryExtensionPoint.java | 28 + .../jms/provider/JMSResourceFactoryImpl.java | 223 +++ .../jms/provider/ObjectMessageProcessor.java | 75 + .../binding/jms/provider/RRBJMSBindingInvoker.java | 279 ++++ .../jms/provider/RRBJMSBindingListener.java | 122 ++ .../binding/jms/provider/TextMessageProcessor.java | 68 + .../jms/provider/XMLTextMessageProcessor.java | 90 ++ .../transport/TransportReferenceInterceptor.java | 186 +++ .../jms/transport/TransportServiceInterceptor.java | 170 +++ .../WireFormatJMSBytesProviderFactory.java | 65 + .../WireFormatJMSBytesReferenceInterceptor.java | 111 ++ .../WireFormatJMSBytesReferenceProvider.java | 94 ++ .../WireFormatJMSBytesServiceInterceptor.java | 111 ++ .../WireFormatJMSBytesServiceProvider.java | 91 ++ .../WireFormatJMSObjectProviderFactory.java | 65 + .../WireFormatJMSObjectReferenceInterceptor.java | 111 ++ .../WireFormatJMSObjectReferenceProvider.java | 94 ++ .../WireFormatJMSObjectServiceInterceptor.java | 111 ++ .../WireFormatJMSObjectServiceProvider.java | 91 ++ .../jmstext/WireFormatJMSTextProviderFactory.java | 65 + .../WireFormatJMSTextReferenceInterceptor.java | 112 ++ .../WireFormatJMSTextReferenceProvider.java | 95 ++ .../WireFormatJMSTextServiceInterceptor.java | 111 ++ .../jmstext/WireFormatJMSTextServiceProvider.java | 91 ++ .../WireFormatJMSTextXMLProviderFactory.java | 72 + .../WireFormatJMSTextXMLReferenceInterceptor.java | 125 ++ .../WireFormatJMSTextXMLReferenceProvider.java | 110 ++ .../WireFormatJMSTextXMLServiceInterceptor.java | 118 ++ .../WireFormatJMSTextXMLServiceProvider.java | 113 ++ ...che.tuscany.sca.provider.BindingProviderFactory | 19 + ...y.sca.provider.OperationSelectorProviderFactory | 19 + ....tuscany.sca.provider.WireFormatProviderFactory | 22 + .../sca/binding/jms/HelloWorldClientImpl.java | 43 + .../tuscany/sca/binding/jms/HelloWorldService.java | 31 + .../sca/binding/jms/HelloWorldServiceImpl.java | 32 + .../src/test/resources/simple/client.composite | 38 + .../src/test/resources/simple/service.composite | 35 + java/sca/contrib/modules/binding-jms/LICENSE | 205 +++ .../modules/binding-jms/META-INF/MANIFEST.MF | 30 + java/sca/contrib/modules/binding-jms/NOTICE | 6 + java/sca/contrib/modules/binding-jms/pom.xml | 48 + .../apache/tuscany/sca/binding/jms/JMSBinding.java | 241 +++ .../sca/binding/jms/JMSBindingException.java | 45 + .../tuscany/sca/binding/jms/JMSBindingFactory.java | 31 + .../binding/jms/impl/JMSBindingFactoryImpl.java | 34 + .../sca/binding/jms/impl/JMSBindingImpl.java | 573 +++++++ .../jmsdefault/OperationSelectorJMSDefault.java | 45 + .../OperationSelectorJMSDefaultProcessor.java | 76 + .../wireformat/jmsbytes/WireFormatJMSBytes.java | 45 + .../jmsbytes/WireFormatJMSBytesProcessor.java | 78 + .../wireformat/jmsobject/WireFormatJMSObject.java | 45 + .../jmsobject/WireFormatJMSObjectProcessor.java | 78 + .../jms/wireformat/jmstext/WireFormatJMSText.java | 45 + .../jmstext/WireFormatJMSTextProcessor.java | 78 + .../jmstextxml/WireFormatJMSTextXML.java | 48 + .../jmstextxml/WireFormatJMSTextXMLProcessor.java | 78 + .../sca/binding/jms/xml/JMSBindingConstants.java | 72 + .../sca/binding/jms/xml/JMSBindingProcessor.java | 688 +++++++++ ...pache.tuscany.sca.binding.jms.JMSBindingFactory | 17 + ...ca.contribution.processor.StAXArtifactProcessor | 25 + .../binding-jms-validation-messages.properties | 47 + .../jms/impl/JMSBindingProcessorTestCase.java | 211 +++ .../modules/binding-jsonrpc-runtime/LICENSE | 205 +++ .../binding-jsonrpc-runtime/META-INF/MANIFEST.MF | 41 + .../contrib/modules/binding-jsonrpc-runtime/NOTICE | 6 + .../modules/binding-jsonrpc-runtime/pom.xml | 136 ++ .../jsonrpc/provider/JSONRPCBindingInvoker.java | 45 + .../provider/JSONRPCBindingProviderFactory.java | 64 + .../provider/JSONRPCReferenceBindingProvider.java | 70 + .../provider/JSONRPCServiceBindingProvider.java | 184 +++ .../jsonrpc/provider/JSONRPCServiceServlet.java | 282 ++++ .../sca/binding/jsonrpc/provider/JavaToSmd.java | 56 + .../jsonrpc/provider/ScaDomainScriptServlet.java | 114 ++ ...che.tuscany.sca.provider.BindingProviderFactory | 19 + .../sca/binding/jsonrpc/provider/jsonrpc.js | 493 ++++++ .../src/test/java/bean/TestBean.java | 51 + .../src/test/java/echo/Echo.java | 62 + .../src/test/java/echo/EchoBusinessException.java | 29 + .../src/test/java/echo/EchoComponentImpl.java | 98 ++ .../binding/jsonrpc/JSONRPCDataTypeTestCase.java | 180 +++ .../binding/jsonrpc/JSONRPCExceptionTestCase.java | 92 ++ .../binding/jsonrpc/JSONRPCServiceTestCase.java | 76 + .../src/test/resources/JSONRPCBinding.composite | 35 + java/sca/contrib/modules/binding-jsonrpc/LICENSE | 205 +++ .../modules/binding-jsonrpc/META-INF/MANIFEST.MF | 20 + java/sca/contrib/modules/binding-jsonrpc/NOTICE | 6 + java/sca/contrib/modules/binding-jsonrpc/pom.xml | 59 + .../sca/binding/jsonrpc/JSONRPCBinding.java | 32 + .../sca/binding/jsonrpc/JSONRPCBindingFactory.java | 35 + .../jsonrpc/impl/JSONRPCBindingFactoryImpl.java | 38 + .../binding/jsonrpc/impl/JSONRPCBindingImpl.java | 105 ++ ...scany.sca.binding.jsonrpc.JSONRPCBindingFactory | 19 + ...ca.contribution.processor.StAXArtifactProcessor | 19 + java/sca/contrib/modules/binding-rss-rome/LICENSE | 205 +++ .../modules/binding-rss-rome/META-INF/MANIFEST.MF | 39 + java/sca/contrib/modules/binding-rss-rome/NOTICE | 6 + java/sca/contrib/modules/binding-rss-rome/pom.xml | 151 ++ .../sca/binding/rss/collection/Collection.java | 49 + .../binding/rss/collection/MediaCollection.java | 55 + .../binding/rss/collection/NotFoundException.java | 45 + .../binding/rss/provider/RSSBindingInvoker.java | 76 + .../rss/provider/RSSBindingListenerServlet.java | 394 +++++ .../rss/provider/RSSBindingProviderFactory.java | 74 + .../rss/provider/RSSReferenceBindingProvider.java | 65 + .../rss/provider/RSSServiceBindingProvider.java | 85 ++ ...che.tuscany.sca.provider.BindingProviderFactory | 19 + .../apache/tuscany/sca/binding/rss/Consumer.java | 41 + .../tuscany/sca/binding/rss/CustomerClient.java | 25 + .../sca/binding/rss/CustomerClientImpl.java | 45 + .../sca/binding/rss/CustomerCollectionImpl.java | 103 ++ .../apache/tuscany/sca/binding/rss/Provider.java | 47 + .../tuscany/sca/binding/feed/Consumer.composite | 32 + .../tuscany/sca/binding/feed/Provider.composite | 33 + java/sca/contrib/modules/binding-rss/LICENSE | 205 +++ .../modules/binding-rss/META-INF/MANIFEST.MF | 19 + java/sca/contrib/modules/binding-rss/NOTICE | 6 + java/sca/contrib/modules/binding-rss/pom.xml | 79 + .../apache/tuscany/sca/binding/rss/RSSBinding.java | 28 + .../tuscany/sca/binding/rss/RSSBindingFactory.java | 35 + .../binding/rss/impl/RSSBindingFactoryImpl.java | 36 + .../sca/binding/rss/impl/RSSBindingImpl.java | 99 ++ ...pache.tuscany.sca.binding.rss.RSSBindingFactory | 19 + ...ca.contribution.processor.StAXArtifactProcessor | 19 + java/sca/contrib/modules/binding-sca-axis2/LICENSE | 205 +++ .../modules/binding-sca-axis2/META-INF/MANIFEST.MF | 35 + java/sca/contrib/modules/binding-sca-axis2/NOTICE | 6 + java/sca/contrib/modules/binding-sca-axis2/pom.xml | 83 + .../sca/axis2/impl/Axis2SCABindingInvoker.java | 100 ++ .../axis2/impl/Axis2SCABindingProviderFactory.java | 67 + .../impl/Axis2SCAReferenceBindingProvider.java | 184 +++ .../axis2/impl/Axis2SCAServiceBindingProvider.java | 122 ++ .../sca/axis2/impl/Axis2SCAServiceProvider.java | 84 ++ ...che.tuscany.sca.provider.BindingProviderFactory | 19 + .../sca/binding/sca/axis2/AsynchTestCase.java | 80 + .../BindingScaEndpointResolverFactoryImpl.java | 50 + .../sca/axis2/BindingScaEndpointResolverImpl.java | 69 + .../sca/binding/sca/axis2/CallbackTestCase.java | 84 ++ .../sca/binding/sca/axis2/PromotionTestCase.java | 73 + .../sca/binding/sca/axis2/SimpleTestCase.java | 112 ++ .../axis2/helloworld/HelloWorldCallbackRemote.java | 29 + .../sca/axis2/helloworld/HelloWorldClient.java | 27 + .../HelloWorldServiceCallbackOnewayRemote.java | 33 + .../HelloWorldServiceCallbackRemote.java | 31 + .../axis2/helloworld/HelloWorldServiceLocal.java | 27 + .../axis2/helloworld/HelloWorldServiceRemote.java | 29 + .../axis2/helloworld/HelloWorldServiceRemote2.java | 29 + .../HelloWorldClientCallbackOnewayRemoteImpl.java | 43 + .../impl/HelloWorldClientCallbackRemoteImpl.java | 42 + .../helloworld/impl/HelloWorldClientLocalImpl.java | 35 + .../impl/HelloWorldClientRemote2Impl.java | 35 + .../impl/HelloWorldClientRemoteImpl.java | 35 + .../HelloWorldServiceCallbackOnewayRemoteImpl.java | 36 + .../impl/HelloWorldServiceCallbackRemoteImpl.java | 35 + .../impl/HelloWorldServiceLocalImpl.java | 30 + .../HelloWorldServiceMultipleServicesImpl.java | 41 + .../impl/HelloWorldServiceRemoteImpl.java | 30 + ...ny.sca.endpointresolver.EndpointResolverFactory | 19 + .../src/test/resources/nodeA/HelloWorld.composite | 75 + .../resources/nodeA/META-INF/sca-contribution.xml | 24 + .../src/test/resources/nodeB/HelloWorld.composite | 84 ++ .../resources/nodeB/META-INF/sca-contribution.xml | 24 + .../src/test/resources/nodeC/HelloWorld.composite | 35 + .../resources/nodeC/HelloWorldComponent.composite | 37 + .../resources/nodeC/META-INF/sca-contribution.xml | 24 + .../src/test/resources/nodeD/HelloWorld.composite | 35 + .../resources/nodeD/HelloWorldComponent.composite | 37 + .../resources/nodeD/META-INF/sca-contribution.xml | 24 + .../src/test/resources/nodeE/HelloWorld.composite | 36 + .../resources/nodeE/META-INF/sca-contribution.xml | 24 + .../src/test/resources/nodeF/HelloWorld.composite | 43 + .../resources/nodeF/META-INF/sca-contribution.xml | 24 + .../src/test/resources/nodeG/HelloWorld.composite | 36 + .../resources/nodeG/META-INF/sca-contribution.xml | 24 + .../src/test/resources/nodeH/HelloWorld.composite | 38 + .../resources/nodeH/META-INF/sca-contribution.xml | 24 + java/sca/contrib/modules/binding-sca-corba/LICENSE | 205 +++ .../modules/binding-sca-corba/META-INF/MANIFEST.MF | 39 + java/sca/contrib/modules/binding-sca-corba/NOTICE | 6 + java/sca/contrib/modules/binding-sca-corba/pom.xml | 88 ++ .../corba/impl/CorbaSCABindingProviderFactory.java | 64 + .../sca/corba/impl/CorbaSCAInvocationProxy.java | 111 ++ .../binding/sca/corba/impl/CorbaSCAInvoker.java | 97 ++ .../impl/CorbaSCAReferenceBindingProvider.java | 95 ++ .../corba/impl/CorbaSCAServiceBindingProvider.java | 97 ++ .../sca/corba/impl/WrappedSCAException.java | 56 + ...che.tuscany.sca.provider.BindingProviderFactory | 19 + .../modules/common-xml/META-INF/MANIFEST.MF | 29 + java/sca/contrib/modules/common-xml/pom.xml | 66 + .../tuscany/sca/common/xml/SimpleTypeMapper.java | 210 +++ .../sca/common/xml/XSDDataTypeConverter.java | 945 ++++++++++++ .../tuscany/sca/common/xml/dom/DOMHelper.java | 115 ++ .../tuscany/sca/common/xml/dom/SAX2DOMAdapter.java | 245 +++ .../sca/common/xml/stax/DOMXMLStreamReader.java | 36 + .../sca/common/xml/stax/DOMXmlNodeImpl.java | 156 ++ .../xml/stax/DelegatingNamespaceContext.java | 310 ++++ .../xml/stax/NameValueArrayStreamReader.java | 404 +++++ .../common/xml/stax/NameValuePairStreamReader.java | 348 +++++ .../tuscany/sca/common/xml/stax/NamedProperty.java | 59 + .../common/xml/stax/NilElementStreamReader.java | 279 ++++ .../sca/common/xml/stax/SimpleXmlNodeImpl.java | 112 ++ .../sca/common/xml/stax/StAX2SAXAdapter.java | 256 ++++ .../tuscany/sca/common/xml/stax/StAXHelper.java | 87 ++ .../common/xml/stax/WrappingXMLStreamReader.java | 100 ++ .../common/xml/stax/XMLDocumentStreamReader.java | 482 ++++++ .../common/xml/stax/XMLFragmentStreamReader.java | 53 + .../xml/stax/XMLFragmentStreamReaderImpl.java | 858 +++++++++++ .../sca/common/xml/stax/XMLStreamSerializer.java | 287 ++++ .../tuscany/sca/common/xml/stax/XMLStreamable.java | 37 + .../tuscany/sca/common/xml/stax/XmlNode.java | 69 + .../sca/common/xml/stax/XmlNodeIterator.java | 355 +++++ .../common/xml/stax/XmlTreeStreamReaderImpl.java | 531 +++++++ .../sca/common/xml/stax/StAXHelperTestCase.java | 49 + .../xml/stax/XmlTreeStreamReaderTestCase.java | 204 +++ .../modules/compact-base/META-INF/MANIFEST.MF | 15 + java/sca/contrib/modules/compact-base/pom.xml | 527 +++++++ java/sca/contrib/modules/contribution-osgi/LICENSE | 205 +++ java/sca/contrib/modules/contribution-osgi/NOTICE | 6 + java/sca/contrib/modules/contribution-osgi/pom.xml | 78 + .../sca/contribution/osgi/BundleReference.java | 161 ++ .../osgi/impl/OSGiBundleContributionProcessor.java | 161 ++ .../osgi/impl/OSGiBundleProcessor.java | 141 ++ .../impl/OSGiBundleReferenceModelResolver.java | 154 ++ .../osgi/impl/OSGiClassReferenceModelResolver.java | 137 ++ .../osgi/impl/OSGiImportExportListener.java | 215 +++ .../osgi/impl/OSGiModelResolverImpl.java | 119 ++ ...any.sca.contribution.processor.PackageProcessor | 18 + ...tuscany.sca.contribution.resolver.ModelResolver | 18 + ...y.sca.contribution.service.ContributionListener | 18 + .../contribution-resource/META-INF/MANIFEST.MF | 26 + .../contrib/modules/contribution-resource/pom.xml | 58 + .../sca/contribution/resource/ResourceExport.java | 46 + .../sca/contribution/resource/ResourceImport.java | 59 + .../resource/ResourceImportExportFactory.java | 42 + .../resource/impl/ArtifactModelResolver.java | 86 ++ .../resource/impl/ResourceExportImpl.java | 58 + .../resource/impl/ResourceExportModelResolver.java | 65 + .../resource/impl/ResourceExportProcessor.java | 161 ++ .../impl/ResourceImportExportFactoryImpl.java | 41 + .../resource/impl/ResourceImportImpl.java | 107 ++ .../resource/impl/ResourceImportProcessor.java | 167 ++ ...ca.contribution.processor.StAXArtifactProcessor | 19 + ...tuscany.sca.contribution.resolver.ModelResolver | 18 + ...ntribution.resource.ResourceImportExportFactory | 18 + ...ibution-resource-validation-messages.properties | 23 + .../impl/ResourceExportProcessorTestCase.java | 106 ++ .../impl/ResourceImportProcessorTestCase.java | 107 ++ java/sca/contrib/modules/data-api/LICENSE | 205 +++ .../contrib/modules/data-api/META-INF/MANIFEST.MF | 17 + java/sca/contrib/modules/data-api/NOTICE | 6 + java/sca/contrib/modules/data-api/pom.xml | 39 + .../tuscany/sca/data/collection/Collection.java | 78 + .../apache/tuscany/sca/data/collection/Entry.java | 85 ++ .../apache/tuscany/sca/data/collection/Item.java | 159 ++ .../sca/data/collection/ItemCollection.java | 30 + .../sca/data/collection/LocalItemCollection.java | 28 + .../sca/data/collection/NotFoundException.java | 45 + .../modules/databinding-fastinfoset/LICENSE | 202 +++ .../databinding-fastinfoset/META-INF/MANIFEST.MF | 28 + .../contrib/modules/databinding-fastinfoset/NOTICE | 6 + .../modules/databinding-fastinfoset/pom.xml | 70 + .../databinding/fastinfoset/FastInfoset2Node.java | 70 + .../databinding/fastinfoset/FastInfoset2SAX.java | 71 + .../fastinfoset/FastInfoset2XMLStreamReader.java | 67 + .../databinding/fastinfoset/Node2FastInfoset.java | 71 + .../fastinfoset/XMLInputStream2FastInfoset.java | 89 ++ .../fastinfoset/XMLStreamReader2FastInfoset.java | 75 + ....apache.tuscany.sca.databinding.PullTransformer | 22 + ....apache.tuscany.sca.databinding.PushTransformer | 22 + .../FastInfosetTransformerTestCase.java | 127 ++ .../src/test/resources/ipo.xsd | 136 ++ java/sca/contrib/modules/databinding-json/LICENSE | 202 +++ .../modules/databinding-json/META-INF/MANIFEST.MF | 34 + java/sca/contrib/modules/databinding-json/NOTICE | 6 + java/sca/contrib/modules/databinding-json/pom.xml | 118 ++ .../sca/databinding/json/JSON2JavaBean.java | 73 + .../tuscany/sca/databinding/json/JSON2String.java | 61 + .../sca/databinding/json/JSON2XMLStreamReader.java | 65 + .../sca/databinding/json/JSONDataBinding.java | 74 + .../tuscany/sca/databinding/json/JSONHelper.java | 91 ++ .../sca/databinding/json/JavaBean2JSON.java | 82 + .../sca/databinding/json/JavaBean2JSONObject.java | 139 ++ .../tuscany/sca/databinding/json/String2JSON.java | 64 + .../sca/databinding/json/XMLStreamReader2JSON.java | 77 + .../sca/databinding/json/axiom/JSON2OMElement.java | 94 ++ .../json/axiom/JSONBadgerfishDataSource.java | 57 + .../sca/databinding/json/axiom/JSONDataSource.java | 176 +++ .../org.apache.tuscany.sca.databinding.DataBinding | 19 + ....apache.tuscany.sca.databinding.PullTransformer | 31 + .../databinding/json/JSONTransformerTestCase.java | 128 ++ .../databinding/json/JavaBean2JSONTestCase.java | 170 +++ .../tuscany/sca/databinding/json/MyBean.java | 158 ++ .../tuscany/sca/databinding/json/MyInterface.java | 29 + .../sca/databinding/json/MyInterfaceImpl.java | 67 + .../tuscany/sca/databinding/json/POJOTestCase.java | 87 ++ .../databinding-json/src/test/resources/ipo.xsd | 136 ++ java/sca/contrib/modules/databinding-saxon/LICENSE | 202 +++ .../modules/databinding-saxon/META-INF/MANIFEST.MF | 38 + java/sca/contrib/modules/databinding-saxon/NOTICE | 6 + java/sca/contrib/modules/databinding-saxon/pom.xml | 106 ++ .../saxon/DataObject2NodeInfoTransformer.java | 99 ++ .../saxon/ItemList2ObjectTransformer.java | 153 ++ .../saxon/Node2NodeInfoTransformer.java | 77 + .../saxon/NodeInfo2DataObjectTransformer.java | 91 ++ .../saxon/NodeInfo2JavaArrayTransformer.java | 76 + .../saxon/NodeInfo2NodeTransformer.java | 71 + .../databinding/saxon/Object2ValueTransformer.java | 65 + .../databinding/saxon/SaxonDataBindingHelper.java | 41 + .../databinding/saxon/SaxonNodeDataBinding.java | 54 + .../databinding/saxon/SaxonValueDataBinding.java | 53 + .../saxon/SimpleType2ValueTransformer.java | 87 ++ .../sca/databinding/saxon/Value2JavaArray.java | 74 + .../databinding/saxon/Value2ObjectTransformer.java | 66 + .../saxon/Value2SimpleTypeTransformer.java | 65 + .../sca/databinding/saxon/collection/ItemList.java | 34 + .../org.apache.tuscany.sca.databinding.DataBinding | 20 + ....apache.tuscany.sca.databinding.PullTransformer | 34 + .../contrib/modules/databinding-sdo-axiom/LICENSE | 205 +++ .../databinding-sdo-axiom/META-INF/MANIFEST.MF | 40 + .../contrib/modules/databinding-sdo-axiom/NOTICE | 6 + .../contrib/modules/databinding-sdo-axiom/pom.xml | 153 ++ .../sca/databinding/sdo2om/AxiomHelper.java | 142 ++ .../databinding/sdo2om/DataObject2OMElement.java | 86 ++ .../sca/databinding/sdo2om/SDODataSource.java | 89 ++ .../databinding/sdo2om/XMLDocument2OMElement.java | 65 + ....apache.tuscany.sca.databinding.PullTransformer | 20 + .../sdo2om/DataObject2OMElementTestCase.java | 78 + .../sdo2om/SDOTransformerTestCaseBase.java | 82 + .../sdo2om/XMLDocument2OMElementTestCase.java | 63 + .../src/test/resources/ipo.xsd | 136 ++ .../src/test/resources/stock.xsd | 33 + java/sca/contrib/modules/databinding-sdo/LICENSE | 205 +++ .../modules/databinding-sdo/META-INF/MANIFEST.MF | 66 + java/sca/contrib/modules/databinding-sdo/NOTICE | 6 + java/sca/contrib/modules/databinding-sdo/pom.xml | 119 ++ .../sca/databinding/sdo/DataObject2Node.java | 73 + .../sca/databinding/sdo/DataObject2String.java | 64 + .../sdo/DataObject2XMLStreamReader.java | 82 + .../tuscany/sca/databinding/sdo/ImportSDO.java | 87 ++ .../sca/databinding/sdo/ImportSDOProcessor.java | 211 +++ .../sca/databinding/sdo/Node2DataObject.java | 69 + .../sca/databinding/sdo/SDOContextHelper.java | 208 +++ .../sca/databinding/sdo/SDODataBinding.java | 146 ++ .../sca/databinding/sdo/SDOSimpleTypeMapper.java | 68 + .../tuscany/sca/databinding/sdo/SDOTypeHelper.java | 235 +++ .../sca/databinding/sdo/SDOWrapperHandler.java | 177 +++ .../sca/databinding/sdo/String2DataObject.java | 61 + .../sca/databinding/sdo/XMLDocument2String.java | 65 + .../sdo/XMLDocument2XMLStreamReader.java | 69 + .../sdo/XMLStreamReader2DataObject.java | 72 + .../sdo/XMLStreamReader2XMLDocument.java | 66 + ...ca.contribution.processor.StAXArtifactProcessor | 18 + .../org.apache.tuscany.sca.databinding.DataBinding | 19 + ....apache.tuscany.sca.databinding.PullTransformer | 27 + .../databinding-sdo-validation-messages.properties | 23 + .../sdo/fault/InvalidSymbolFault_Exception.java | 70 + .../databinding/sdo/DataObject2NodeTestCase.java | 60 + .../databinding/sdo/DataObject2StringTestCase.java | 65 + .../sdo/DataObject2XMLStreamReaderTestCase.java | 75 + .../sdo/ImportSDOProcessorTestCase.java | 90 ++ .../databinding/sdo/SDOContextHelperTestCase.java | 55 + .../databinding/sdo/SDODataBindingTestCase.java | 114 ++ .../sdo/SDOTransformerTestCaseBase.java | 82 + .../databinding/sdo/SDOWrapperHandlerTestCase.java | 83 + .../sca/databinding/sdo/TestModelResolver.java | 63 + .../sdo/XMLDocument2XMLStreamReaderTestCase.java | 62 + .../databinding-sdo/src/test/resources/ipo.xsd | 136 ++ .../src/test/resources/model/sca-core.xsd | 233 +++ .../resources/model/sca-implementation-mock.xsd | 43 + .../databinding-sdo/src/test/resources/stock.xsd | 33 + .../databinding-sdo/src/test/resources/wrapper.xml | 27 + .../databinding-sdo/src/test/resources/wrapper.xsd | 38 + .../contrib/modules/databinding-xmlbeans/LICENSE | 202 +++ .../databinding-xmlbeans/META-INF/MANIFEST.MF | 27 + .../contrib/modules/databinding-xmlbeans/NOTICE | 6 + .../contrib/modules/databinding-xmlbeans/pom.xml | 119 ++ .../sca/databinding/xmlbeans/Node2XmlObject.java | 61 + .../databinding/xmlbeans/XMLBeansDataBinding.java | 82 + .../xmlbeans/XMLBeansWrapperHandler.java | 110 ++ .../xmlbeans/XMLStreamReader2XmlObject.java | 62 + .../sca/databinding/xmlbeans/XmlObject2Node.java | 60 + .../xmlbeans/XmlObject2XMLStreamReader.java | 55 + .../org.apache.tuscany.sca.databinding.DataBinding | 19 + ....apache.tuscany.sca.databinding.PullTransformer | 22 + .../databinding/xmlbeans/XmlObjectTestCase.java | 105 ++ .../src/test/resources/ipo.xsd | 136 ++ .../src/test/resources/ipo.xsdconfig | 21 + java/sca/contrib/modules/domain-manager/LICENSE | 205 +++ .../modules/domain-manager/META-INF/MANIFEST.MF | 69 + java/sca/contrib/modules/domain-manager/NOTICE | 6 + java/sca/contrib/modules/domain-manager/pom.xml | 181 +++ .../impl/CompositeConfigurationCollectionImpl.java | 127 ++ .../impl/CompositeConfigurationServiceImpl.java | 515 +++++++ .../impl/CompositeGeneratorServiceImpl.java | 256 ++++ .../manager/impl/ContributionCollectionImpl.java | 687 +++++++++ .../manager/impl/ContributionServiceImpl.java | 77 + .../impl/DeployableCompositeCollectionImpl.java | 404 +++++ .../impl/DeployableCompositeServiceImpl.java | 128 ++ .../impl/DeployedCompositeCollectionImpl.java | 378 +++++ .../manager/impl/DomainManagerConfiguration.java | 53 + .../impl/DomainManagerConfigurationImpl.java | 85 ++ .../sca/domain/manager/impl/DomainManagerUtil.java | 296 ++++ .../domain/manager/impl/FileCollectionImpl.java | 136 ++ .../sca/domain/manager/impl/FileServiceImpl.java | 153 ++ .../manager/impl/NodeConfigurationServiceImpl.java | 96 ++ .../impl/NodeProcessCollectionFacadeImpl.java | 251 +++ .../domain/manager/impl/QuickStartServiceImpl.java | 236 +++ .../launcher/DomainManagerLauncherBootstrap.java | 121 ++ .../src/main/resources/DomainManager.composite | 281 ++++ .../src/main/resources/cloud-gadget.html | 408 +++++ .../domain-manager/src/main/resources/cloud.html | 68 + .../src/main/resources/composite-gadget.html | 277 ++++ .../src/main/resources/composite.html | 66 + .../src/main/resources/files-gadget.html | 124 ++ .../domain-manager/src/main/resources/files.html | 64 + .../src/main/resources/home-gadget.html | 45 + .../domain-manager/src/main/resources/home.html | 65 + .../src/main/resources/icons/feed-icon.png | Bin 0 -> 818 bytes .../domain-manager/src/main/resources/manager.css | 104 ++ .../src/main/resources/toolbar-gadget.html | 47 + .../domain-manager/src/main/resources/utils.js | 246 +++ .../src/main/resources/workspace-gadget.html | 232 +++ .../src/main/resources/workspace.html | 65 + .../domain/manager/impl/DomainManagerTestCase.java | 117 ++ .../assets/META-INF/sca-contribution.xml | 27 + .../store/META-INF/sca-contribution.xml | 25 + .../src/test/resources/workspace.xml | 21 + java/sca/contrib/modules/host-corba-jee/LICENSE | 205 +++ .../modules/host-corba-jee/META-INF/MANIFEST.MF | 23 + java/sca/contrib/modules/host-corba-jee/NOTICE | 6 + java/sca/contrib/modules/host-corba-jee/pom.xml | 44 + .../corba/jee/CorbaRuntimeModuleActivator.java | 52 + .../tuscany/sca/host/corba/jee/JEECorbaHost.java | 162 ++ .../org.apache.tuscany.sca.core.ModuleActivator | 18 + .../corba/jee/testing/JEECorbaHostTestCase.java | 208 +++ .../sca/host/corba/jee/testing/TestContext.java | 174 +++ .../jee/testing/TestInitialContextFactory.java | 37 + .../corba/jee/testing/general/TestInterface.java | 30 + .../jee/testing/general/TestInterfaceHelper.java | 100 ++ .../jee/testing/general/TestInterfaceHolder.java | 51 + .../testing/general/TestInterfaceOperations.java | 31 + .../testing/general/_TestInterfaceImplBase.java | 74 + .../jee/testing/general/_TestInterfaceStub.java | 73 + .../jee/testing/servants/TestInterfaceServant.java | 35 + .../host-corba-jee/src/test/resources/general.idl | 45 + .../sca/contrib/modules/host-corba-jse-tns/LICENSE | 205 +++ .../host-corba-jse-tns/META-INF/MANIFEST.MF | 21 + java/sca/contrib/modules/host-corba-jse-tns/NOTICE | 6 + .../sca/contrib/modules/host-corba-jse-tns/pom.xml | 53 + .../corba/jse/tns/CorbaRuntimeModuleActivator.java | 53 + .../host/corba/jse/tns/TnsDefaultCorbaHost.java | 116 ++ .../org.apache.tuscany.sca.core.ModuleActivator | 18 + .../corba/testing/TnsDefaultCorbaHostTestCase.java | 97 ++ java/sca/contrib/modules/host-corba-jse/LICENSE | 205 +++ .../modules/host-corba-jse/META-INF/MANIFEST.MF | 26 + java/sca/contrib/modules/host-corba-jse/NOTICE | 6 + java/sca/contrib/modules/host-corba-jse/pom.xml | 38 + .../corba/jse/CorbaRuntimeModuleActivator.java | 48 + .../sca/host/corba/jse/DefaultCorbaHost.java | 181 +++ .../sca/host/corba/naming/NamingContextBase.java | 863 +++++++++++ .../sca/host/corba/naming/TransientNameServer.java | 133 ++ .../host/corba/naming/TransientNameService.java | 200 +++ .../host/corba/naming/TransientNamingContext.java | 440 ++++++ .../corba/naming/TransientServiceException.java | 44 + .../org.apache.tuscany.sca.core.ModuleActivator | 18 + .../corba/testing/DefaultCorbaHostTestCase.java | 250 +++ .../host/corba/testing/general/TestInterface.java | 30 + .../corba/testing/general/TestInterfaceHelper.java | 98 ++ .../corba/testing/general/TestInterfaceHolder.java | 51 + .../testing/general/TestInterfaceOperations.java | 31 + .../testing/general/_TestInterfaceImplBase.java | 74 + .../corba/testing/general/_TestInterfaceStub.java | 73 + .../testing/servants/TestInterfaceServant.java | 35 + .../host-corba-jse/src/test/resources/general.idl | 43 + java/sca/contrib/modules/host-corba/LICENSE | 205 +++ .../modules/host-corba/META-INF/MANIFEST.MF | 17 + java/sca/contrib/modules/host-corba/NOTICE | 6 + java/sca/contrib/modules/host-corba/pom.xml | 38 + .../apache/tuscany/sca/host/corba/CorbaHost.java | 56 + .../tuscany/sca/host/corba/CorbaHostException.java | 47 + .../sca/host/corba/CorbaHostExtensionPoint.java | 51 + .../tuscany/sca/host/corba/CorbaHostUtils.java | 61 + .../tuscany/sca/host/corba/CorbanameURL.java | 202 +++ .../host/corba/DefaultCorbaHostExtensionPoint.java | 48 + .../sca/host/corba/ExtensibleCorbaHost.java | 55 + .../apache/tuscany/sca/host/corba/SocketUtil.java | 226 +++ ....tuscany.sca.host.corba.CorbaHostExtensionPoint | 18 + .../tuscany/sca/host/corba/UtilsTestCase.java | 145 ++ java/sca/contrib/modules/host-tomcat/LICENSE | 205 +++ .../modules/host-tomcat/META-INF/MANIFEST.MF | 23 + java/sca/contrib/modules/host-tomcat/NOTICE | 6 + java/sca/contrib/modules/host-tomcat/pom.xml | 69 + .../tuscany/sca/http/tomcat/ServletWrapper.java | 58 + .../sca/http/tomcat/TomcatDefaultServlet.java | 114 ++ .../tuscany/sca/http/tomcat/TomcatServer.java | 653 ++++++++ .../module/TomcatRuntimeModuleActivator.java | 69 + .../org.apache.tuscany.sca.core.ModuleActivator | 18 + .../sca/http/tomcat/TomcatServerTestCase.java | 353 +++++ .../src/test/resources/content/test.html | 21 + .../src/test/resources/tuscany.keyStore | Bin 0 -> 1265 bytes java/sca/contrib/modules/host-webapp-junit/LICENSE | 205 +++ .../modules/host-webapp-junit/META-INF/MANIFEST.MF | 19 + java/sca/contrib/modules/host-webapp-junit/NOTICE | 6 + java/sca/contrib/modules/host-webapp-junit/pom.xml | 48 + .../sca/host/webapp/junit/JUnitServletFilter.java | 355 +++++ .../sca/host/webapp/junit/XMLFormatter.java | 286 ++++ .../modules/implementation-bpel-ode/LICENSE | 251 +++ .../implementation-bpel-ode/META-INF/MANIFEST.MF | 47 + .../contrib/modules/implementation-bpel-ode/NOTICE | 17 + .../modules/implementation-bpel-ode/pom.xml | 415 +++++ .../implementation/bpel/ode/BPELODEDeployFile.java | 225 +++ .../implementation/bpel/ode/EmbeddedODEServer.java | 261 ++++ .../implementation/bpel/ode/GeronimoTxFactory.java | 48 + .../implementation/bpel/ode/ODEBindingContext.java | 79 + .../sca/implementation/bpel/ode/ODEDeployment.java | 44 + .../bpel/ode/ODEDeploymentException.java | 41 + .../bpel/ode/ODEExternalService.java | 285 ++++ .../bpel/ode/ODEInitializationException.java | 41 + .../bpel/ode/ODEMessageExchangeContext.java | 57 + .../bpel/ode/ODEShutdownException.java | 41 + .../sca/implementation/bpel/ode/TuscanyEPR.java | 54 + .../sca/implementation/bpel/ode/TuscanyPRC.java | 71 + .../bpel/ode/TuscanyProcessConfImpl.java | 433 ++++++ .../ode/provider/BPELImplementationProvider.java | 145 ++ .../BPELImplementationProviderFactory.java | 69 + .../bpel/ode/provider/BPELInvoker.java | 251 +++ ...cany.sca.provider.ImplementationProviderFactory | 19 + .../bpel/ode/EmbeddedODEServerTestCase.java | 124 ++ .../src/test/resources/helloworld/deploy.xml | 30 + .../src/test/resources/helloworld/greetings.wsdl | 87 ++ .../src/test/resources/helloworld/helloworld.bpel | 66 + .../src/test/resources/helloworld/helloworld.wsdl | 82 + .../src/test/resources/log4j.properties | 36 + .../contrib/modules/implementation-bpel/LICENSE | 251 +++ .../implementation-bpel/META-INF/MANIFEST.MF | 33 + .../sca/contrib/modules/implementation-bpel/NOTICE | 17 + .../contrib/modules/implementation-bpel/pom.xml | 82 + .../sca/implementation/bpel/BPELFactory.java | 42 + .../implementation/bpel/BPELImplementation.java | 91 ++ .../implementation/bpel/BPELProcessDefinition.java | 109 ++ .../implementation/bpel/impl/BPELFactoryImpl.java | 45 + .../bpel/impl/BPELImplementationImpl.java | 132 ++ .../bpel/impl/BPELProcessDefinitionImpl.java | 116 ++ .../bpel/xml/BPELDocumentProcessor.java | 532 +++++++ .../bpel/xml/BPELImplementationProcessor.java | 516 +++++++ .../implementation/bpel/xml/BPELImportElement.java | 65 + .../bpel/xml/BPELPartnerLinkElement.java | 130 ++ .../bpel/xml/BPELPartnerLinkTypeElement.java | 112 ++ ...ca.contribution.processor.StAXArtifactProcessor | 19 + ...sca.contribution.processor.URLArtifactProcessor | 19 + ...che.tuscany.sca.implementation.bpel.BPELFactory | 18 + .../impl-bpel-validation-messages.properties | 34 + .../bpel/BPELDocumentProcessorTestCase.java | 59 + .../bpel/BPELImplementationProcessorTestCase.java | 107 ++ .../src/test/resources/helloworld/helloworld.bpel | 66 + .../src/test/resources/helloworld/helloworld.wsdl | 82 + .../sca/contrib/modules/implementation-ejb/LICENSE | 205 +++ .../implementation-ejb/META-INF/MANIFEST.MF | 29 + java/sca/contrib/modules/implementation-ejb/NOTICE | 6 + .../sca/contrib/modules/implementation-ejb/pom.xml | 62 + .../sca/implementation/ejb/EJBImplementation.java | 44 + .../ejb/EJBImplementationFactory.java | 36 + .../ejb/impl/EJBImplementationFactoryImpl.java | 39 + .../ejb/impl/EJBImplementationImpl.java | 95 ++ .../ejb/xml/EJBImplementationProcessor.java | 147 ++ ...ca.contribution.processor.StAXArtifactProcessor | 19 + ...sca.implementation.ejb.EJBImplementationFactory | 19 + .../impl-ejb-validation-messages.properties | 21 + .../sca/implementation/ejb/xml/ReadTestCase.java | 71 + .../sca/implementation/ejb/xml/WriteTestCase.java | 68 + .../sca/implementation/ejb/xml/TestEJB.composite | 29 + .../contrib/modules/implementation-osgi/LICENSE | 203 +++ .../sca/contrib/modules/implementation-osgi/NOTICE | 6 + .../contrib/modules/implementation-osgi/pom.xml | 145 ++ .../implementation/osgi/OSGiImplementation.java | 45 + .../osgi/context/OSGiAnnotations.java | 325 ++++ .../osgi/context/OSGiPropertyInjector.java | 293 ++++ .../context/OSGiPropertyValueObjectFactory.java | 226 +++ .../osgi/impl/OSGiImplementationImpl.java | 168 +++ .../osgi/runtime/OSGiImplementationProvider.java | 1254 +++++++++++++++ .../runtime/OSGiImplementationProviderFactory.java | 111 ++ .../osgi/runtime/OSGiInstanceWrapper.java | 299 ++++ .../osgi/runtime/OSGiRemotableInvoker.java | 139 ++ .../osgi/runtime/OSGiTargetInvoker.java | 199 +++ .../osgi/xml/OSGiImplementationProcessor.java | 550 +++++++ ...ca.contribution.processor.StAXArtifactProcessor | 19 + ...cany.sca.provider.ImplementationProviderFactory | 19 + .../impl-osgi-validation-messages.properties | 25 + .../osgi/runtime/OSGiPropertyTestCase.java | 49 + .../implementation/osgi/runtime/OSGiTestCase.java | 74 + .../implementation/osgi/test/OSGiTestBundles.java | 116 ++ .../sca/implementation/osgi/test/OSGiTestImpl.java | 51 + .../osgi/test/OSGiTestInterface.java | 32 + .../osgi/test/OSGiTestWithPropertyImpl.java | 66 + .../osgi/xml/OSGiReadImplTestCase.java | 132 ++ .../implementation/osgi/xml/TestModelResolver.java | 106 ++ .../test/resources/OSGiTestService.componentType | 28 + .../src/test/resources/osgiproptest.composite | 37 + .../src/test/resources/osgitest.composite | 36 + .../contrib/modules/implementation-pojo/LICENSE | 205 +++ .../implementation-pojo/META-INF/MANIFEST.MF | 30 + .../sca/contrib/modules/implementation-pojo/NOTICE | 6 + .../contrib/modules/implementation-pojo/pom.xml | 68 + .../apache/tuscany/sca/pojo/JavaConstructor.java | 42 + .../org/apache/tuscany/sca/pojo/JavaElement.java | 92 ++ .../org/apache/tuscany/sca/pojo/JavaFactory.java | 82 + .../org/apache/tuscany/sca/pojo/JavaParameter.java | 29 + .../org/apache/tuscany/sca/pojo/JavaResource.java | 65 + .../tuscany/sca/pojo/impl/JavaConstructorImpl.java | 54 + .../tuscany/sca/pojo/impl/JavaElementImpl.java | 194 +++ .../tuscany/sca/pojo/impl/JavaFactoryImpl.java | 74 + .../tuscany/sca/pojo/impl/JavaParameterImpl.java | 37 + .../tuscany/sca/pojo/impl/JavaResourceImpl.java | 63 + .../org.apache.tuscany.sca.pojo.JavaFactory | 20 + .../implementation-resource-runtime/LICENSE | 205 +++ .../META-INF/MANIFEST.MF | 25 + .../modules/implementation-resource-runtime/NOTICE | 6 + .../implementation-resource-runtime/pom.xml | 67 + .../resource/provider/GetResourceInvoker.java | 67 + .../provider/ResourceImplementationProvider.java | 75 + .../ResourceImplementationProviderFactory.java | 47 + ...cany.sca.provider.ImplementationProviderFactory | 19 + .../resource/ResourceImplementationTestCase.java | 83 + .../src/test/resources/content/test.html | 21 + .../src/test/resources/resource.composite | 30 + .../modules/implementation-resource/LICENSE | 205 +++ .../implementation-resource/META-INF/MANIFEST.MF | 31 + .../contrib/modules/implementation-resource/NOTICE | 6 + .../modules/implementation-resource/pom.xml | 60 + .../sca/implementation/resource/Resource.java | 34 + .../resource/ResourceImplementation.java | 57 + .../resource/ResourceImplementationFactory.java | 35 + .../impl/ResourceImplementationFactoryImpl.java | 47 + .../resource/impl/ResourceImplementationImpl.java | 130 ++ .../impl/ResourceImplementationProcessor.java | 166 ++ ...ca.contribution.processor.StAXArtifactProcessor | 19 + ...entation.resource.ResourceImplementationFactory | 19 + .../impl-resource-validation-messages.properties | 23 + .../modules/implementation-script-runtime/LICENSE | 251 +++ .../META-INF/MANIFEST.MF | 58 + .../modules/implementation-script-runtime/NOTICE | 12 + .../modules/implementation-script-runtime/pom.xml | 183 +++ .../script/engines/TuscanyJRubyScriptEngine.java | 697 +++++++++ .../provider/ScriptImplementationProvider.java | 176 +++ .../ScriptImplementationProviderFactory.java | 55 + .../script/provider/ScriptInvoker.java | 84 ++ .../script/provider/ScriptPropertyFactory.java | 225 +++ ...cany.sca.provider.ImplementationProviderFactory | 19 + .../script/itests/AbstractSCATestCase.java | 60 + .../helloworld/AbstractHelloWorldTestCase.java | 38 + .../helloworld/GroovyHelloWorldTestCase.java | 29 + .../script/itests/helloworld/HelloWorld.java | 30 + .../script/itests/helloworld/HelloWorldProxy.java | 37 + .../itests/helloworld/JRubyHelloWorldTestCase.java | 29 + .../helloworld/JavaScriptHelloWorldTestCase.java | 29 + .../helloworld/JythonHelloWorldTestCase.java | 29 + .../properties/AbstractHelloWorldTestCase.java | 38 + .../properties/GroovyHelloWorldTestCase.java | 29 + .../script/itests/properties/HelloWorld.java | 30 + .../script/itests/properties/HelloWorldProxy.java | 37 + .../itests/properties/JRubyHelloWorldTestCase.java | 28 + .../properties/JavaScriptHelloWorldTestCase.java | 29 + .../properties/JythonHelloWorldTestCase.java | 29 + .../itests/references/GroovyReferenceTestCase.java | 29 + .../script/itests/references/HelloWorldTarget.java | 34 + .../itests/references/JRubyReferenceTestCase.java | 29 + .../references/JavaScriptReferenceTestCase.java | 29 + .../itests/references/JythonReferenceTestCase.java | 29 + .../itests/helloworld/GroovyHelloWorld.composite | 33 + .../itests/helloworld/JRubyHelloWorld.composite | 33 + .../helloworld/JavaScriptHelloWorld.composite | 33 + .../itests/helloworld/JythonHelloWorld.composite | 33 + .../itests/helloworld/helloworld.componentType | 30 + .../script/itests/helloworld/helloworld.groovy | 22 + .../script/itests/helloworld/helloworld.js | 23 + .../script/itests/helloworld/helloworld.py | 20 + .../script/itests/helloworld/helloworld.rb | 21 + .../itests/properties/GroovyHelloWorld.composite | 33 + .../itests/properties/JRubyHelloWorld.composite | 33 + .../properties/JavaScriptHelloWorld.composite | 33 + .../itests/properties/JythonHelloWorld.composite | 33 + .../itests/properties/helloworld.componentType | 32 + .../script/itests/properties/helloworld.groovy | 22 + .../script/itests/properties/helloworld.js | 23 + .../script/itests/properties/helloworld.py | 20 + .../script/itests/properties/helloworld.rb | 21 + .../itests/references/GroovyReference.composite | 38 + .../itests/references/JRubyReference.composite | 38 + .../references/JavaScriptReference.composite | 38 + .../itests/references/JythonReference.composite | 38 + .../itests/references/reference.componentType | 31 + .../script/itests/references/reference.groovy | 22 + .../script/itests/references/reference.js | 22 + .../script/itests/references/reference.py | 20 + .../script/itests/references/reference.rb | 21 + .../contrib/modules/implementation-script/LICENSE | 251 +++ .../implementation-script/META-INF/MANIFEST.MF | 28 + .../contrib/modules/implementation-script/NOTICE | 12 + .../contrib/modules/implementation-script/pom.xml | 48 + .../script/ScriptImplementation.java | 113 ++ .../script/ScriptImplementationProcessor.java | 163 ++ ...ca.contribution.processor.StAXArtifactProcessor | 19 + .../modules/implementation-spring-runtime/LICENSE | 205 +++ .../META-INF/MANIFEST.MF | 54 + .../modules/implementation-spring-runtime/NOTICE | 6 + .../modules/implementation-spring-runtime/pom.xml | 113 ++ .../spring/impl/SCAApplicationContext.java | 53 + .../spring/impl/SCANamespaceHandlerResolver.java | 53 + .../spring/impl/SCAParentApplicationContext.java | 272 ++++ .../spring/impl/ScaNamespaceHandler.java | 40 + .../impl/ScaPropertyBeanDefinitionParser.java | 37 + .../impl/ScaReferenceBeanDefinitionParser.java | 38 + .../impl/ScaServiceBeanDefinitionParser.java | 38 + .../provider/SpringImplementationProvider.java | 90 ++ .../SpringImplementationProviderFactory.java | 79 + .../spring/provider/SpringInvocationException.java | 40 + .../spring/provider/SpringInvoker.java | 128 ++ ...cany.sca.provider.ImplementationProviderFactory | 19 + .../spring/itests/AbstractSCATestCase.java | 61 + .../helloworld/AbstractHelloWorldTestCase.java | 43 + .../spring/itests/helloworld/HelloWorld.java | 35 + .../spring/itests/helloworld/HelloWorldImpl.java | 38 + .../spring/itests/helloworld/HelloWorldProxy.java | 42 + .../helloworld/SpringContextAccessTestCase.java | 35 + .../SpringExplicitHelloWorldTestCase.java | 34 + .../SpringExplicitReferenceTestCase.java | 39 + .../helloworld/SpringHelloWorldTestCase.java | 32 + .../SpringImplicitReferenceTestCase.java | 42 + .../helloworld/SpringImportHelloWorldTestCase.java | 32 + .../helloworld/SpringSCAPropertyTestCase.java | 39 + .../spring/itests/mock/TestBean.java | 31 + .../spring/itests/mock/TestBeanImpl.java | 42 + .../spring/itests/mock/TestContextAccessBean.java | 77 + .../spring/itests/mock/TestHelloWorldBean.java | 39 + .../spring/itests/mock/TestReference.java | 27 + .../spring/itests/mock/TestReferenceBean.java | 57 + .../spring/itests/mock/TestSCAPropertyBean.java | 55 + .../META-INF/sca/SpringContextAccess-context.xml | 31 + .../sca/SpringExplicitHelloWorld-context.xml | 39 + .../sca/SpringExplicitReference-context.xml | 33 + .../sca/SpringHelloWorld-Imported-context.xml | 31 + .../META-INF/sca/SpringHelloWorld-context.xml | 31 + .../sca/SpringImplicitReference-context.xml | 34 + .../sca/SpringImportHelloWorld-context.xml | 29 + .../META-INF/sca/testReferenceContext.xml | 33 + .../resources/META-INF/sca/testServiceContext.xml | 31 + .../SpringHelloWorld-Imported-context.xml | 31 + .../helloworld/SpringContextAccess.composite | 35 + .../helloworld/SpringExplicitHelloWorld.composite | 33 + .../helloworld/SpringExplicitReference.composite | 32 + .../itests/helloworld/SpringHelloWorld.composite | 32 + .../helloworld/SpringImplicitReference.composite | 39 + .../helloworld/SpringImportHelloWorld.composite | 32 + .../itests/helloworld/SpringSCAProperty.composite | 39 + .../src/test/resources/spring/META-INF/MANIFEST.MF | 3 + .../META-INF/spring/SpringSCAProperty-context.xml | 34 + .../src/test/resources/test.xml | 27 + .../contrib/modules/implementation-spring/LICENSE | 205 +++ .../implementation-spring/META-INF/MANIFEST.MF | 83 + .../contrib/modules/implementation-spring/NOTICE | 6 + .../contrib/modules/implementation-spring/pom.xml | 107 ++ .../spring/SpringBeanNotFoundException.java | 39 + .../spring/SpringImplementation.java | 187 +++ .../spring/SpringImplementationProcessor.java | 232 +++ .../ComponentNameAnnotationProcessor.java | 151 ++ .../processor/ConstructorAnnotationProcessor.java | 119 ++ .../processor/InitDestroyAnnotationProcessor.java | 72 + .../processor/PropertyAnnotationProcessor.java | 220 +++ .../processor/ReferenceAnnotationProcessor.java | 186 +++ .../sca/implementation/spring/xml/Constants.java | 64 + .../spring/xml/SpringBeanElement.java | 67 + .../spring/xml/SpringBeanIntrospector.java | 108 ++ .../spring/xml/SpringConstructorArgElement.java | 60 + .../spring/xml/SpringPropertyElement.java | 61 + .../spring/xml/SpringSCAPropertyElement.java | 52 + .../spring/xml/SpringSCAReferenceElement.java | 54 + .../spring/xml/SpringSCAServiceElement.java | 64 + .../spring/xml/SpringXMLComponentTypeLoader.java | 637 ++++++++ ...ca.contribution.processor.StAXArtifactProcessor | 19 + .../src/main/resources/META-INF/spring.handlers | 1 + .../src/main/resources/META-INF/spring.schemas | 1 + .../impl-spring-validation-messages.properties | 23 + .../org/springframework/sca/xml/spring-sca.xsd | 99 ++ .../modules/implementation-widget-runtime/LICENSE | 205 +++ .../META-INF/MANIFEST.MF | 27 + .../modules/implementation-widget-runtime/NOTICE | 6 + .../modules/implementation-widget-runtime/pom.xml | 102 ++ .../provider/WidgetImplementationInvoker.java | 253 ++++ .../provider/WidgetImplementationProvider.java | 67 + .../WidgetImplementationProviderFactory.java | 47 + .../widget/provider/WidgetProxyHelper.java | 51 + ...cany.sca.provider.ImplementationProviderFactory | 19 + .../src/main/resources/atomModel.js | 1590 ++++++++++++++++++++ .../src/main/resources/binding-atom.js | 137 ++ .../src/main/resources/binding-http.js | 105 ++ .../src/main/resources/binding-jsonrpc.js | 492 ++++++ .../widget/WidgetImplementationTestCase.java | 54 + .../src/test/java/store/Catalog.java | 32 + .../src/test/java/store/CatalogImpl.java | 47 + .../src/test/java/store/ShoppingCartImpl.java | 124 ++ .../src/test/resources/content/atomModel.js | 1590 ++++++++++++++++++++ .../src/test/resources/content/store.html | 127 ++ .../src/test/resources/content/storeJS.html | 152 ++ .../src/test/resources/content/unitTests.html | 250 +++ .../src/test/resources/widget.composite | 54 + .../src/test/resources/widgetJS.composite | 58 + .../contrib/modules/implementation-widget/LICENSE | 205 +++ .../implementation-widget/META-INF/MANIFEST.MF | 34 + .../contrib/modules/implementation-widget/NOTICE | 6 + .../contrib/modules/implementation-widget/pom.xml | 60 + .../tuscany/sca/implementation/widget/Widget.java | 34 + .../widget/WidgetImplementation.java | 134 ++ .../widget/WidgetImplementationFactory.java | 45 + .../widget/WidgetImplementationIntrospector.java | 145 ++ .../widget/WidgetImplementationProcessor.java | 175 +++ ...ca.contribution.processor.StAXArtifactProcessor | 19 + ...plementation.widget.WidgetImplementationFactory | 19 + .../impl-widget-validation-messages.properties | 23 + .../contrib/modules/implementation-xquery/LICENSE | 202 +++ .../implementation-xquery/META-INF/MANIFEST.MF | 64 + .../contrib/modules/implementation-xquery/NOTICE | 6 + .../contrib/modules/implementation-xquery/pom.xml | 86 ++ .../xquery/XQueryImplementation.java | 75 + .../xquery/XQueryImplementationFactory.java | 32 + .../xquery/XQueryImplementationProvider.java | 166 ++ .../XQueryImplementationProviderFactory.java | 54 + .../xquery/XQueryInvokationException.java | 33 + .../sca/implementation/xquery/XQueryInvoker.java | 318 ++++ .../impl/XQueryImplementationFactoryImpl.java | 35 + .../xquery/impl/XQueryImplementationImpl.java | 102 ++ .../xquery/xml/XQueryImplementationProcessor.java | 157 ++ .../xquery/xml/XQueryIntrospector.java | 328 ++++ ...ca.contribution.processor.StAXArtifactProcessor | 19 + ...cany.sca.provider.ImplementationProviderFactory | 19 + .../impl-xquery-validation-messages.properties | 22 + java/sca/contrib/modules/node-dynamic/LICENSE | 205 +++ java/sca/contrib/modules/node-dynamic/NOTICE | 6 + java/sca/contrib/modules/node-dynamic/pom.xml | 87 ++ .../apache/tuscany/sca/node/DynamicNodeMain.java | 50 + .../src/main/resources/log4j.properties | 51 + .../contrib/modules/node-launcher-webapp/LICENSE | 205 +++ .../contrib/modules/node-launcher-webapp/NOTICE | 6 + .../contrib/modules/node-launcher-webapp/pom.xml | 72 + .../src/main/webapp/META-INF/sca-contribution.xml | 21 + .../src/main/webapp/WEB-INF/web.xml | 41 + .../node-launcher-webapp/src/main/webapp/index.jsp | 27 + java/sca/contrib/modules/node-manager/LICENSE | 205 +++ .../modules/node-manager/META-INF/MANIFEST.MF | 22 + java/sca/contrib/modules/node-manager/NOTICE | 6 + java/sca/contrib/modules/node-manager/pom.xml | 112 ++ .../node/manager/NodeManagerUtil.java | 51 + .../node/manager/NodeProcessCollectionImpl.java | 338 +++++ .../node/manager/PingServiceImpl.java | 61 + .../src/main/resources/NodeDaemon.composite | 39 + java/sca/contrib/modules/policy-logging/LICENSE | 205 +++ .../modules/policy-logging/META-INF/MANIFEST.MF | 28 + java/sca/contrib/modules/policy-logging/NOTICE | 6 + java/sca/contrib/modules/policy-logging/pom.xml | 52 + .../logging/LoggingPolicyDefinitionsProvider.java | 67 + .../JDKLoggingImplementationPolicyProvider.java | 90 ++ .../sca/policy/logging/jdk/JDKLoggingPolicy.java | 85 ++ .../logging/jdk/JDKLoggingPolicyInterceptor.java | 129 ++ .../logging/jdk/JDKLoggingPolicyProcessor.java | 136 ++ .../jdk/JDKLoggingPolicyProviderFactory.java | 75 + .../jdk/JDKLoggingReferencePolicyProvider.java | 89 ++ .../jdk/JDKLoggingServicePolicyProvider.java | 87 ++ ...ca.contribution.processor.StAXArtifactProcessor | 19 + ...apache.tuscany.sca.provider.DefinitionsProvider | 19 + ...ache.tuscany.sca.provider.PolicyProviderFactory | 19 + .../tuscany/sca/policy/logging/definitions.xml | 31 + .../sca/policy/logging/jdk/PolicyReadTestCase.java | 91 ++ .../sca/policy/logging/jdk/mock_policies.xml | 23 + .../sca/contrib/modules/policy-reliability/LICENSE | 205 +++ java/sca/contrib/modules/policy-reliability/NOTICE | 6 + .../sca/contrib/modules/policy-reliability/pom.xml | 70 + .../ReliabilityPolicyDefinitionsProvider.java | 72 + ...che.tuscany.sca.provider.SCADefinitionsProvider | 19 + .../tuscany/sca/policy/reliability/definitions.xml | 62 + .../contrib/modules/policy-security-jsr250/LICENSE | 205 +++ .../policy-security-jsr250/META-INF/MANIFEST.MF | 28 + .../contrib/modules/policy-security-jsr250/NOTICE | 6 + .../contrib/modules/policy-security-jsr250/pom.xml | 64 + .../tuscany/sca/policy/jsr250/JSR250Activator.java | 51 + .../introspect/impl/JSR250PolicyProcessor.java | 179 +++ .../org.apache.tuscany.sca.core.ModuleActivator | 18 + .../impl/PolicyProcessorTestCaseFIXME.java | 399 +++++ .../sca/contrib/modules/policy-transaction/LICENSE | 205 +++ .../policy-transaction/META-INF/MANIFEST.MF | 45 + java/sca/contrib/modules/policy-transaction/NOTICE | 6 + .../sca/contrib/modules/policy-transaction/pom.xml | 58 + .../transaction/IncompatibleIntentException.java | 44 + .../TransactionImplementationPolicyProvider.java | 61 + .../sca/policy/transaction/TransactionIntent.java | 28 + .../policy/transaction/TransactionInterceptor.java | 122 ++ .../transaction/TransactionManagerHelper.java | 243 +++ .../transaction/TransactionManagerWrapper.java | 90 ++ .../transaction/TransactionModuleActivator.java | 84 ++ .../sca/policy/transaction/TransactionPolicy.java | 46 + .../TransactionPolicyDefinitionsProvider.java | 71 + .../policy/transaction/TransactionPolicyImpl.java | 59 + .../transaction/TransactionPolicyProcessor.java | 96 ++ .../TransactionPolicyProviderFactory.java | 92 ++ .../TransactionReferencePolicyProvider.java | 61 + .../TransactionServicePolicyProvider.java | 61 + .../policy/transaction/TransactionalAction.java | 31 + ...ca.contribution.processor.StAXArtifactProcessor | 19 + .../org.apache.tuscany.sca.core.ModuleActivator | 18 + ...apache.tuscany.sca.provider.DefinitionsProvider | 19 + ...ache.tuscany.sca.provider.PolicyProviderFactory | 19 + .../src/main/resources/log4j.properties | 29 + .../tuscany/sca/policy/transaction/definitions.xml | 66 + .../sca/policy/transaction/tuscany_definitions.xml | 54 + .../sca/policy/transaction/PolicyReadTestCase.java | 54 + .../TransactionManagerHelperTestCase.java | 194 +++ java/sca/contrib/modules/tracing-aspectj/LICENSE | 205 +++ .../modules/tracing-aspectj/META-INF/MANIFEST.MF | 22 + java/sca/contrib/modules/tracing-aspectj/NOTICE | 6 + .../contrib/modules/tracing-aspectj/launcher.bat | 5 + java/sca/contrib/modules/tracing-aspectj/pom.xml | 98 ++ .../apache/tuscany/sca/aspectj/LoggingAspect.java | 105 ++ .../tuscany/sca/aspectj/SimpleTracingAspect.java | 87 ++ .../apache/tuscany/sca/aspectj/TimingAspect.java | 60 + .../apache/tuscany/sca/aspectj/TracingAspect.java | 92 ++ .../src/main/resources/META-INF/aop.xml | 25 + .../tuscany/sca/aspectj/TracingTestCase.java | 41 + 1365 files changed, 132490 insertions(+) create mode 100644 java/sca/contrib/modules/binding-atom-abdera/LICENSE create mode 100644 java/sca/contrib/modules/binding-atom-abdera/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/binding-atom-abdera/NOTICE create mode 100644 java/sca/contrib/modules/binding-atom-abdera/ReceiptToms.gif create mode 100644 java/sca/contrib/modules/binding-atom-abdera/ReceiptValue.jpg create mode 100644 java/sca/contrib/modules/binding-atom-abdera/pom.xml create mode 100644 java/sca/contrib/modules/binding-atom-abdera/src/main/java/org/apache/tuscany/sca/binding/atom/collection/Collection.java create mode 100644 java/sca/contrib/modules/binding-atom-abdera/src/main/java/org/apache/tuscany/sca/binding/atom/collection/MediaCollection.java create mode 100644 java/sca/contrib/modules/binding-atom-abdera/src/main/java/org/apache/tuscany/sca/binding/atom/collection/NotFoundException.java create mode 100644 java/sca/contrib/modules/binding-atom-abdera/src/main/java/org/apache/tuscany/sca/binding/atom/provider/AtomBindingInvoker.java create mode 100644 java/sca/contrib/modules/binding-atom-abdera/src/main/java/org/apache/tuscany/sca/binding/atom/provider/AtomBindingListenerServlet.java create mode 100644 java/sca/contrib/modules/binding-atom-abdera/src/main/java/org/apache/tuscany/sca/binding/atom/provider/AtomBindingProviderFactory.java create mode 100644 java/sca/contrib/modules/binding-atom-abdera/src/main/java/org/apache/tuscany/sca/binding/atom/provider/AtomBindingUtil.java create mode 100644 java/sca/contrib/modules/binding-atom-abdera/src/main/java/org/apache/tuscany/sca/binding/atom/provider/AtomReferenceBindingProvider.java create mode 100644 java/sca/contrib/modules/binding-atom-abdera/src/main/java/org/apache/tuscany/sca/binding/atom/provider/AtomServiceBindingProvider.java create mode 100644 java/sca/contrib/modules/binding-atom-abdera/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.BindingProviderFactory create mode 100644 java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/AtomDeleteTestCase.java create mode 100644 java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/AtomGetTestCase.java create mode 100644 java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/AtomPostTestCase.java create mode 100644 java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/AtomPutTestCase.java create mode 100644 java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/AtomTestCaseUtils.java create mode 100644 java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/Consumer.java create mode 100644 java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/ConsumerProviderAtomTestCase.java create mode 100644 java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/ContentNegotiationTest.java create mode 100644 java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/CustomerClient.java create mode 100644 java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/CustomerClientImpl.java create mode 100644 java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/CustomerCollectionImpl.java create mode 100644 java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/MediaCollectionImpl.java create mode 100644 java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/MediaCollectionTestCase.java create mode 100644 java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/Provider.java create mode 100644 java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/ProviderEntryEntityTagsTestCase.java create mode 100644 java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/ProviderFeedEntityTagsTestCase.java create mode 100644 java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/ProviderServiceDocumentTestCase.java create mode 100644 java/sca/contrib/modules/binding-atom-abdera/src/test/resources/org/apache/tuscany/sca/binding/atom/Consumer.composite create mode 100644 java/sca/contrib/modules/binding-atom-abdera/src/test/resources/org/apache/tuscany/sca/binding/atom/Provider.composite create mode 100644 java/sca/contrib/modules/binding-atom-abdera/src/test/resources/org/apache/tuscany/sca/binding/atom/ReceiptProvider.composite create mode 100644 java/sca/contrib/modules/binding-atom/LICENSE create mode 100644 java/sca/contrib/modules/binding-atom/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/binding-atom/NOTICE create mode 100644 java/sca/contrib/modules/binding-atom/pom.xml create mode 100644 java/sca/contrib/modules/binding-atom/src/main/java/org/apache/tuscany/sca/binding/atom/AtomBinding.java create mode 100644 java/sca/contrib/modules/binding-atom/src/main/java/org/apache/tuscany/sca/binding/atom/AtomBindingFactory.java create mode 100644 java/sca/contrib/modules/binding-atom/src/main/java/org/apache/tuscany/sca/binding/atom/impl/AtomBindingFactoryImpl.java create mode 100644 java/sca/contrib/modules/binding-atom/src/main/java/org/apache/tuscany/sca/binding/atom/impl/AtomBindingImpl.java create mode 100644 java/sca/contrib/modules/binding-atom/src/main/resources/META-INF/services/org.apache.tuscany.sca.binding.atom.AtomBindingFactory create mode 100644 java/sca/contrib/modules/binding-atom/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor create mode 100644 java/sca/contrib/modules/binding-atom/src/test/java/org/apache/tuscany/sca/binding/atom/AtomBindingProcessorTestCase.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/LICENSE create mode 100644 java/sca/contrib/modules/binding-corba-runtime/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/binding-corba-runtime/NOTICE create mode 100644 java/sca/contrib/modules/binding-corba-runtime/pom.xml create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/CorbaBindingProviderFactory.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/CorbaInvoker.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/CorbaReferenceBindingProvider.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/CorbaServiceBindingProvider.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/exceptions/CorbaException.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/exceptions/RequestConfigurationException.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/meta/CorbaArray.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/meta/CorbaUnionElement.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/meta/CorbaUnionElementType.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/reference/DynaCorbaRequest.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/reference/DynaCorbaResponse.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/reference/InterfaceInstanceCreator.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/reference/InterfaceMethodInterceptor.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/service/ComponentInvocationProxy.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/service/DynaCorbaServant.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/service/InvocationException.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/service/InvocationProxy.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/service/OperationTypes.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/AnnotationAttributes.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/NodeType.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/TypeTree.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/TypeTreeCreator.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/TypeTreeNode.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/UnionAttributes.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/ArrayTypeHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/BooleanTypeHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/ByteTypeHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/CharTypeHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/DoubleTypeHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/EnumTypeHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/FloatTypeHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/IntTypeHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/LongTypeHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/ReferenceTypeHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/SequenceTypeHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/ShortTypeHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/StringTypeHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/StructTypeHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/TypeHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/TypeHelpersProxy.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/UnionTypeHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/Utils.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/util/MethodFinder.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/util/OperationMapper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.BindingProviderFactory create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/CorbaServantTestCase.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/CorbaTypesTestCase.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/MappingTestInterface.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/MethodFinderTestCase.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/OperationMappingTestCase.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/TestConstants.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/ArraysUnionsTests.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/ArraysUnionsTestsHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/ArraysUnionsTestsHolder.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/ArraysUnionsTestsOperations.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/InnerUnion.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/InnerUnionHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/InnerUnionHolder.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/RichUnion.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/RichUnionHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/RichUnionHolder.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/StringArrayHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/StringArrayHolder.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/TestStruct.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/TestStructHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/TestStructHolder.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/_ArraysUnionsTestsImplBase.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/_ArraysUnionsTestsStub.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/enums/Color.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/enums/ColorHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/enums/ColorHolder.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/enums/EnumManager.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/enums/EnumManagerHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/enums/EnumManagerHolder.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/enums/EnumManagerOperations.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/enums/_EnumManagerImplBase.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/enums/_EnumManagerStub.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/Calc.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcHolder.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcOperations.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/Arguments.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/ArgumentsHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/ArgumentsHolder.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/DivByZero.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/DivByZeroHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/DivByZeroHolder.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/NotSupported.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/NotSupportedHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/NotSupportedHolder.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/_CalcImplBase.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/_CalcStub.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/ArraysSetter.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/ArraysSetterHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/ArraysSetterHolder.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/ArraysSetterOperations.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/PrimitivesSetter.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/PrimitivesSetterHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/PrimitivesSetterHolder.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/PrimitivesSetterOperations.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/RemoteObject.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/RemoteObjectHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/RemoteObjectHolder.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/RemoteObjectOperations.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/SimpleStruct.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/SimpleStructHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/SimpleStructHolder.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/SomeStruct.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/SomeStructHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/SomeStructHolder.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/TestObject.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/TestObjectHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/TestObjectHolder.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/TestObjectOperations.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/_ArraysSetterImplBase.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/_ArraysSetterStub.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/_PrimitivesSetterImplBase.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/_PrimitivesSetterStub.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/_RemoteObjectImplBase.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/_RemoteObjectStub.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/_TestObjectImplBase.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/_TestObjectStub.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/boolean_listHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/boolean_listHolder.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/char_listHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/char_listHolder.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/double_listHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/double_listHolder.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/float_listHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/float_listHolder.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/long_listHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/long_listHolder.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/long_long_listHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/long_long_listHolder.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/long_seq1Helper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/long_seq1Holder.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/long_seq2Helper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/long_seq2Holder.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/long_seq3Helper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/long_seq3Holder.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/octet_listHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/octet_listHolder.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/remote_object_listHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/remote_object_listHolder.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/short_listHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/short_listHolder.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/string_listHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/string_listHolder.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/unsigned_long_listHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/unsigned_long_listHolder.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/unsigned_long_long_listHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/unsigned_long_long_listHolder.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/unsigned_short_listHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/unsigned_short_listHolder.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/wchar_listHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/wchar_listHolder.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/wstring_listHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/wstring_listHolder.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/ArraysTestStruct.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/Calc.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/DummyObject.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InnerUnion.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidCorbaArray.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidEnum1.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidEnum2.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidEnum3.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidStruct1.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidStruct2.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidStruct3.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidUnion1.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidUnion2.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidUnion3.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidUnion4.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidUnion5.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/NonCorbaException.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/RichUnion.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/SimpleStruct.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/SomeStruct.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/DummyObject.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/DummyObjectHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/DummyObjectHolder.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/DummyObjectOperations.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/ObjectManager.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/ObjectManagerHelper.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/ObjectManagerHolder.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/ObjectManagerOperations.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/_DummyObjectImplBase.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/_DummyObjectStub.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/_ObjectManagerImplBase.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/_ObjectManagerStub.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/ArraysSetterServant.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/ArraysUnionsServant.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/ArraysUnionsTuscanyServant.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/CalcServant.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/DummyObjectServant.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/EnumManagerServant.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/InvalidTestObjectServant.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/InvalidTypesServant.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/NonCorbaServant.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/ObjectManagerServant.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/PrimitivesSetterServant.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/TestObjectServant.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/service/mocks/TestDataType.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/service/mocks/TestInterface.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/service/mocks/TestInterfaceContract.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/service/mocks/TestOperation.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/service/mocks/TestRuntimeComponentService.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/service/mocks/TestRuntimeWire.java create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/resources/arrays_unions.idl create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/resources/enums.idl create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/resources/exceptions.idl create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/resources/general_tests.idl create mode 100644 java/sca/contrib/modules/binding-corba-runtime/src/test/resources/references.idl create mode 100644 java/sca/contrib/modules/binding-corba/LICENSE create mode 100644 java/sca/contrib/modules/binding-corba/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/binding-corba/NOTICE create mode 100644 java/sca/contrib/modules/binding-corba/pom.xml create mode 100644 java/sca/contrib/modules/binding-corba/src/main/java/org/apache/tuscany/sca/binding/corba/CorbaBinding.java create mode 100644 java/sca/contrib/modules/binding-corba/src/main/java/org/apache/tuscany/sca/binding/corba/CorbaBindingFactory.java create mode 100644 java/sca/contrib/modules/binding-corba/src/main/java/org/apache/tuscany/sca/binding/corba/impl/CorbaBindingFactoryImpl.java create mode 100644 java/sca/contrib/modules/binding-corba/src/main/java/org/apache/tuscany/sca/binding/corba/impl/CorbaBindingImpl.java create mode 100644 java/sca/contrib/modules/binding-corba/src/main/java/org/apache/tuscany/sca/binding/corba/impl/CorbaBindingProcessor.java create mode 100644 java/sca/contrib/modules/binding-corba/src/main/resources/META-INF/services/org.apache.tuscany.sca.binding.corba.CorbaBindingFactory create mode 100644 java/sca/contrib/modules/binding-corba/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor create mode 100644 java/sca/contrib/modules/binding-ejb-runtime/LICENSE create mode 100644 java/sca/contrib/modules/binding-ejb-runtime/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/binding-ejb-runtime/NOTICE create mode 100644 java/sca/contrib/modules/binding-ejb-runtime/pom.xml create mode 100644 java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/corba/ClassLoadingUtil.java create mode 100644 java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/corba/DynamicStubClassLoader.java create mode 100644 java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/corba/Java2IDLUtil.java create mode 100644 java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/corba/ObjectInputStreamExt.java create mode 100644 java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/corba/StubMethodInterceptor.java create mode 100644 java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/corba/UtilInitializer.java create mode 100644 java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/provider/EJBBindingInvoker.java create mode 100644 java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/provider/EJBBindingProviderFactory.java create mode 100644 java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/provider/EJBBindingReferenceBindingProvider.java create mode 100644 java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/util/EJBHandler.java create mode 100644 java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/util/EJBLocator.java create mode 100644 java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/util/EJBObjectFactory.java create mode 100644 java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/util/EJBStubHelper.java create mode 100644 java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/util/InterfaceInfo.java create mode 100644 java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/util/JavaReflectionAdapter.java create mode 100644 java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/util/MethodInfo.java create mode 100644 java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/util/NamingEndpoint.java create mode 100644 java/sca/contrib/modules/binding-ejb-runtime/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.BindingProviderFactory create mode 100644 java/sca/contrib/modules/binding-ejb-runtime/src/main/resources/binding-ejb-validation-messages.properties create mode 100644 java/sca/contrib/modules/binding-ejb-runtime/src/test/java/account/BankManagerFacade.java create mode 100644 java/sca/contrib/modules/binding-ejb-runtime/src/test/java/account/Customer.java create mode 100644 java/sca/contrib/modules/binding-ejb-runtime/src/test/java/account/CustomerImpl.java create mode 100644 java/sca/contrib/modules/binding-ejb-runtime/src/test/java/calculator/AddService.java create mode 100644 java/sca/contrib/modules/binding-ejb-runtime/src/test/java/calculator/AddServiceHome.java create mode 100644 java/sca/contrib/modules/binding-ejb-runtime/src/test/java/org/apache/geronimo/samples/bank/ejb/BankManagerFacade.java create mode 100644 java/sca/contrib/modules/binding-ejb-runtime/src/test/java/org/apache/geronimo/samples/bank/ejb/BankManagerFacadeHome.java create mode 100644 java/sca/contrib/modules/binding-ejb-runtime/src/test/java/org/apache/tuscany/sca/binding/ejb/tests/EJBReferenceTestCase.java create mode 100644 java/sca/contrib/modules/binding-ejb-runtime/src/test/java/org/apache/tuscany/sca/binding/ejb/tests/MockServer.java create mode 100644 java/sca/contrib/modules/binding-ejb-runtime/src/test/java/org/apache/tuscany/sca/binding/ejb/tests/SocketTracer.java create mode 100644 java/sca/contrib/modules/binding-ejb-runtime/src/test/resources/account/account.composite create mode 100644 java/sca/contrib/modules/binding-ejb/LICENSE create mode 100644 java/sca/contrib/modules/binding-ejb/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/binding-ejb/NOTICE create mode 100644 java/sca/contrib/modules/binding-ejb/pom.xml create mode 100644 java/sca/contrib/modules/binding-ejb/src/main/java/org/apache/tuscany/sca/binding/ejb/EJBBinding.java create mode 100644 java/sca/contrib/modules/binding-ejb/src/main/java/org/apache/tuscany/sca/binding/ejb/EJBBindingException.java create mode 100644 java/sca/contrib/modules/binding-ejb/src/main/java/org/apache/tuscany/sca/binding/ejb/EJBBindingFactory.java create mode 100644 java/sca/contrib/modules/binding-ejb/src/main/java/org/apache/tuscany/sca/binding/ejb/impl/EJBBindingFactoryImpl.java create mode 100644 java/sca/contrib/modules/binding-ejb/src/main/java/org/apache/tuscany/sca/binding/ejb/impl/EJBBindingImpl.java create mode 100644 java/sca/contrib/modules/binding-ejb/src/main/java/org/apache/tuscany/sca/binding/ejb/impl/EJBBindingProcessor.java create mode 100644 java/sca/contrib/modules/binding-ejb/src/main/resources/META-INF/services/org.apache.tuscany.sca.binding.ejb.EJBBindingFactory create mode 100644 java/sca/contrib/modules/binding-ejb/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor create mode 100644 java/sca/contrib/modules/binding-ejb/src/main/resources/binding-ejb-validation-messages.properties create mode 100644 java/sca/contrib/modules/binding-gdata-runtime/LICENSE create mode 100644 java/sca/contrib/modules/binding-gdata-runtime/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/binding-gdata-runtime/NOTICE create mode 100644 java/sca/contrib/modules/binding-gdata-runtime/pom.xml create mode 100644 java/sca/contrib/modules/binding-gdata-runtime/src/main/java/org/apache/tuscany/sca/binding/gdata/collection/Collection.java create mode 100644 java/sca/contrib/modules/binding-gdata-runtime/src/main/java/org/apache/tuscany/sca/binding/gdata/collection/MediaCollection.java create mode 100644 java/sca/contrib/modules/binding-gdata-runtime/src/main/java/org/apache/tuscany/sca/binding/gdata/collection/NotFoundException.java create mode 100644 java/sca/contrib/modules/binding-gdata-runtime/src/main/java/org/apache/tuscany/sca/binding/gdata/provider/GdataBindingInvoker.java create mode 100644 java/sca/contrib/modules/binding-gdata-runtime/src/main/java/org/apache/tuscany/sca/binding/gdata/provider/GdataBindingListenerServlet.java create mode 100644 java/sca/contrib/modules/binding-gdata-runtime/src/main/java/org/apache/tuscany/sca/binding/gdata/provider/GdataBindingProviderFactory.java create mode 100644 java/sca/contrib/modules/binding-gdata-runtime/src/main/java/org/apache/tuscany/sca/binding/gdata/provider/GdataBindingUtil.java create mode 100644 java/sca/contrib/modules/binding-gdata-runtime/src/main/java/org/apache/tuscany/sca/binding/gdata/provider/GdataReferenceBindingProvider.java create mode 100644 java/sca/contrib/modules/binding-gdata-runtime/src/main/java/org/apache/tuscany/sca/binding/gdata/provider/GdataServiceBindingProvider.java create mode 100644 java/sca/contrib/modules/binding-gdata-runtime/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.BindingProviderFactory create mode 100644 java/sca/contrib/modules/binding-gdata-runtime/src/main/resources/tuscany-binding-gdata.xsd create mode 100644 java/sca/contrib/modules/binding-gdata-runtime/src/test/java/org/apache/tuscany/sca/binding/gdata/Consumer.java create mode 100644 java/sca/contrib/modules/binding-gdata-runtime/src/test/java/org/apache/tuscany/sca/binding/gdata/ConsumerProviderTestCase.java create mode 100644 java/sca/contrib/modules/binding-gdata-runtime/src/test/java/org/apache/tuscany/sca/binding/gdata/CustomerClient.java create mode 100644 java/sca/contrib/modules/binding-gdata-runtime/src/test/java/org/apache/tuscany/sca/binding/gdata/CustomerClientImpl.java create mode 100644 java/sca/contrib/modules/binding-gdata-runtime/src/test/java/org/apache/tuscany/sca/binding/gdata/CustomerCollectionImpl.java create mode 100644 java/sca/contrib/modules/binding-gdata-runtime/src/test/java/org/apache/tuscany/sca/binding/gdata/GoogleBloggerServiceTestCase.java create mode 100644 java/sca/contrib/modules/binding-gdata-runtime/src/test/java/org/apache/tuscany/sca/binding/gdata/GoogleCalendarServiceTestCase.java create mode 100644 java/sca/contrib/modules/binding-gdata-runtime/src/test/java/org/apache/tuscany/sca/binding/gdata/GoogleContactsServiceTestCase.java create mode 100644 java/sca/contrib/modules/binding-gdata-runtime/src/test/java/org/apache/tuscany/sca/binding/gdata/Provider.java create mode 100644 java/sca/contrib/modules/binding-gdata-runtime/src/test/java/org/apache/tuscany/sca/binding/gdata/StartLocalhostServlet.java create mode 100644 java/sca/contrib/modules/binding-gdata-runtime/src/test/resources/log4j.properties create mode 100644 java/sca/contrib/modules/binding-gdata-runtime/src/test/resources/org/apache/tuscany/sca/binding/gdata/Consumer.composite create mode 100644 java/sca/contrib/modules/binding-gdata-runtime/src/test/resources/org/apache/tuscany/sca/binding/gdata/ConsumerGoogleBlogger.composite create mode 100644 java/sca/contrib/modules/binding-gdata-runtime/src/test/resources/org/apache/tuscany/sca/binding/gdata/ConsumerGoogleCalendar.composite create mode 100644 java/sca/contrib/modules/binding-gdata-runtime/src/test/resources/org/apache/tuscany/sca/binding/gdata/ConsumerGoogleContacts.composite create mode 100644 java/sca/contrib/modules/binding-gdata-runtime/src/test/resources/org/apache/tuscany/sca/binding/gdata/Provider.composite create mode 100644 java/sca/contrib/modules/binding-gdata/LICENSE create mode 100644 java/sca/contrib/modules/binding-gdata/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/binding-gdata/NOTICE create mode 100644 java/sca/contrib/modules/binding-gdata/pom.xml create mode 100644 java/sca/contrib/modules/binding-gdata/src/main/java/org/apache/tuscany/sca/binding/gdata/GdataBinding.java create mode 100644 java/sca/contrib/modules/binding-gdata/src/main/java/org/apache/tuscany/sca/binding/gdata/GdataBindingFactory.java create mode 100644 java/sca/contrib/modules/binding-gdata/src/main/java/org/apache/tuscany/sca/binding/gdata/impl/GdataBindingFactoryImpl.java create mode 100644 java/sca/contrib/modules/binding-gdata/src/main/java/org/apache/tuscany/sca/binding/gdata/impl/GdataBindingImpl.java create mode 100644 java/sca/contrib/modules/binding-gdata/src/main/java/org/apache/tuscany/sca/binding/gdata/xml/GdataBindingProcessor.java create mode 100644 java/sca/contrib/modules/binding-gdata/src/main/resources/META-INF/services/org.apache.tuscany.sca.binding.gdata.GdataBindingFactory create mode 100644 java/sca/contrib/modules/binding-gdata/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor create mode 100644 java/sca/contrib/modules/binding-http-runtime/LICENSE create mode 100644 java/sca/contrib/modules/binding-http-runtime/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/binding-http-runtime/NOTICE create mode 100644 java/sca/contrib/modules/binding-http-runtime/pom.xml create mode 100644 java/sca/contrib/modules/binding-http-runtime/src/main/java/org/apache/tuscany/sca/binding/http/provider/HTTPBindingListenerServlet.java create mode 100644 java/sca/contrib/modules/binding-http-runtime/src/main/java/org/apache/tuscany/sca/binding/http/provider/HTTPBindingProviderFactory.java create mode 100644 java/sca/contrib/modules/binding-http-runtime/src/main/java/org/apache/tuscany/sca/binding/http/provider/HTTPGetListenerServlet.java create mode 100644 java/sca/contrib/modules/binding-http-runtime/src/main/java/org/apache/tuscany/sca/binding/http/provider/HTTPServiceBindingProvider.java create mode 100644 java/sca/contrib/modules/binding-http-runtime/src/main/java/org/apache/tuscany/sca/binding/http/provider/HTTPServiceListenerServlet.java create mode 100644 java/sca/contrib/modules/binding-http-runtime/src/main/java/org/apache/tuscany/sca/binding/http/util/HTTPHeadersParser.java create mode 100644 java/sca/contrib/modules/binding-http-runtime/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.BindingProviderFactory create mode 100644 java/sca/contrib/modules/binding-http-runtime/src/test/java/org/apache/tuscany/sca/binding/http/HTTPBindingCacheTestCaseFIXME.java create mode 100644 java/sca/contrib/modules/binding-http-runtime/src/test/java/org/apache/tuscany/sca/binding/http/HTTPBindingTestCase.java create mode 100644 java/sca/contrib/modules/binding-http-runtime/src/test/java/org/apache/tuscany/sca/binding/http/NotModifiedException.java create mode 100644 java/sca/contrib/modules/binding-http-runtime/src/test/java/org/apache/tuscany/sca/binding/http/PreconditionFailedException.java create mode 100644 java/sca/contrib/modules/binding-http-runtime/src/test/java/org/apache/tuscany/sca/binding/http/TestBindingCacheImpl.java create mode 100644 java/sca/contrib/modules/binding-http-runtime/src/test/java/org/apache/tuscany/sca/binding/http/TestGetImpl.java create mode 100644 java/sca/contrib/modules/binding-http-runtime/src/test/java/org/apache/tuscany/sca/binding/http/TestServiceCacheImpl.java create mode 100644 java/sca/contrib/modules/binding-http-runtime/src/test/java/org/apache/tuscany/sca/binding/http/TestServiceImpl.java create mode 100644 java/sca/contrib/modules/binding-http-runtime/src/test/resources/content/test.html create mode 100644 java/sca/contrib/modules/binding-http-runtime/src/test/resources/test.composite create mode 100644 java/sca/contrib/modules/binding-http-runtime/src/test/resources/testCache.composite create mode 100644 java/sca/contrib/modules/binding-http/LICENSE create mode 100644 java/sca/contrib/modules/binding-http/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/binding-http/NOTICE create mode 100644 java/sca/contrib/modules/binding-http/pom.xml create mode 100644 java/sca/contrib/modules/binding-http/src/main/java/org/apache/tuscany/sca/binding/http/HTTPBinding.java create mode 100644 java/sca/contrib/modules/binding-http/src/main/java/org/apache/tuscany/sca/binding/http/HTTPBindingFactory.java create mode 100644 java/sca/contrib/modules/binding-http/src/main/java/org/apache/tuscany/sca/binding/http/HTTPCacheContext.java create mode 100644 java/sca/contrib/modules/binding-http/src/main/java/org/apache/tuscany/sca/binding/http/HTTPHeader.java create mode 100644 java/sca/contrib/modules/binding-http/src/main/java/org/apache/tuscany/sca/binding/http/impl/HTTPBindingFactoryImpl.java create mode 100644 java/sca/contrib/modules/binding-http/src/main/java/org/apache/tuscany/sca/binding/http/impl/HTTPBindingImpl.java create mode 100644 java/sca/contrib/modules/binding-http/src/main/resources/META-INF/services/org.apache.tuscany.sca.binding.http.HTTPBindingFactory create mode 100644 java/sca/contrib/modules/binding-http/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor create mode 100644 java/sca/contrib/modules/binding-jms-policy/LICENSE create mode 100644 java/sca/contrib/modules/binding-jms-policy/NOTICE create mode 100644 java/sca/contrib/modules/binding-jms-policy/pom.xml create mode 100644 java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/JMSBindingDefinitionsProvider.java create mode 100644 java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/authentication/token/JMSTokenAuthenticationPolicy.java create mode 100644 java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/authentication/token/JMSTokenAuthenticationPolicyProcessor.java create mode 100644 java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/authentication/token/JMSTokenAuthenticationPolicyProviderFactory.java create mode 100644 java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/authentication/token/JMSTokenAuthenticationReferencePolicyInterceptor.java create mode 100644 java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/authentication/token/JMSTokenAuthenticationReferencePolicyProvider.java create mode 100644 java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/authentication/token/JMSTokenAuthenticationServicePolicyInterceptor.java create mode 100644 java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/authentication/token/JMSTokenAuthenticationServicePolicyProvider.java create mode 100644 java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/header/JMSHeaderPolicy.java create mode 100644 java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/header/JMSHeaderPolicyProcessor.java create mode 100644 java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/header/JMSHeaderPolicyProviderFactory.java create mode 100644 java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/header/JMSHeaderReferencePolicyInterceptor.java create mode 100644 java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/header/JMSHeaderReferencePolicyProvider.java create mode 100644 java/sca/contrib/modules/binding-jms-policy/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor create mode 100644 java/sca/contrib/modules/binding-jms-policy/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.PolicyProviderFactory create mode 100644 java/sca/contrib/modules/binding-jms-policy/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.SCADefinitionsProvider create mode 100644 java/sca/contrib/modules/binding-jms-policy/src/main/resources/binding-jms-policy-validation-messages.properties create mode 100644 java/sca/contrib/modules/binding-jms-policy/src/main/resources/org/apache/tuscany/sca/binding/jms/policy/definitions.xml create mode 100644 java/sca/contrib/modules/binding-jms-policy/src/test/java/org/apache/tuscany/sca/binding/jms/policy/PolicyProcessorTestCase.java create mode 100644 java/sca/contrib/modules/binding-jms-policy/src/test/resources/org/apache/tuscany/sca/binding/jms/policy/mock_policy_definitions.xml create mode 100644 java/sca/contrib/modules/binding-jms-runtime/LICENSE create mode 100644 java/sca/contrib/modules/binding-jms-runtime/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/binding-jms-runtime/NOTICE create mode 100644 java/sca/contrib/modules/binding-jms-runtime/pom.xml create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/context/JMSBindingContext.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/headers/HeaderReferenceInterceptor.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/operationselector/jmsdefault/OperationSelectorJMSDefaultProviderFactory.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/operationselector/jmsdefault/OperationSelectorJMSDefaultServiceInterceptor.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/operationselector/jmsdefault/OperationSelectorJMSDefaultServiceProvider.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/AbstractMessageProcessor.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/BytesMessageProcessor.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/DefaultJMSBindingListener.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/DefaultJMSResourceFactoryExtensionPoint.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/JMSBindingInvoker.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/JMSBindingProviderFactory.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/JMSBindingReferenceBindingProvider.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/JMSBindingServiceBindingProvider.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/JMSMessageProcessor.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/JMSMessageProcessorUtil.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/JMSResourceFactory.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/JMSResourceFactoryExtensionPoint.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/JMSResourceFactoryImpl.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/ObjectMessageProcessor.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/RRBJMSBindingInvoker.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/RRBJMSBindingListener.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/TextMessageProcessor.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/XMLTextMessageProcessor.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/transport/TransportReferenceInterceptor.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/transport/TransportServiceInterceptor.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsbytes/WireFormatJMSBytesProviderFactory.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsbytes/WireFormatJMSBytesReferenceInterceptor.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsbytes/WireFormatJMSBytesReferenceProvider.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsbytes/WireFormatJMSBytesServiceInterceptor.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsbytes/WireFormatJMSBytesServiceProvider.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsobject/WireFormatJMSObjectProviderFactory.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsobject/WireFormatJMSObjectReferenceInterceptor.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsobject/WireFormatJMSObjectReferenceProvider.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsobject/WireFormatJMSObjectServiceInterceptor.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsobject/WireFormatJMSObjectServiceProvider.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstext/WireFormatJMSTextProviderFactory.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstext/WireFormatJMSTextReferenceInterceptor.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstext/WireFormatJMSTextReferenceProvider.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstext/WireFormatJMSTextServiceInterceptor.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstext/WireFormatJMSTextServiceProvider.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstextxml/WireFormatJMSTextXMLProviderFactory.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstextxml/WireFormatJMSTextXMLReferenceInterceptor.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstextxml/WireFormatJMSTextXMLReferenceProvider.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstextxml/WireFormatJMSTextXMLServiceInterceptor.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstextxml/WireFormatJMSTextXMLServiceProvider.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.BindingProviderFactory create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.OperationSelectorProviderFactory create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.WireFormatProviderFactory create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/test/java/org/apache/tuscany/sca/binding/jms/HelloWorldClientImpl.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/test/java/org/apache/tuscany/sca/binding/jms/HelloWorldService.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/test/java/org/apache/tuscany/sca/binding/jms/HelloWorldServiceImpl.java create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/test/resources/simple/client.composite create mode 100644 java/sca/contrib/modules/binding-jms-runtime/src/test/resources/simple/service.composite create mode 100644 java/sca/contrib/modules/binding-jms/LICENSE create mode 100644 java/sca/contrib/modules/binding-jms/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/binding-jms/NOTICE create mode 100644 java/sca/contrib/modules/binding-jms/pom.xml create mode 100644 java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/JMSBinding.java create mode 100644 java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/JMSBindingException.java create mode 100644 java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/JMSBindingFactory.java create mode 100644 java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/impl/JMSBindingFactoryImpl.java create mode 100644 java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/impl/JMSBindingImpl.java create mode 100644 java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/operationselector/jmsdefault/OperationSelectorJMSDefault.java create mode 100644 java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/operationselector/jmsdefault/OperationSelectorJMSDefaultProcessor.java create mode 100644 java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsbytes/WireFormatJMSBytes.java create mode 100644 java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsbytes/WireFormatJMSBytesProcessor.java create mode 100644 java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsobject/WireFormatJMSObject.java create mode 100644 java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsobject/WireFormatJMSObjectProcessor.java create mode 100644 java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstext/WireFormatJMSText.java create mode 100644 java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstext/WireFormatJMSTextProcessor.java create mode 100644 java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstextxml/WireFormatJMSTextXML.java create mode 100644 java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstextxml/WireFormatJMSTextXMLProcessor.java create mode 100644 java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/xml/JMSBindingConstants.java create mode 100644 java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/xml/JMSBindingProcessor.java create mode 100644 java/sca/contrib/modules/binding-jms/src/main/resources/META-INF/services/org.apache.tuscany.sca.binding.jms.JMSBindingFactory create mode 100644 java/sca/contrib/modules/binding-jms/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor create mode 100644 java/sca/contrib/modules/binding-jms/src/main/resources/binding-jms-validation-messages.properties create mode 100644 java/sca/contrib/modules/binding-jms/src/test/java/org/apache/tuscany/sca/binding/jms/impl/JMSBindingProcessorTestCase.java create mode 100644 java/sca/contrib/modules/binding-jsonrpc-runtime/LICENSE create mode 100644 java/sca/contrib/modules/binding-jsonrpc-runtime/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/binding-jsonrpc-runtime/NOTICE create mode 100644 java/sca/contrib/modules/binding-jsonrpc-runtime/pom.xml create mode 100644 java/sca/contrib/modules/binding-jsonrpc-runtime/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/provider/JSONRPCBindingInvoker.java create mode 100644 java/sca/contrib/modules/binding-jsonrpc-runtime/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/provider/JSONRPCBindingProviderFactory.java create mode 100644 java/sca/contrib/modules/binding-jsonrpc-runtime/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/provider/JSONRPCReferenceBindingProvider.java create mode 100644 java/sca/contrib/modules/binding-jsonrpc-runtime/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/provider/JSONRPCServiceBindingProvider.java create mode 100644 java/sca/contrib/modules/binding-jsonrpc-runtime/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/provider/JSONRPCServiceServlet.java create mode 100644 java/sca/contrib/modules/binding-jsonrpc-runtime/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/provider/JavaToSmd.java create mode 100644 java/sca/contrib/modules/binding-jsonrpc-runtime/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/provider/ScaDomainScriptServlet.java create mode 100644 java/sca/contrib/modules/binding-jsonrpc-runtime/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.BindingProviderFactory create mode 100644 java/sca/contrib/modules/binding-jsonrpc-runtime/src/main/resources/org/apache/tuscany/sca/binding/jsonrpc/provider/jsonrpc.js create mode 100644 java/sca/contrib/modules/binding-jsonrpc-runtime/src/test/java/bean/TestBean.java create mode 100644 java/sca/contrib/modules/binding-jsonrpc-runtime/src/test/java/echo/Echo.java create mode 100644 java/sca/contrib/modules/binding-jsonrpc-runtime/src/test/java/echo/EchoBusinessException.java create mode 100644 java/sca/contrib/modules/binding-jsonrpc-runtime/src/test/java/echo/EchoComponentImpl.java create mode 100644 java/sca/contrib/modules/binding-jsonrpc-runtime/src/test/java/org/apache/tuscany/sca/binding/jsonrpc/JSONRPCDataTypeTestCase.java create mode 100644 java/sca/contrib/modules/binding-jsonrpc-runtime/src/test/java/org/apache/tuscany/sca/binding/jsonrpc/JSONRPCExceptionTestCase.java create mode 100644 java/sca/contrib/modules/binding-jsonrpc-runtime/src/test/java/org/apache/tuscany/sca/binding/jsonrpc/JSONRPCServiceTestCase.java create mode 100644 java/sca/contrib/modules/binding-jsonrpc-runtime/src/test/resources/JSONRPCBinding.composite create mode 100644 java/sca/contrib/modules/binding-jsonrpc/LICENSE create mode 100644 java/sca/contrib/modules/binding-jsonrpc/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/binding-jsonrpc/NOTICE create mode 100644 java/sca/contrib/modules/binding-jsonrpc/pom.xml create mode 100644 java/sca/contrib/modules/binding-jsonrpc/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/JSONRPCBinding.java create mode 100644 java/sca/contrib/modules/binding-jsonrpc/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/JSONRPCBindingFactory.java create mode 100644 java/sca/contrib/modules/binding-jsonrpc/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/impl/JSONRPCBindingFactoryImpl.java create mode 100644 java/sca/contrib/modules/binding-jsonrpc/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/impl/JSONRPCBindingImpl.java create mode 100644 java/sca/contrib/modules/binding-jsonrpc/src/main/resources/META-INF/services/org.apache.tuscany.sca.binding.jsonrpc.JSONRPCBindingFactory create mode 100644 java/sca/contrib/modules/binding-jsonrpc/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor create mode 100644 java/sca/contrib/modules/binding-rss-rome/LICENSE create mode 100644 java/sca/contrib/modules/binding-rss-rome/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/binding-rss-rome/NOTICE create mode 100644 java/sca/contrib/modules/binding-rss-rome/pom.xml create mode 100644 java/sca/contrib/modules/binding-rss-rome/src/main/java/org/apache/tuscany/sca/binding/rss/collection/Collection.java create mode 100644 java/sca/contrib/modules/binding-rss-rome/src/main/java/org/apache/tuscany/sca/binding/rss/collection/MediaCollection.java create mode 100644 java/sca/contrib/modules/binding-rss-rome/src/main/java/org/apache/tuscany/sca/binding/rss/collection/NotFoundException.java create mode 100644 java/sca/contrib/modules/binding-rss-rome/src/main/java/org/apache/tuscany/sca/binding/rss/provider/RSSBindingInvoker.java create mode 100644 java/sca/contrib/modules/binding-rss-rome/src/main/java/org/apache/tuscany/sca/binding/rss/provider/RSSBindingListenerServlet.java create mode 100644 java/sca/contrib/modules/binding-rss-rome/src/main/java/org/apache/tuscany/sca/binding/rss/provider/RSSBindingProviderFactory.java create mode 100644 java/sca/contrib/modules/binding-rss-rome/src/main/java/org/apache/tuscany/sca/binding/rss/provider/RSSReferenceBindingProvider.java create mode 100644 java/sca/contrib/modules/binding-rss-rome/src/main/java/org/apache/tuscany/sca/binding/rss/provider/RSSServiceBindingProvider.java create mode 100644 java/sca/contrib/modules/binding-rss-rome/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.BindingProviderFactory create mode 100644 java/sca/contrib/modules/binding-rss-rome/src/test/java/org/apache/tuscany/sca/binding/rss/Consumer.java create mode 100644 java/sca/contrib/modules/binding-rss-rome/src/test/java/org/apache/tuscany/sca/binding/rss/CustomerClient.java create mode 100644 java/sca/contrib/modules/binding-rss-rome/src/test/java/org/apache/tuscany/sca/binding/rss/CustomerClientImpl.java create mode 100644 java/sca/contrib/modules/binding-rss-rome/src/test/java/org/apache/tuscany/sca/binding/rss/CustomerCollectionImpl.java create mode 100644 java/sca/contrib/modules/binding-rss-rome/src/test/java/org/apache/tuscany/sca/binding/rss/Provider.java create mode 100644 java/sca/contrib/modules/binding-rss-rome/src/test/resources/org/apache/tuscany/sca/binding/feed/Consumer.composite create mode 100644 java/sca/contrib/modules/binding-rss-rome/src/test/resources/org/apache/tuscany/sca/binding/feed/Provider.composite create mode 100644 java/sca/contrib/modules/binding-rss/LICENSE create mode 100644 java/sca/contrib/modules/binding-rss/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/binding-rss/NOTICE create mode 100644 java/sca/contrib/modules/binding-rss/pom.xml create mode 100644 java/sca/contrib/modules/binding-rss/src/main/java/org/apache/tuscany/sca/binding/rss/RSSBinding.java create mode 100644 java/sca/contrib/modules/binding-rss/src/main/java/org/apache/tuscany/sca/binding/rss/RSSBindingFactory.java create mode 100644 java/sca/contrib/modules/binding-rss/src/main/java/org/apache/tuscany/sca/binding/rss/impl/RSSBindingFactoryImpl.java create mode 100644 java/sca/contrib/modules/binding-rss/src/main/java/org/apache/tuscany/sca/binding/rss/impl/RSSBindingImpl.java create mode 100644 java/sca/contrib/modules/binding-rss/src/main/resources/META-INF/services/org.apache.tuscany.sca.binding.rss.RSSBindingFactory create mode 100644 java/sca/contrib/modules/binding-rss/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor create mode 100644 java/sca/contrib/modules/binding-sca-axis2/LICENSE create mode 100644 java/sca/contrib/modules/binding-sca-axis2/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/binding-sca-axis2/NOTICE create mode 100644 java/sca/contrib/modules/binding-sca-axis2/pom.xml create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/main/java/org/apache/tuscany/sca/binding/sca/axis2/impl/Axis2SCABindingInvoker.java create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/main/java/org/apache/tuscany/sca/binding/sca/axis2/impl/Axis2SCABindingProviderFactory.java create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/main/java/org/apache/tuscany/sca/binding/sca/axis2/impl/Axis2SCAReferenceBindingProvider.java create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/main/java/org/apache/tuscany/sca/binding/sca/axis2/impl/Axis2SCAServiceBindingProvider.java create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/main/java/org/apache/tuscany/sca/binding/sca/axis2/impl/Axis2SCAServiceProvider.java create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.BindingProviderFactory create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/AsynchTestCase.java create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/BindingScaEndpointResolverFactoryImpl.java create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/BindingScaEndpointResolverImpl.java create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/CallbackTestCase.java create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/PromotionTestCase.java create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/SimpleTestCase.java create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/HelloWorldCallbackRemote.java create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/HelloWorldClient.java create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/HelloWorldServiceCallbackOnewayRemote.java create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/HelloWorldServiceCallbackRemote.java create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/HelloWorldServiceLocal.java create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/HelloWorldServiceRemote.java create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/HelloWorldServiceRemote2.java create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/impl/HelloWorldClientCallbackOnewayRemoteImpl.java create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/impl/HelloWorldClientCallbackRemoteImpl.java create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/impl/HelloWorldClientLocalImpl.java create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/impl/HelloWorldClientRemote2Impl.java create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/impl/HelloWorldClientRemoteImpl.java create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/impl/HelloWorldServiceCallbackOnewayRemoteImpl.java create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/impl/HelloWorldServiceCallbackRemoteImpl.java create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/impl/HelloWorldServiceLocalImpl.java create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/impl/HelloWorldServiceMultipleServicesImpl.java create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/impl/HelloWorldServiceRemoteImpl.java create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/test/resources/META-INF/services/org.apache.tuscany.sca.endpointresolver.EndpointResolverFactory create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeA/HelloWorld.composite create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeA/META-INF/sca-contribution.xml create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeB/HelloWorld.composite create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeB/META-INF/sca-contribution.xml create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeC/HelloWorld.composite create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeC/HelloWorldComponent.composite create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeC/META-INF/sca-contribution.xml create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeD/HelloWorld.composite create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeD/HelloWorldComponent.composite create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeD/META-INF/sca-contribution.xml create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeE/HelloWorld.composite create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeE/META-INF/sca-contribution.xml create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeF/HelloWorld.composite create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeF/META-INF/sca-contribution.xml create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeG/HelloWorld.composite create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeG/META-INF/sca-contribution.xml create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeH/HelloWorld.composite create mode 100644 java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeH/META-INF/sca-contribution.xml create mode 100644 java/sca/contrib/modules/binding-sca-corba/LICENSE create mode 100644 java/sca/contrib/modules/binding-sca-corba/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/binding-sca-corba/NOTICE create mode 100644 java/sca/contrib/modules/binding-sca-corba/pom.xml create mode 100644 java/sca/contrib/modules/binding-sca-corba/src/main/java/org/apache/tuscany/sca/binding/sca/corba/impl/CorbaSCABindingProviderFactory.java create mode 100644 java/sca/contrib/modules/binding-sca-corba/src/main/java/org/apache/tuscany/sca/binding/sca/corba/impl/CorbaSCAInvocationProxy.java create mode 100644 java/sca/contrib/modules/binding-sca-corba/src/main/java/org/apache/tuscany/sca/binding/sca/corba/impl/CorbaSCAInvoker.java create mode 100644 java/sca/contrib/modules/binding-sca-corba/src/main/java/org/apache/tuscany/sca/binding/sca/corba/impl/CorbaSCAReferenceBindingProvider.java create mode 100644 java/sca/contrib/modules/binding-sca-corba/src/main/java/org/apache/tuscany/sca/binding/sca/corba/impl/CorbaSCAServiceBindingProvider.java create mode 100644 java/sca/contrib/modules/binding-sca-corba/src/main/java/org/apache/tuscany/sca/binding/sca/corba/impl/WrappedSCAException.java create mode 100644 java/sca/contrib/modules/binding-sca-corba/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.BindingProviderFactory create mode 100644 java/sca/contrib/modules/common-xml/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/common-xml/pom.xml create mode 100644 java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/SimpleTypeMapper.java create mode 100644 java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/XSDDataTypeConverter.java create mode 100644 java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/dom/DOMHelper.java create mode 100644 java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/dom/SAX2DOMAdapter.java create mode 100644 java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/DOMXMLStreamReader.java create mode 100644 java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/DOMXmlNodeImpl.java create mode 100644 java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/DelegatingNamespaceContext.java create mode 100644 java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/NameValueArrayStreamReader.java create mode 100644 java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/NameValuePairStreamReader.java create mode 100644 java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/NamedProperty.java create mode 100644 java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/NilElementStreamReader.java create mode 100644 java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/SimpleXmlNodeImpl.java create mode 100644 java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/StAX2SAXAdapter.java create mode 100644 java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/StAXHelper.java create mode 100644 java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/WrappingXMLStreamReader.java create mode 100644 java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/XMLDocumentStreamReader.java create mode 100644 java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/XMLFragmentStreamReader.java create mode 100644 java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/XMLFragmentStreamReaderImpl.java create mode 100644 java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/XMLStreamSerializer.java create mode 100644 java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/XMLStreamable.java create mode 100644 java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/XmlNode.java create mode 100644 java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/XmlNodeIterator.java create mode 100644 java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/XmlTreeStreamReaderImpl.java create mode 100644 java/sca/contrib/modules/common-xml/src/test/java/org/apache/tuscany/sca/common/xml/stax/StAXHelperTestCase.java create mode 100644 java/sca/contrib/modules/common-xml/src/test/java/org/apache/tuscany/sca/common/xml/stax/XmlTreeStreamReaderTestCase.java create mode 100644 java/sca/contrib/modules/compact-base/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/compact-base/pom.xml create mode 100644 java/sca/contrib/modules/contribution-osgi/LICENSE create mode 100644 java/sca/contrib/modules/contribution-osgi/NOTICE create mode 100644 java/sca/contrib/modules/contribution-osgi/pom.xml create mode 100644 java/sca/contrib/modules/contribution-osgi/src/main/java/org/apache/tuscany/sca/contribution/osgi/BundleReference.java create mode 100644 java/sca/contrib/modules/contribution-osgi/src/main/java/org/apache/tuscany/sca/contribution/osgi/impl/OSGiBundleContributionProcessor.java create mode 100644 java/sca/contrib/modules/contribution-osgi/src/main/java/org/apache/tuscany/sca/contribution/osgi/impl/OSGiBundleProcessor.java create mode 100644 java/sca/contrib/modules/contribution-osgi/src/main/java/org/apache/tuscany/sca/contribution/osgi/impl/OSGiBundleReferenceModelResolver.java create mode 100644 java/sca/contrib/modules/contribution-osgi/src/main/java/org/apache/tuscany/sca/contribution/osgi/impl/OSGiClassReferenceModelResolver.java create mode 100644 java/sca/contrib/modules/contribution-osgi/src/main/java/org/apache/tuscany/sca/contribution/osgi/impl/OSGiImportExportListener.java create mode 100644 java/sca/contrib/modules/contribution-osgi/src/main/java/org/apache/tuscany/sca/contribution/osgi/impl/OSGiModelResolverImpl.java create mode 100644 java/sca/contrib/modules/contribution-osgi/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.PackageProcessor create mode 100644 java/sca/contrib/modules/contribution-osgi/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.resolver.ModelResolver create mode 100644 java/sca/contrib/modules/contribution-osgi/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.service.ContributionListener create mode 100644 java/sca/contrib/modules/contribution-resource/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/contribution-resource/pom.xml create mode 100644 java/sca/contrib/modules/contribution-resource/src/main/java/org/apache/tuscany/sca/contribution/resource/ResourceExport.java create mode 100644 java/sca/contrib/modules/contribution-resource/src/main/java/org/apache/tuscany/sca/contribution/resource/ResourceImport.java create mode 100644 java/sca/contrib/modules/contribution-resource/src/main/java/org/apache/tuscany/sca/contribution/resource/ResourceImportExportFactory.java create mode 100644 java/sca/contrib/modules/contribution-resource/src/main/java/org/apache/tuscany/sca/contribution/resource/impl/ArtifactModelResolver.java create mode 100644 java/sca/contrib/modules/contribution-resource/src/main/java/org/apache/tuscany/sca/contribution/resource/impl/ResourceExportImpl.java create mode 100644 java/sca/contrib/modules/contribution-resource/src/main/java/org/apache/tuscany/sca/contribution/resource/impl/ResourceExportModelResolver.java create mode 100644 java/sca/contrib/modules/contribution-resource/src/main/java/org/apache/tuscany/sca/contribution/resource/impl/ResourceExportProcessor.java create mode 100644 java/sca/contrib/modules/contribution-resource/src/main/java/org/apache/tuscany/sca/contribution/resource/impl/ResourceImportExportFactoryImpl.java create mode 100644 java/sca/contrib/modules/contribution-resource/src/main/java/org/apache/tuscany/sca/contribution/resource/impl/ResourceImportImpl.java create mode 100644 java/sca/contrib/modules/contribution-resource/src/main/java/org/apache/tuscany/sca/contribution/resource/impl/ResourceImportProcessor.java create mode 100644 java/sca/contrib/modules/contribution-resource/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor create mode 100644 java/sca/contrib/modules/contribution-resource/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.resolver.ModelResolver create mode 100644 java/sca/contrib/modules/contribution-resource/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.resource.ResourceImportExportFactory create mode 100644 java/sca/contrib/modules/contribution-resource/src/main/resources/contribution-resource-validation-messages.properties create mode 100644 java/sca/contrib/modules/contribution-resource/src/test/java/org/apache/tuscany/sca/contribution/resource/impl/ResourceExportProcessorTestCase.java create mode 100644 java/sca/contrib/modules/contribution-resource/src/test/java/org/apache/tuscany/sca/contribution/resource/impl/ResourceImportProcessorTestCase.java create mode 100644 java/sca/contrib/modules/data-api/LICENSE create mode 100644 java/sca/contrib/modules/data-api/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/data-api/NOTICE create mode 100644 java/sca/contrib/modules/data-api/pom.xml create mode 100644 java/sca/contrib/modules/data-api/src/main/java/org/apache/tuscany/sca/data/collection/Collection.java create mode 100644 java/sca/contrib/modules/data-api/src/main/java/org/apache/tuscany/sca/data/collection/Entry.java create mode 100644 java/sca/contrib/modules/data-api/src/main/java/org/apache/tuscany/sca/data/collection/Item.java create mode 100644 java/sca/contrib/modules/data-api/src/main/java/org/apache/tuscany/sca/data/collection/ItemCollection.java create mode 100644 java/sca/contrib/modules/data-api/src/main/java/org/apache/tuscany/sca/data/collection/LocalItemCollection.java create mode 100644 java/sca/contrib/modules/data-api/src/main/java/org/apache/tuscany/sca/data/collection/NotFoundException.java create mode 100644 java/sca/contrib/modules/databinding-fastinfoset/LICENSE create mode 100644 java/sca/contrib/modules/databinding-fastinfoset/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/databinding-fastinfoset/NOTICE create mode 100644 java/sca/contrib/modules/databinding-fastinfoset/pom.xml create mode 100644 java/sca/contrib/modules/databinding-fastinfoset/src/main/java/org/apache/tuscany/sca/databinding/fastinfoset/FastInfoset2Node.java create mode 100644 java/sca/contrib/modules/databinding-fastinfoset/src/main/java/org/apache/tuscany/sca/databinding/fastinfoset/FastInfoset2SAX.java create mode 100644 java/sca/contrib/modules/databinding-fastinfoset/src/main/java/org/apache/tuscany/sca/databinding/fastinfoset/FastInfoset2XMLStreamReader.java create mode 100644 java/sca/contrib/modules/databinding-fastinfoset/src/main/java/org/apache/tuscany/sca/databinding/fastinfoset/Node2FastInfoset.java create mode 100644 java/sca/contrib/modules/databinding-fastinfoset/src/main/java/org/apache/tuscany/sca/databinding/fastinfoset/XMLInputStream2FastInfoset.java create mode 100644 java/sca/contrib/modules/databinding-fastinfoset/src/main/java/org/apache/tuscany/sca/databinding/fastinfoset/XMLStreamReader2FastInfoset.java create mode 100644 java/sca/contrib/modules/databinding-fastinfoset/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PullTransformer create mode 100644 java/sca/contrib/modules/databinding-fastinfoset/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PushTransformer create mode 100644 java/sca/contrib/modules/databinding-fastinfoset/src/test/java/org/apache/tuscany/sca/databinding/fastinfoset/FastInfosetTransformerTestCase.java create mode 100644 java/sca/contrib/modules/databinding-fastinfoset/src/test/resources/ipo.xsd create mode 100644 java/sca/contrib/modules/databinding-json/LICENSE create mode 100644 java/sca/contrib/modules/databinding-json/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/databinding-json/NOTICE create mode 100644 java/sca/contrib/modules/databinding-json/pom.xml create mode 100644 java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JSON2JavaBean.java create mode 100644 java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JSON2String.java create mode 100644 java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JSON2XMLStreamReader.java create mode 100644 java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JSONDataBinding.java create mode 100644 java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JSONHelper.java create mode 100644 java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JavaBean2JSON.java create mode 100644 java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JavaBean2JSONObject.java create mode 100644 java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/String2JSON.java create mode 100644 java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/XMLStreamReader2JSON.java create mode 100644 java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/axiom/JSON2OMElement.java create mode 100644 java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/axiom/JSONBadgerfishDataSource.java create mode 100644 java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/axiom/JSONDataSource.java create mode 100644 java/sca/contrib/modules/databinding-json/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.DataBinding create mode 100644 java/sca/contrib/modules/databinding-json/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PullTransformer create mode 100644 java/sca/contrib/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/JSONTransformerTestCase.java create mode 100644 java/sca/contrib/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/JavaBean2JSONTestCase.java create mode 100644 java/sca/contrib/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/MyBean.java create mode 100644 java/sca/contrib/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/MyInterface.java create mode 100644 java/sca/contrib/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/MyInterfaceImpl.java create mode 100644 java/sca/contrib/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/POJOTestCase.java create mode 100644 java/sca/contrib/modules/databinding-json/src/test/resources/ipo.xsd create mode 100644 java/sca/contrib/modules/databinding-saxon/LICENSE create mode 100644 java/sca/contrib/modules/databinding-saxon/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/databinding-saxon/NOTICE create mode 100644 java/sca/contrib/modules/databinding-saxon/pom.xml create mode 100644 java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/DataObject2NodeInfoTransformer.java create mode 100644 java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/ItemList2ObjectTransformer.java create mode 100644 java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/Node2NodeInfoTransformer.java create mode 100644 java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/NodeInfo2DataObjectTransformer.java create mode 100644 java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/NodeInfo2JavaArrayTransformer.java create mode 100644 java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/NodeInfo2NodeTransformer.java create mode 100644 java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/Object2ValueTransformer.java create mode 100644 java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/SaxonDataBindingHelper.java create mode 100644 java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/SaxonNodeDataBinding.java create mode 100644 java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/SaxonValueDataBinding.java create mode 100644 java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/SimpleType2ValueTransformer.java create mode 100644 java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/Value2JavaArray.java create mode 100644 java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/Value2ObjectTransformer.java create mode 100644 java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/Value2SimpleTypeTransformer.java create mode 100644 java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/collection/ItemList.java create mode 100644 java/sca/contrib/modules/databinding-saxon/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.DataBinding create mode 100644 java/sca/contrib/modules/databinding-saxon/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PullTransformer create mode 100644 java/sca/contrib/modules/databinding-sdo-axiom/LICENSE create mode 100644 java/sca/contrib/modules/databinding-sdo-axiom/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/databinding-sdo-axiom/NOTICE create mode 100644 java/sca/contrib/modules/databinding-sdo-axiom/pom.xml create mode 100644 java/sca/contrib/modules/databinding-sdo-axiom/src/main/java/org/apache/tuscany/sca/databinding/sdo2om/AxiomHelper.java create mode 100644 java/sca/contrib/modules/databinding-sdo-axiom/src/main/java/org/apache/tuscany/sca/databinding/sdo2om/DataObject2OMElement.java create mode 100644 java/sca/contrib/modules/databinding-sdo-axiom/src/main/java/org/apache/tuscany/sca/databinding/sdo2om/SDODataSource.java create mode 100644 java/sca/contrib/modules/databinding-sdo-axiom/src/main/java/org/apache/tuscany/sca/databinding/sdo2om/XMLDocument2OMElement.java create mode 100644 java/sca/contrib/modules/databinding-sdo-axiom/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PullTransformer create mode 100644 java/sca/contrib/modules/databinding-sdo-axiom/src/test/java/org/apache/tuscany/sca/databinding/sdo2om/DataObject2OMElementTestCase.java create mode 100644 java/sca/contrib/modules/databinding-sdo-axiom/src/test/java/org/apache/tuscany/sca/databinding/sdo2om/SDOTransformerTestCaseBase.java create mode 100644 java/sca/contrib/modules/databinding-sdo-axiom/src/test/java/org/apache/tuscany/sca/databinding/sdo2om/XMLDocument2OMElementTestCase.java create mode 100644 java/sca/contrib/modules/databinding-sdo-axiom/src/test/resources/ipo.xsd create mode 100644 java/sca/contrib/modules/databinding-sdo-axiom/src/test/resources/stock.xsd create mode 100644 java/sca/contrib/modules/databinding-sdo/LICENSE create mode 100644 java/sca/contrib/modules/databinding-sdo/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/databinding-sdo/NOTICE create mode 100644 java/sca/contrib/modules/databinding-sdo/pom.xml create mode 100644 java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/DataObject2Node.java create mode 100644 java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/DataObject2String.java create mode 100644 java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/DataObject2XMLStreamReader.java create mode 100644 java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/ImportSDO.java create mode 100644 java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/ImportSDOProcessor.java create mode 100644 java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/Node2DataObject.java create mode 100644 java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/SDOContextHelper.java create mode 100644 java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/SDODataBinding.java create mode 100644 java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/SDOSimpleTypeMapper.java create mode 100644 java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/SDOTypeHelper.java create mode 100644 java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/SDOWrapperHandler.java create mode 100644 java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/String2DataObject.java create mode 100644 java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/XMLDocument2String.java create mode 100644 java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/XMLDocument2XMLStreamReader.java create mode 100644 java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/XMLStreamReader2DataObject.java create mode 100644 java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/XMLStreamReader2XMLDocument.java create mode 100644 java/sca/contrib/modules/databinding-sdo/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor create mode 100644 java/sca/contrib/modules/databinding-sdo/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.DataBinding create mode 100644 java/sca/contrib/modules/databinding-sdo/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PullTransformer create mode 100644 java/sca/contrib/modules/databinding-sdo/src/main/resources/databinding-sdo-validation-messages.properties create mode 100644 java/sca/contrib/modules/databinding-sdo/src/test/java/com/example/stock/sdo/fault/InvalidSymbolFault_Exception.java create mode 100644 java/sca/contrib/modules/databinding-sdo/src/test/java/org/apache/tuscany/sca/databinding/sdo/DataObject2NodeTestCase.java create mode 100644 java/sca/contrib/modules/databinding-sdo/src/test/java/org/apache/tuscany/sca/databinding/sdo/DataObject2StringTestCase.java create mode 100644 java/sca/contrib/modules/databinding-sdo/src/test/java/org/apache/tuscany/sca/databinding/sdo/DataObject2XMLStreamReaderTestCase.java create mode 100644 java/sca/contrib/modules/databinding-sdo/src/test/java/org/apache/tuscany/sca/databinding/sdo/ImportSDOProcessorTestCase.java create mode 100644 java/sca/contrib/modules/databinding-sdo/src/test/java/org/apache/tuscany/sca/databinding/sdo/SDOContextHelperTestCase.java create mode 100644 java/sca/contrib/modules/databinding-sdo/src/test/java/org/apache/tuscany/sca/databinding/sdo/SDODataBindingTestCase.java create mode 100644 java/sca/contrib/modules/databinding-sdo/src/test/java/org/apache/tuscany/sca/databinding/sdo/SDOTransformerTestCaseBase.java create mode 100644 java/sca/contrib/modules/databinding-sdo/src/test/java/org/apache/tuscany/sca/databinding/sdo/SDOWrapperHandlerTestCase.java create mode 100644 java/sca/contrib/modules/databinding-sdo/src/test/java/org/apache/tuscany/sca/databinding/sdo/TestModelResolver.java create mode 100644 java/sca/contrib/modules/databinding-sdo/src/test/java/org/apache/tuscany/sca/databinding/sdo/XMLDocument2XMLStreamReaderTestCase.java create mode 100755 java/sca/contrib/modules/databinding-sdo/src/test/resources/ipo.xsd create mode 100755 java/sca/contrib/modules/databinding-sdo/src/test/resources/model/sca-core.xsd create mode 100755 java/sca/contrib/modules/databinding-sdo/src/test/resources/model/sca-implementation-mock.xsd create mode 100644 java/sca/contrib/modules/databinding-sdo/src/test/resources/stock.xsd create mode 100644 java/sca/contrib/modules/databinding-sdo/src/test/resources/wrapper.xml create mode 100644 java/sca/contrib/modules/databinding-sdo/src/test/resources/wrapper.xsd create mode 100755 java/sca/contrib/modules/databinding-xmlbeans/LICENSE create mode 100644 java/sca/contrib/modules/databinding-xmlbeans/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/databinding-xmlbeans/NOTICE create mode 100644 java/sca/contrib/modules/databinding-xmlbeans/pom.xml create mode 100644 java/sca/contrib/modules/databinding-xmlbeans/src/main/java/org/apache/tuscany/sca/databinding/xmlbeans/Node2XmlObject.java create mode 100644 java/sca/contrib/modules/databinding-xmlbeans/src/main/java/org/apache/tuscany/sca/databinding/xmlbeans/XMLBeansDataBinding.java create mode 100644 java/sca/contrib/modules/databinding-xmlbeans/src/main/java/org/apache/tuscany/sca/databinding/xmlbeans/XMLBeansWrapperHandler.java create mode 100644 java/sca/contrib/modules/databinding-xmlbeans/src/main/java/org/apache/tuscany/sca/databinding/xmlbeans/XMLStreamReader2XmlObject.java create mode 100644 java/sca/contrib/modules/databinding-xmlbeans/src/main/java/org/apache/tuscany/sca/databinding/xmlbeans/XmlObject2Node.java create mode 100644 java/sca/contrib/modules/databinding-xmlbeans/src/main/java/org/apache/tuscany/sca/databinding/xmlbeans/XmlObject2XMLStreamReader.java create mode 100644 java/sca/contrib/modules/databinding-xmlbeans/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.DataBinding create mode 100644 java/sca/contrib/modules/databinding-xmlbeans/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PullTransformer create mode 100644 java/sca/contrib/modules/databinding-xmlbeans/src/test/java/org/apache/tuscany/sca/databinding/xmlbeans/XmlObjectTestCase.java create mode 100755 java/sca/contrib/modules/databinding-xmlbeans/src/test/resources/ipo.xsd create mode 100755 java/sca/contrib/modules/databinding-xmlbeans/src/test/resources/ipo.xsdconfig create mode 100644 java/sca/contrib/modules/domain-manager/LICENSE create mode 100644 java/sca/contrib/modules/domain-manager/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/domain-manager/NOTICE create mode 100644 java/sca/contrib/modules/domain-manager/pom.xml create mode 100644 java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/CompositeConfigurationCollectionImpl.java create mode 100644 java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/CompositeConfigurationServiceImpl.java create mode 100644 java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/CompositeGeneratorServiceImpl.java create mode 100644 java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/ContributionCollectionImpl.java create mode 100644 java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/ContributionServiceImpl.java create mode 100644 java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/DeployableCompositeCollectionImpl.java create mode 100644 java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/DeployableCompositeServiceImpl.java create mode 100644 java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/DeployedCompositeCollectionImpl.java create mode 100644 java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/DomainManagerConfiguration.java create mode 100644 java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/DomainManagerConfigurationImpl.java create mode 100644 java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/DomainManagerUtil.java create mode 100644 java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/FileCollectionImpl.java create mode 100644 java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/FileServiceImpl.java create mode 100644 java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/NodeConfigurationServiceImpl.java create mode 100644 java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/NodeProcessCollectionFacadeImpl.java create mode 100644 java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/QuickStartServiceImpl.java create mode 100644 java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/launcher/DomainManagerLauncherBootstrap.java create mode 100644 java/sca/contrib/modules/domain-manager/src/main/resources/DomainManager.composite create mode 100644 java/sca/contrib/modules/domain-manager/src/main/resources/cloud-gadget.html create mode 100644 java/sca/contrib/modules/domain-manager/src/main/resources/cloud.html create mode 100644 java/sca/contrib/modules/domain-manager/src/main/resources/composite-gadget.html create mode 100644 java/sca/contrib/modules/domain-manager/src/main/resources/composite.html create mode 100644 java/sca/contrib/modules/domain-manager/src/main/resources/files-gadget.html create mode 100644 java/sca/contrib/modules/domain-manager/src/main/resources/files.html create mode 100644 java/sca/contrib/modules/domain-manager/src/main/resources/home-gadget.html create mode 100644 java/sca/contrib/modules/domain-manager/src/main/resources/home.html create mode 100644 java/sca/contrib/modules/domain-manager/src/main/resources/icons/feed-icon.png create mode 100644 java/sca/contrib/modules/domain-manager/src/main/resources/manager.css create mode 100644 java/sca/contrib/modules/domain-manager/src/main/resources/toolbar-gadget.html create mode 100644 java/sca/contrib/modules/domain-manager/src/main/resources/utils.js create mode 100644 java/sca/contrib/modules/domain-manager/src/main/resources/workspace-gadget.html create mode 100644 java/sca/contrib/modules/domain-manager/src/main/resources/workspace.html create mode 100644 java/sca/contrib/modules/domain-manager/src/test/java/org/apache/tuscany/sca/domain/manager/impl/DomainManagerTestCase.java create mode 100644 java/sca/contrib/modules/domain-manager/src/test/resources/contributions/assets/META-INF/sca-contribution.xml create mode 100644 java/sca/contrib/modules/domain-manager/src/test/resources/contributions/store/META-INF/sca-contribution.xml create mode 100644 java/sca/contrib/modules/domain-manager/src/test/resources/workspace.xml create mode 100644 java/sca/contrib/modules/host-corba-jee/LICENSE create mode 100644 java/sca/contrib/modules/host-corba-jee/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/host-corba-jee/NOTICE create mode 100644 java/sca/contrib/modules/host-corba-jee/pom.xml create mode 100644 java/sca/contrib/modules/host-corba-jee/src/main/java/org/apache/tuscany/sca/host/corba/jee/CorbaRuntimeModuleActivator.java create mode 100644 java/sca/contrib/modules/host-corba-jee/src/main/java/org/apache/tuscany/sca/host/corba/jee/JEECorbaHost.java create mode 100644 java/sca/contrib/modules/host-corba-jee/src/main/resources/META-INF/services/org.apache.tuscany.sca.core.ModuleActivator create mode 100644 java/sca/contrib/modules/host-corba-jee/src/test/java/org/apache/tuscany/sca/host/corba/jee/testing/JEECorbaHostTestCase.java create mode 100644 java/sca/contrib/modules/host-corba-jee/src/test/java/org/apache/tuscany/sca/host/corba/jee/testing/TestContext.java create mode 100644 java/sca/contrib/modules/host-corba-jee/src/test/java/org/apache/tuscany/sca/host/corba/jee/testing/TestInitialContextFactory.java create mode 100644 java/sca/contrib/modules/host-corba-jee/src/test/java/org/apache/tuscany/sca/host/corba/jee/testing/general/TestInterface.java create mode 100644 java/sca/contrib/modules/host-corba-jee/src/test/java/org/apache/tuscany/sca/host/corba/jee/testing/general/TestInterfaceHelper.java create mode 100644 java/sca/contrib/modules/host-corba-jee/src/test/java/org/apache/tuscany/sca/host/corba/jee/testing/general/TestInterfaceHolder.java create mode 100644 java/sca/contrib/modules/host-corba-jee/src/test/java/org/apache/tuscany/sca/host/corba/jee/testing/general/TestInterfaceOperations.java create mode 100644 java/sca/contrib/modules/host-corba-jee/src/test/java/org/apache/tuscany/sca/host/corba/jee/testing/general/_TestInterfaceImplBase.java create mode 100644 java/sca/contrib/modules/host-corba-jee/src/test/java/org/apache/tuscany/sca/host/corba/jee/testing/general/_TestInterfaceStub.java create mode 100644 java/sca/contrib/modules/host-corba-jee/src/test/java/org/apache/tuscany/sca/host/corba/jee/testing/servants/TestInterfaceServant.java create mode 100644 java/sca/contrib/modules/host-corba-jee/src/test/resources/general.idl create mode 100644 java/sca/contrib/modules/host-corba-jse-tns/LICENSE create mode 100644 java/sca/contrib/modules/host-corba-jse-tns/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/host-corba-jse-tns/NOTICE create mode 100644 java/sca/contrib/modules/host-corba-jse-tns/pom.xml create mode 100644 java/sca/contrib/modules/host-corba-jse-tns/src/main/java/org/apache/tuscany/sca/host/corba/jse/tns/CorbaRuntimeModuleActivator.java create mode 100644 java/sca/contrib/modules/host-corba-jse-tns/src/main/java/org/apache/tuscany/sca/host/corba/jse/tns/TnsDefaultCorbaHost.java create mode 100644 java/sca/contrib/modules/host-corba-jse-tns/src/main/resources/META-INF/services/org.apache.tuscany.sca.core.ModuleActivator create mode 100644 java/sca/contrib/modules/host-corba-jse-tns/src/test/java/org/apache/tuscany/sca/host/corba/testing/TnsDefaultCorbaHostTestCase.java create mode 100644 java/sca/contrib/modules/host-corba-jse/LICENSE create mode 100644 java/sca/contrib/modules/host-corba-jse/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/host-corba-jse/NOTICE create mode 100644 java/sca/contrib/modules/host-corba-jse/pom.xml create mode 100644 java/sca/contrib/modules/host-corba-jse/src/main/java/org/apache/tuscany/sca/host/corba/jse/CorbaRuntimeModuleActivator.java create mode 100644 java/sca/contrib/modules/host-corba-jse/src/main/java/org/apache/tuscany/sca/host/corba/jse/DefaultCorbaHost.java create mode 100644 java/sca/contrib/modules/host-corba-jse/src/main/java/org/apache/tuscany/sca/host/corba/naming/NamingContextBase.java create mode 100644 java/sca/contrib/modules/host-corba-jse/src/main/java/org/apache/tuscany/sca/host/corba/naming/TransientNameServer.java create mode 100644 java/sca/contrib/modules/host-corba-jse/src/main/java/org/apache/tuscany/sca/host/corba/naming/TransientNameService.java create mode 100644 java/sca/contrib/modules/host-corba-jse/src/main/java/org/apache/tuscany/sca/host/corba/naming/TransientNamingContext.java create mode 100644 java/sca/contrib/modules/host-corba-jse/src/main/java/org/apache/tuscany/sca/host/corba/naming/TransientServiceException.java create mode 100644 java/sca/contrib/modules/host-corba-jse/src/main/resources/META-INF/services/org.apache.tuscany.sca.core.ModuleActivator create mode 100644 java/sca/contrib/modules/host-corba-jse/src/test/java/org/apache/tuscany/sca/host/corba/testing/DefaultCorbaHostTestCase.java create mode 100644 java/sca/contrib/modules/host-corba-jse/src/test/java/org/apache/tuscany/sca/host/corba/testing/general/TestInterface.java create mode 100644 java/sca/contrib/modules/host-corba-jse/src/test/java/org/apache/tuscany/sca/host/corba/testing/general/TestInterfaceHelper.java create mode 100644 java/sca/contrib/modules/host-corba-jse/src/test/java/org/apache/tuscany/sca/host/corba/testing/general/TestInterfaceHolder.java create mode 100644 java/sca/contrib/modules/host-corba-jse/src/test/java/org/apache/tuscany/sca/host/corba/testing/general/TestInterfaceOperations.java create mode 100644 java/sca/contrib/modules/host-corba-jse/src/test/java/org/apache/tuscany/sca/host/corba/testing/general/_TestInterfaceImplBase.java create mode 100644 java/sca/contrib/modules/host-corba-jse/src/test/java/org/apache/tuscany/sca/host/corba/testing/general/_TestInterfaceStub.java create mode 100644 java/sca/contrib/modules/host-corba-jse/src/test/java/org/apache/tuscany/sca/host/corba/testing/servants/TestInterfaceServant.java create mode 100644 java/sca/contrib/modules/host-corba-jse/src/test/resources/general.idl create mode 100644 java/sca/contrib/modules/host-corba/LICENSE create mode 100644 java/sca/contrib/modules/host-corba/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/host-corba/NOTICE create mode 100644 java/sca/contrib/modules/host-corba/pom.xml create mode 100644 java/sca/contrib/modules/host-corba/src/main/java/org/apache/tuscany/sca/host/corba/CorbaHost.java create mode 100644 java/sca/contrib/modules/host-corba/src/main/java/org/apache/tuscany/sca/host/corba/CorbaHostException.java create mode 100644 java/sca/contrib/modules/host-corba/src/main/java/org/apache/tuscany/sca/host/corba/CorbaHostExtensionPoint.java create mode 100644 java/sca/contrib/modules/host-corba/src/main/java/org/apache/tuscany/sca/host/corba/CorbaHostUtils.java create mode 100644 java/sca/contrib/modules/host-corba/src/main/java/org/apache/tuscany/sca/host/corba/CorbanameURL.java create mode 100644 java/sca/contrib/modules/host-corba/src/main/java/org/apache/tuscany/sca/host/corba/DefaultCorbaHostExtensionPoint.java create mode 100644 java/sca/contrib/modules/host-corba/src/main/java/org/apache/tuscany/sca/host/corba/ExtensibleCorbaHost.java create mode 100755 java/sca/contrib/modules/host-corba/src/main/java/org/apache/tuscany/sca/host/corba/SocketUtil.java create mode 100644 java/sca/contrib/modules/host-corba/src/main/resources/META-INF/services/org.apache.tuscany.sca.host.corba.CorbaHostExtensionPoint create mode 100644 java/sca/contrib/modules/host-corba/src/test/java/org/apache/tuscany/sca/host/corba/UtilsTestCase.java create mode 100644 java/sca/contrib/modules/host-tomcat/LICENSE create mode 100644 java/sca/contrib/modules/host-tomcat/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/host-tomcat/NOTICE create mode 100644 java/sca/contrib/modules/host-tomcat/pom.xml create mode 100644 java/sca/contrib/modules/host-tomcat/src/main/java/org/apache/tuscany/sca/http/tomcat/ServletWrapper.java create mode 100644 java/sca/contrib/modules/host-tomcat/src/main/java/org/apache/tuscany/sca/http/tomcat/TomcatDefaultServlet.java create mode 100644 java/sca/contrib/modules/host-tomcat/src/main/java/org/apache/tuscany/sca/http/tomcat/TomcatServer.java create mode 100644 java/sca/contrib/modules/host-tomcat/src/main/java/org/apache/tuscany/sca/http/tomcat/module/TomcatRuntimeModuleActivator.java create mode 100644 java/sca/contrib/modules/host-tomcat/src/main/resources/META-INF/services/org.apache.tuscany.sca.core.ModuleActivator create mode 100644 java/sca/contrib/modules/host-tomcat/src/test/java/org/apache/tuscany/sca/http/tomcat/TomcatServerTestCase.java create mode 100644 java/sca/contrib/modules/host-tomcat/src/test/resources/content/test.html create mode 100644 java/sca/contrib/modules/host-tomcat/src/test/resources/tuscany.keyStore create mode 100644 java/sca/contrib/modules/host-webapp-junit/LICENSE create mode 100644 java/sca/contrib/modules/host-webapp-junit/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/host-webapp-junit/NOTICE create mode 100644 java/sca/contrib/modules/host-webapp-junit/pom.xml create mode 100644 java/sca/contrib/modules/host-webapp-junit/src/main/java/org/apache/tuscany/sca/host/webapp/junit/JUnitServletFilter.java create mode 100644 java/sca/contrib/modules/host-webapp-junit/src/main/java/org/apache/tuscany/sca/host/webapp/junit/XMLFormatter.java create mode 100644 java/sca/contrib/modules/implementation-bpel-ode/LICENSE create mode 100644 java/sca/contrib/modules/implementation-bpel-ode/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/implementation-bpel-ode/NOTICE create mode 100644 java/sca/contrib/modules/implementation-bpel-ode/pom.xml create mode 100644 java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/BPELODEDeployFile.java create mode 100644 java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/EmbeddedODEServer.java create mode 100644 java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/GeronimoTxFactory.java create mode 100644 java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/ODEBindingContext.java create mode 100644 java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/ODEDeployment.java create mode 100644 java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/ODEDeploymentException.java create mode 100644 java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/ODEExternalService.java create mode 100644 java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/ODEInitializationException.java create mode 100644 java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/ODEMessageExchangeContext.java create mode 100644 java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/ODEShutdownException.java create mode 100644 java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/TuscanyEPR.java create mode 100644 java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/TuscanyPRC.java create mode 100644 java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/TuscanyProcessConfImpl.java create mode 100644 java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/provider/BPELImplementationProvider.java create mode 100644 java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/provider/BPELImplementationProviderFactory.java create mode 100644 java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/provider/BPELInvoker.java create mode 100644 java/sca/contrib/modules/implementation-bpel-ode/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.ImplementationProviderFactory create mode 100644 java/sca/contrib/modules/implementation-bpel-ode/src/test/java/org/apache/tuscany/sca/implementation/bpel/ode/EmbeddedODEServerTestCase.java create mode 100644 java/sca/contrib/modules/implementation-bpel-ode/src/test/resources/helloworld/deploy.xml create mode 100644 java/sca/contrib/modules/implementation-bpel-ode/src/test/resources/helloworld/greetings.wsdl create mode 100644 java/sca/contrib/modules/implementation-bpel-ode/src/test/resources/helloworld/helloworld.bpel create mode 100644 java/sca/contrib/modules/implementation-bpel-ode/src/test/resources/helloworld/helloworld.wsdl create mode 100644 java/sca/contrib/modules/implementation-bpel-ode/src/test/resources/log4j.properties create mode 100644 java/sca/contrib/modules/implementation-bpel/LICENSE create mode 100644 java/sca/contrib/modules/implementation-bpel/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/implementation-bpel/NOTICE create mode 100644 java/sca/contrib/modules/implementation-bpel/pom.xml create mode 100644 java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/BPELFactory.java create mode 100644 java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/BPELImplementation.java create mode 100644 java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/BPELProcessDefinition.java create mode 100644 java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/impl/BPELFactoryImpl.java create mode 100644 java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/impl/BPELImplementationImpl.java create mode 100644 java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/impl/BPELProcessDefinitionImpl.java create mode 100644 java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/xml/BPELDocumentProcessor.java create mode 100644 java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/xml/BPELImplementationProcessor.java create mode 100644 java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/xml/BPELImportElement.java create mode 100644 java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/xml/BPELPartnerLinkElement.java create mode 100644 java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/xml/BPELPartnerLinkTypeElement.java create mode 100644 java/sca/contrib/modules/implementation-bpel/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor create mode 100644 java/sca/contrib/modules/implementation-bpel/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.URLArtifactProcessor create mode 100644 java/sca/contrib/modules/implementation-bpel/src/main/resources/META-INF/services/org.apache.tuscany.sca.implementation.bpel.BPELFactory create mode 100644 java/sca/contrib/modules/implementation-bpel/src/main/resources/impl-bpel-validation-messages.properties create mode 100644 java/sca/contrib/modules/implementation-bpel/src/test/java/org/apache/tuscany/sca/implementation/bpel/BPELDocumentProcessorTestCase.java create mode 100644 java/sca/contrib/modules/implementation-bpel/src/test/java/org/apache/tuscany/sca/implementation/bpel/BPELImplementationProcessorTestCase.java create mode 100644 java/sca/contrib/modules/implementation-bpel/src/test/resources/helloworld/helloworld.bpel create mode 100644 java/sca/contrib/modules/implementation-bpel/src/test/resources/helloworld/helloworld.wsdl create mode 100644 java/sca/contrib/modules/implementation-ejb/LICENSE create mode 100644 java/sca/contrib/modules/implementation-ejb/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/implementation-ejb/NOTICE create mode 100644 java/sca/contrib/modules/implementation-ejb/pom.xml create mode 100644 java/sca/contrib/modules/implementation-ejb/src/main/java/org/apache/tuscany/sca/implementation/ejb/EJBImplementation.java create mode 100644 java/sca/contrib/modules/implementation-ejb/src/main/java/org/apache/tuscany/sca/implementation/ejb/EJBImplementationFactory.java create mode 100644 java/sca/contrib/modules/implementation-ejb/src/main/java/org/apache/tuscany/sca/implementation/ejb/impl/EJBImplementationFactoryImpl.java create mode 100644 java/sca/contrib/modules/implementation-ejb/src/main/java/org/apache/tuscany/sca/implementation/ejb/impl/EJBImplementationImpl.java create mode 100644 java/sca/contrib/modules/implementation-ejb/src/main/java/org/apache/tuscany/sca/implementation/ejb/xml/EJBImplementationProcessor.java create mode 100644 java/sca/contrib/modules/implementation-ejb/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor create mode 100644 java/sca/contrib/modules/implementation-ejb/src/main/resources/META-INF/services/org.apache.tuscany.sca.implementation.ejb.EJBImplementationFactory create mode 100644 java/sca/contrib/modules/implementation-ejb/src/main/resources/impl-ejb-validation-messages.properties create mode 100644 java/sca/contrib/modules/implementation-ejb/src/test/java/org/apache/tuscany/sca/implementation/ejb/xml/ReadTestCase.java create mode 100644 java/sca/contrib/modules/implementation-ejb/src/test/java/org/apache/tuscany/sca/implementation/ejb/xml/WriteTestCase.java create mode 100644 java/sca/contrib/modules/implementation-ejb/src/test/resources/org/apache/tuscany/sca/implementation/ejb/xml/TestEJB.composite create mode 100644 java/sca/contrib/modules/implementation-osgi/LICENSE create mode 100644 java/sca/contrib/modules/implementation-osgi/NOTICE create mode 100644 java/sca/contrib/modules/implementation-osgi/pom.xml create mode 100644 java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/OSGiImplementation.java create mode 100644 java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/context/OSGiAnnotations.java create mode 100644 java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/context/OSGiPropertyInjector.java create mode 100644 java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/context/OSGiPropertyValueObjectFactory.java create mode 100644 java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/impl/OSGiImplementationImpl.java create mode 100644 java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/runtime/OSGiImplementationProvider.java create mode 100644 java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/runtime/OSGiImplementationProviderFactory.java create mode 100644 java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/runtime/OSGiInstanceWrapper.java create mode 100644 java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/runtime/OSGiRemotableInvoker.java create mode 100644 java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/runtime/OSGiTargetInvoker.java create mode 100644 java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/xml/OSGiImplementationProcessor.java create mode 100644 java/sca/contrib/modules/implementation-osgi/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor create mode 100644 java/sca/contrib/modules/implementation-osgi/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.ImplementationProviderFactory create mode 100644 java/sca/contrib/modules/implementation-osgi/src/main/resources/impl-osgi-validation-messages.properties create mode 100644 java/sca/contrib/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/runtime/OSGiPropertyTestCase.java create mode 100644 java/sca/contrib/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/runtime/OSGiTestCase.java create mode 100644 java/sca/contrib/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/test/OSGiTestBundles.java create mode 100644 java/sca/contrib/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/test/OSGiTestImpl.java create mode 100644 java/sca/contrib/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/test/OSGiTestInterface.java create mode 100644 java/sca/contrib/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/test/OSGiTestWithPropertyImpl.java create mode 100644 java/sca/contrib/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/xml/OSGiReadImplTestCase.java create mode 100644 java/sca/contrib/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/xml/TestModelResolver.java create mode 100644 java/sca/contrib/modules/implementation-osgi/src/test/resources/OSGiTestService.componentType create mode 100644 java/sca/contrib/modules/implementation-osgi/src/test/resources/osgiproptest.composite create mode 100644 java/sca/contrib/modules/implementation-osgi/src/test/resources/osgitest.composite create mode 100644 java/sca/contrib/modules/implementation-pojo/LICENSE create mode 100644 java/sca/contrib/modules/implementation-pojo/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/implementation-pojo/NOTICE create mode 100644 java/sca/contrib/modules/implementation-pojo/pom.xml create mode 100644 java/sca/contrib/modules/implementation-pojo/src/main/java/org/apache/tuscany/sca/pojo/JavaConstructor.java create mode 100644 java/sca/contrib/modules/implementation-pojo/src/main/java/org/apache/tuscany/sca/pojo/JavaElement.java create mode 100644 java/sca/contrib/modules/implementation-pojo/src/main/java/org/apache/tuscany/sca/pojo/JavaFactory.java create mode 100644 java/sca/contrib/modules/implementation-pojo/src/main/java/org/apache/tuscany/sca/pojo/JavaParameter.java create mode 100644 java/sca/contrib/modules/implementation-pojo/src/main/java/org/apache/tuscany/sca/pojo/JavaResource.java create mode 100644 java/sca/contrib/modules/implementation-pojo/src/main/java/org/apache/tuscany/sca/pojo/impl/JavaConstructorImpl.java create mode 100644 java/sca/contrib/modules/implementation-pojo/src/main/java/org/apache/tuscany/sca/pojo/impl/JavaElementImpl.java create mode 100644 java/sca/contrib/modules/implementation-pojo/src/main/java/org/apache/tuscany/sca/pojo/impl/JavaFactoryImpl.java create mode 100644 java/sca/contrib/modules/implementation-pojo/src/main/java/org/apache/tuscany/sca/pojo/impl/JavaParameterImpl.java create mode 100644 java/sca/contrib/modules/implementation-pojo/src/main/java/org/apache/tuscany/sca/pojo/impl/JavaResourceImpl.java create mode 100644 java/sca/contrib/modules/implementation-pojo/src/main/resources/META-INF/services/org.apache.tuscany.sca.pojo.JavaFactory create mode 100644 java/sca/contrib/modules/implementation-resource-runtime/LICENSE create mode 100644 java/sca/contrib/modules/implementation-resource-runtime/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/implementation-resource-runtime/NOTICE create mode 100644 java/sca/contrib/modules/implementation-resource-runtime/pom.xml create mode 100644 java/sca/contrib/modules/implementation-resource-runtime/src/main/java/org/apache/tuscany/sca/implementation/resource/provider/GetResourceInvoker.java create mode 100644 java/sca/contrib/modules/implementation-resource-runtime/src/main/java/org/apache/tuscany/sca/implementation/resource/provider/ResourceImplementationProvider.java create mode 100644 java/sca/contrib/modules/implementation-resource-runtime/src/main/java/org/apache/tuscany/sca/implementation/resource/provider/ResourceImplementationProviderFactory.java create mode 100644 java/sca/contrib/modules/implementation-resource-runtime/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.ImplementationProviderFactory create mode 100644 java/sca/contrib/modules/implementation-resource-runtime/src/test/java/org/apache/tuscany/sca/implementation/resource/ResourceImplementationTestCase.java create mode 100644 java/sca/contrib/modules/implementation-resource-runtime/src/test/resources/content/test.html create mode 100644 java/sca/contrib/modules/implementation-resource-runtime/src/test/resources/resource.composite create mode 100644 java/sca/contrib/modules/implementation-resource/LICENSE create mode 100644 java/sca/contrib/modules/implementation-resource/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/implementation-resource/NOTICE create mode 100644 java/sca/contrib/modules/implementation-resource/pom.xml create mode 100644 java/sca/contrib/modules/implementation-resource/src/main/java/org/apache/tuscany/sca/implementation/resource/Resource.java create mode 100644 java/sca/contrib/modules/implementation-resource/src/main/java/org/apache/tuscany/sca/implementation/resource/ResourceImplementation.java create mode 100644 java/sca/contrib/modules/implementation-resource/src/main/java/org/apache/tuscany/sca/implementation/resource/ResourceImplementationFactory.java create mode 100644 java/sca/contrib/modules/implementation-resource/src/main/java/org/apache/tuscany/sca/implementation/resource/impl/ResourceImplementationFactoryImpl.java create mode 100644 java/sca/contrib/modules/implementation-resource/src/main/java/org/apache/tuscany/sca/implementation/resource/impl/ResourceImplementationImpl.java create mode 100644 java/sca/contrib/modules/implementation-resource/src/main/java/org/apache/tuscany/sca/implementation/resource/impl/ResourceImplementationProcessor.java create mode 100644 java/sca/contrib/modules/implementation-resource/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor create mode 100644 java/sca/contrib/modules/implementation-resource/src/main/resources/META-INF/services/org.apache.tuscany.sca.implementation.resource.ResourceImplementationFactory create mode 100644 java/sca/contrib/modules/implementation-resource/src/main/resources/impl-resource-validation-messages.properties create mode 100644 java/sca/contrib/modules/implementation-script-runtime/LICENSE create mode 100644 java/sca/contrib/modules/implementation-script-runtime/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/implementation-script-runtime/NOTICE create mode 100644 java/sca/contrib/modules/implementation-script-runtime/pom.xml create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/main/java/org/apache/tuscany/sca/implementation/script/engines/TuscanyJRubyScriptEngine.java create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/main/java/org/apache/tuscany/sca/implementation/script/provider/ScriptImplementationProvider.java create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/main/java/org/apache/tuscany/sca/implementation/script/provider/ScriptImplementationProviderFactory.java create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/main/java/org/apache/tuscany/sca/implementation/script/provider/ScriptInvoker.java create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/main/java/org/apache/tuscany/sca/implementation/script/provider/ScriptPropertyFactory.java create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.ImplementationProviderFactory create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/java/org/apache/tuscany/sca/implementation/script/itests/AbstractSCATestCase.java create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/java/org/apache/tuscany/sca/implementation/script/itests/helloworld/AbstractHelloWorldTestCase.java create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/java/org/apache/tuscany/sca/implementation/script/itests/helloworld/GroovyHelloWorldTestCase.java create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/java/org/apache/tuscany/sca/implementation/script/itests/helloworld/HelloWorld.java create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/java/org/apache/tuscany/sca/implementation/script/itests/helloworld/HelloWorldProxy.java create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/java/org/apache/tuscany/sca/implementation/script/itests/helloworld/JRubyHelloWorldTestCase.java create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/java/org/apache/tuscany/sca/implementation/script/itests/helloworld/JavaScriptHelloWorldTestCase.java create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/java/org/apache/tuscany/sca/implementation/script/itests/helloworld/JythonHelloWorldTestCase.java create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/java/org/apache/tuscany/sca/implementation/script/itests/properties/AbstractHelloWorldTestCase.java create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/java/org/apache/tuscany/sca/implementation/script/itests/properties/GroovyHelloWorldTestCase.java create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/java/org/apache/tuscany/sca/implementation/script/itests/properties/HelloWorld.java create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/java/org/apache/tuscany/sca/implementation/script/itests/properties/HelloWorldProxy.java create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/java/org/apache/tuscany/sca/implementation/script/itests/properties/JRubyHelloWorldTestCase.java create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/java/org/apache/tuscany/sca/implementation/script/itests/properties/JavaScriptHelloWorldTestCase.java create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/java/org/apache/tuscany/sca/implementation/script/itests/properties/JythonHelloWorldTestCase.java create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/java/org/apache/tuscany/sca/implementation/script/itests/references/GroovyReferenceTestCase.java create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/java/org/apache/tuscany/sca/implementation/script/itests/references/HelloWorldTarget.java create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/java/org/apache/tuscany/sca/implementation/script/itests/references/JRubyReferenceTestCase.java create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/java/org/apache/tuscany/sca/implementation/script/itests/references/JavaScriptReferenceTestCase.java create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/java/org/apache/tuscany/sca/implementation/script/itests/references/JythonReferenceTestCase.java create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/resources/org/apache/tuscany/sca/implementation/script/itests/helloworld/GroovyHelloWorld.composite create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/resources/org/apache/tuscany/sca/implementation/script/itests/helloworld/JRubyHelloWorld.composite create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/resources/org/apache/tuscany/sca/implementation/script/itests/helloworld/JavaScriptHelloWorld.composite create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/resources/org/apache/tuscany/sca/implementation/script/itests/helloworld/JythonHelloWorld.composite create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/resources/org/apache/tuscany/sca/implementation/script/itests/helloworld/helloworld.componentType create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/resources/org/apache/tuscany/sca/implementation/script/itests/helloworld/helloworld.groovy create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/resources/org/apache/tuscany/sca/implementation/script/itests/helloworld/helloworld.js create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/resources/org/apache/tuscany/sca/implementation/script/itests/helloworld/helloworld.py create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/resources/org/apache/tuscany/sca/implementation/script/itests/helloworld/helloworld.rb create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/resources/org/apache/tuscany/sca/implementation/script/itests/properties/GroovyHelloWorld.composite create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/resources/org/apache/tuscany/sca/implementation/script/itests/properties/JRubyHelloWorld.composite create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/resources/org/apache/tuscany/sca/implementation/script/itests/properties/JavaScriptHelloWorld.composite create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/resources/org/apache/tuscany/sca/implementation/script/itests/properties/JythonHelloWorld.composite create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/resources/org/apache/tuscany/sca/implementation/script/itests/properties/helloworld.componentType create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/resources/org/apache/tuscany/sca/implementation/script/itests/properties/helloworld.groovy create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/resources/org/apache/tuscany/sca/implementation/script/itests/properties/helloworld.js create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/resources/org/apache/tuscany/sca/implementation/script/itests/properties/helloworld.py create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/resources/org/apache/tuscany/sca/implementation/script/itests/properties/helloworld.rb create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/resources/org/apache/tuscany/sca/implementation/script/itests/references/GroovyReference.composite create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/resources/org/apache/tuscany/sca/implementation/script/itests/references/JRubyReference.composite create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/resources/org/apache/tuscany/sca/implementation/script/itests/references/JavaScriptReference.composite create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/resources/org/apache/tuscany/sca/implementation/script/itests/references/JythonReference.composite create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/resources/org/apache/tuscany/sca/implementation/script/itests/references/reference.componentType create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/resources/org/apache/tuscany/sca/implementation/script/itests/references/reference.groovy create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/resources/org/apache/tuscany/sca/implementation/script/itests/references/reference.js create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/resources/org/apache/tuscany/sca/implementation/script/itests/references/reference.py create mode 100644 java/sca/contrib/modules/implementation-script-runtime/src/test/resources/org/apache/tuscany/sca/implementation/script/itests/references/reference.rb create mode 100644 java/sca/contrib/modules/implementation-script/LICENSE create mode 100644 java/sca/contrib/modules/implementation-script/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/implementation-script/NOTICE create mode 100644 java/sca/contrib/modules/implementation-script/pom.xml create mode 100644 java/sca/contrib/modules/implementation-script/src/main/java/org/apache/tuscany/sca/implementation/script/ScriptImplementation.java create mode 100644 java/sca/contrib/modules/implementation-script/src/main/java/org/apache/tuscany/sca/implementation/script/ScriptImplementationProcessor.java create mode 100644 java/sca/contrib/modules/implementation-script/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/LICENSE create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/NOTICE create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/pom.xml create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/main/java/org/apache/tuscany/sca/implementation/spring/impl/SCAApplicationContext.java create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/main/java/org/apache/tuscany/sca/implementation/spring/impl/SCANamespaceHandlerResolver.java create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/main/java/org/apache/tuscany/sca/implementation/spring/impl/SCAParentApplicationContext.java create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/main/java/org/apache/tuscany/sca/implementation/spring/impl/ScaNamespaceHandler.java create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/main/java/org/apache/tuscany/sca/implementation/spring/impl/ScaPropertyBeanDefinitionParser.java create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/main/java/org/apache/tuscany/sca/implementation/spring/impl/ScaReferenceBeanDefinitionParser.java create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/main/java/org/apache/tuscany/sca/implementation/spring/impl/ScaServiceBeanDefinitionParser.java create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/main/java/org/apache/tuscany/sca/implementation/spring/provider/SpringImplementationProvider.java create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/main/java/org/apache/tuscany/sca/implementation/spring/provider/SpringImplementationProviderFactory.java create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/main/java/org/apache/tuscany/sca/implementation/spring/provider/SpringInvocationException.java create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/main/java/org/apache/tuscany/sca/implementation/spring/provider/SpringInvoker.java create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.ImplementationProviderFactory create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/test/java/org/apache/tuscany/sca/implementation/spring/itests/AbstractSCATestCase.java create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/test/java/org/apache/tuscany/sca/implementation/spring/itests/helloworld/AbstractHelloWorldTestCase.java create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/test/java/org/apache/tuscany/sca/implementation/spring/itests/helloworld/HelloWorld.java create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/test/java/org/apache/tuscany/sca/implementation/spring/itests/helloworld/HelloWorldImpl.java create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/test/java/org/apache/tuscany/sca/implementation/spring/itests/helloworld/HelloWorldProxy.java create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/test/java/org/apache/tuscany/sca/implementation/spring/itests/helloworld/SpringContextAccessTestCase.java create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/test/java/org/apache/tuscany/sca/implementation/spring/itests/helloworld/SpringExplicitHelloWorldTestCase.java create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/test/java/org/apache/tuscany/sca/implementation/spring/itests/helloworld/SpringExplicitReferenceTestCase.java create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/test/java/org/apache/tuscany/sca/implementation/spring/itests/helloworld/SpringHelloWorldTestCase.java create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/test/java/org/apache/tuscany/sca/implementation/spring/itests/helloworld/SpringImplicitReferenceTestCase.java create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/test/java/org/apache/tuscany/sca/implementation/spring/itests/helloworld/SpringImportHelloWorldTestCase.java create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/test/java/org/apache/tuscany/sca/implementation/spring/itests/helloworld/SpringSCAPropertyTestCase.java create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/test/java/org/apache/tuscany/sca/implementation/spring/itests/mock/TestBean.java create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/test/java/org/apache/tuscany/sca/implementation/spring/itests/mock/TestBeanImpl.java create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/test/java/org/apache/tuscany/sca/implementation/spring/itests/mock/TestContextAccessBean.java create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/test/java/org/apache/tuscany/sca/implementation/spring/itests/mock/TestHelloWorldBean.java create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/test/java/org/apache/tuscany/sca/implementation/spring/itests/mock/TestReference.java create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/test/java/org/apache/tuscany/sca/implementation/spring/itests/mock/TestReferenceBean.java create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/test/java/org/apache/tuscany/sca/implementation/spring/itests/mock/TestSCAPropertyBean.java create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/test/resources/META-INF/sca/SpringContextAccess-context.xml create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/test/resources/META-INF/sca/SpringExplicitHelloWorld-context.xml create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/test/resources/META-INF/sca/SpringExplicitReference-context.xml create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/test/resources/META-INF/sca/SpringHelloWorld-Imported-context.xml create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/test/resources/META-INF/sca/SpringHelloWorld-context.xml create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/test/resources/META-INF/sca/SpringImplicitReference-context.xml create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/test/resources/META-INF/sca/SpringImportHelloWorld-context.xml create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/test/resources/META-INF/sca/testReferenceContext.xml create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/test/resources/META-INF/sca/testServiceContext.xml create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/test/resources/SpringHelloWorld-Imported-context.xml create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/test/resources/org/apache/tuscany/sca/implementation/spring/itests/helloworld/SpringContextAccess.composite create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/test/resources/org/apache/tuscany/sca/implementation/spring/itests/helloworld/SpringExplicitHelloWorld.composite create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/test/resources/org/apache/tuscany/sca/implementation/spring/itests/helloworld/SpringExplicitReference.composite create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/test/resources/org/apache/tuscany/sca/implementation/spring/itests/helloworld/SpringHelloWorld.composite create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/test/resources/org/apache/tuscany/sca/implementation/spring/itests/helloworld/SpringImplicitReference.composite create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/test/resources/org/apache/tuscany/sca/implementation/spring/itests/helloworld/SpringImportHelloWorld.composite create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/test/resources/org/apache/tuscany/sca/implementation/spring/itests/helloworld/SpringSCAProperty.composite create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/test/resources/spring/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/test/resources/spring/META-INF/spring/SpringSCAProperty-context.xml create mode 100644 java/sca/contrib/modules/implementation-spring-runtime/src/test/resources/test.xml create mode 100644 java/sca/contrib/modules/implementation-spring/LICENSE create mode 100644 java/sca/contrib/modules/implementation-spring/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/implementation-spring/NOTICE create mode 100644 java/sca/contrib/modules/implementation-spring/pom.xml create mode 100644 java/sca/contrib/modules/implementation-spring/src/main/java/org/apache/tuscany/sca/implementation/spring/SpringBeanNotFoundException.java create mode 100644 java/sca/contrib/modules/implementation-spring/src/main/java/org/apache/tuscany/sca/implementation/spring/SpringImplementation.java create mode 100644 java/sca/contrib/modules/implementation-spring/src/main/java/org/apache/tuscany/sca/implementation/spring/SpringImplementationProcessor.java create mode 100644 java/sca/contrib/modules/implementation-spring/src/main/java/org/apache/tuscany/sca/implementation/spring/processor/ComponentNameAnnotationProcessor.java create mode 100644 java/sca/contrib/modules/implementation-spring/src/main/java/org/apache/tuscany/sca/implementation/spring/processor/ConstructorAnnotationProcessor.java create mode 100644 java/sca/contrib/modules/implementation-spring/src/main/java/org/apache/tuscany/sca/implementation/spring/processor/InitDestroyAnnotationProcessor.java create mode 100644 java/sca/contrib/modules/implementation-spring/src/main/java/org/apache/tuscany/sca/implementation/spring/processor/PropertyAnnotationProcessor.java create mode 100644 java/sca/contrib/modules/implementation-spring/src/main/java/org/apache/tuscany/sca/implementation/spring/processor/ReferenceAnnotationProcessor.java create mode 100644 java/sca/contrib/modules/implementation-spring/src/main/java/org/apache/tuscany/sca/implementation/spring/xml/Constants.java create mode 100644 java/sca/contrib/modules/implementation-spring/src/main/java/org/apache/tuscany/sca/implementation/spring/xml/SpringBeanElement.java create mode 100644 java/sca/contrib/modules/implementation-spring/src/main/java/org/apache/tuscany/sca/implementation/spring/xml/SpringBeanIntrospector.java create mode 100644 java/sca/contrib/modules/implementation-spring/src/main/java/org/apache/tuscany/sca/implementation/spring/xml/SpringConstructorArgElement.java create mode 100644 java/sca/contrib/modules/implementation-spring/src/main/java/org/apache/tuscany/sca/implementation/spring/xml/SpringPropertyElement.java create mode 100644 java/sca/contrib/modules/implementation-spring/src/main/java/org/apache/tuscany/sca/implementation/spring/xml/SpringSCAPropertyElement.java create mode 100644 java/sca/contrib/modules/implementation-spring/src/main/java/org/apache/tuscany/sca/implementation/spring/xml/SpringSCAReferenceElement.java create mode 100644 java/sca/contrib/modules/implementation-spring/src/main/java/org/apache/tuscany/sca/implementation/spring/xml/SpringSCAServiceElement.java create mode 100644 java/sca/contrib/modules/implementation-spring/src/main/java/org/apache/tuscany/sca/implementation/spring/xml/SpringXMLComponentTypeLoader.java create mode 100644 java/sca/contrib/modules/implementation-spring/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor create mode 100644 java/sca/contrib/modules/implementation-spring/src/main/resources/META-INF/spring.handlers create mode 100644 java/sca/contrib/modules/implementation-spring/src/main/resources/META-INF/spring.schemas create mode 100644 java/sca/contrib/modules/implementation-spring/src/main/resources/impl-spring-validation-messages.properties create mode 100644 java/sca/contrib/modules/implementation-spring/src/main/resources/org/springframework/sca/xml/spring-sca.xsd create mode 100644 java/sca/contrib/modules/implementation-widget-runtime/LICENSE create mode 100644 java/sca/contrib/modules/implementation-widget-runtime/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/implementation-widget-runtime/NOTICE create mode 100644 java/sca/contrib/modules/implementation-widget-runtime/pom.xml create mode 100644 java/sca/contrib/modules/implementation-widget-runtime/src/main/java/org/apache/tuscany/sca/implementation/widget/provider/WidgetImplementationInvoker.java create mode 100644 java/sca/contrib/modules/implementation-widget-runtime/src/main/java/org/apache/tuscany/sca/implementation/widget/provider/WidgetImplementationProvider.java create mode 100644 java/sca/contrib/modules/implementation-widget-runtime/src/main/java/org/apache/tuscany/sca/implementation/widget/provider/WidgetImplementationProviderFactory.java create mode 100644 java/sca/contrib/modules/implementation-widget-runtime/src/main/java/org/apache/tuscany/sca/implementation/widget/provider/WidgetProxyHelper.java create mode 100644 java/sca/contrib/modules/implementation-widget-runtime/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.ImplementationProviderFactory create mode 100644 java/sca/contrib/modules/implementation-widget-runtime/src/main/resources/atomModel.js create mode 100644 java/sca/contrib/modules/implementation-widget-runtime/src/main/resources/binding-atom.js create mode 100644 java/sca/contrib/modules/implementation-widget-runtime/src/main/resources/binding-http.js create mode 100644 java/sca/contrib/modules/implementation-widget-runtime/src/main/resources/binding-jsonrpc.js create mode 100644 java/sca/contrib/modules/implementation-widget-runtime/src/test/java/org/apache/tuscany/sca/implementation/widget/WidgetImplementationTestCase.java create mode 100644 java/sca/contrib/modules/implementation-widget-runtime/src/test/java/store/Catalog.java create mode 100644 java/sca/contrib/modules/implementation-widget-runtime/src/test/java/store/CatalogImpl.java create mode 100644 java/sca/contrib/modules/implementation-widget-runtime/src/test/java/store/ShoppingCartImpl.java create mode 100644 java/sca/contrib/modules/implementation-widget-runtime/src/test/resources/content/atomModel.js create mode 100644 java/sca/contrib/modules/implementation-widget-runtime/src/test/resources/content/store.html create mode 100644 java/sca/contrib/modules/implementation-widget-runtime/src/test/resources/content/storeJS.html create mode 100644 java/sca/contrib/modules/implementation-widget-runtime/src/test/resources/content/unitTests.html create mode 100644 java/sca/contrib/modules/implementation-widget-runtime/src/test/resources/widget.composite create mode 100644 java/sca/contrib/modules/implementation-widget-runtime/src/test/resources/widgetJS.composite create mode 100644 java/sca/contrib/modules/implementation-widget/LICENSE create mode 100644 java/sca/contrib/modules/implementation-widget/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/implementation-widget/NOTICE create mode 100644 java/sca/contrib/modules/implementation-widget/pom.xml create mode 100644 java/sca/contrib/modules/implementation-widget/src/main/java/org/apache/tuscany/sca/implementation/widget/Widget.java create mode 100644 java/sca/contrib/modules/implementation-widget/src/main/java/org/apache/tuscany/sca/implementation/widget/WidgetImplementation.java create mode 100644 java/sca/contrib/modules/implementation-widget/src/main/java/org/apache/tuscany/sca/implementation/widget/WidgetImplementationFactory.java create mode 100644 java/sca/contrib/modules/implementation-widget/src/main/java/org/apache/tuscany/sca/implementation/widget/WidgetImplementationIntrospector.java create mode 100644 java/sca/contrib/modules/implementation-widget/src/main/java/org/apache/tuscany/sca/implementation/widget/WidgetImplementationProcessor.java create mode 100644 java/sca/contrib/modules/implementation-widget/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor create mode 100644 java/sca/contrib/modules/implementation-widget/src/main/resources/META-INF/services/org.apache.tuscany.sca.implementation.widget.WidgetImplementationFactory create mode 100644 java/sca/contrib/modules/implementation-widget/src/main/resources/impl-widget-validation-messages.properties create mode 100644 java/sca/contrib/modules/implementation-xquery/LICENSE create mode 100644 java/sca/contrib/modules/implementation-xquery/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/implementation-xquery/NOTICE create mode 100644 java/sca/contrib/modules/implementation-xquery/pom.xml create mode 100644 java/sca/contrib/modules/implementation-xquery/src/main/java/org/apache/tuscany/sca/implementation/xquery/XQueryImplementation.java create mode 100644 java/sca/contrib/modules/implementation-xquery/src/main/java/org/apache/tuscany/sca/implementation/xquery/XQueryImplementationFactory.java create mode 100644 java/sca/contrib/modules/implementation-xquery/src/main/java/org/apache/tuscany/sca/implementation/xquery/XQueryImplementationProvider.java create mode 100644 java/sca/contrib/modules/implementation-xquery/src/main/java/org/apache/tuscany/sca/implementation/xquery/XQueryImplementationProviderFactory.java create mode 100644 java/sca/contrib/modules/implementation-xquery/src/main/java/org/apache/tuscany/sca/implementation/xquery/XQueryInvokationException.java create mode 100644 java/sca/contrib/modules/implementation-xquery/src/main/java/org/apache/tuscany/sca/implementation/xquery/XQueryInvoker.java create mode 100644 java/sca/contrib/modules/implementation-xquery/src/main/java/org/apache/tuscany/sca/implementation/xquery/impl/XQueryImplementationFactoryImpl.java create mode 100644 java/sca/contrib/modules/implementation-xquery/src/main/java/org/apache/tuscany/sca/implementation/xquery/impl/XQueryImplementationImpl.java create mode 100644 java/sca/contrib/modules/implementation-xquery/src/main/java/org/apache/tuscany/sca/implementation/xquery/xml/XQueryImplementationProcessor.java create mode 100644 java/sca/contrib/modules/implementation-xquery/src/main/java/org/apache/tuscany/sca/implementation/xquery/xml/XQueryIntrospector.java create mode 100644 java/sca/contrib/modules/implementation-xquery/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor create mode 100644 java/sca/contrib/modules/implementation-xquery/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.ImplementationProviderFactory create mode 100644 java/sca/contrib/modules/implementation-xquery/src/main/resources/impl-xquery-validation-messages.properties create mode 100644 java/sca/contrib/modules/node-dynamic/LICENSE create mode 100644 java/sca/contrib/modules/node-dynamic/NOTICE create mode 100644 java/sca/contrib/modules/node-dynamic/pom.xml create mode 100644 java/sca/contrib/modules/node-dynamic/src/main/java/org/apache/tuscany/sca/node/DynamicNodeMain.java create mode 100644 java/sca/contrib/modules/node-dynamic/src/main/resources/log4j.properties create mode 100644 java/sca/contrib/modules/node-launcher-webapp/LICENSE create mode 100644 java/sca/contrib/modules/node-launcher-webapp/NOTICE create mode 100644 java/sca/contrib/modules/node-launcher-webapp/pom.xml create mode 100644 java/sca/contrib/modules/node-launcher-webapp/src/main/webapp/META-INF/sca-contribution.xml create mode 100644 java/sca/contrib/modules/node-launcher-webapp/src/main/webapp/WEB-INF/web.xml create mode 100644 java/sca/contrib/modules/node-launcher-webapp/src/main/webapp/index.jsp create mode 100644 java/sca/contrib/modules/node-manager/LICENSE create mode 100644 java/sca/contrib/modules/node-manager/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/node-manager/NOTICE create mode 100644 java/sca/contrib/modules/node-manager/pom.xml create mode 100644 java/sca/contrib/modules/node-manager/src/main/java/org/apache/tuscany/sca/implementation/node/manager/NodeManagerUtil.java create mode 100644 java/sca/contrib/modules/node-manager/src/main/java/org/apache/tuscany/sca/implementation/node/manager/NodeProcessCollectionImpl.java create mode 100644 java/sca/contrib/modules/node-manager/src/main/java/org/apache/tuscany/sca/implementation/node/manager/PingServiceImpl.java create mode 100644 java/sca/contrib/modules/node-manager/src/main/resources/NodeDaemon.composite create mode 100644 java/sca/contrib/modules/policy-logging/LICENSE create mode 100644 java/sca/contrib/modules/policy-logging/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/policy-logging/NOTICE create mode 100644 java/sca/contrib/modules/policy-logging/pom.xml create mode 100644 java/sca/contrib/modules/policy-logging/src/main/java/org/apache/tuscany/sca/policy/logging/LoggingPolicyDefinitionsProvider.java create mode 100644 java/sca/contrib/modules/policy-logging/src/main/java/org/apache/tuscany/sca/policy/logging/jdk/JDKLoggingImplementationPolicyProvider.java create mode 100644 java/sca/contrib/modules/policy-logging/src/main/java/org/apache/tuscany/sca/policy/logging/jdk/JDKLoggingPolicy.java create mode 100644 java/sca/contrib/modules/policy-logging/src/main/java/org/apache/tuscany/sca/policy/logging/jdk/JDKLoggingPolicyInterceptor.java create mode 100644 java/sca/contrib/modules/policy-logging/src/main/java/org/apache/tuscany/sca/policy/logging/jdk/JDKLoggingPolicyProcessor.java create mode 100644 java/sca/contrib/modules/policy-logging/src/main/java/org/apache/tuscany/sca/policy/logging/jdk/JDKLoggingPolicyProviderFactory.java create mode 100644 java/sca/contrib/modules/policy-logging/src/main/java/org/apache/tuscany/sca/policy/logging/jdk/JDKLoggingReferencePolicyProvider.java create mode 100644 java/sca/contrib/modules/policy-logging/src/main/java/org/apache/tuscany/sca/policy/logging/jdk/JDKLoggingServicePolicyProvider.java create mode 100644 java/sca/contrib/modules/policy-logging/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor create mode 100644 java/sca/contrib/modules/policy-logging/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.DefinitionsProvider create mode 100644 java/sca/contrib/modules/policy-logging/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.PolicyProviderFactory create mode 100644 java/sca/contrib/modules/policy-logging/src/main/resources/org/apache/tuscany/sca/policy/logging/definitions.xml create mode 100644 java/sca/contrib/modules/policy-logging/src/test/java/org/apache/tuscany/sca/policy/logging/jdk/PolicyReadTestCase.java create mode 100644 java/sca/contrib/modules/policy-logging/src/test/resources/org/apache/tuscany/sca/policy/logging/jdk/mock_policies.xml create mode 100644 java/sca/contrib/modules/policy-reliability/LICENSE create mode 100644 java/sca/contrib/modules/policy-reliability/NOTICE create mode 100644 java/sca/contrib/modules/policy-reliability/pom.xml create mode 100644 java/sca/contrib/modules/policy-reliability/src/main/java/org/apache/tuscany/sca/policy/reliability/ReliabilityPolicyDefinitionsProvider.java create mode 100644 java/sca/contrib/modules/policy-reliability/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.SCADefinitionsProvider create mode 100644 java/sca/contrib/modules/policy-reliability/src/main/resources/org/apache/tuscany/sca/policy/reliability/definitions.xml create mode 100644 java/sca/contrib/modules/policy-security-jsr250/LICENSE create mode 100644 java/sca/contrib/modules/policy-security-jsr250/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/policy-security-jsr250/NOTICE create mode 100644 java/sca/contrib/modules/policy-security-jsr250/pom.xml create mode 100644 java/sca/contrib/modules/policy-security-jsr250/src/main/java/org/apache/tuscany/sca/policy/jsr250/JSR250Activator.java create mode 100644 java/sca/contrib/modules/policy-security-jsr250/src/main/java/org/apache/tuscany/sca/policy/jsr250/introspect/impl/JSR250PolicyProcessor.java create mode 100644 java/sca/contrib/modules/policy-security-jsr250/src/main/resources/META-INF/services/org.apache.tuscany.sca.core.ModuleActivator create mode 100644 java/sca/contrib/modules/policy-security-jsr250/src/test/java/org/apache/tuscany/sca/policy/jsr250/introspect/impl/PolicyProcessorTestCaseFIXME.java create mode 100644 java/sca/contrib/modules/policy-transaction/LICENSE create mode 100644 java/sca/contrib/modules/policy-transaction/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/policy-transaction/NOTICE create mode 100644 java/sca/contrib/modules/policy-transaction/pom.xml create mode 100644 java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/IncompatibleIntentException.java create mode 100644 java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionImplementationPolicyProvider.java create mode 100644 java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionIntent.java create mode 100644 java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionInterceptor.java create mode 100644 java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionManagerHelper.java create mode 100644 java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionManagerWrapper.java create mode 100644 java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionModuleActivator.java create mode 100644 java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionPolicy.java create mode 100644 java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionPolicyDefinitionsProvider.java create mode 100644 java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionPolicyImpl.java create mode 100644 java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionPolicyProcessor.java create mode 100644 java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionPolicyProviderFactory.java create mode 100644 java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionReferencePolicyProvider.java create mode 100644 java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionServicePolicyProvider.java create mode 100644 java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionalAction.java create mode 100644 java/sca/contrib/modules/policy-transaction/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor create mode 100644 java/sca/contrib/modules/policy-transaction/src/main/resources/META-INF/services/org.apache.tuscany.sca.core.ModuleActivator create mode 100644 java/sca/contrib/modules/policy-transaction/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.DefinitionsProvider create mode 100644 java/sca/contrib/modules/policy-transaction/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.PolicyProviderFactory create mode 100644 java/sca/contrib/modules/policy-transaction/src/main/resources/log4j.properties create mode 100644 java/sca/contrib/modules/policy-transaction/src/main/resources/org/apache/tuscany/sca/policy/transaction/definitions.xml create mode 100644 java/sca/contrib/modules/policy-transaction/src/main/resources/org/apache/tuscany/sca/policy/transaction/tuscany_definitions.xml create mode 100644 java/sca/contrib/modules/policy-transaction/src/test/java/org/apache/tuscany/sca/policy/transaction/PolicyReadTestCase.java create mode 100644 java/sca/contrib/modules/policy-transaction/src/test/java/org/apache/tuscany/sca/policy/transaction/TransactionManagerHelperTestCase.java create mode 100644 java/sca/contrib/modules/tracing-aspectj/LICENSE create mode 100644 java/sca/contrib/modules/tracing-aspectj/META-INF/MANIFEST.MF create mode 100644 java/sca/contrib/modules/tracing-aspectj/NOTICE create mode 100644 java/sca/contrib/modules/tracing-aspectj/launcher.bat create mode 100644 java/sca/contrib/modules/tracing-aspectj/pom.xml create mode 100644 java/sca/contrib/modules/tracing-aspectj/src/main/java/org/apache/tuscany/sca/aspectj/LoggingAspect.java create mode 100644 java/sca/contrib/modules/tracing-aspectj/src/main/java/org/apache/tuscany/sca/aspectj/SimpleTracingAspect.java create mode 100644 java/sca/contrib/modules/tracing-aspectj/src/main/java/org/apache/tuscany/sca/aspectj/TimingAspect.java create mode 100644 java/sca/contrib/modules/tracing-aspectj/src/main/java/org/apache/tuscany/sca/aspectj/TracingAspect.java create mode 100644 java/sca/contrib/modules/tracing-aspectj/src/main/resources/META-INF/aop.xml create mode 100644 java/sca/contrib/modules/tracing-aspectj/src/test/java/org/apache/tuscany/sca/aspectj/TracingTestCase.java (limited to 'java/sca/contrib/modules') diff --git a/java/sca/contrib/modules/binding-atom-abdera/LICENSE b/java/sca/contrib/modules/binding-atom-abdera/LICENSE new file mode 100644 index 0000000000..6e529a25c4 --- /dev/null +++ b/java/sca/contrib/modules/binding-atom-abdera/LICENSE @@ -0,0 +1,205 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + + diff --git a/java/sca/contrib/modules/binding-atom-abdera/META-INF/MANIFEST.MF b/java/sca/contrib/modules/binding-atom-abdera/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..85b23310e3 --- /dev/null +++ b/java/sca/contrib/modules/binding-atom-abdera/META-INF/MANIFEST.MF @@ -0,0 +1,55 @@ +Manifest-Version: 1.0 +Export-Package: org.apache.tuscany.sca.binding.atom.collection;uses:=" + org.oasisopen.sca.annotation,org.apache.abdera.model";version="2.0.0" +Private-Package: org.apache.tuscany.sca.binding.atom.provider;version= + "1.4" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA Atom Feed Binding Extension +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397264250 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA Atom Feed Binding Extension +Import-Package: javax.activation;version="1.1";resolution:=optional, + javax.servlet, + javax.servlet.http, + javax.xml.namespace, + + org.apache.abdera, + org.apache.abdera.factory, + org.apache.abdera.i18n.iri, + org.apache.abdera.model, + org.apache.abdera.parser, + org.apache.abdera.protocol;resolution:=optional, + org.apache.abdera.protocol.client;resolution:=optional, + org.apache.abdera.protocol.client.util;resolution:=optional, + org.apache.abdera.writer, + org.apache.commons.codec.binary, + org.apache.commons.httpclient, + org.apache.commons.httpclient.auth, + org.apache.commons.httpclient.methods, + org.apache.commons.httpclient.params, + org.apache.tuscany.sca.assembly;version="2.0.0", + org.apache.tuscany.sca.binding.atom;version="2.0.0", + org.apache.tuscany.sca.binding.atom.collection;version="2.0.0", + org.apache.tuscany.sca.binding.http;version="2.0.0", + org.apache.tuscany.sca.core;version="2.0.0", + org.apache.tuscany.sca.data.collection;version="2.0.0", + org.apache.tuscany.sca.databinding;version="2.0.0", + org.apache.tuscany.sca.databinding.impl;version="2.0.0", + org.apache.tuscany.sca.host.http;version="2.0.0", + org.apache.tuscany.sca.interfacedef;version="2.0.0", + org.apache.tuscany.sca.interfacedef.impl;version="2.0.0", + org.apache.tuscany.sca.interfacedef.util;version="2.0.0", + org.apache.tuscany.sca.invocation;version="2.0.0", + org.apache.tuscany.sca.policy;version="2.0.0", + org.apache.tuscany.sca.provider;version="2.0.0", + org.apache.tuscany.sca.runtime;version="2.0.0", + + org.oasisopen.sca;version="2.0.0", + org.oasisopen.sca.annotation;version="2.0.0" +Bundle-SymbolicName: org.apache.tuscany.sca.binding.atom.abdera +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/binding-atom-abdera/NOTICE b/java/sca/contrib/modules/binding-atom-abdera/NOTICE new file mode 100644 index 0000000000..51042eab05 --- /dev/null +++ b/java/sca/contrib/modules/binding-atom-abdera/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/binding-atom-abdera/ReceiptToms.gif b/java/sca/contrib/modules/binding-atom-abdera/ReceiptToms.gif new file mode 100644 index 0000000000..bfeee9b2f4 Binary files /dev/null and b/java/sca/contrib/modules/binding-atom-abdera/ReceiptToms.gif differ diff --git a/java/sca/contrib/modules/binding-atom-abdera/ReceiptValue.jpg b/java/sca/contrib/modules/binding-atom-abdera/ReceiptValue.jpg new file mode 100644 index 0000000000..584f39ea8d Binary files /dev/null and b/java/sca/contrib/modules/binding-atom-abdera/ReceiptValue.jpg differ diff --git a/java/sca/contrib/modules/binding-atom-abdera/pom.xml b/java/sca/contrib/modules/binding-atom-abdera/pom.xml new file mode 100644 index 0000000000..b5ccbe90e8 --- /dev/null +++ b/java/sca/contrib/modules/binding-atom-abdera/pom.xml @@ -0,0 +1,207 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + + tuscany-binding-atom-abdera + Apache Tuscany SCA Atom Feed Binding Extension + + + + org.apache.tuscany.sca + tuscany-binding-atom + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-assembly + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-interface-java + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-data-api + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-core-spi + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-databinding + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-host-http + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-binding-http + 2.0-SNAPSHOT + + + + commons-httpclient + commons-httpclient + 3.0.1 + + + + org.apache.abdera + abdera-core + 0.4.0-incubating + + + org.apache.geronimo.specs + geronimo-activation_1.0.2_spec + + + + + + org.apache.abdera + abdera-parser + 0.4.0-incubating + + + org.apache.geronimo.specs + geronimo-stax-api_1.0_spec + + + xom + xom + + + org.apache.ws.commons.axiom + axiom-impl + + + + + + org.apache.ws.commons.axiom + axiom-impl + 1.2.7 + + + + org.apache.abdera + abdera-client + 0.4.0-incubating + + + + org.apache.abdera + abdera-extensions-main + 0.4.0-incubating + + + + org.apache.abdera + abdera-extensions-json + 0.4.0-incubating + + + + javax.servlet + servlet-api + 2.5 + + + + org.apache.tuscany.sca + tuscany-host-jetty + 2.0-SNAPSHOT + test + + + + org.apache.tuscany.sca + tuscany-implementation-java-runtime + 2.0-SNAPSHOT + test + + + + org.apache.tuscany.sca + tuscany-node-impl + 2.0-SNAPSHOT + test + + + + junit + junit + 4.5 + test + + + + commons-codec + commons-codec + 1.3 + + + commons-codec + commons-codec + + + + + + commons-logging + commons-logging + 1.1.1 + + + javax.servlet + servlet-api + + + avalon-framework + avalon-framework + + + + + + + diff --git a/java/sca/contrib/modules/binding-atom-abdera/src/main/java/org/apache/tuscany/sca/binding/atom/collection/Collection.java b/java/sca/contrib/modules/binding-atom-abdera/src/main/java/org/apache/tuscany/sca/binding/atom/collection/Collection.java new file mode 100644 index 0000000000..81ec1ddad3 --- /dev/null +++ b/java/sca/contrib/modules/binding-atom-abdera/src/main/java/org/apache/tuscany/sca/binding/atom/collection/Collection.java @@ -0,0 +1,81 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.atom.collection; + +import org.apache.abdera.model.Entry; +import org.apache.abdera.model.Feed; +import org.oasisopen.sca.annotation.Remotable; + +/** + * Provides access to a collection of resources using Atom. + * + * @version $Rev$ $Date$ + */ +@Remotable +public interface Collection { + + /** + * Get an Atom feed for a collection of resources. + * + * @return the Atom feed + */ + Feed getFeed(); + + /** + * Get an Atom feed for a collection of resources resulting + * from a query. + * + * @param queryString a query string + * @return the Atom feed + */ + Feed query(String queryString); + + /** + * Creates a new entry. + * + * @param entry + * @return + */ + Entry post(Entry entry); + + /** + * Retrieves an entry. + * + * @param id + * @return + */ + Entry get(String id) throws NotFoundException; + + /** + * Update an entry. + * + * @param id + * @param entry + * @return + */ + void put(String id, Entry entry) throws NotFoundException; + + /** + * Delete an entry. + * + * @param id + */ + void delete(String id) throws NotFoundException; + +} diff --git a/java/sca/contrib/modules/binding-atom-abdera/src/main/java/org/apache/tuscany/sca/binding/atom/collection/MediaCollection.java b/java/sca/contrib/modules/binding-atom-abdera/src/main/java/org/apache/tuscany/sca/binding/atom/collection/MediaCollection.java new file mode 100644 index 0000000000..455eef81cd --- /dev/null +++ b/java/sca/contrib/modules/binding-atom-abdera/src/main/java/org/apache/tuscany/sca/binding/atom/collection/MediaCollection.java @@ -0,0 +1,55 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.atom.collection; + +import java.io.InputStream; + +import org.oasisopen.sca.annotation.Remotable; + +import org.apache.abdera.model.Entry; + +/** + * Provides access to a collection of resources using Atom. + * + * @version $Rev$ $Date$ + */ +@Remotable +public interface MediaCollection extends Collection { + + /** + * Creates a new media entry + * + * @param title + * @param slug + * @param contentType + * @param media + */ + Entry postMedia(String title, String slug, String contentType, InputStream media); + + /** + * Update a media entry. + * + * @param id + * @param contentType + * @param media + * @return + */ + void putMedia(String id, String contentType, InputStream media) throws NotFoundException; + +} diff --git a/java/sca/contrib/modules/binding-atom-abdera/src/main/java/org/apache/tuscany/sca/binding/atom/collection/NotFoundException.java b/java/sca/contrib/modules/binding-atom-abdera/src/main/java/org/apache/tuscany/sca/binding/atom/collection/NotFoundException.java new file mode 100644 index 0000000000..b457840922 --- /dev/null +++ b/java/sca/contrib/modules/binding-atom-abdera/src/main/java/org/apache/tuscany/sca/binding/atom/collection/NotFoundException.java @@ -0,0 +1,45 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.atom.collection; + +/** + * Indicates that a resource could not be found. + * + * @version $Rev$ $Date$ + */ +public class NotFoundException extends Exception { + private static final long serialVersionUID = -5046027674128627383L; + + public NotFoundException() { + } + + public NotFoundException(String message) { + super(message); + } + + public NotFoundException(Throwable cause) { + super(cause); + } + + public NotFoundException(String message, Throwable cause) { + super(message, cause); + } + +} diff --git a/java/sca/contrib/modules/binding-atom-abdera/src/main/java/org/apache/tuscany/sca/binding/atom/provider/AtomBindingInvoker.java b/java/sca/contrib/modules/binding-atom-abdera/src/main/java/org/apache/tuscany/sca/binding/atom/provider/AtomBindingInvoker.java new file mode 100644 index 0000000000..84232aa3af --- /dev/null +++ b/java/sca/contrib/modules/binding-atom-abdera/src/main/java/org/apache/tuscany/sca/binding/atom/provider/AtomBindingInvoker.java @@ -0,0 +1,485 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.atom.provider; + +import static org.apache.tuscany.sca.binding.atom.provider.AtomBindingUtil.entry; +import static org.apache.tuscany.sca.binding.atom.provider.AtomBindingUtil.feedEntry; + +import java.io.InputStreamReader; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.List; + +import org.apache.abdera.Abdera; +import org.apache.abdera.factory.Factory; +import org.apache.abdera.model.Document; +import org.apache.abdera.model.Feed; +import org.apache.abdera.parser.Parser; +import org.apache.commons.httpclient.HttpClient; +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.httpclient.methods.StringRequestEntity; +import org.apache.tuscany.sca.binding.atom.collection.NotFoundException; +import org.apache.tuscany.sca.data.collection.Entry; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; +import org.oasisopen.sca.ServiceRuntimeException; + +/** + * Invoker for the Atom binding. + * + * @version $Rev$ $Date$ + */ +class AtomBindingInvoker implements Invoker { + + private static final Factory abderaFactory = Abdera.getNewFactory(); + private static final Parser abderaParser = Abdera.getNewParser(); + + Operation operation; + String uri; + HttpClient httpClient; + String authorizationHeader; + AtomReferenceBindingProvider provider; + + AtomBindingInvoker(Operation operation, String uri, HttpClient httpClient, String authorizationHeader, AtomReferenceBindingProvider bindingProvider) { + this.operation = operation; + this.uri = uri; + this.httpClient = httpClient; + this.authorizationHeader = authorizationHeader; + this.provider = bindingProvider; + } + + public Message invoke(Message msg) { + // Shouldn't get here, as the only supported methods are + // defined in the ResourceCollection interface, and implemented + // by specific invoker subclasses + throw new UnsupportedOperationException(operation.getName()); + } + + /** + * Get operation invoker + */ + public static class GetInvoker extends AtomBindingInvoker { + + public GetInvoker(Operation operation, String uri, HttpClient httpClient, String authorizationHeader, AtomReferenceBindingProvider bindingProvider) { + super(operation, uri, httpClient, authorizationHeader, bindingProvider); + } + + @Override + public Message invoke(Message msg) { + // Get an entry + String id = (String)((Object[])msg.getBody())[0]; + + // Send an HTTP GET + GetMethod getMethod = new GetMethod(uri + "/" + id); + getMethod.setRequestHeader("Authorization", authorizationHeader); + boolean parsing = false; + try { + httpClient.executeMethod(getMethod); + int status = getMethod.getStatusCode(); + + // Read the Atom entry + if (status == 200) { + Document doc = + abderaParser.parse(new InputStreamReader(getMethod.getResponseBodyAsStream())); + parsing = true; + org.apache.abdera.model.Entry feedEntry = doc.getRoot(); + + if (provider.supportsFeedEntries()) { + + // Return the Atom entry + msg.setBody(feedEntry); + + } else { + + // Convert the feed entry to a data entry and return the data item + Entry entry = entry(feedEntry, provider.getItemClassType(), + provider.getItemXMLType(), provider.getMediator()); + msg.setBody(entry.getData()); + } + + } else if (status == 404) { + msg.setFaultBody(new NotFoundException()); + } else { + msg.setFaultBody(new ServiceRuntimeException("HTTP status code: " + status)); + } + + } catch (Exception e) { + msg.setFaultBody(new ServiceRuntimeException(e)); + } finally { + if (!parsing) { + // Release the connection unless the Abdera parser is + // parsing the response, in this case it will release it + getMethod.releaseConnection(); + } + } + + return msg; + } + } + + /** + * Post operation invoker + */ + public static class PostInvoker extends AtomBindingInvoker { + + public PostInvoker(Operation operation, String uri, HttpClient httpClient, String authorizationHeader, AtomReferenceBindingProvider bindingProvider) { + super(operation, uri, httpClient, authorizationHeader, bindingProvider); + } + + @Override + public Message invoke(Message msg) { + // Post an entry + Object[] args = (Object[])msg.getBody(); + org.apache.abdera.model.Entry feedEntry; + if (provider.supportsFeedEntries()) { + + // Expect an Atom entry + feedEntry = (org.apache.abdera.model.Entry)args[0]; + } else { + + // Expect a key and data item + Entry entry = new Entry(args[0], args[1]); + feedEntry = feedEntry(entry, provider.getItemClassType(), + provider.getItemXMLType(), provider.getMediator(), abderaFactory); + } + + // Send an HTTP POST + PostMethod postMethod = new PostMethod(uri); + postMethod.setRequestHeader("Authorization", authorizationHeader); + boolean parsing = false; + try { + + // Write the Atom entry + StringWriter writer = new StringWriter(); + feedEntry.writeTo(writer); + // postMethod.setRequestHeader("Content-type", "application/atom+xml; charset=utf-8"); + postMethod.setRequestHeader("Content-type", "application/atom+xml;type=entry"); + postMethod.setRequestEntity(new StringRequestEntity(writer.toString())); + + httpClient.executeMethod(postMethod); + int status = postMethod.getStatusCode(); + + // Read the Atom entry + if (status == 200 || status == 201) { + Document doc = abderaParser.parse(new InputStreamReader(postMethod.getResponseBodyAsStream())); + parsing = true; + org.apache.abdera.model.Entry createdEntry = doc.getRoot(); + + // Returns the created Atom entry ID + if (provider.supportsFeedEntries()) { + + // Returns the created entry + msg.setBody(createdEntry); + + } else { + + // Returns the id of the created entry + msg.setBody(createdEntry.getId().toString()); + } + + } else if (status == 404) { + msg.setFaultBody(new NotFoundException()); + } else { + msg.setFaultBody(new ServiceRuntimeException("HTTP status code: " + status)); + } + + } catch (Exception e) { + msg.setFaultBody(new ServiceRuntimeException(e)); + } finally { + if (!parsing) { + // Release the connection unless the Abdera parser is + // parsing the response, in this case it will release it + postMethod.releaseConnection(); + } + } + + return msg; + } + } + + /** + * Put operation invoker + */ + public static class PutInvoker extends AtomBindingInvoker { + + public PutInvoker(Operation operation, String uri, HttpClient httpClient, String authorizationHeader, AtomReferenceBindingProvider bindingProvider) { + super(operation, uri, httpClient, authorizationHeader, bindingProvider); + } + + @Override + public Message invoke(Message msg) { + // Put an entry + Object[] args = (Object[])msg.getBody(); + String id; + org.apache.abdera.model.Entry feedEntry; + if (provider.supportsFeedEntries()) { + + // Expect a key and Atom entry + id = (String)args[0]; + feedEntry = (org.apache.abdera.model.Entry)args[1]; + } else { + + // Expect a key and data item + id = (String)args[0]; + Entry entry = new Entry(id, args[1]); + feedEntry = feedEntry(entry, provider.getItemClassType(), + provider.getItemXMLType(), provider.getMediator(), abderaFactory); + } + + // Send an HTTP PUT + PutMethod putMethod = new PutMethod(uri + "/" + id); + putMethod.setRequestHeader("Authorization", authorizationHeader); + + try { + + // Write the Atom entry + StringWriter writer = new StringWriter(); + feedEntry.writeTo(writer); + putMethod.setRequestHeader("Content-type", "application/atom+xml; charset=utf-8"); + putMethod.setRequestEntity(new StringRequestEntity(writer.toString())); + + httpClient.executeMethod(putMethod); + int status = putMethod.getStatusCode(); + if (status == 200 || status == 201 || status == 412) { + + msg.setBody(null); + + } else if (status == 404) { + msg.setFaultBody(new NotFoundException()); + } else { + msg.setFaultBody(new ServiceRuntimeException("HTTP status code: " + status)); + } + + } catch (Exception e) { + msg.setFaultBody(new ServiceRuntimeException(e)); + } finally { + putMethod.releaseConnection(); + } + + return msg; + } + } + + /** + * Delete operation invoker + */ + public static class DeleteInvoker extends AtomBindingInvoker { + + public DeleteInvoker(Operation operation, String uri, HttpClient httpClient, String authorizationHeader, AtomReferenceBindingProvider bindingProvider) { + super(operation, uri, httpClient, authorizationHeader, bindingProvider); + } + + @Override + public Message invoke(Message msg) { + // Delete an entry + String id = (String)((Object[])msg.getBody())[0]; + + // Send an HTTP DELETE + DeleteMethod deleteMethod = new DeleteMethod(uri + "/" + id); + deleteMethod.setRequestHeader("Authorization", authorizationHeader); + try { + httpClient.executeMethod(deleteMethod); + int status = deleteMethod.getStatusCode(); + if (status == 200) { + msg.setBody(null); + + } else if (status == 404) { + msg.setFaultBody(new NotFoundException()); + } else { + msg.setFaultBody(new ServiceRuntimeException("HTTP status code: " + status)); + } + + } catch (Exception e) { + msg.setFaultBody(new ServiceRuntimeException(e)); + } finally { + deleteMethod.releaseConnection(); + } + + return msg; + } + } + + /** + * GetAll operation invoker + */ + public static class GetAllInvoker extends AtomBindingInvoker { + + public GetAllInvoker(Operation operation, String uri, HttpClient httpClient, String authorizationHeader, AtomReferenceBindingProvider bindingProvider) { + super(operation, uri, httpClient, authorizationHeader, bindingProvider); + } + + @Override + public Message invoke(Message msg) { + // Get a feed + + // Send an HTTP GET + GetMethod getMethod = new GetMethod(uri); + getMethod.setRequestHeader("Authorization", authorizationHeader); + boolean parsing = false; + try { + httpClient.executeMethod(getMethod); + int status = getMethod.getStatusCode(); + // AtomBindingInvoker.printResponseHeader( getMethod ); + + // Read the Atom feed + if (status == 200) { + Document doc = abderaParser.parse(new InputStreamReader(getMethod.getResponseBodyAsStream())); + parsing = true; + Feed feed = doc.getRoot(); + + if (provider.supportsFeedEntries()) { + + // Returns the Atom feed + msg.setBody(feed); + + } else { + + // Returns an array of data entries + List> entries = new ArrayList>(); + for (org.apache.abdera.model.Entry feedEntry: feed.getEntries()) { + Entry entry = entry(feedEntry, provider.getItemClassType(), + provider.getItemXMLType(), provider.getMediator()); + entries.add(entry); + } + msg.setBody(entries.toArray(new Entry[entries.size()])); + } + + } else if (status == 404) { + msg.setFaultBody(new NotFoundException()); + } else { + msg.setFaultBody(new ServiceRuntimeException("HTTP status code: " + status)); + } + + } catch (Exception e) { + msg.setFaultBody(new ServiceRuntimeException(e)); + } finally { + if (!parsing) { + // Release the connection unless the Abdera parser is + // parsing the response, in this case it will release it + getMethod.releaseConnection(); + } + } + + return msg; + } + } + + /** + * Query operation invoker + */ + public static class QueryInvoker extends AtomBindingInvoker { + + public QueryInvoker(Operation operation, String uri, HttpClient httpClient, String authorizationHeader, AtomReferenceBindingProvider bindingProvider) { + super(operation, uri, httpClient, authorizationHeader, bindingProvider); + } + + @Override + public Message invoke(Message msg) { + // Get a feed from a query + String queryString = (String)((Object[])msg.getBody())[0]; + + // Send an HTTP GET + GetMethod getMethod = new GetMethod(uri); + getMethod.setRequestHeader("Authorization", authorizationHeader); + getMethod.setQueryString(queryString); + boolean parsing = false; + try { + httpClient.executeMethod(getMethod); + int status = getMethod.getStatusCode(); + + // Read the Atom feed + if (status == 200) { + Document doc = abderaParser.parse(new InputStreamReader(getMethod.getResponseBodyAsStream())); + parsing = true; + Feed feed = doc.getRoot(); + + if (provider.supportsFeedEntries()) { + + // Returns the Atom feed + msg.setBody(feed); + + } else { + + // Returns an array of data entries + List> entries = new ArrayList>(); + for (org.apache.abdera.model.Entry feedEntry: feed.getEntries()) { + Entry entry = entry(feedEntry, provider.getItemClassType(), + provider.getItemXMLType(), provider.getMediator()); + entries.add(entry); + } + msg.setBody(entries.toArray(new Entry[entries.size()])); + } + + } else if (status == 404) { + msg.setFaultBody(new NotFoundException()); + } else { + msg.setFaultBody(new ServiceRuntimeException("HTTP status code: " + status)); + } + + } catch (Exception e) { + msg.setFaultBody(new ServiceRuntimeException(e)); + } finally { + if (!parsing) { + // Release the connection unless the Abdera parser is + // parsing the response, in this case it will release it + getMethod.releaseConnection(); + } + } + + return msg; + } + } + + /** + * PostMedia operation invoker + */ + public static class PostMediaInvoker extends AtomBindingInvoker { + + public PostMediaInvoker(Operation operation, String uri, HttpClient httpClient, String authorizationHeader, AtomReferenceBindingProvider bindingProvider) { + super(operation, uri, httpClient, authorizationHeader, bindingProvider); + } + + @Override + public Message invoke(Message msg) { + // PostInvoker can detect media by content type (non-Feed, non-Entry) + return super.invoke(msg); + } + } + + /** + * PutMedia operation invoker + */ + public static class PutMediaInvoker extends AtomBindingInvoker { + + public PutMediaInvoker(Operation operation, String uri, HttpClient httpClient, String authorizationHeader, AtomReferenceBindingProvider bindingProvider) { + super(operation, uri, httpClient, authorizationHeader, bindingProvider); + } + + @Override + public Message invoke(Message msg) { + // PutInvoker can detect media by content type (non-Feed, non-Entry) + return super.invoke(msg); + } + } + +} diff --git a/java/sca/contrib/modules/binding-atom-abdera/src/main/java/org/apache/tuscany/sca/binding/atom/provider/AtomBindingListenerServlet.java b/java/sca/contrib/modules/binding-atom-abdera/src/main/java/org/apache/tuscany/sca/binding/atom/provider/AtomBindingListenerServlet.java new file mode 100644 index 0000000000..f6c713fae7 --- /dev/null +++ b/java/sca/contrib/modules/binding-atom-abdera/src/main/java/org/apache/tuscany/sca/binding/atom/provider/AtomBindingListenerServlet.java @@ -0,0 +1,871 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.atom.provider; + +import static org.apache.tuscany.sca.binding.atom.provider.AtomBindingUtil.entry; +import static org.apache.tuscany.sca.binding.atom.provider.AtomBindingUtil.feedEntry; + +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.UnsupportedEncodingException; +import java.io.Writer; +import java.net.URL; +import java.net.URLDecoder; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.Enumeration; +import java.util.List; +import java.util.StringTokenizer; +import java.util.logging.Logger; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.xml.namespace.QName; + +import org.apache.abdera.Abdera; +import org.apache.abdera.factory.Factory; +import org.apache.abdera.i18n.iri.IRI; +import org.apache.abdera.model.Category; +import org.apache.abdera.model.Collection; +import org.apache.abdera.model.Document; +import org.apache.abdera.model.Element; +import org.apache.abdera.model.Feed; +import org.apache.abdera.model.Link; +import org.apache.abdera.model.Service; +import org.apache.abdera.model.Workspace; +import org.apache.abdera.parser.ParseException; +import org.apache.abdera.parser.Parser; +import org.apache.abdera.writer.WriterFactory; + +import org.apache.commons.codec.binary.Base64; +import org.apache.tuscany.sca.binding.http.HTTPCacheContext; +import org.apache.tuscany.sca.data.collection.Entry; +import org.apache.tuscany.sca.databinding.Mediator; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.impl.DataTypeImpl; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.interfacedef.util.XMLType; +import org.apache.tuscany.sca.invocation.InvocationChain; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.invocation.MessageFactory; +import org.apache.tuscany.sca.runtime.RuntimeWire; + +/** + * A resource collection binding listener, implemented as a Servlet and + * registered in a Servlet host provided by the SCA hosting runtime. + * + * @version $Rev$ $Date$ + */ +class AtomBindingListenerServlet extends HttpServlet { + private static final Logger logger = Logger.getLogger(AtomBindingListenerServlet.class.getName()); + private static final long serialVersionUID = 1L; + + private static final Factory abderaFactory = Abdera.getNewFactory(); + private static final Parser abderaParser = Abdera.getNewParser(); + private static final String ETAG = "ETag"; + private static final String LASTMODIFIED = "Last-Modified"; + private static final String LOCATION = "Location"; + private static final String CONTENTLOCATION = "Content-Location"; + private static final SimpleDateFormat dateFormat = new SimpleDateFormat( "EEE, dd MMM yyyy HH:mm:ss Z" ); // RFC 822 date time + + private RuntimeWire wire; + private Invoker getFeedInvoker; + private Invoker getAllInvoker; + private Invoker queryInvoker; + private Invoker getInvoker; + private Invoker postInvoker; + private Invoker postMediaInvoker; + private Invoker putInvoker; + private Invoker putMediaInvoker; + private Invoker deleteInvoker; + private MessageFactory messageFactory; + private String title; + private Mediator mediator; + private DataType itemClassType; + private DataType itemXMLType; + private boolean supportsFeedEntries; + + /** + * Constructs a new binding listener. + * + * @param wire + * @param messageFactory + * @param feedType + */ + AtomBindingListenerServlet(RuntimeWire wire, MessageFactory messageFactory, Mediator mediator, String title) { + this.wire = wire; + this.messageFactory = messageFactory; + this.mediator = mediator; + this.title = title; + + // Get the invokers for the supported operations + Operation getOperation = null; + for (InvocationChain invocationChain : this.wire.getInvocationChains()) { + invocationChain.setAllowsPassByReference(true); + Operation operation = invocationChain.getTargetOperation(); + String operationName = operation.getName(); + if (operationName.equals("getFeed")) { + getFeedInvoker = invocationChain.getHeadInvoker(); + } else if (operationName.equals("getAll")) { + getAllInvoker = invocationChain.getHeadInvoker(); + } else if (operationName.equals("query")) { + queryInvoker = invocationChain.getHeadInvoker(); + } else if (operationName.equals("get")) { + getInvoker = invocationChain.getHeadInvoker(); + getOperation = operation; + } else if (operationName.equals("put")) { + putInvoker = invocationChain.getHeadInvoker(); + } else if (operationName.equals("putMedia")) { + putMediaInvoker = invocationChain.getHeadInvoker(); + } else if (operationName.equals("post")) { + postInvoker = invocationChain.getHeadInvoker(); + } else if (operationName.equals("postMedia")) { + postMediaInvoker = invocationChain.getHeadInvoker(); + } else if (operationName.equals("delete")) { + deleteInvoker = invocationChain.getHeadInvoker(); + } + } + + // Determine the collection item type + itemXMLType = new DataTypeImpl>(String.class.getName(), String.class, String.class); + Class itemClass = getOperation.getOutputType().getPhysical(); + if (itemClass == org.apache.abdera.model.Entry.class) { + supportsFeedEntries = true; + } + DataType outputType = getOperation.getOutputType(); + QName qname = outputType.getLogical().getElementName(); + qname = new QName(qname.getNamespaceURI(), itemClass.getSimpleName()); + itemClassType = new DataTypeImpl("java:complexType", itemClass, new XMLType(qname, null)); + + } + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + // No authentication required for a get request + + // Test for any cache info in the request + HTTPCacheContext cacheContext = null; + try { + cacheContext = HTTPCacheContext.getCacheContextFromRequest( request ); + } catch ( java.text.ParseException e ) { + } + // System.out.println( "AtomBindingListener.doGet cache context=" + cacheContext ); + + // Get the request path + int servletPathLength = request.getContextPath().length() + request.getServletPath().length(); + String path = URLDecoder.decode(request.getRequestURI().substring(servletPathLength), "UTF-8"); + + logger.fine("get " + request.getRequestURI()); + + // Handle an Atom request + if (path != null && path.equals("/atomsvc")) { + /* + + + + resource + + entries + application/atom+xml;type=entry + + + + + */ + + // Return the Atom service document + response.setContentType("application/atomsvc+xml; charset=utf-8"); + + String href = request.getRequestURL().toString(); + href = href.substring(0, href.length() - "/atomsvc".length()); + + String workspaceURL = new String( href ); + int pathIndex = workspaceURL.indexOf( request.getServletPath() ); + if ( -1 != pathIndex ) + workspaceURL = workspaceURL.substring( 0, pathIndex ) + "/"; + + Service service = abderaFactory.newService(); + //service.setText("service"); + + Workspace workspace = abderaFactory.newWorkspace(); + if ( title != null ) + workspace.setTitle(title); + else + workspace.setTitle("workspace"); + workspace.setBaseUri( new IRI( workspaceURL )); + + Collection collection = workspace.addCollection("collection", href ); + Feed feed = getFeed( request ); + if ( feed != null ) { + String title = feed.getTitle(); + if ( title != null ) + collection.setTitle(title); + else + collection.setTitle("entries"); + collection.addAccepts("application/atom+xml;type=feed"); + collection.addAccepts("application/json;type=feed"); + collection.addAccepts("application/atom+xml;type=entry"); + collection.addAccepts("application/json;type=entry"); + List categories = feed.getCategories(); + if ( categories != null ) { + collection.addCategories(categories, false, null); + } else + collection.addCategories().setFixed(false); + + } else { + collection.setTitle("entries"); + // collection.addAccepts("application/atom+xml;type=feed"); + collection.addAccepts("application/atom+xml; type=entry"); + collection.addAccepts("application/json;type=entry"); + collection.addCategories().setFixed(false); + } + workspace.addCollection(collection); + + service.addWorkspace(workspace); + + //FIXME add prettyPrint support + try { + service.getDocument().writeTo(response.getOutputStream()); + } catch (IOException ioe) { + throw new ServletException(ioe); + } + + } else if (path == null || path.length() == 0 || path.equals("/")) { + + // Return a feed containing the entries in the collection + Feed feed = getFeed( request ); + if (feed != null) { + String feedETag = null; + if (feed.getId() != null) + feedETag = feed.getId().toString(); + Date feedUpdated = feed.getUpdated(); + // Test request for predicates. + String predicate = request.getHeader( "If-Match" ); + if (( predicate != null ) && ( !predicate.equals(feedETag) )) { + // No match, should short circuit + response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); + return; + } + predicate = request.getHeader( "If-None-Match" ); + if (( predicate != null ) && ( predicate.equals(feedETag) )) { + // Match, should short circuit + response.sendError(HttpServletResponse.SC_NOT_MODIFIED); + return; + } + if ( feedUpdated != null ) { + predicate = request.getHeader( "If-Unmodified-Since" ); + if ( predicate != null ) { + try { + Date predicateDate = dateFormat.parse( predicate ); + if ( predicateDate.compareTo( feedUpdated ) < 0 ) { + // Match, should short circuit + response.sendError(HttpServletResponse.SC_NOT_MODIFIED); + return; + } + } catch ( java.text.ParseException e ) { + // Ignore and move on + } + } + predicate = request.getHeader( "If-Modified-Since" ); + if ( predicate != null ) { + try { + Date predicateDate = dateFormat.parse( predicate ); + if ( predicateDate.compareTo( feedUpdated ) > 0 ) { + // Match, should short circuit + response.sendError(HttpServletResponse.SC_NOT_MODIFIED); + return; + } + } catch ( java.text.ParseException e ) { + // Ignore and move on + } + } + } + // Provide Etag based on Id and time if given. + // Ignore if not given. (Browser may cache if trivial ETag is given.) + if ( feedETag != null ) + response.addHeader(ETAG, feedETag ); + if ( feedUpdated != null ) + response.addHeader(LASTMODIFIED, dateFormat.format( feedUpdated )); + + // Content negotiation + String acceptType = request.getHeader( "Accept" ); + String preferredType = getContentPreference( acceptType ); + if (( preferredType != null ) && ((preferredType.indexOf( "json") > -1) || (preferredType.indexOf( "JSON") > -1 ))) { + // JSON response body + response.setContentType("application/json;type=feed"); + + try { + Abdera abdera = new Abdera(); + WriterFactory wf = abdera.getWriterFactory(); + org.apache.abdera.writer.Writer json = wf.getWriter("json"); + feed.writeTo(json, response.getWriter()); + } catch (Exception e) { + throw new ServletException(e); + } + + } else { + // Write the Atom feed + response.setContentType("application/atom+xml;type=feed"); + try { + feed.getDocument().writeTo(response.getOutputStream()); + } catch (IOException ioe) { + throw new ServletException(ioe); + } + } + } else { + response.sendError(HttpServletResponse.SC_NOT_FOUND); + } + + } else if (path.startsWith("/")) { + // Return a specific entry in the collection + org.apache.abdera.model.Entry feedEntry; + + // Invoke the get operation on the service implementation + Message requestMessage = messageFactory.createMessage(); + String id = path.substring(1); + requestMessage.setBody(new Object[] {id}); + Message responseMessage = getInvoker.invoke(requestMessage); + if (responseMessage.isFault()) { + throw new ServletException((Throwable)responseMessage.getBody()); + } + if (supportsFeedEntries) { + // The service implementation returns a feed entry + feedEntry = responseMessage.getBody(); + } else { + // The service implementation only returns a data item, create an entry + // from it + Entry entry = new Entry(id, responseMessage.getBody()); + feedEntry = feedEntry(entry, itemClassType, itemXMLType, mediator, abderaFactory); + } + // Write the Atom entry + if (feedEntry != null) { + String entryETag = null; + if (feedEntry.getId() != null) + entryETag = feedEntry.getId().toString(); + Date entryUpdated = feedEntry.getUpdated(); + if ( entryUpdated != null ) + response.addHeader(LASTMODIFIED, dateFormat.format( entryUpdated )); + // TODO Check If-Modified-Since If-Unmodified-Since predicates against LASTMODIFIED. + // If true return 304 and null body. + + Link link = feedEntry.getSelfLink(); + if (link != null) { + response.addHeader(LOCATION, link.getHref().toString()); + } else { + link = feedEntry.getLink( "Edit" ); + if (link != null) { + response.addHeader(LOCATION, link.getHref().toString()); + } + } + + // Test request for predicates. + String predicate = request.getHeader( "If-Match" ); + if (( predicate != null ) && ( !predicate.equals(entryETag) )) { + // No match, should short circuit + response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); + return; + } + predicate = request.getHeader( "If-None-Match" ); + if (( predicate != null ) && ( predicate.equals(entryETag) )) { + // Match, should short circuit + response.sendError(HttpServletResponse.SC_NOT_MODIFIED); + return; + } + if ( entryUpdated != null ) { + predicate = request.getHeader( "If-Unmodified-Since" ); + if ( predicate != null ) { + try { + Date predicateDate = dateFormat.parse( predicate ); + if ( predicateDate.compareTo( entryUpdated ) < 0 ) { + // Match, should short circuit + response.sendError(HttpServletResponse.SC_NOT_MODIFIED); + return; + } + } catch ( java.text.ParseException e ) { + // Ignore and move on + } + } + predicate = request.getHeader( "If-Modified-Since" ); + if ( predicate != null ) { + try { + Date predicateDate = dateFormat.parse( predicate ); + if ( predicateDate.compareTo( entryUpdated ) > 0 ) { + // Match, should short circuit + response.sendError(HttpServletResponse.SC_NOT_MODIFIED); + return; + } + } catch ( java.text.ParseException e ) { + // Ignore and move on + } + } + } + // Provide Etag based on Id and time if given. + // Ignore if not given. (Browser may cache if trivial ETag is given.) + if (entryETag != null) + response.addHeader(ETAG, entryETag ); + if ( entryUpdated != null ) + response.addHeader(LASTMODIFIED, dateFormat.format( entryUpdated )); + + // Content negotiation + String acceptType = request.getHeader( "Accept" ); + String preferredType = getContentPreference( acceptType ); + if (( preferredType != null ) && ((preferredType.indexOf( "json") > -1) || (preferredType.indexOf( "JSON") > -1 ))) { + // JSON response body + response.setContentType("application/json;type=entry"); + try { + Abdera abdera = new Abdera(); + WriterFactory wf = abdera.getWriterFactory(); + org.apache.abdera.writer.Writer json = wf.getWriter("json"); + feedEntry.writeTo(json, response.getWriter()); + } catch (Exception e) { + throw new ServletException(e); + } + } else { + // XML response body + response.setContentType("application/atom+xml;type=entry"); + try { + feedEntry.writeTo(getWriter(response)); + } catch (IOException ioe) { + throw new ServletException(ioe); + } + } + } else { + response.sendError(HttpServletResponse.SC_NOT_FOUND); + } + } else { + // Path doesn't match any known pattern + response.sendError(HttpServletResponse.SC_NOT_FOUND); + } + + } + + protected Feed getFeed( HttpServletRequest request ) throws ServletException { + if (supportsFeedEntries) { + // The service implementation supports feed entries, invoke its getFeed operation + Message requestMessage = messageFactory.createMessage(); + Message responseMessage; + if (request.getQueryString() != null) { + requestMessage.setBody(new Object[] {request.getQueryString()}); + responseMessage = queryInvoker.invoke(requestMessage); + } else { + responseMessage = getFeedInvoker.invoke(requestMessage); + } + if (responseMessage.isFault()) { + throw new ServletException((Throwable)responseMessage.getBody()); + } + return (Feed)responseMessage.getBody(); + } else { + + // The service implementation does not support feed entries, + // invoke its getAll operation to get the data item collection, then create + // feed entries from the items + Message requestMessage = messageFactory.createMessage(); + Message responseMessage; + if (request.getQueryString() != null) { + requestMessage.setBody(new Object[] {request.getQueryString()}); + responseMessage = queryInvoker.invoke(requestMessage); + } else { + responseMessage = getAllInvoker.invoke(requestMessage); + } + if (responseMessage.isFault()) { + throw new ServletException((Throwable)responseMessage.getBody()); + } + Entry[] collection = + (Entry[])responseMessage.getBody(); + if (collection != null) { + + // Create the feed + Feed feed = abderaFactory.newFeed(); + + // Set the feed title + if (title != null) { + feed.setTitle(title); + } else { + feed.setTitle("Feed"); + } + // All feeds must provide Id and updated elements. + // However, some do not, so provide some program protection. + feed.setId( "Feed" + feed.hashCode()); + Date responseLastModified = new Date( 0 ); + + // Add entries to the feed + for (Entry entry: collection) { + org.apache.abdera.model.Entry feedEntry = feedEntry(entry, itemClassType, itemXMLType, mediator, abderaFactory); + // Use the most recent entry update as the feed update + Date entryUpdated = feedEntry.getUpdated(); + if (( entryUpdated != null ) && (entryUpdated.compareTo( responseLastModified ) > 0 )) + responseLastModified = entryUpdated; + feed.addEntry(feedEntry); + } + // If no entries were newly updated, + if ( responseLastModified.compareTo( new Date( 0 ) ) == 0 ) + responseLastModified = new Date(); + return feed; + } + } + return null; + } + + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, + IOException { + // Authenticate the user + String user = processAuthorizationHeader(request); + if (user == null) { + unauthorized(response); + return; + } + + // Get the request path + String path = URLDecoder.decode(request.getRequestURI().substring(request.getServletPath().length()), "UTF-8"); + + if (path == null || path.length() == 0 || path.equals("/")) { + org.apache.abdera.model.Entry createdFeedEntry = null; + + // Create a new Atom entry + String contentType = request.getContentType(); + if (contentType != null && contentType.startsWith("application/atom+xml")) { + + // Read the entry from the request + org.apache.abdera.model.Entry feedEntry; + try { + Document doc = abderaParser.parse(request.getReader()); + feedEntry = doc.getRoot(); + } catch (ParseException pe) { + throw new ServletException(pe); + } + + // Let the component implementation create it + if (supportsFeedEntries) { + + // The service implementation supports feed entries, pass the entry to it + Message requestMessage = messageFactory.createMessage(); + requestMessage.setBody(new Object[] {feedEntry}); + Message responseMessage = postInvoker.invoke(requestMessage); + if (responseMessage.isFault()) { + throw new ServletException((Throwable)responseMessage.getBody()); + } + createdFeedEntry = responseMessage.getBody(); + } else { + + // The service implementation does not support feed entries, pass the data item to it + Message requestMessage = messageFactory.createMessage(); + Entry entry = entry(feedEntry, itemClassType, itemXMLType, mediator); + requestMessage.setBody(new Object[] {entry.getKey(), entry.getData()}); + Message responseMessage = postInvoker.invoke(requestMessage); + if (responseMessage.isFault()) { + throw new ServletException((Throwable)responseMessage.getBody()); + } + entry.setKey(responseMessage.getBody()); + createdFeedEntry = feedEntry(entry, itemClassType, itemXMLType, mediator, abderaFactory); + } + + } else if (contentType != null) { + // Create a new media entry + + // Get incoming headers + String title = request.getHeader("Title"); + String slug = request.getHeader("Slug"); + + // Let the component implementation create the media entry + Message requestMessage = messageFactory.createMessage(); + requestMessage.setBody(new Object[] {title, slug, contentType, request.getInputStream()}); + Message responseMessage = postMediaInvoker.invoke(requestMessage); + if (responseMessage.isFault()) { + throw new ServletException((Throwable)responseMessage.getBody()); + } + createdFeedEntry = responseMessage.getBody(); + + // Transfer media info to response header. + // Summary is a comma separated list of header properties. + String summary = createdFeedEntry.getSummary(); + addPropertiesToHeader( response, summary ); + + } else { + response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE); + } + + // A new entry for non-media was created successfully. + if (createdFeedEntry != null) { + // Set location of the created entry in the Location header + IRI feedId = createdFeedEntry.getId(); + if ( feedId != null ) + response.addHeader(ETAG, "\"" + feedId.toString() + "\"" ); + Date entryUpdated = createdFeedEntry.getUpdated(); + if ( entryUpdated != null ) + response.addHeader(LASTMODIFIED, dateFormat.format( entryUpdated )); + Link link = createdFeedEntry.getSelfLink(); + if (link != null) { + response.addHeader(LOCATION, link.getHref().toString()); + } + Link editLink = createdFeedEntry.getEditLink(); + if (editLink != null) { + response.addHeader(LOCATION, editLink.getHref().toString()); + } + Link editMediaLink = createdFeedEntry.getEditMediaLink(); + if (editMediaLink != null) { + response.addHeader(CONTENTLOCATION, editMediaLink.getHref().toString()); + } + + // Write the created Atom entry + response.setStatus(HttpServletResponse.SC_CREATED); + response.setContentType("application/atom+xml;type=entry"); + try { + createdFeedEntry.writeTo(getWriter(response)); + } catch (ParseException pe) { + throw new ServletException(pe); + } + + } else { + response.sendError(HttpServletResponse.SC_NOT_FOUND); + } + + } else { + response.sendError(HttpServletResponse.SC_NOT_FOUND); + } + } + + private Writer getWriter(HttpServletResponse response) throws UnsupportedEncodingException, IOException { + Writer writer = new OutputStreamWriter(response.getOutputStream(), "UTF-8"); + return writer; + } + + @Override + protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + // Authenticate the user + String user = processAuthorizationHeader(request); + if (user == null) { + unauthorized(response); + return; + } + + // Get the request path + String path = request.getRequestURI().substring(request.getServletPath().length()); + + if (path != null && path.startsWith("/")) { + String id = path.substring(1); + + // Update an Atom entry + String contentType = request.getContentType(); + if (contentType != null && contentType.startsWith("application/atom+xml")) { + + // Read the entry from the request + org.apache.abdera.model.Entry feedEntry; + try { + Document doc = abderaParser.parse(request.getReader()); + feedEntry = doc.getRoot(); + } catch (ParseException pe) { + throw new ServletException(pe); + } + + // Let the component implementation create it + if (supportsFeedEntries) { + // The service implementation supports feed entries, pass the entry to it + Message requestMessage = messageFactory.createMessage(); + requestMessage.setBody(new Object[] {id, feedEntry}); + Message responseMessage = putInvoker.invoke(requestMessage); + if (responseMessage.isFault()) { + Object body = responseMessage.getBody(); + if (body.getClass().getName().endsWith(".NotFoundException")) { + response.sendError(HttpServletResponse.SC_NOT_FOUND); + } else { + throw new ServletException((Throwable)responseMessage.getBody()); + } + } + } else { + // The service implementation does not support feed entries, pass the data item to it + Message requestMessage = messageFactory.createMessage(); + Entry entry = entry(feedEntry, itemClassType, itemXMLType, mediator); + requestMessage.setBody(new Object[] {entry.getKey(), entry.getData()}); + Message responseMessage = putInvoker.invoke(requestMessage); + if (responseMessage.isFault()) { + Object body = responseMessage.getBody(); + if (body.getClass().getName().endsWith(".NotFoundException")) { + response.sendError(HttpServletResponse.SC_NOT_FOUND); + } else { + throw new ServletException((Throwable)responseMessage.getBody()); + } + } + } + + } else if (contentType != null) { + + // Update a media entry + + // Let the component implementation create the media entry + Message requestMessage = messageFactory.createMessage(); + requestMessage.setBody(new Object[] {id, contentType, request.getInputStream()}); + Message responseMessage = putMediaInvoker.invoke(requestMessage); + + Object body = responseMessage.getBody(); + if (responseMessage.isFault()) { + if (body.getClass().getName().endsWith(".NotFoundException")) { + response.sendError(HttpServletResponse.SC_NOT_FOUND); + } else { + throw new ServletException((Throwable)responseMessage.getBody()); + } + } + + // Transfer content to response header. + + } else { + response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE); + } + } else { + response.sendError(HttpServletResponse.SC_NOT_FOUND); + } + } + + @Override + protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, + IOException { + + // Authenticate the user + String user = processAuthorizationHeader(request); + if (user == null) { + unauthorized(response); + return; + } + + // Get the request path + String path = URLDecoder.decode(request.getRequestURI().substring(request.getServletPath().length()), "UTF-8"); + + String id; + if (path != null && path.startsWith("/")) { + id = path.substring(1); + } else { + id = ""; + } + + // Delete a specific entry from the collection + Message requestMessage = messageFactory.createMessage(); + requestMessage.setBody(new Object[] {id}); + Message responseMessage = deleteInvoker.invoke(requestMessage); + if (responseMessage.isFault()) { + Object body = responseMessage.getBody(); + if (body.getClass().getName().endsWith(".NotFoundException")) { + response.sendError(HttpServletResponse.SC_NOT_FOUND); + } else { + throw new ServletException((Throwable)responseMessage.getBody()); + } + } + } + + /** + * Process the authorization header + * + * @param request + * @return + * @throws ServletException + */ + private String processAuthorizationHeader(HttpServletRequest request) throws ServletException { + + // FIXME temporarily disabling this as it doesn't work with all browsers + if (true) + return "admin"; + + try { + String authorization = request.getHeader("Authorization"); + if (authorization != null) { + StringTokenizer tokens = new StringTokenizer(authorization); + if (tokens.hasMoreTokens()) { + String basic = tokens.nextToken(); + if (basic.equalsIgnoreCase("Basic")) { + String credentials = tokens.nextToken(); + String userAndPassword = new String(Base64.decodeBase64(credentials.getBytes())); + int colon = userAndPassword.indexOf(":"); + if (colon != -1) { + String user = userAndPassword.substring(0, colon); + String password = userAndPassword.substring(colon + 1); + + // Authenticate the User. + if (authenticate(user, password)) { + return user; + } + } + } + } + } + } catch (Exception e) { + throw new ServletException(e); + } + return null; + } + + /** + * Authenticate a user. + * + * @param user + * @param password + * @return + */ + private boolean authenticate(String user, String password) { + // TODO Handle this using SCA security policies + return ("admin".equals(user) && "admin".equals(password)); + } + + /** + * Reject an unauthorized request. + * + * @param response + */ + private void unauthorized(HttpServletResponse response) throws IOException { + response.setHeader("WWW-Authenticate", "BASIC realm=\"Tuscany\""); + response.sendError(HttpServletResponse.SC_UNAUTHORIZED); + } + + public static String getContentPreference( String acceptType ) { + if (( acceptType == null ) || ( acceptType.length() < 1 )) { + return "application/atom+xml"; + } + StringTokenizer st = new StringTokenizer( acceptType, "," ); + if ( st.hasMoreTokens() ) + return st.nextToken(); + return "application/atom+xml"; + } + + /** Take a list of key values and add them to the header. + * For instance "Content-Type=image/gif,Content-Length=14201" + * @param response + * @param properties + */ + public static void addPropertiesToHeader( HttpServletResponse response, String properties ) { + if ( properties == null ) return; + StringTokenizer props = new StringTokenizer( properties, ","); + while( props.hasMoreTokens()) { + String prop = props.nextToken(); + StringTokenizer keyVal = new StringTokenizer( prop, "="); + String key = null; + String val = null; + if ( keyVal.hasMoreTokens() ) + key = keyVal.nextToken(); + if ( keyVal.hasMoreTokens() ) + val = keyVal.nextToken(); + if (( key != null ) && ( val != null )) { + response.addHeader(key, val); + } + } + } + +} diff --git a/java/sca/contrib/modules/binding-atom-abdera/src/main/java/org/apache/tuscany/sca/binding/atom/provider/AtomBindingProviderFactory.java b/java/sca/contrib/modules/binding-atom-abdera/src/main/java/org/apache/tuscany/sca/binding/atom/provider/AtomBindingProviderFactory.java new file mode 100644 index 0000000000..2651324ccf --- /dev/null +++ b/java/sca/contrib/modules/binding-atom-abdera/src/main/java/org/apache/tuscany/sca/binding/atom/provider/AtomBindingProviderFactory.java @@ -0,0 +1,74 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.atom.provider; + +import org.apache.tuscany.sca.binding.atom.AtomBinding; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.core.FactoryExtensionPoint; +import org.apache.tuscany.sca.databinding.DataBindingExtensionPoint; +import org.apache.tuscany.sca.databinding.Mediator; +import org.apache.tuscany.sca.databinding.TransformerExtensionPoint; +import org.apache.tuscany.sca.databinding.impl.MediatorImpl; +import org.apache.tuscany.sca.host.http.ServletHost; +import org.apache.tuscany.sca.host.http.ServletHostExtensionPoint; +import org.apache.tuscany.sca.invocation.MessageFactory; +import org.apache.tuscany.sca.provider.BindingProviderFactory; +import org.apache.tuscany.sca.provider.ReferenceBindingProvider; +import org.apache.tuscany.sca.provider.ServiceBindingProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; + +/** + * Implementation of a Binding provider factory for the Atom binding. + * + * @version $Rev$ $Date$ + */ +public class AtomBindingProviderFactory implements BindingProviderFactory { + + private MessageFactory messageFactory; + private Mediator mediator; + private ServletHost servletHost; + + public AtomBindingProviderFactory(ExtensionPointRegistry extensionPoints) { + ServletHostExtensionPoint servletHosts = extensionPoints.getExtensionPoint(ServletHostExtensionPoint.class); + this.servletHost = servletHosts.getServletHosts().get(0); + FactoryExtensionPoint modelFactories = extensionPoints.getExtensionPoint(FactoryExtensionPoint.class); + this.messageFactory = modelFactories.getFactory(MessageFactory.class); + this.mediator = new MediatorImpl(extensionPoints.getExtensionPoint(DataBindingExtensionPoint.class), + extensionPoints.getExtensionPoint(TransformerExtensionPoint.class)); + } + + public ReferenceBindingProvider createReferenceBindingProvider(RuntimeComponent component, + RuntimeComponentReference reference, + AtomBinding binding) { + return new AtomReferenceBindingProvider(component, reference, binding, mediator); + } + + public ServiceBindingProvider createServiceBindingProvider(RuntimeComponent component, + RuntimeComponentService service, + AtomBinding binding) { + return new AtomServiceBindingProvider(component, service, binding, servletHost, messageFactory, mediator); + } + + public Class getModelType() { + return AtomBinding.class; + } +} diff --git a/java/sca/contrib/modules/binding-atom-abdera/src/main/java/org/apache/tuscany/sca/binding/atom/provider/AtomBindingUtil.java b/java/sca/contrib/modules/binding-atom-abdera/src/main/java/org/apache/tuscany/sca/binding/atom/provider/AtomBindingUtil.java new file mode 100644 index 0000000000..62fde86122 --- /dev/null +++ b/java/sca/contrib/modules/binding-atom-abdera/src/main/java/org/apache/tuscany/sca/binding/atom/provider/AtomBindingUtil.java @@ -0,0 +1,164 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.atom.provider; + +import java.util.Date; + +import org.apache.abdera.factory.Factory; +import org.apache.abdera.model.Content; +import org.apache.abdera.model.Link; +import org.apache.tuscany.sca.data.collection.Entry; +import org.apache.tuscany.sca.data.collection.Item; +import org.apache.tuscany.sca.databinding.Mediator; +import org.apache.tuscany.sca.interfacedef.DataType; + +/** + * Utility methods used in this package. + * + * @version $Rev$ $Date$ + */ +class AtomBindingUtil { + + /** + * Create a data item from an Atom entry. + * @param feedEntry + * @param itemClassType + * @param itemXMLType + * @param mediator + * @return + */ + static Entry entry(org.apache.abdera.model.Entry feedEntry, + DataType itemClassType, DataType itemXMLType, Mediator mediator) { + if (feedEntry != null) { + if (itemClassType.getPhysical() == Item.class) { + String key = feedEntry.getId().toString(); + + Item item = new Item(); + item.setTitle(feedEntry.getTitle()); + item.setContents(feedEntry.getContent()); + + for (Link link : feedEntry.getLinks()) { + if (link.getRel() == null || "self".equals(link.getRel())) { + if (item.getLink() == null) { + item.setLink(link.getHref().toString()); + } + } else if ("related".equals(link.getRel())) { + item.setRelated(link.getHref().toString()); + } else if ("alternate".equals(link.getRel())) { + item.setAlternate(link.getHref().toString()); + } + } + + item.setDate(feedEntry.getUpdated()); + + return new Entry(key, item); + + } else { + String key = null; + if ( feedEntry.getId() != null) { + key = feedEntry.getId().toString(); + } + + // Create the item from XML + if (feedEntry.getContentElement().getElements().size() == 0) { + return null; + } + + String value = feedEntry.getContent(); + Object data = mediator.mediate(value, itemXMLType, itemClassType, null); + + return new Entry(key, data); + } + } else { + return null; + } + } + + /** + * Create an Atom entry for a key and item from a collection. + * @param entry + * @param itemClassType + * @param itemXMLType + * @param mediator + * @param factory + * @return + */ + static org.apache.abdera.model.Entry feedEntry(Entry entry, + DataType itemClassType, DataType itemXMLType, Mediator mediator, + Factory factory) { + Object key = entry.getKey(); + Object data = entry.getData(); + if (data instanceof Item) { + Item item = (Item)data; + + org.apache.abdera.model.Entry feedEntry = factory.newEntry(); + if (key != null) { + feedEntry.setId(key.toString()); + } + feedEntry.setTitle(item.getTitle()); + feedEntry.setContentAsHtml(item.getContents()); + + String href = item.getLink(); + if (href == null && key != null) { + href = key.toString(); + } + + if (href != null) { + feedEntry.addLink(href); + } + String related = item.getRelated(); + if (related != null) { + feedEntry.addLink(related, "related"); + } + String alternate = item.getAlternate(); + if (alternate != null) { + feedEntry.addLink(alternate, "alternate"); + } + + Date date = item.getDate(); + if (date != null) { + feedEntry.setUpdated(date); + } + return feedEntry; + + } else if (data != null) { + org.apache.abdera.model.Entry feedEntry = factory.newEntry(); + feedEntry.setId(key.toString()); + feedEntry.setTitle("item"); + + + // Convert the item to XML + String value = mediator.mediate(data, itemClassType, itemXMLType, null).toString(); + + Content content = factory.newContent(); + content.setContentType(Content.Type.XML); + content.setValue(value); + + feedEntry.setContentElement(content); + + feedEntry.addLink(key.toString()); + + return feedEntry; + } else { + return null; + } + } + +} diff --git a/java/sca/contrib/modules/binding-atom-abdera/src/main/java/org/apache/tuscany/sca/binding/atom/provider/AtomReferenceBindingProvider.java b/java/sca/contrib/modules/binding-atom-abdera/src/main/java/org/apache/tuscany/sca/binding/atom/provider/AtomReferenceBindingProvider.java new file mode 100644 index 0000000000..f2b1d1f72b --- /dev/null +++ b/java/sca/contrib/modules/binding-atom-abdera/src/main/java/org/apache/tuscany/sca/binding/atom/provider/AtomReferenceBindingProvider.java @@ -0,0 +1,183 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.atom.provider; + +import java.net.URI; + +import javax.xml.namespace.QName; + +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.httpclient.Credentials; +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.HttpConnectionManager; +import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; +import org.apache.commons.httpclient.UsernamePasswordCredentials; +import org.apache.commons.httpclient.auth.AuthScope; +import org.apache.tuscany.sca.binding.atom.AtomBinding; +import org.apache.tuscany.sca.databinding.Mediator; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.interfacedef.impl.DataTypeImpl; +import org.apache.tuscany.sca.interfacedef.util.XMLType; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.provider.ReferenceBindingProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; + +/** + * Implementation of the Atom binding provider. + * + * @version $Rev$ $Date$ + */ +class AtomReferenceBindingProvider implements ReferenceBindingProvider { + + private RuntimeComponentReference reference; + private AtomBinding binding; + private String authorizationHeader; + private HttpClient httpClient; + private Mediator mediator; + private DataType itemClassType; + private DataType itemXMLType; + private boolean supportsFeedEntries; + + /** + * Constructs a new AtomReferenceBindingProvider + * @param component + * @param reference + * @param binding + * @param mediator + */ + AtomReferenceBindingProvider(RuntimeComponent component, + RuntimeComponentReference reference, + AtomBinding binding, + Mediator mediator) { + this.reference = reference; + this.binding = binding; + this.mediator = mediator; + + // Prepare authorization header + String authorization = "admin" + ":" + "admin"; + authorizationHeader = "Basic " + new String(Base64.encodeBase64(authorization.getBytes())); + + // Create an HTTP client + HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); + connectionManager.getParams().setDefaultMaxConnectionsPerHost(10); + connectionManager.getParams().setConnectionTimeout(60000); + httpClient = new HttpClient(connectionManager); + } + + public Invoker createInvoker(Operation operation) { + + String operationName = operation.getName(); + if (operationName.equals("get")) { + + // Determine the collection item type + itemXMLType = new DataTypeImpl>(String.class.getName(), String.class, String.class); + Class itemClass = operation.getOutputType().getPhysical(); + DataType outputType = operation.getOutputType(); + QName qname = outputType.getLogical().getElementName(); + qname = new QName(qname.getNamespaceURI(), itemClass.getSimpleName()); + itemClassType = new DataTypeImpl("java:complexType", itemClass, new XMLType(qname, null)); + if (itemClassType.getPhysical() == org.apache.abdera.model.Entry.class) { + supportsFeedEntries = true; + } + + return new AtomBindingInvoker.GetInvoker(operation, binding.getURI(), httpClient, authorizationHeader, this); + + } else if (operationName.equals("post")) { + return new AtomBindingInvoker.PostInvoker(operation, binding.getURI(), httpClient, authorizationHeader, this); + } else if (operationName.equals("put")) { + return new AtomBindingInvoker.PutInvoker(operation, binding.getURI(), httpClient, authorizationHeader, this); + } else if (operationName.equals("delete")) { + return new AtomBindingInvoker.DeleteInvoker(operation, binding.getURI(), httpClient, authorizationHeader, this); + } else if (operationName.equals("getFeed") || operationName.equals("getAll")) { + return new AtomBindingInvoker.GetAllInvoker(operation, binding.getURI(), httpClient, authorizationHeader, this); + } else if (operationName.equals("postMedia")) { + return new AtomBindingInvoker.PostMediaInvoker(operation, binding.getURI(), httpClient, authorizationHeader, this); + } else if (operationName.equals("putMedia")) { + return new AtomBindingInvoker.PutMediaInvoker(operation, binding.getURI(), httpClient, authorizationHeader, this); + } else if (operationName.equals("query")) { + return new AtomBindingInvoker.QueryInvoker(operation, binding.getURI(), httpClient, authorizationHeader, this); + } + + return new AtomBindingInvoker(operation, binding.getURI(), httpClient, authorizationHeader, this); + } + + public InterfaceContract getBindingInterfaceContract() { + return reference.getInterfaceContract(); + } + + public void start() { + + // Configure the HTTP client credentials + Credentials credentials = new UsernamePasswordCredentials("admin", "admin"); + httpClient.getParams().setAuthenticationPreemptive(true); + URI uri = URI.create(binding.getURI()); + httpClient.getState().setCredentials(new AuthScope(uri.getHost(), uri.getPort()), credentials); + + // Find the get operation on the reference interface + if (true) { + return; + } + } + + public void stop() { + + } + + public boolean supportsOneWayInvocation() { + return false; + } + + /** + * Returns the mediator. + * @return + */ + Mediator getMediator() { + return mediator; + } + + /** + * Returns the item class type. + * @return + */ + DataType getItemClassType() { + return itemClassType; + } + + /** + * Returns the item XML type. + * @return + */ + DataType getItemXMLType() { + return itemXMLType; + } + + /** + * Returns true if the invoker should work with Atom + * feed entries. + * @return + */ + boolean supportsFeedEntries() { + return supportsFeedEntries; + } + +} diff --git a/java/sca/contrib/modules/binding-atom-abdera/src/main/java/org/apache/tuscany/sca/binding/atom/provider/AtomServiceBindingProvider.java b/java/sca/contrib/modules/binding-atom-abdera/src/main/java/org/apache/tuscany/sca/binding/atom/provider/AtomServiceBindingProvider.java new file mode 100644 index 0000000000..e1d470f5a3 --- /dev/null +++ b/java/sca/contrib/modules/binding-atom-abdera/src/main/java/org/apache/tuscany/sca/binding/atom/provider/AtomServiceBindingProvider.java @@ -0,0 +1,87 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.atom.provider; + +import org.apache.tuscany.sca.binding.atom.AtomBinding; +import org.apache.tuscany.sca.databinding.Mediator; +import org.apache.tuscany.sca.host.http.ServletHost; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.invocation.MessageFactory; +import org.apache.tuscany.sca.provider.ServiceBindingProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; +import org.apache.tuscany.sca.runtime.RuntimeWire; + +/** + * Implementation of the Atom binding provider. + * + * @version $Rev$ $Date$ + */ +class AtomServiceBindingProvider implements ServiceBindingProvider { + + private RuntimeComponentService service; + private AtomBinding binding; + private ServletHost servletHost; + private MessageFactory messageFactory; + private String servletMapping; + private Mediator mediator; + + AtomServiceBindingProvider(RuntimeComponent component, + RuntimeComponentService service, + AtomBinding binding, + ServletHost servletHost, + MessageFactory messageFactory, + Mediator mediator) { + this.service = service; + this.binding = binding; + this.servletHost = servletHost; + this.messageFactory = messageFactory; + this.mediator = mediator; + } + + public InterfaceContract getBindingInterfaceContract() { + return service.getInterfaceContract(); + } + + public boolean supportsOneWayInvocation() { + return false; + } + + public void start() { + RuntimeComponentService componentService = (RuntimeComponentService)service; + RuntimeWire wire = componentService.getRuntimeWire(binding); + + AtomBindingListenerServlet servlet = + new AtomBindingListenerServlet(wire, messageFactory, mediator, binding.getTitle()); + + servletMapping = binding.getURI(); + if (!servletMapping.endsWith("/")) { + servletMapping += "/"; + } + if (!servletMapping.endsWith("*")) { + servletMapping += "*"; + } + servletHost.addServletMapping(servletMapping, servlet); + } + + public void stop() { + servletHost.removeServletMapping(servletMapping); + } +} diff --git a/java/sca/contrib/modules/binding-atom-abdera/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.BindingProviderFactory b/java/sca/contrib/modules/binding-atom-abdera/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.BindingProviderFactory new file mode 100644 index 0000000000..1b9052299c --- /dev/null +++ b/java/sca/contrib/modules/binding-atom-abdera/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.BindingProviderFactory @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for the binding extension +org.apache.tuscany.sca.binding.atom.provider.AtomBindingProviderFactory;model=org.apache.tuscany.sca.binding.atom.AtomBinding diff --git a/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/AtomDeleteTestCase.java b/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/AtomDeleteTestCase.java new file mode 100644 index 0000000000..4e586a5510 --- /dev/null +++ b/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/AtomDeleteTestCase.java @@ -0,0 +1,109 @@ +package org.apache.tuscany.sca.binding.atom; + +import java.util.UUID; + +import junit.framework.Assert; + +import org.apache.abdera.Abdera; +import org.apache.abdera.model.Content; +import org.apache.abdera.model.Entry; +import org.apache.tuscany.sca.binding.atom.collection.Collection; +import org.apache.tuscany.sca.node.Contribution; +import org.apache.tuscany.sca.node.ContributionLocationHelper; +import org.apache.tuscany.sca.node.Node; +import org.apache.tuscany.sca.node.NodeFactory; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +public class AtomDeleteTestCase { + protected static Node consumerNode; + protected static Node providerNode; + protected static CustomerClient testService; + protected static Abdera abdera; + + @BeforeClass + public static void init() throws Exception { + try { + System.out.println(">>>AtomDeleteTestCase.init entry"); + String contribution = ContributionLocationHelper.getContributionLocation(AtomDeleteTestCase.class); + providerNode = + NodeFactory.newInstance().createNode("org/apache/tuscany/sca/binding/atom/Provider.composite", + new Contribution("provider", contribution)); + consumerNode = + NodeFactory.newInstance().createNode("org/apache/tuscany/sca/binding/atom/Consumer.composite", + new Contribution("consumer", contribution)); + providerNode.start(); + consumerNode.start(); + testService = consumerNode.getService(CustomerClient.class, "CustomerClient"); + abdera = new Abdera(); + } catch (Exception e) { + e.printStackTrace(); + + } + } + + @AfterClass + public static void destroy() throws Exception { + // System.out.println(">>>AtomDeleteTestCase.destroy entry"); + consumerNode.stop(); + consumerNode.destroy(); + providerNode.stop(); + providerNode.destroy(); + } + + @Test + public void testPrelim() throws Exception { + Assert.assertNotNull(providerNode); + Assert.assertNotNull(consumerNode); + Assert.assertNotNull(testService); + Assert.assertNotNull(abdera); + } + + @Test + public void testAtomDelete() throws Exception { + Collection resourceCollection = testService.getCustomerCollection(); + Assert.assertNotNull(resourceCollection); + + Entry postEntry = postEntry("Sponge Bob"); + System.out.println(">>> post entry= " + postEntry.getTitle()); + + Entry newEntry = resourceCollection.post(postEntry); + System.out.println("<<< Entry posted for " + newEntry.getTitle()); + + System.out.println(">>> get id=" + newEntry.getId()); + + resourceCollection.delete(newEntry.getId().toString()); + + } + + @Test + public void testAtomDeleteException() throws Exception { + Collection resourceCollection = testService.getCustomerCollection(); + Assert.assertNotNull(resourceCollection); + + try { + // Generates custom ID + String id = "urn:uuid:customer-" + UUID.randomUUID().toString(); + resourceCollection.delete(id); + } catch (Exception e) { + // ID doesn't match with the existing IDs and NotFoundException is + // thrown + Assert.assertEquals("NotFoundException", e.getClass().getSimpleName()); + } + + } + + private Entry postEntry(String value) { + Entry entry = abdera.newEntry(); + entry.setTitle("customer " + value); + + Content content = abdera.getFactory().newContent(); + content.setContentType(Content.Type.TEXT); + content.setValue(value); + entry.setContentElement(content); + + return entry; + } + +} diff --git a/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/AtomGetTestCase.java b/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/AtomGetTestCase.java new file mode 100644 index 0000000000..eaa2bc4a97 --- /dev/null +++ b/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/AtomGetTestCase.java @@ -0,0 +1,107 @@ +package org.apache.tuscany.sca.binding.atom; + +import junit.framework.Assert; + +import org.apache.abdera.Abdera; +import org.apache.abdera.model.Content; +import org.apache.abdera.model.Entry; +import org.apache.tuscany.sca.binding.atom.collection.Collection; +import org.apache.tuscany.sca.node.Contribution; +import org.apache.tuscany.sca.node.ContributionLocationHelper; +import org.apache.tuscany.sca.node.Node; +import org.apache.tuscany.sca.node.NodeFactory; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +public class AtomGetTestCase { + protected static Node consumerNode; + protected static Node providerNode; + protected static CustomerClient testService; + protected static Abdera abdera; + + @BeforeClass + public static void init() throws Exception { + System.out.println(">>>AtomGetTestCase.init entry"); + String contribution = ContributionLocationHelper.getContributionLocation(AtomDeleteTestCase.class); + providerNode = NodeFactory.newInstance().createNode( + "org/apache/tuscany/sca/binding/atom/Provider.composite", new Contribution("provider", contribution)); + consumerNode = NodeFactory.newInstance().createNode( + "org/apache/tuscany/sca/binding/atom/Consumer.composite", new Contribution("consumer", contribution)); + providerNode.start(); + consumerNode.start(); + testService = consumerNode.getService(CustomerClient.class, "CustomerClient"); + abdera = new Abdera(); + } + + @AfterClass + public static void destroy() throws Exception { + // System.out.println(">>>AtomGetTestCase.destroy entry"); + consumerNode.stop(); + consumerNode.destroy(); + providerNode.stop(); + providerNode.destroy(); + } + + @Test + public void testPrelim() throws Exception { + Assert.assertNotNull(providerNode); + Assert.assertNotNull(consumerNode); + Assert.assertNotNull(testService); + Assert.assertNotNull(abdera); + } + + @Test + public void testAtomGet() throws Exception { + Collection resourceCollection = testService.getCustomerCollection(); + Assert.assertNotNull(resourceCollection); + + Entry postEntry = postEntry("Sponge Bob"); + System.out.println(">>> post entry= " + postEntry.getTitle()); + + Entry newEntry = resourceCollection.post(postEntry); + System.out.println("<<< Entry posted for " + newEntry.getTitle()); + + System.out.println(">>> get id=" + newEntry.getId()); + + Entry getEntry = resourceCollection.get(newEntry.getId().toString()); + + Assert.assertEquals(newEntry.getTitle(), getEntry.getTitle()); + System.out.println("<<< get id=" + getEntry.getId() + " entry=" + getEntry.getTitle()); + } + + @Test + public void testAtomGetException() throws Exception { + Collection resourceCollection = testService.getCustomerCollection(); + Assert.assertNotNull(resourceCollection); + + Entry postEntry = postEntry("Sponge Bob"); + System.out.println(">>> post entry= " + postEntry.getTitle()); + + Entry newEntry = resourceCollection.post(postEntry); + System.out.println("<<< Entry posted for " + newEntry.getTitle()); + System.out.println(newEntry.getId()); + + // Delete the entry to force the Collection to throw NotFoundException + resourceCollection.delete(newEntry.getId().toString()); + + try { + resourceCollection.get(newEntry.getId().toString()); + } catch (Exception e) { + Assert.assertEquals("NotFoundException", e.getClass().getSimpleName()); + } + } + + private Entry postEntry(String value) { + Entry entry = abdera.newEntry(); + entry.setTitle("customer " + value); + + Content content = abdera.getFactory().newContent(); + content.setContentType(Content.Type.TEXT); + content.setValue(value); + entry.setContentElement(content); + + return entry; + } + +} diff --git a/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/AtomPostTestCase.java b/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/AtomPostTestCase.java new file mode 100644 index 0000000000..ffe8a03f20 --- /dev/null +++ b/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/AtomPostTestCase.java @@ -0,0 +1,96 @@ +package org.apache.tuscany.sca.binding.atom; + +import junit.framework.Assert; + +import org.apache.abdera.Abdera; +import org.apache.abdera.model.Content; +import org.apache.abdera.model.Entry; +import org.apache.tuscany.sca.binding.atom.collection.Collection; +import org.apache.tuscany.sca.node.Contribution; +import org.apache.tuscany.sca.node.ContributionLocationHelper; +import org.apache.tuscany.sca.node.Node; +import org.apache.tuscany.sca.node.NodeFactory; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +public class AtomPostTestCase { + protected static Node consumerNode; + protected static Node providerNode; + protected static CustomerClient testService; + protected static Abdera abdera; + + @BeforeClass + public static void init() throws Exception { + System.out.println(">>>AtomPostTestCase.init entry"); + String contribution = ContributionLocationHelper.getContributionLocation(AtomDeleteTestCase.class); + providerNode = NodeFactory.newInstance().createNode( + "org/apache/tuscany/sca/binding/atom/Provider.composite", new Contribution("provider", contribution)); + consumerNode = NodeFactory.newInstance().createNode( + "org/apache/tuscany/sca/binding/atom/Consumer.composite", new Contribution("consumer", contribution)); + providerNode.start(); + consumerNode.start(); + testService = consumerNode.getService(CustomerClient.class, "CustomerClient"); + abdera = new Abdera(); + } + + @AfterClass + public static void destroy() throws Exception { + System.out.println(">>>AtomPostTestCase.destroy entry"); + consumerNode.stop(); + consumerNode.destroy(); + providerNode.stop(); + providerNode.destroy(); + } + + @Test + public void testPrelim() throws Exception { + Assert.assertNotNull(providerNode); + Assert.assertNotNull(consumerNode); + Assert.assertNotNull(testService); + Assert.assertNotNull(abdera); + } + + @Test + public void testAtomPost() throws Exception { + Collection resourceCollection = testService.getCustomerCollection(); + Assert.assertNotNull(resourceCollection); + + Entry postEntry = postEntry("Sponge Bob"); + System.out.println(">>> post entry= " + postEntry.getTitle()); + + Entry newEntry = resourceCollection.post(postEntry); + + Assert.assertEquals(postEntry.getTitle(), newEntry.getTitle()); + + System.out.println("<<< new entry= " + newEntry.getTitle()); + + } + + @Test + public void testAtomPostException() throws Exception { + Collection resourceCollection = testService.getCustomerCollection(); + Assert.assertNotNull(resourceCollection); + + Entry postEntry = postEntry("Exception_Test"); + + try { + resourceCollection.post(postEntry); + } catch (Exception e) { + Assert.assertEquals("HTTP status code: 500", e.getMessage()); + } + } + + private Entry postEntry(String value) { + Entry entry = abdera.newEntry(); + entry.setTitle("customer " + value); + + Content content = abdera.getFactory().newContent(); + content.setContentType(Content.Type.TEXT); + content.setValue(value); + entry.setContentElement(content); + + return entry; + } + +} diff --git a/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/AtomPutTestCase.java b/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/AtomPutTestCase.java new file mode 100644 index 0000000000..08c1ed7ac9 --- /dev/null +++ b/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/AtomPutTestCase.java @@ -0,0 +1,114 @@ +package org.apache.tuscany.sca.binding.atom; + +import java.util.UUID; + +import junit.framework.Assert; + +import org.apache.abdera.Abdera; +import org.apache.abdera.model.Content; +import org.apache.abdera.model.Entry; +import org.apache.tuscany.sca.binding.atom.collection.Collection; +import org.apache.tuscany.sca.node.Contribution; +import org.apache.tuscany.sca.node.ContributionLocationHelper; +import org.apache.tuscany.sca.node.Node; +import org.apache.tuscany.sca.node.NodeFactory; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +public class AtomPutTestCase { + protected static Node consumerNode; + protected static Node providerNode; + protected static CustomerClient testService; + protected static Abdera abdera; + + @BeforeClass + public static void init() throws Exception { + System.out.println(">>>AtomPutTestCase.init entry"); + String contribution = ContributionLocationHelper.getContributionLocation(AtomDeleteTestCase.class); + providerNode = NodeFactory.newInstance().createNode( + "org/apache/tuscany/sca/binding/atom/Provider.composite", new Contribution("provider", contribution)); + consumerNode = NodeFactory.newInstance().createNode( + "org/apache/tuscany/sca/binding/atom/Consumer.composite", new Contribution("consumer", contribution)); + providerNode.start(); + consumerNode.start(); + testService = consumerNode.getService(CustomerClient.class, "CustomerClient"); + abdera = new Abdera(); + } + + @AfterClass + public static void destroy() throws Exception { + // System.out.println(">>>AtomPutTestCase.destroy entry"); + consumerNode.stop(); + consumerNode.destroy(); + providerNode.stop(); + providerNode.destroy(); + } + + @Test + public void testPrelim() throws Exception { + Assert.assertNotNull(providerNode); + Assert.assertNotNull(consumerNode); + Assert.assertNotNull(testService); + Assert.assertNotNull(abdera); + } + + @Test + public void testAtomPut() throws Exception { + Collection resourceCollection = testService.getCustomerCollection(); + Assert.assertNotNull(resourceCollection); + + Entry postEntry = postEntry("Sponge Bob"); + System.out.println(">>> post entry= " + postEntry.getTitle()); + + Entry newEntry = resourceCollection.post(postEntry); + System.out.println("<<< Entry posted for " + newEntry.getTitle()); + System.out.println(newEntry.getId()); + + System.out.println(">>> put id=" + newEntry.getId() + " entry=" + newEntry.getTitle()); + resourceCollection.put(newEntry.getId().toString(), updateEntry(newEntry, "James Bond")); + System.out.println("<<< put id=" + newEntry.getId() + " entry=" + newEntry.getTitle()); + } + + @Test + public void testAtomPutException() throws Exception { + Collection resourceCollection = testService.getCustomerCollection(); + Assert.assertNotNull(resourceCollection); + + Entry postEntry = postEntry("Sponge Bob"); + System.out.println(">>> post entry= " + postEntry.getTitle()); + + // Generate random ID to pass as parameter in PUT() -- + String id = "urn:uuid:customer-" + UUID.randomUUID().toString(); + try { + // ID doesn't match with the existing IDs and NotFoundException is thrown + resourceCollection.put(id, updateEntry(postEntry, "James Bond")); + } catch (Exception e) { + Assert.assertEquals("NotFoundException", e.getClass().getSimpleName()); + } + } + + private Entry postEntry(String value) { + Entry entry = abdera.newEntry(); + entry.setTitle("customer " + value); + + Content content = abdera.getFactory().newContent(); + content.setContentType(Content.Type.TEXT); + content.setValue(value); + entry.setContentElement(content); + + return entry; + } + + private Entry updateEntry(Entry entry, String value) { + entry.setTitle("customer " + value); + + Content content = abdera.getFactory().newContent(); + content.setContentType(Content.Type.TEXT); + content.setValue(value); + entry.setContentElement(content); + + return entry; + } + +} diff --git a/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/AtomTestCaseUtils.java b/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/AtomTestCaseUtils.java new file mode 100644 index 0000000000..6beed6881f --- /dev/null +++ b/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/AtomTestCaseUtils.java @@ -0,0 +1,96 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.atom; + +import java.io.IOException; + +import org.apache.abdera.Abdera; +import org.apache.abdera.model.Base; +import org.apache.abdera.model.Content; +import org.apache.abdera.model.Entry; +import org.apache.abdera.protocol.client.ClientResponse; +import org.apache.abdera.protocol.client.RequestOptions; +import org.apache.abdera.writer.Writer; +import org.apache.abdera.writer.WriterFactory; + +/** + * Utilities to help print and test various aspects of entity tag support. + */ +public class AtomTestCaseUtils { + + public static void prettyPrint(Abdera abdera, Base doc) throws IOException { + WriterFactory factory = abdera.getWriterFactory(); + Writer writer = factory.getWriter("prettyxml"); + writer.writeTo(doc, System.out); + System.out.println(); + } + + public static void printRequestHeaders( String title, String indent, RequestOptions request ) { + System.out.println( title ); + if ( request == null ) { + System.out.println( indent + " request is null"); + return; + } + String [] headerNames = request.getHeaderNames(); + for ( String headerName: headerNames) { + String header = request.getHeader(headerName); + System.out.println( indent + " header name,value=" + headerName + "," + header ); + } + } + + public static void printResponseHeaders( String title, String indent, ClientResponse response ) { + System.out.println( title ); + if ( response == null ) { + System.out.println( indent + " response is null"); + return; + } + String [] headerNames = response.getHeaderNames(); + for ( String headerName: headerNames) { + String header = response.getHeader(headerName); + System.out.println( indent + " header name,value=" + headerName + "," + header ); + } + + } + + public static Entry newEntry(String value) { + Abdera abdera = new Abdera(); + Entry entry = abdera.newEntry(); + entry.setTitle("customer " + value); + + Content content = abdera.getFactory().newContent(); + content.setContentType(Content.Type.TEXT); + content.setValue(value); + entry.setContentElement(content); + + return entry; + } + + public static Entry updateEntry(Entry entry, String value) { + Abdera abdera = new Abdera(); + entry.setTitle("customer " + value); + + Content content = abdera.getFactory().newContent(); + content.setContentType(Content.Type.TEXT); + content.setValue(value); + entry.setContentElement(content); + + return entry; + } + +} diff --git a/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/Consumer.java b/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/Consumer.java new file mode 100644 index 0000000000..5b4d995dc1 --- /dev/null +++ b/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/Consumer.java @@ -0,0 +1,42 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.atom; + +import org.apache.tuscany.sca.node.Contribution; +import org.apache.tuscany.sca.node.ContributionLocationHelper; +import org.apache.tuscany.sca.node.Node; +import org.apache.tuscany.sca.node.NodeFactory; + +public class Consumer { + + public static void main(String[] args) throws Exception { + + String contribution = ContributionLocationHelper.getContributionLocation(AtomDeleteTestCase.class); + Node node = NodeFactory.newInstance().createNode( + "org/apache/tuscany/sca/binding/atom/Consumer.composite", new Contribution("consumer", contribution)); + node.start(); + + CustomerClient testService = node.getService(CustomerClient.class, "CustomerClient"); + testService.testCustomerCollection(); + + node.stop(); + node.destroy(); + } +} diff --git a/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/ConsumerProviderAtomTestCase.java b/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/ConsumerProviderAtomTestCase.java new file mode 100644 index 0000000000..383344f3cb --- /dev/null +++ b/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/ConsumerProviderAtomTestCase.java @@ -0,0 +1,165 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.atom; + +import java.util.Date; + +import junit.framework.Assert; + +import org.apache.abdera.Abdera; +import org.apache.abdera.model.Content; +import org.apache.abdera.model.Entry; +import org.apache.abdera.model.Feed; +import org.apache.tuscany.sca.binding.atom.collection.Collection; +import org.apache.tuscany.sca.node.Contribution; +import org.apache.tuscany.sca.node.ContributionLocationHelper; +import org.apache.tuscany.sca.node.Node; +import org.apache.tuscany.sca.node.NodeFactory; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * Test case for the given package. + */ +public class ConsumerProviderAtomTestCase { + + protected static Node consumerNode; + protected static Node providerNode; + protected static CustomerClient testService; + protected static Abdera abdera; + + @BeforeClass + public static void init() throws Exception { + System.out.println(">>>AtomBindingIntegratedTestCase.init entry"); + String contribution = ContributionLocationHelper.getContributionLocation(AtomDeleteTestCase.class); + providerNode = NodeFactory.newInstance().createNode( + "org/apache/tuscany/sca/binding/atom/Provider.composite", new Contribution("provider", contribution)); + consumerNode = NodeFactory.newInstance().createNode( + "org/apache/tuscany/sca/binding/atom/Consumer.composite", new Contribution("consumer", contribution)); + providerNode.start(); + consumerNode.start(); + testService = consumerNode.getService(CustomerClient.class, "CustomerClient"); + abdera = new Abdera(); + } + + @AfterClass + public static void destroy() throws Exception { + System.out.println(">>>AtomBindingIntegratedTestCase.destroy entry"); + consumerNode.stop(); + consumerNode.destroy(); + providerNode.stop(); + providerNode.destroy(); + } + + @Test + public void testPrelim() throws Exception { + Assert.assertNotNull(providerNode); + Assert.assertNotNull(consumerNode); + Assert.assertNotNull(testService); + Assert.assertNotNull(abdera); + } + + @Test + public void testEntry() throws Exception { + // System.out.println( getClass().getName() + ".testEntry entry" ); + Entry entry = abdera.newEntry(); + Assert.assertNotNull(entry); + + String testTitle = "Sponge Bob"; + entry.setTitle(testTitle); + Assert.assertEquals(testTitle, entry.getTitle()); + + String testContent = "This is the content"; + entry.setContent(testContent); + Assert.assertEquals(testContent, entry.getContent()); + + Date now = new Date(); + entry.setEdited(now); + Assert.assertEquals(now, entry.getEdited()); + + Date later = new Date(); + entry.setPublished(later); + Assert.assertEquals(later, entry.getPublished()); + + String testSummary = "This is the summary"; + entry.setSummary(testSummary); + Assert.assertEquals(testSummary, entry.getSummary()); + } + + @Test + public void testCustomerCollection() throws Exception { + System.out.println(getClass().getName() + ".testCustomerCollection entry"); + Collection resourceCollection = testService.getCustomerCollection(); + Assert.assertNotNull(resourceCollection); + + Entry newEntry = newEntry("Sponge Bob"); + System.out.println(">>> post entry=" + newEntry.getTitle()); + newEntry = resourceCollection.post(newEntry); + System.out.println("<<< post id=" + newEntry.getId() + " entry=" + newEntry.getTitle()); + + newEntry = newEntry("Jane Bond"); + System.out.println(">>> post entry=" + newEntry.getTitle()); + newEntry = resourceCollection.post(newEntry); + System.out.println("<<< post id=" + newEntry.getId() + " entry=" + newEntry.getTitle()); + + System.out.println(">>> get id=" + newEntry.getId()); + Entry entry = resourceCollection.get(newEntry.getId().toString()); + System.out.println("<<< get id=" + entry.getId() + " entry=" + entry.getTitle()); + + System.out.println(">>> put id=" + newEntry.getId() + " entry=" + entry.getTitle()); + resourceCollection.put(entry.getId().toString(), updateEntry(entry, "James Bond")); + System.out.println("<<< put id=" + entry.getId() + " entry=" + entry.getTitle()); + + System.out.println(">>> delete id=" + entry.getId()); + resourceCollection.delete(entry.getId().toString()); + System.out.println("<<< delete id=" + entry.getId()); + + System.out.println(">>> get collection"); + Feed feed = resourceCollection.getFeed(); + System.out.println("<<< get collection"); + for (Object o : feed.getEntries()) { + Entry e = (Entry)o; + System.out.println("id = " + e.getId() + " entry = " + e.getTitle()); + } + } + + private Entry newEntry(String value) { + Entry entry = abdera.newEntry(); + entry.setTitle("customer " + value); + + Content content = abdera.getFactory().newContent(); + content.setContentType(Content.Type.TEXT); + content.setValue(value); + entry.setContentElement(content); + + return entry; + } + + private Entry updateEntry(Entry entry, String value) { + entry.setTitle("customer " + value); + + Content content = abdera.getFactory().newContent(); + content.setContentType(Content.Type.TEXT); + content.setValue(value); + entry.setContentElement(content); + + return entry; + } +} diff --git a/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/ContentNegotiationTest.java b/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/ContentNegotiationTest.java new file mode 100644 index 0000000000..7ec9c1480e --- /dev/null +++ b/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/ContentNegotiationTest.java @@ -0,0 +1,265 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.atom; + +import java.io.IOException; +import java.io.Reader; +import java.util.Date; + +import junit.framework.Assert; + +import org.apache.abdera.Abdera; +import org.apache.abdera.factory.Factory; +import org.apache.abdera.i18n.iri.IRI; +import org.apache.abdera.model.Content; +import org.apache.abdera.model.Document; +import org.apache.abdera.model.Entry; +import org.apache.abdera.model.Feed; +import org.apache.abdera.parser.Parser; +import org.apache.abdera.protocol.Response.ResponseType; +import org.apache.abdera.protocol.client.AbderaClient; +import org.apache.abdera.protocol.client.ClientResponse; +import org.apache.abdera.protocol.client.RequestOptions; +import org.apache.tuscany.sca.node.Contribution; +import org.apache.tuscany.sca.node.ContributionLocationHelper; +import org.apache.tuscany.sca.node.Node; +import org.apache.tuscany.sca.node.NodeFactory; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * Tests use of content negotiation for Atom binding in Tuscany. Uses the SCA + * provided Provider composite to act as a server. Uses the Abdera provided + * Client to act as a client. + */ +public class ContentNegotiationTest { + public final static String providerURI = "http://localhost:8084/customer"; + protected static Node providerNode; + protected static Abdera abdera; + protected static AbderaClient client; + protected static Parser abderaParser; + protected static String lastId; + + @BeforeClass + public static void init() throws Exception { + System.out.println(">>>ContentNegotiationTest.init"); + String contribution = ContributionLocationHelper.getContributionLocation(AtomDeleteTestCase.class); + providerNode = NodeFactory.newInstance().createNode( + "org/apache/tuscany/sca/binding/atom/Provider.composite", new Contribution("provider", contribution)); + providerNode.start(); + abdera = new Abdera(); + client = new AbderaClient(abdera); + abderaParser = Abdera.getNewParser(); + } + + @AfterClass + public static void destroy() throws Exception { + System.out.println(">>>ContentNegotiationTest.destroy"); + providerNode.stop(); + providerNode.destroy(); + } + + @Test + public void testPrelim() throws Exception { + Assert.assertNotNull(providerNode); + Assert.assertNotNull(client); + } + + @Test + public void testPost() throws Exception { + System.out.println(">>>ContentNegotiationTest.testPost"); + // Testing of entry creation + Factory factory = abdera.getFactory(); + String customerName = "Fred Farkle"; + Entry entry = factory.newEntry(); + entry.setTitle("customer " + customerName); + entry.setUpdated(new Date()); + entry.addAuthor("Apache Tuscany"); + // ID created by collection. + Content content = abdera.getFactory().newContent(); + content.setContentType(Content.Type.TEXT); + content.setValue(customerName); + entry.setContentElement(content); + + RequestOptions opts = new RequestOptions(); + final String contentType = "application/atom+xml; type=entry"; + opts.setContentType(contentType); + // AtomTestCaseUtils.printRequestHeaders( "Post request headers", " ", + // opts ); + IRI colUri = new IRI(providerURI).resolve("customer"); + // res = client.post(colUri.toString() + "?test=foo", entry, opts); + ClientResponse res = client.post(colUri.toString(), entry, opts); + + // Assert response status code is 201-OK. + // Assert response header Content-Type: application/atom+xml; + // charset=UTF-8 + Assert.assertEquals(201, res.getStatus()); + String returnedContentType = res.getContentType().toString().trim(); + Assert.assertEquals(contentType, returnedContentType); + + String eTag = res.getHeader("ETag"); + if (eTag != null) + lastId = eTag.substring(1, eTag.length() - 1); + + // AtomTestCaseUtils.printResponseHeaders( + // "Entry post response headers:", " ", res ); + // System.out.println("Entry post response content:"); + // AtomTestCaseUtils.prettyPrint(abdera, res.getDocument()); + } + + @Test + public void testXMLEntryGet() throws Exception { + System.out.println(">>>ContentNegotiationTest.testXMLEntryGet"); + RequestOptions opts = new RequestOptions(); + opts.setHeader("Accept", "application/atom+xml"); + + IRI colUri = new IRI(providerURI).resolve("customer"); + ClientResponse res = client.get(colUri.toString() + "/" + lastId, opts); + Assert.assertEquals(200, res.getStatus()); + String returnedContentType = res.getContentType().toString().trim(); + // Assert.assertEquals(contentType, returnedContentType ); + res.release(); + } + + @Test + public void testJSONEntryGet() throws Exception { + System.out.println(">>>ContentNegotiationTest.testJSONEntryGet"); + RequestOptions opts = new RequestOptions(); + opts.setHeader("Accept", "application/json"); + + IRI colUri = new IRI(providerURI).resolve("customer"); + ClientResponse res = client.get(colUri.toString() + "/" + lastId, opts); + try { + Assert.assertEquals(200, res.getStatus()); + // Abdera 0.4 throws exception on getContentType with + // application/json. + // System.out.println( + // "ContentNegotiationTest.testJSONEntryGet contentType=" + + // res.getContentType()); + String contentType = res.getHeader("Content-Type"); + Assert.assertTrue(-1 < contentType.indexOf("application/json")); + // Following is a poor man's JSONObject test to avoid dependency on + // JSON libs. + // JSONObject jsonResp = new JSONObject(res.); + // Assert.assertEquals(12345, jsonResp.getInt("result")); + String responseBody = readResponse(res.getReader()); + Assert.assertTrue(responseBody.startsWith("{")); + Assert.assertTrue(responseBody.endsWith("}")); + Assert.assertTrue(-1 < responseBody.indexOf("\"id\"")); + Assert.assertTrue(-1 < responseBody.indexOf("\"title\"")); + Assert.assertTrue(-1 < responseBody.indexOf("\"updated\"")); + // AtomTestCaseUtils.printResponseHeaders( + // "JSON Entry response headers:", " ", res ); + // System.out.println( + // "ContentNegotiationTest.testJSONEntryGet JSON entry body=" + + // responseBody ); + } finally { + res.release(); + } + } + + @Test + public void testXMLFeedGet() throws Exception { + System.out.println(">>>ContentNegotiationTest.testXMLFeedGet"); + RequestOptions opts = new RequestOptions(); + opts.setHeader("Accept", "application/atom+xml"); + + // Atom feed request + ClientResponse res = client.get(providerURI, opts); + Assert.assertNotNull(res); + try { + // Asser feed provided since no predicates + Assert.assertEquals(200, res.getStatus()); + Assert.assertEquals(ResponseType.SUCCESS, res.getType()); + // AtomTestCaseUtils.printResponseHeaders( "Feed response headers:", + // " ", res ); + // System.out.println("Feed response content:"); + // AtomTestCaseUtils.prettyPrint(abdera, res.getDocument()); + + // Perform other tests on feed. + Document doc = res.getDocument(); + Assert.assertNotNull(doc); + Feed feed = doc.getRoot(); + Assert.assertNotNull(feed); + // RFC 4287 requires non-null id, title, updated elements + Assert.assertNotNull(feed.getId()); + Assert.assertNotNull(feed.getTitle()); + Assert.assertNotNull(feed.getUpdated()); + // AtomTestCaseUtils.printFeed( "Feed values", " ", feed ); + } finally { + res.release(); + } + } + + @Test + public void testJSONFeedGet() throws Exception { + System.out.println(">>>ContentNegotiationTest.testJSONFeedGet"); + RequestOptions opts = new RequestOptions(); + opts.setHeader("Accept", "application/json"); + + // JSON feed request + ClientResponse res = client.get(providerURI, opts); + Assert.assertNotNull(res); + try { + // Assert feed provided since no predicates + Assert.assertEquals(200, res.getStatus()); + // Abdera 0.4 throws exception on getContentType with + // application/json. + // System.out.println( + // "ContentNegotiationTest.testJSONEntryGet contentType=" + + // res.getContentType()); + String contentType = res.getHeader("Content-Type"); + Assert.assertTrue(-1 < contentType.indexOf("application/json")); + // Following is a poor man's JSONObject test to avoid dependency on + // JSON libs. + // JSONObject jsonResp = new JSONObject(res.); + // Assert.assertEquals(12345, jsonResp.getInt("result")); + String responseBody = readResponse(res.getReader()); + Assert.assertTrue(responseBody.startsWith("{")); + Assert.assertTrue(responseBody.endsWith("}")); + Assert.assertTrue(-1 < responseBody.indexOf("\"id\"")); + Assert.assertTrue(-1 < responseBody.indexOf("\"title\"")); + Assert.assertTrue(-1 < responseBody.indexOf("\"updated\"")); + Assert.assertTrue(-1 < responseBody.indexOf("\"entries\"")); + // AtomTestCaseUtils.printResponseHeaders( + // "JSON Entry response headers:", " ", res ); + // System.out.println( + // "ContentNegotiationTest.testJSONEntryGet JSON entry body=" + + // responseBody ); + } finally { + res.release(); + } + } + + protected String readResponse(Reader responseReader) { + if (responseReader == null) + return ""; + StringBuffer sb = new StringBuffer(1024); + try { + int charValue = 0; + while ((charValue = responseReader.read()) != -1) { + // result = result + (char) charValue; + sb.append((char)charValue); + } + } catch (IOException e) { + } + return sb.toString(); + } +} diff --git a/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/CustomerClient.java b/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/CustomerClient.java new file mode 100644 index 0000000000..bc32b91367 --- /dev/null +++ b/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/CustomerClient.java @@ -0,0 +1,29 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.atom; + +import org.apache.tuscany.sca.binding.atom.collection.Collection; + +public interface CustomerClient { + + void testCustomerCollection() throws Exception; + + Collection getCustomerCollection(); +} diff --git a/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/CustomerClientImpl.java b/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/CustomerClientImpl.java new file mode 100644 index 0000000000..0aefce608b --- /dev/null +++ b/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/CustomerClientImpl.java @@ -0,0 +1,99 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.atom; + +import org.apache.abdera.Abdera; +import org.apache.abdera.model.Content; +import org.apache.abdera.model.Entry; +import org.apache.abdera.model.Feed; +import org.apache.tuscany.sca.binding.atom.collection.Collection; +import org.oasisopen.sca.annotation.Reference; + +public class CustomerClientImpl implements CustomerClient { + + protected final Abdera abdera = new Abdera(); + + @Reference + public Collection customerCollection; + + public void testCustomerCollection() throws Exception { + + Entry newEntry = newEntry("Sponge Bob"); + System.out.println(">>> post entry=" + newEntry.getTitle()); + newEntry = customerCollection.post(newEntry); + System.out.println("<<< post id=" + newEntry.getId() + " entry=" + newEntry.getTitle()); + + newEntry = newEntry("Jane Bond"); + System.out.println(">>> post entry=" + newEntry.getTitle()); + newEntry = customerCollection.post(newEntry); + System.out.println("<<< post id=" + newEntry.getId() + " entry=" + newEntry.getTitle()); + + System.out.println(">>> get id=" + newEntry.getId()); + Entry entry = customerCollection.get(newEntry.getId().toString()); + System.out.println("<<< get id=" + entry.getId() + " entry=" + entry.getTitle()); + + System.out.println(">>> put id=" + newEntry.getId() + " entry=" + entry.getTitle()); + customerCollection.put(entry.getId().toString(), updateEntry(entry, "James Bond")); + System.out.println("<<< put id=" + entry.getId() + " entry=" + entry.getTitle()); + + System.out.println(">>> delete id=" + entry.getId()); + customerCollection.delete(entry.getId().toString()); + System.out.println("<<< delete id=" + entry.getId()); + + System.out.println(">>> get collection"); + Feed feed = customerCollection.getFeed(); + System.out.println("<<< get collection"); + for (Object o : feed.getEntries()) { + Entry e = (Entry)o; + System.out.println("id = " + e.getId() + " entry = " + e.getTitle()); + } + } + + public Collection getCustomerCollection() { + return customerCollection; + } + + private Entry newEntry(String value) { + + Entry entry = this.abdera.newEntry(); + entry.setTitle("customer " + value); + + Content content = this.abdera.getFactory().newContent(); + content.setContentType(Content.Type.TEXT); + content.setValue(value); + + entry.setContentElement(content); + + return entry; + } + + private Entry updateEntry(Entry entry, String value) { + + entry.setTitle("customer " + value); + + Content content = this.abdera.getFactory().newContent(); + content.setContentType(Content.Type.TEXT); + content.setValue(value); + + entry.setContentElement(content); + + return entry; + } +} diff --git a/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/CustomerCollectionImpl.java b/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/CustomerCollectionImpl.java new file mode 100644 index 0000000000..222dc3e394 --- /dev/null +++ b/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/CustomerCollectionImpl.java @@ -0,0 +1,149 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.atom; + +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.apache.abdera.Abdera; +import org.apache.abdera.model.Content; +import org.apache.abdera.model.Entry; +import org.apache.abdera.model.Feed; +import org.apache.tuscany.sca.binding.atom.collection.Collection; +import org.apache.tuscany.sca.binding.atom.collection.NotFoundException; +import org.oasisopen.sca.annotation.Scope; + +@Scope("COMPOSITE") +public class CustomerCollectionImpl implements Collection { + private final Abdera abdera = new Abdera(); + private Map entries = new HashMap(); + public Date lastModified = new Date(); + + /** + * Default constructor + */ + public CustomerCollectionImpl() { + + } + + public Entry post(Entry entry) { + System.out.println(">>> CustomerCollectionImpl.post entry=" + entry.getTitle()); + + if(!("Exception_Test".equalsIgnoreCase(entry.getTitle()))) + { + String id = "urn:uuid:customer-" + UUID.randomUUID().toString(); + entry.setId(id); + + entry.addLink("" + id, "edit"); + entry.addLink("" + id, "alternate"); + Date now = new Date(); + entry.setUpdated(now); + lastModified = now; + entries.put(id, entry); + + System.out.println(">>> CustomerCollectionImpl.post return id=" + id); + + return entry; + + } + else + { + throw new IllegalArgumentException("Exception in Post method"); + } + } + + public Entry get(String id) { + System.out.println(">>> CustomerCollectionImpl.get id=" + id); + return entries.get(id); + } + + public void put(String id, Entry entry) throws NotFoundException { + System.out.println(">>> CustomerCollectionImpl.put id=" + id + " entry=" + entry.getTitle()); + if(entries.containsKey(id)){ + Date now = new Date(); + entry.setUpdated(now); + lastModified = now; + entries.put(id, entry); + } + else { + throw new NotFoundException(); + } + } + + public void delete(String id) throws NotFoundException { + System.out.println(">>> CustomerCollectionImpl.delete id=" + id); + if(entries.containsKey(id)){ + entries.remove(id); + lastModified = new Date(); + } + else { + throw new NotFoundException(); + } + } + + public Feed getFeed() { + System.out.println(">>> CustomerCollectionImpl.getFeed"); + + Feed feed = this.abdera.getFactory().newFeed(); + feed.setId("customers" + this.hashCode() ); // provide unique id for feed instance. + feed.setTitle("customers"); + feed.setSubtitle("This is a sample feed"); + feed.setUpdated(lastModified); + feed.addLink(""); + feed.addLink("", "self"); + + for (Entry entry : entries.values()) { + feed.addEntry(entry); + } + + return feed; + } + + public Feed query(String queryString) { + System.out.println(">>> CustomerCollectionImpl.query collection " + queryString); + return getFeed(); + } + + // This method used for testing. + protected void testPut(String value) { + String id = "urn:uuid:customer-" + UUID.randomUUID().toString(); + + Entry entry = abdera.getFactory().newEntry(); + entry.setId(id); + entry.setTitle("customer " + value); + + Content content = this.abdera.getFactory().newContent(); + content.setContentType(Content.Type.TEXT); + content.setValue(value); + + entry.setContentElement(content); + + entry.addLink("" + id, "edit"); + entry.addLink("" + id, "alternate"); + + entry.setUpdated(new Date()); + + entries.put(id, entry); + System.out.println(">>> id=" + id); + } + +} diff --git a/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/MediaCollectionImpl.java b/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/MediaCollectionImpl.java new file mode 100644 index 0000000000..41257d9a7f --- /dev/null +++ b/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/MediaCollectionImpl.java @@ -0,0 +1,210 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.atom; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.apache.abdera.Abdera; +import org.apache.abdera.factory.Factory; +import org.apache.abdera.i18n.iri.IRI; +import org.apache.abdera.model.Content; +import org.apache.abdera.model.Entry; +import org.apache.abdera.model.Feed; +import org.apache.tuscany.sca.binding.atom.collection.Collection; +import org.apache.tuscany.sca.binding.atom.collection.MediaCollection; +import org.apache.tuscany.sca.binding.atom.collection.NotFoundException; +import org.oasisopen.sca.annotation.Scope; + +@Scope("COMPOSITE") +public class MediaCollectionImpl implements MediaCollection { + private final Abdera abdera = new Abdera(); + private Map entries = new HashMap(); + private Map mediaFiles = new HashMap(); + public Date lastModified = new Date(); + + public Entry post(Entry entry) { + System.out.println(">>> MediaCollectionImpl.post entry=" + entry.getTitle()); + + if(!("Exception_Test".equalsIgnoreCase(entry.getTitle()))) + { + String id = "urn:uuid:customer-" + UUID.randomUUID().toString(); + entry.setId(id); + + entry.addLink("" + id, "edit"); + entry.addLink("" + id, "alternate"); + Date now = new Date(); + entry.setUpdated(now); + lastModified = now; + entries.put(id, entry); + + System.out.println(">>> MediaCollectionImpl.post return id=" + id); + + return entry; + + } + else + { + throw new IllegalArgumentException("Exception in Post method"); + } + } + + public Entry get(String id) { + System.out.println(">>> MediaCollectionImpl.get id=" + id); + return entries.get(id); + } + + public void put(String id, Entry entry) throws NotFoundException { + System.out.println(">>> MediaCollectionImpl.put id=" + id + " entry=" + entry.getTitle()); + if(entries.containsKey(id)){ + Date now = new Date(); + entry.setUpdated(now); + lastModified = now; + entries.put(id, entry); + } + else { + throw new NotFoundException(); + } + } + + public void delete(String id) throws NotFoundException { + System.out.println(">>> MediaCollectionImpl.delete id=" + id); + if(entries.containsKey(id)){ + entries.remove(id); + lastModified = new Date(); + } + else { + throw new NotFoundException(); + } + } + + public Feed getFeed() { + System.out.println(">>> MediaCollectionImpl.getFeed"); + + Feed feed = this.abdera.getFactory().newFeed(); + feed.setId("customers" + this.hashCode() ); // provide unique id for feed instance. + feed.setTitle("customers"); + feed.setSubtitle("This is a sample feed"); + feed.setUpdated(lastModified); + feed.addLink(""); + feed.addLink("", "self"); + + for (Entry entry : entries.values()) { + feed.addEntry(entry); + } + + return feed; + } + + public Feed query(String queryString) { + System.out.println(">>> MediaCollectionImpl.query collection " + queryString); + return getFeed(); + } + + // This method used for testing. + protected void testPut(String value) { + String id = "urn:uuid:customer-" + UUID.randomUUID().toString(); + + Entry entry = abdera.getFactory().newEntry(); + entry.setId(id); + entry.setTitle("customer " + value); + + Content content = this.abdera.getFactory().newContent(); + content.setContentType(Content.Type.TEXT); + content.setValue(value); + + entry.setContentElement(content); + + entry.addLink("" + id, "edit"); + entry.addLink("" + id, "alternate"); + + entry.setUpdated(new Date()); + + entries.put(id, entry); + System.out.println(">>> id=" + id); + } + + // MediaCollection role + public Entry postMedia(String title, String slug, String contentType, InputStream media) { + System.out.println(">>> MediaCollectionImpl.postMedia title=" + title + ", slug=" + slug + ", contentType=" + contentType ); + + Factory factory = abdera.getFactory(); + Entry entry = factory.newEntry(); + // Must provide entry to media as per Atom Pub spec (http://tools.ietf.org/html/rfc5023#section-9.6) + // + // + // The Beach (REQUIRED) + // urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a (REQUIRED) + // 2005-10-07T17:17:08Z + // (REQUIRED, OPTIONAL to populate + // + // + // + // + + // Normalize title + entry.setTitle( title ); + String normalTitle = title.replace( " ", "_" ); + String hostURL = "http://media.example.org/"; + int lastDelimiterPos = contentType != null ? contentType.lastIndexOf( "/" ) : -1; + String extension = ""; + if ( lastDelimiterPos != -1 ) { + extension = contentType.substring( lastDelimiterPos + 1 ); + } else { + extension = contentType; + } + long mediaLength = -1; + try { + mediaLength = media.skip( Long.MAX_VALUE ); + } catch ( IOException e ){} + + // A true implementation would store the media to a repository, e.g. file system. + // This implementation record's the id and the location. + String id = "urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a-" + mediaFiles.size(); + String reposLocation = hostURL + "edit/" + normalTitle; + mediaFiles.put( id, reposLocation ); + + // Build entry for media link. + entry.setUpdated( new Date() ); + entry.setId( id ); + // Convention. Return header properties as key values. + entry.setSummary( "Content-Type=" + contentType + ",Content-Length=" + mediaLength ); + entry.setContent( new IRI( hostURL + normalTitle + "." + extension ), contentType ); + entry.addLink( reposLocation + ".atom", "edit" ); + entry.addLink( reposLocation + "." + extension, "edit-media" ); + return entry; + } + + public void putMedia(String id, String contentType, InputStream media) throws NotFoundException { + System.out.println(">>> MediaCollectionImpl.putMedia id=" + id + ", contentType=" + contentType ); + + // Must responsd with success or not found as per Atom Pub spec (http://tools.ietf.org/html/rfc5023#section-9.6) + // Body is null. + if ( !id.endsWith( "0" ) ) + throw new NotFoundException( "Media at id=" + id + " not found." ); + + // A true implementation would update the media in the media repository. + } + +} diff --git a/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/MediaCollectionTestCase.java b/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/MediaCollectionTestCase.java new file mode 100644 index 0000000000..0aabf225a4 --- /dev/null +++ b/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/MediaCollectionTestCase.java @@ -0,0 +1,287 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.atom; + +import java.io.File; +import java.io.FileInputStream; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; + +import junit.framework.Assert; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import org.apache.tuscany.sca.host.embedded.SCADomain; + +import org.apache.abdera.Abdera; +import org.apache.abdera.i18n.iri.IRI; +import org.apache.abdera.model.Entry; +import org.apache.abdera.model.Feed; +import org.apache.abdera.model.Document; +import org.apache.abdera.model.Link; +import org.apache.abdera.protocol.client.AbderaClient; +import org.apache.abdera.protocol.client.ClientResponse; +import org.apache.abdera.protocol.client.RequestOptions; +import org.apache.abdera.protocol.client.util.BaseRequestEntity; +import org.apache.abdera.util.EntityTag; +import org.apache.abdera.parser.Parser; + +import org.apache.commons.httpclient.Header; +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.methods.PostMethod; +import org.apache.commons.httpclient.methods.PutMethod; +import org.apache.commons.httpclient.methods.InputStreamRequestEntity; + +/** + * Tests use of server provided entry entity tags for Atom binding in Tuscany. + * Tests conditional gets (e.g. get if-none-match) or conditional posts (post if-match) + * using entity tags or last modified header entries. + * Uses the SCA provided Provider composite to act as a server. + * Uses the Abdera provided Client to act as a client. + */ +public class MediaCollectionTestCase { + public final static String providerURI = "http://localhost:8084/receipt"; + protected static SCADomain scaConsumerDomain; + protected static SCADomain scaProviderDomain; + protected static CustomerClient testService; + protected static Abdera abdera; + protected static AbderaClient client; + protected static Parser abderaParser; + protected static String eTag; + protected static Date lastModified; + protected static String mediaId; + protected static final SimpleDateFormat dateFormat = new SimpleDateFormat( "EEE, dd MMM yyyy HH:mm:ss Z" ); // RFC 822 date time + + @BeforeClass + public static void init() throws Exception { + System.out.println(">>>MediaCollectionTestCase.init"); + scaProviderDomain = SCADomain.newInstance("org/apache/tuscany/sca/binding/atom/ReceiptProvider.composite"); + abdera = new Abdera(); + client = new AbderaClient(abdera); + abderaParser = Abdera.getNewParser(); + } + + @AfterClass + public static void destroy() throws Exception { + System.out.println(">>>MediaCollectionTestCase.destroy"); + scaProviderDomain.close(); + } + + @Test + public void testPrelim() throws Exception { + Assert.assertNotNull(scaProviderDomain); + Assert.assertNotNull( client ); + } + + @Test + public void testMediaEntryPost() throws Exception { + // Pseudo Code (see APP (http://tools.ietf.org/html/rfc5023#section-9.6) + // Post request + // POST /edit/ HTTP/1.1 + // Host: media.example.org + // Content-Type: image/png + // Slug: The Beach + // Content-Length: nnn + // ...binary data... + + // Testing of entry creation + String receiptName = "Auto Repair Bill"; + String fileName = "ReceiptToms.gif"; + File input = new File( fileName ); + boolean exists = input.exists(); + Assert.assertTrue( exists ); + + // Prepare HTTP post + // PostMethod post = new PostMethod( colUri.toString() ); + PostMethod post = new PostMethod( providerURI ); + post.addRequestHeader( "Content-Type", "image/gif" ); + post.addRequestHeader( "Title", "Title " + receiptName + "" ); + post.addRequestHeader( "Slug", "Slug " + receiptName + "" ); + post.setRequestEntity( + new InputStreamRequestEntity( new FileInputStream( input ), "image/gif" ) ); + + // Get HTTP client + HttpClient httpclient = new HttpClient(); + try { + // Execute request + int result = httpclient.executeMethod(post); + // Pseudo Code (see APP (http://tools.ietf.org/html/rfc5023#section-9.6) + // Post response + // Tuscany responds with proper media links. Note that the media is + // stored in a different location than the media information which is + // stored in the Atom feed. + // HTTP/1.1 201 Created + // Display status code + // System.out.println("Response status code: " + result + ", status text=" + post.getStatusText() ); + Assert.assertEquals(201, result ); + // Display response + // System.out.println("Response body: "); + // System.out.println(post.getResponseBodyAsString()); // Warning: BodyAsString recommends BodyAsStream + + // Location: http://example.org/media/edit/the_beach.atom (REQUIRED) + // System.out.println( "Response Location=" + post.getResponseHeader( "Location" ).getValue() + "." ); + Header header = post.getResponseHeader( "Location" ); + Assert.assertNotNull( header ); + Assert.assertNotNull( header.getValue() ); + // ContentLocation: http://example.org/media/edit/the_beach.jpg (REQUIRED) + // System.out.println( "Response Content-Location=" + post.getResponseHeader( "Content-Location" ).getValue() ); + header = post.getResponseHeader( "Content-Location" ); + Assert.assertNotNull( header ); + Assert.assertNotNull( header.getValue() ); + // Content-Type: application/atom+xml;type=entry;charset="utf-8" + // System.out.println( "Response Content-Type=" + post.getResponseHeader( "Content-Type" ).getValue()); + header = post.getResponseHeader( "Content-Type" ); + Assert.assertNotNull( header ); + Assert.assertNotNull( header.getValue() ); + // Content-Length: nnn (OPTIONAL) + // System.out.println( "Response Content-Length=" + post.getResponseHeader( "Content-Length" ).getValue() ); + header = post.getResponseHeader( "Content-Length" ); + Assert.assertNotNull( header ); + Assert.assertNotNull( header.getValue() ); + // + // + // The Beach (REQUIRED) + // urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a (REQUIRED) + // 2005-10-07T17:17:08Z + // Daffy + // (REQUIRED, OPTIONAL to populate + // + // + // + // + Document document = abderaParser.parse( post.getResponseBodyAsStream() ); + Entry entry = document.getRoot(); + String title = entry.getTitle(); + // System.out.println( "mediaPost entry.title=" + title ); + Assert.assertNotNull( title ); + IRI id = entry.getId(); + // System.out.println( "mediaPost entry.id=" + id ); + Assert.assertNotNull( id ); + mediaId = id.toString(); + Assert.assertNotNull( mediaId ); // Save for put/update request + Date updated = entry.getUpdated(); + // System.out.println( "mediaPost entry.updated=" + updated); + Assert.assertNotNull( updated ); + String summary = entry.getSummary(); + // System.out.println( "mediaPost entry.summary=" + summary); + Assert.assertNotNull( summary ); + IRI contentSrc = entry.getContentSrc(); + // System.out.println( "mediaPost entry.content.src=" + contentSrc + ", type=" + entry.getContentType()); + Assert.assertNotNull( contentSrc ); + Link editLink = entry.getEditLink(); + // System.out.println( "mediaPost entry.editLink" + " rel=" + editLink.getRel() + ", href=" + editLink.getHref() ); + Assert.assertNotNull( editLink ); + Assert.assertNotNull( editLink.getRel() ); + Assert.assertNotNull( editLink.getHref() ); + Link editMediaLink = entry.getEditMediaLink(); + // System.out.println( "mediaPost entry.editMediaLink" + " rel=" + editMediaLink.getRel() + ", href=" + editMediaLink.getHref() ); + Assert.assertNotNull( editMediaLink ); + Assert.assertNotNull( editMediaLink.getRel() ); + Assert.assertNotNull( editMediaLink.getHref() ); + + } finally { + // Release current connection to the connection pool once you are done + post.releaseConnection(); + } + } + + @Test + public void testMediaEntryPutFound() throws Exception { + // Pseudo Code (see APP (http://tools.ietf.org/html/rfc5023#section-9.6) + // Testing of entry update + String receiptName = "Value Autoglass Bill"; + String fileName = "ReceiptValue.jpg"; + File input = new File( fileName ); + boolean exists = input.exists(); + Assert.assertTrue( exists ); + + // Prepare HTTP put request + // PUT /edit/the_beach.png HTTP/1.1 + // Host: media.example.org + // Content-Type: image/png + // Content-Length: nnn + // ...binary data... + PutMethod put = new PutMethod( providerURI + "/" + mediaId ); + put.addRequestHeader( "Content-Type", "image/jpg" ); + put.addRequestHeader( "Title", "Title " + receiptName + "" ); + put.addRequestHeader( "Slug", "Slug " + receiptName + "" ); + put.setRequestEntity( + new InputStreamRequestEntity( new FileInputStream( input ), "image/jpg" ) ); + + // Get HTTP client + HttpClient httpclient = new HttpClient(); + try { + // Execute request + int result = httpclient.executeMethod(put); + // Pseudo Code (see APP (http://tools.ietf.org/html/rfc5023#section-9.6) + // Display status code + // System.out.println("Response status code: " + result + ", status text=" + put.getStatusText() ); + Assert.assertEquals(200, result ); + // Display response. Should be empty for put. + // System.out.println("Response body: "); + // System.out.println(put.getResponseBodyAsString()); // Warning: BodyAsString recommends BodyAsStream + } finally { + // Release current connection to the connection pool once you are done + put.releaseConnection(); + } + } + + @Test + public void testMediaEntryPutNotFound() throws Exception { + // Pseudo Code (see APP (http://tools.ietf.org/html/rfc5023#section-9.6) + // Testing of entry update + String receiptName = "Value Autoglass Bill"; + String fileName = "ReceiptValue.jpg"; + File input = new File( fileName ); + boolean exists = input.exists(); + Assert.assertTrue( exists ); + + // Prepare HTTP put request + // PUT /edit/the_beach.png HTTP/1.1 + // Host: media.example.org + // Content-Type: image/png + // Content-Length: nnn + // ...binary data... + PutMethod put = new PutMethod( providerURI + "/" + mediaId + "-bogus" ); // Does not exist. + put.addRequestHeader( "Content-Type", "image/jpg" ); + put.addRequestHeader( "Title", "Title " + receiptName + "" ); + put.addRequestHeader( "Slug", "Slug " + receiptName + "" ); + put.setRequestEntity( + new InputStreamRequestEntity( new FileInputStream( input ), "image/jpg" ) ); + + // Get HTTP client + HttpClient httpclient = new HttpClient(); + try { + // Execute request + int result = httpclient.executeMethod(put); + // Pseudo Code (see APP (http://tools.ietf.org/html/rfc5023#section-9.6) + // Display status code + // System.out.println("Response status code: " + result + ", status text=" + put.getStatusText() ); + Assert.assertEquals(404, result ); + // Display response. Should be empty for put. + // System.out.println("Response body: "); + // System.out.println(put.getResponseBodyAsString()); // Warning: BodyAsString recommends BodyAsStream + } finally { + // Release current connection to the connection pool once you are done + put.releaseConnection(); + } + } +} diff --git a/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/Provider.java b/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/Provider.java new file mode 100644 index 0000000000..a881f2dd0a --- /dev/null +++ b/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/Provider.java @@ -0,0 +1,48 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.atom; + +import java.io.IOException; + +import org.apache.tuscany.sca.node.Contribution; +import org.apache.tuscany.sca.node.ContributionLocationHelper; +import org.apache.tuscany.sca.node.Node; +import org.apache.tuscany.sca.node.NodeFactory; + +public class Provider { + + public static void main(String[] args) { + + String contribution = ContributionLocationHelper.getContributionLocation(AtomDeleteTestCase.class); + Node node = NodeFactory.newInstance().createNode( + "org/apache/tuscany/sca/binding/atom/Provider.composite", new Contribution("provider", contribution)); + node.start(); + System.out.println("Provider.composite ready..."); + + try { + System.in.read(); + } catch (IOException e) { + e.printStackTrace(); + } + + node.stop(); + node.destroy(); + } +} diff --git a/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/ProviderEntryEntityTagsTestCase.java b/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/ProviderEntryEntityTagsTestCase.java new file mode 100644 index 0000000000..703419f527 --- /dev/null +++ b/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/ProviderEntryEntityTagsTestCase.java @@ -0,0 +1,428 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.atom; + +import java.text.SimpleDateFormat; +import java.util.Date; + +import junit.framework.Assert; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import org.apache.tuscany.sca.binding.atom.collection.Collection; +import org.apache.tuscany.sca.host.embedded.SCADomain; + +import org.apache.abdera.Abdera; +import org.apache.abdera.i18n.iri.IRI; +import org.apache.abdera.factory.Factory; +import org.apache.abdera.model.Base; +import org.apache.abdera.model.Content; +import org.apache.abdera.model.Entry; +import org.apache.abdera.model.Feed; +import org.apache.abdera.model.Document; +import org.apache.abdera.model.Service; +import org.apache.abdera.protocol.Response.ResponseType; +import org.apache.abdera.protocol.client.AbderaClient; +import org.apache.abdera.protocol.client.ClientResponse; +import org.apache.abdera.protocol.client.RequestOptions; +import org.apache.abdera.protocol.client.util.BaseRequestEntity; +import org.apache.abdera.util.EntityTag; +import org.apache.abdera.parser.Parser; + +/** + * Tests use of server provided entry entity tags for Atom binding in Tuscany. + * Tests conditional gets (e.g. get if-none-match) or conditional posts (post if-match) + * using entity tags or last modified header entries. + * Uses the SCA provided Provider composite to act as a server. + * Uses the Abdera provided Client to act as a client. + */ +public class ProviderEntryEntityTagsTestCase { + public final static String providerURI = "http://localhost:8084/customer"; + protected static SCADomain scaConsumerDomain; + protected static SCADomain scaProviderDomain; + protected static CustomerClient testService; + protected static Abdera abdera; + protected static AbderaClient client; + protected static Parser abderaParser; + protected static String eTag; + protected static Date lastModified; + protected static final SimpleDateFormat dateFormat = new SimpleDateFormat( "EEE, dd MMM yyyy HH:mm:ss Z" ); // RFC 822 date time + + @BeforeClass + public static void init() throws Exception { + System.out.println(">>>ProviderEntryEntityTagsTestCase.init"); + scaProviderDomain = SCADomain.newInstance("org/apache/tuscany/sca/binding/atom/Provider.composite"); + abdera = new Abdera(); + client = new AbderaClient(abdera); + abderaParser = Abdera.getNewParser(); + } + + @AfterClass + public static void destroy() throws Exception { + System.out.println(">>>ProviderEntryEntityTagsTestCase.destroy"); + scaProviderDomain.close(); + } + + @Test + public void testPrelim() throws Exception { + Assert.assertNotNull(scaProviderDomain); + Assert.assertNotNull( client ); + } + + @Test + public void testEmptyCachePost() throws Exception { + // Pseudo-code + // 1) Example HTTP POST request (new entry put, new etag response) + // User client post request + // POST /myblog/entries HTTP/1.1 + // Slug: First Post + // + // + // + // Atom-Powered Robots Run Amok + // urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a + // 2007-02-123T17:09:02Z + // Captain Lansing + // It's something moving... solid metal + // + + // Expected Atom server response (note unique ETag) + // HTTP/1.1 201 Created + // Date: Fri, 23 Feb 2007 21:17:11 GMT + // Content-Length: nnn + // Content-Type: application/atom+xml;type=entry + // Location: http://example.org/edit/first-post.atom + // Content-Location: http://example.org/edit/first-post.atom + // ETag: "e180ee84f0671b1" + // Last-Modified: Fri, 25 Jul 2008 14:36:44 -0500 + // + // + // + // Atom-Powered Robots Run Amok + // urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a + // 2007-02-123T17:09:02Z + // Captain Lansing + // It's something moving... solid metal + // + + // Testing of entry creation + Factory factory = abdera.getFactory(); + String customerName = "Fred Farkle"; + Entry entry = factory.newEntry(); + entry.setTitle("customer " + customerName); + entry.setUpdated(new Date()); + entry.addAuthor("Apache Tuscany"); + // ID created by collection. + // entry.setId(id); // auto-provided + // entry.addLink("" + id, "edit"); // auto-provided + // entry.addLink("" + id, "alternate"); // auto-provided + Content content = abdera.getFactory().newContent(); + content.setContentType(Content.Type.TEXT); + content.setValue(customerName); + entry.setContentElement(content); + + RequestOptions opts = new RequestOptions(); + final String contentType = "application/atom+xml; type=entry"; + opts.setContentType(contentType); + // AtomTestCaseUtils.printRequestHeaders( "Post request headers", " ", opts ); + IRI colUri = new IRI(providerURI).resolve("customer"); + // res = client.post(colUri.toString() + "?test=foo", entry, opts); + ClientResponse res = client.post(colUri.toString(), entry, opts); + + // Assert response status code is 201-OK. + // Assert response header Content-Type: application/atom+xml; charset=UTF-8 + // Assert response header Location: http://example.org/edit/first-post.atom + // Assert response header Content-Location: http://example.org/edit/first-post.atom + // Assert response header ETag: "e180ee84f0671b1" + // Assert response header Last-Modified: Fri, 25 Jul 2008 14:36:44 -0500 + // Assert collection size is 1. + Assert.assertEquals(201, res.getStatus()); + Assert.assertEquals(contentType, res.getContentType().toString().trim()); + // Assert.assertNotNull( res.getLocation().toString() ); + // Assert.assertEquals( "", res.getContentLocation().toString() ); + // Save eTag for subsequent tests; + eTag = res.getHeader( "ETag" ); + Assert.assertNotNull( eTag ); + lastModified = res.getLastModified(); + Assert.assertNotNull(lastModified); + } + + @Test + public void testDirtyCachePut() throws Exception { + // 2) Conditional PUT request (post with etag. entry provided is stale) + // User client PUT request + // PUT /edit/first-post.atom HTTP/1.1 + // > If-Match: "e180ee84f0671b1" + // + // + // + // Atom-Powered Robots Run Amok + // urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a + // 2007-02-24T16:34:06Z + // Captain Lansing + // Update: it's a hoax! + // + // Testing of entry creation + Factory factory = abdera.getFactory(); + String customerName = "Molly Ringwald"; + Entry entry = factory.newEntry(); + entry.setTitle("customer " + customerName); + entry.setUpdated( new Date()); + entry.addAuthor("Apache Tuscany"); + String id = eTag.substring( 1, eTag.length()-1); + entry.setId(id); // auto-provided + // entry.addLink("" + id, "edit"); // auto-provided + // entry.addLink("" + id, "alternate"); // auto-provided + Content content = abdera.getFactory().newContent(); + content.setContentType(Content.Type.TEXT); + content.setValue(customerName); + entry.setContentElement(content); + + RequestOptions opts = new RequestOptions(); + final String contentType = "application/atom+xml; type=entry"; + opts.setContentType(contentType); + opts.setHeader( "If-None-Match", eTag); + + // AtomTestCaseUtils.printRequestHeaders( "Put request headers", " ", opts ); + IRI colUri = new IRI(providerURI).resolve("customer"); + // res = client.post(colUri.toString() + "?test=foo", entry, opts); + id = eTag.substring( 1, eTag.length()-1); + // Warning. AbderaClient.put(String uri,Base base,RequestOptions options) caches on the client side. + // ClientResponse res = client.put(colUri.toString() + id, entry, opts); + ClientResponse res = client.put(colUri.toString() + "/" + id, new BaseRequestEntity( entry ), opts); + // Expected Atom server response (item was edited by another user) + // > HTTP/1.1 412 Precondition Failed + // Date: Sat, 24 Feb 2007 16:34:11 GMT + + // If-Match Assert response status code is 412. Precondition failed. + // If-None-Match Assert response status code is 200. OK + Assert.assertEquals(200, res.getStatus()); + // Put provides null body and no etags. + res.release(); + } + + @Test + public void testETagMissGet() throws Exception { + // 4) Conditional GET example (get with etag. etag not in cache) + // User client GET request + // GET /edit/first-post.atom HTTP/1.1 + // > If-None-Match: "e180ee84f0671b1" + + RequestOptions opts = new RequestOptions(); + final String contentType = "application/atom+xml; type=entry"; + opts.setContentType(contentType); + opts.setHeader( "If-None-Match", "123456"); + opts.setHeader( "Pragma", "no-cache"); // turn off client caching + + IRI colUri = new IRI(providerURI).resolve("customer"); + // res = client.post(colUri.toString() + "?test=foo", entry, opts); + String id = eTag.substring( 1, eTag.length()-1); + // Warning. AbderaClient.put(String uri,Base base,RequestOptions options) caches on the client side. + // ClientResponse res = client.put(colUri.toString() + id, entry, opts); + ClientResponse res = client.get(colUri.toString() + "/" + id, opts); + // Expected Atom server response (item was edited by another user) + // > HTTP/1.1 412 Precondition Failed + // Date: Sat, 24 Feb 2007 16:34:11 GMT + + // Atom server response (item was up to date) + // > HTTP/1.1 200 OK + // Date: Sat, 24 Feb 2007 13:17:11 GMT + // > ETag: "bb4f5e86e92ddb8549604a0df0763581" + // > Last-Modified: Mon, 28 Jul 2008 10:25:37 -0500 + + // Assert response status code is 200 OK. + // Assert header Content-Type: application/atom+xml;type=entry + // Assert header Location: http://example.org/edit/first-post.atom + // Assert header Content-Location: http://example.org/edit/first-post.atom + // Assert header ETag: "555555" (etag response != etag request) + // Assert header Last-Modified: Fri, 25 Jul 2008 14:36:44 -0500 + Assert.assertEquals(200, res.getStatus()); + Assert.assertEquals(contentType, res.getContentType().toString().trim()); + // Assert.assertNotNull( res.getLocation().toString() ); + // Assert.assertEquals( "", res.getContentLocation().toString() ); + Assert.assertNotNull( res.getHeader( "ETag" ) ); + lastModified = res.getLastModified(); + Assert.assertNotNull(lastModified); + res.release(); + } + + @Test + public void testETagHitGet() throws Exception { + // 3) Conditional GET example (get with etag. etag match) + // User client GET request + // GET /edit/first-post.atom HTTP/1.1 + // > If-None-Match: "e180ee84f0671b1" + + RequestOptions opts = new RequestOptions(); + final String contentType = "application/atom+xml; type=entry"; + opts.setContentType(contentType); + opts.setHeader( "If-None-Match", eTag); + opts.setHeader( "Pragma", "no-cache"); // turn off client caching + + IRI colUri = new IRI(providerURI).resolve("customer"); + // res = client.post(colUri.toString() + "?test=foo", entry, opts); + String id = eTag.substring( 1, eTag.length()-1); + // Warning. AbderaClient.put(String uri,Base base,RequestOptions options) caches on the client side. + // ClientResponse res = client.put(colUri.toString() + id, entry, opts); + ClientResponse res = client.get(colUri.toString() + "/" + id, opts); + // Atom server response (item was up to date) + // > HTTP/1.1 304 Not Modified + // Date: Sat, 24 Feb 2007 13:17:11 GMT + + // Assert response status code is 304 Not Modified. + // Assert header ETag: "e180ee84f0671b1" + // Assert header Last-Modified: Fri, 25 Jul 2008 14:36:44 -0500 + // Assert.assertEquals(304, res.getStatus()); + res.release(); + } + + + @Test + public void testUpToDateGet() throws Exception { + // 3) Conditional GET example (get with If-Mod. entry is up to date) + // User client GET request + // GET /edit/first-post.atom HTTP/1.1 + // > If-Modified-Since: Sat, 29 Oct 2025 19:43:31 GMT + RequestOptions opts = new RequestOptions(); + final String contentType = "application/atom+xml; type=entry"; + opts.setContentType(contentType); + opts.setHeader( "If-Modified-Since", "Sat, 29 Oct 2025 19:43:31 GMT"); // "EEE, dd MMM yyyy HH:mm:ss Z // RFC 822 Date + opts.setHeader( "Pragma", "no-cache"); // turn off client caching + + IRI colUri = new IRI(providerURI).resolve("customer"); + // res = client.post(colUri.toString() + "?test=foo", entry, opts); + String id = eTag.substring( 1, eTag.length()-1); + // Warning. AbderaClient.put(String uri,Base base,RequestOptions options) caches on the client side. + // ClientResponse res = client.put(colUri.toString() + id, entry, opts); + // Warning. AbderaClient.put(String uri,Base base,RequestOptions options) caches on the client side. + // ClientResponse res = client.get(colUri.toString() + "/" + id, opts); + ClientResponse res = client.execute( "GET", colUri.toString(), (BaseRequestEntity)null, opts); + + // Atom server response (item was up to date) + // > HTTP/1.1 304 Not Modified + // Date: Sat, 24 Feb 2007 13:17:11 GMT + + // Assert response status code is 304 Not Modified. + Assert.assertEquals(304, res.getStatus()); + res.release(); + } + + @Test + public void testOutOfDateGet() throws Exception { + // 4) Conditional GET example (get with If-Mod. entry is not to date) + // User client GET request + // GET /edit/first-post.atom HTTP/1.1 + // > If-Modified-Since: Sat, 29 Oct 1844 19:43:31 GMT + RequestOptions opts = new RequestOptions(); + final String contentType = "application/atom+xml; type=entry"; + opts.setContentType(contentType); + opts.setHeader( "If-Modified-Since", "Sat, 29 Oct 1844 19:43:31 GMT"); // "EEE, dd MMM yyyy HH:mm:ss Z // RFC 822 Date + opts.setHeader( "Pragma", "no-cache"); // turn off client caching + + IRI colUri = new IRI(providerURI).resolve("customer"); + // res = client.post(colUri.toString() + "?test=foo", entry, opts); + String id = eTag.substring( 1, eTag.length()-1); + // Warning. AbderaClient.put(String uri,Base base,RequestOptions options) caches on the client side. + // ClientResponse res = client.put(colUri.toString() + id, entry, opts); + ClientResponse res = client.get(colUri.toString() + "/" + id, opts); + + // Atom server response (item was up to date) + // > HTTP/1.1 200 OK + // Date: Sat, 24 Feb 2007 13:17:11 GMT + // > ETag: "bb4f5e86e92ddb8549604a0df0763581" + // > Last-Modified: Mon, 28 Jul 2008 10:25:37 -0500 + + // Assert response status code is 200 OK. + // Assert header ETag: "e180ee84f0671b1" + // Assert header Last-Modified: Greater than If-Mod + Assert.assertEquals(200, res.getStatus()); + Assert.assertEquals(contentType, res.getContentType().toString().trim()); + // Assert.assertNotNull( res.getLocation().toString() ); + // Assert.assertEquals( "", res.getContentLocation().toString() ); + Assert.assertNotNull( res.getHeader( "ETag" ) ); + lastModified = res.getLastModified(); + Assert.assertNotNull(lastModified); + res.release(); + } + + @Test + public void testUpToDateUnModGet() throws Exception { + // 3) Conditional GET example (get with If-Unmod. entry is not modified (< predicate date). + // User client GET request + // GET /edit/first-post.atom HTTP/1.1 + // > If-Unmodified-Since: Sat, 29 Oct 2025 19:43:31 GMT + RequestOptions opts = new RequestOptions(); + final String contentType = "application/atom+xml; type=entry"; + opts.setContentType(contentType); + opts.setHeader( "If-Unmodified-Since", "Sat, 29 Oct 2050 19:43:31 GMT" ); + opts.setHeader( "Pragma", "no-cache"); // turn off client caching + + IRI colUri = new IRI(providerURI).resolve("customer"); + // res = client.post(colUri.toString() + "?test=foo", entry, opts); + String id = eTag.substring( 1, eTag.length()-1); + // Warning. AbderaClient.put(String uri,Base base,RequestOptions options) caches on the client side. + // ClientResponse res = client.put(colUri.toString() + id, entry, opts); + ClientResponse res = client.get(colUri.toString() + "/" + id, opts); + + // Atom server response (item was up to date) + // > HTTP/1.1 200 OK + // Date: Sat, 24 Feb 2007 13:17:11 GMT + // > ETag: "bb4f5e86e92ddb8549604a0df0763581" + // > Last-Modified: Mon, 28 Jul 2008 10:25:37 -0500 + + // Assert response status code is 200 OK. + // Assert header Content-Type: application/atom+xml;type=entry + // Assert header Location: http://example.org/edit/first-post.atom + // Assert header Content-Location: http://example.org/edit/first-post.atom + // Assert header ETag: "e180ee84f0671b1" + // Assert header Last-Modified: Less than If-Unmod + Assert.assertEquals(200, res.getStatus()); + res.release(); + } + + @Test + public void testOutOfDateUnModGet() throws Exception { + // 4) Conditional GET example (get with If-Unmod. entry is modified (> predicate date) + // User client GET request + // GET /edit/first-post.atom HTTP/1.1 + // Host: example.org + // > If-Unmodified-Since: Sat, 29 Oct 1844 19:43:31 GMT + RequestOptions opts = new RequestOptions(); + final String contentType = "application/atom+xml; type=entry"; + opts.setContentType(contentType); + opts.setHeader( "If-Unmodified-Since", "Sat, 29 Oct 1844 19:43:31 GMT" ); + opts.setHeader( "Pragma", "no-cache"); // turn off client caching + + IRI colUri = new IRI(providerURI).resolve("customer"); + // res = client.post(colUri.toString() + "?test=foo", entry, opts); + String id = eTag.substring( 1, eTag.length()-1); + // Warning. AbderaClient.put(String uri,Base base,RequestOptions options) caches on the client side. + // ClientResponse res = client.put(colUri.toString() + id, entry, opts); + ClientResponse res = client.get(colUri.toString() + "/" + id, opts); + + // Atom server response (item was up to date) + // > HTTP/1.1 304 Not Modified + // Date: Sat, 24 Feb 2007 13:17:11 GMT + + // Assert response status code is 304 Not Modified. + Assert.assertEquals(304, res.getStatus()); + res.release(); + } +} diff --git a/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/ProviderFeedEntityTagsTestCase.java b/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/ProviderFeedEntityTagsTestCase.java new file mode 100644 index 0000000000..4915f7426e --- /dev/null +++ b/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/ProviderFeedEntityTagsTestCase.java @@ -0,0 +1,382 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.atom; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.StringReader; +import java.net.Socket; +import java.text.SimpleDateFormat; +import java.util.Date; + +import junit.framework.Assert; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import org.apache.tuscany.sca.host.embedded.SCADomain; + +import org.apache.abdera.Abdera; +import org.apache.abdera.i18n.iri.IRI; +import org.apache.abdera.factory.Factory; +import org.apache.abdera.model.Base; +import org.apache.abdera.model.Content; +import org.apache.abdera.model.Entry; +import org.apache.abdera.model.Feed; +import org.apache.abdera.model.Document; +import org.apache.abdera.model.Service; +import org.apache.abdera.model.Collection; +import org.apache.abdera.protocol.Response.ResponseType; +import org.apache.abdera.protocol.client.AbderaClient; +import org.apache.abdera.protocol.client.ClientResponse; +import org.apache.abdera.protocol.client.RequestOptions; +import org.apache.abdera.protocol.client.util.BaseRequestEntity; +import org.apache.abdera.util.EntityTag; +import org.apache.abdera.parser.Parser; + +/** + * Tests use of server provided feed entity tags for Atom binding in Tuscany. + * Tests conditional gets (e.g. get if-none-match) or conditional posts (post if-match) + * using entity tags and last modified entries in headers. + * Uses the SCA provided Provider composite to act as a server. + * Uses the Abdera provided Client to act as a client. + */ +public class ProviderFeedEntityTagsTestCase { + public final static String providerURI = "http://localhost:8084/customer"; + protected static SCADomain scaConsumerDomain; + protected static SCADomain scaProviderDomain; + protected static CustomerClient testService; + protected static Abdera abdera; + protected static AbderaClient client; + protected static Parser abderaParser; + protected static String eTag; + protected static Date lastModified; + protected static final SimpleDateFormat dateFormat = new SimpleDateFormat( "EEE, dd MMM yyyy HH:mm:ss Z" ); // RFC 822 date time + + @BeforeClass + public static void init() throws Exception { + System.out.println(">>>ProviderFeedEntityTagsTestCase.init"); + scaProviderDomain = SCADomain.newInstance("org/apache/tuscany/sca/binding/atom/Provider.composite"); + abdera = new Abdera(); + client = new AbderaClient(abdera); + abderaParser = Abdera.getNewParser(); + } + + @AfterClass + public static void destroy() throws Exception { + System.out.println(">>>ProviderFeedEntityTagsTestCase.destroy"); + scaProviderDomain.close(); + } + + @Test + public void testPrelim() throws Exception { + Assert.assertNotNull(scaProviderDomain); + Assert.assertNotNull( client ); + } + + @Test + public void testFeedBasics() throws Exception { + System.out.println(">>>ProviderFeedEntityTagsTestCase.testFeedBasics"); + // Normal feed request + ClientResponse res = client.get(providerURI); + Assert.assertNotNull(res); + try { + // Assert feed provided since no predicates + Assert.assertEquals(200, res.getStatus()); + Assert.assertEquals(ResponseType.SUCCESS, res.getType()); + // AtomTestCaseUtils.printResponseHeaders( "Feed response headers:", " ", res ); + // System.out.println("Feed response content:"); + // AtomTestCaseUtils.prettyPrint(abdera, res.getDocument()); + + // Perform other tests on feed. + // Warning. AbderaClient.getEntityTag is very particular on tag pattern. + // Document doc = res.getDocument(); + String body = read( res.getInputStream() ); + // RFC 4287 requires non-null id, title, updated elements + Assert.assertTrue( -1 != body.indexOf( "" )); + Assert.assertTrue( -1 != body.indexOf( "" )); + Assert.assertTrue( -1 != body.indexOf( "" )); + + eTag = res.getHeader("ETag"); + Assert.assertNotNull( eTag ); + lastModified = res.getLastModified(); + Assert.assertNotNull( lastModified ); + } finally { + res.release(); + } + } + + @Test + public void testUnmodifiedGetIfMatch() throws Exception { + System.out.println(">>>ProviderFeedEntityTagsTestCase.testFeedUnmodifiedGetIfMatch"); + // Feed request with predicates + RequestOptions opts = new RequestOptions(); + final String contentType = "application/atom+xml"; + opts.setContentType(contentType); + opts.setHeader( "If-Match", eTag); + + ClientResponse res = client.get(providerURI, opts); + Assert.assertNotNull(res); + try { + String thisETag = res.getHeader("ETag"); + Assert.assertNotNull( thisETag ); + Date thisLastModified = res.getLastModified(); + Assert.assertNotNull( thisLastModified ); + + // Should return 200 - Feed provided since it matches etag. + Assert.assertEquals(200, res.getStatus()); + Assert.assertEquals(ResponseType.SUCCESS, res.getType()); + // AtomTestCaseUtils.printResponseHeaders( "Feed response headers:", " ", res ); + // System.out.println("Feed response content:"); + // AtomTestCaseUtils.prettyPrint(abdera, res.getDocument()); + } finally { + res.release(); + } + } + + @Test + public void testUnmodifiedGetIfNoneMatch() throws Exception { + System.out.println(">>>ProviderFeedEntityTagsTestCase.testFeedUnmodifiedGetIfNoneMatch"); + // Feed request with predicates + RequestOptions opts = new RequestOptions(); + final String contentType = "application/atom+xml"; + opts.setContentType(contentType); + opts.setHeader( "If-None-Match", eTag); + + ClientResponse res = client.get(providerURI, opts); + Assert.assertNotNull(res); + try { + // Should return 304 - Feed not provided since it matches ETag. + Assert.assertEquals(304, res.getStatus()); + } finally { + res.release(); + } + } + + @Test + public void testUnmodifiedGetIfUnModified() throws Exception { + System.out.println(">>>ProviderFeedEntityTagsTestCase.testFeedUnmodifiedGetIfUnModified"); + // Feed request with predicates + RequestOptions opts = new RequestOptions(); + final String contentType = "application/atom+xml"; + opts.setContentType(contentType); + opts.setHeader( "If-Unmodified-Since", dateFormat.format( new Date() )); + + ClientResponse res = client.get(providerURI, opts); + Assert.assertNotNull(res); + try { + // Should return 304 - Feed not provided since feed is modified since. + Assert.assertEquals(304, res.getStatus()); + } finally { + res.release(); + } + } + + @Test + public void testUnmodifiedGetIfModified() throws Exception { + System.out.println(">>>ProviderFeedEntityTagsTestCase.testFeedUnmodifiedGetIfModified"); + // Feed request with predicates + RequestOptions opts = new RequestOptions(); + final String contentType = "application/atom+xml"; + opts.setContentType(contentType); + opts.setHeader( "If-Modified-Since", dateFormat.format( new Date( 0 ) )); + + ClientResponse res = client.get(providerURI, opts); + Assert.assertNotNull(res); + try { + // Should return 200 - Feed provided since feed is changed. + Assert.assertEquals(200, res.getStatus()); + Assert.assertEquals(ResponseType.SUCCESS, res.getType()); + + String thisETag = res.getHeader("ETag"); + Assert.assertNotNull( thisETag ); + Date thisLastModified = res.getLastModified(); + Assert.assertNotNull( thisLastModified ); + } finally { + res.release(); + } + } + + @Test + public void testModifiedGetIfNoneMatch() throws Exception { + System.out.println(">>>ProviderFeedEntityTagsTestCase.testFeedModifiedGetIfNoneMatch"); + // Post some new content to the feed. + Factory factory = abdera.getFactory(); + String customerName = "Fred Farkle"; + Entry entry = factory.newEntry(); + entry.setTitle("customer " + customerName); + entry.setUpdated(new Date()); + entry.addAuthor("Apache Tuscany"); + Content content = abdera.getFactory().newContent(); + content.setContentType(Content.Type.TEXT); + content.setValue(customerName); + entry.setContentElement(content); + + RequestOptions opts = new RequestOptions(); + String contentType = "application/atom+xml; type=entry"; + opts.setContentType(contentType); + IRI colUri = new IRI(providerURI).resolve("customer"); + ClientResponse res = client.post(colUri.toString(), entry, opts); + + // Feed request with predicates + opts = new RequestOptions(); + contentType = "application/atom+xml"; + opts.setContentType(contentType); + opts.setHeader( "If-None-Match", eTag); + + res = client.get(providerURI, opts); + Assert.assertNotNull(res); + try { + // Should return 304 - Feed not provided since it matches ETag. + Assert.assertEquals(304, res.getStatus()); + // AtomTestCaseUtils.printResponseHeaders( "Feed response headers:", " ", res ); + // System.out.println("Feed response content:"); + // AtomTestCaseUtils.prettyPrint(abdera, res.getDocument()); + } finally { + res.release(); + } + } + + @Test + public void testModifiedGetIfMatch() throws Exception { + System.out.println(">>>ProviderFeedEntityTagsTestCase.testFeedModifiedGetIfMatch"); + // Feed request with predicates + RequestOptions opts = new RequestOptions(); + final String contentType = "application/atom+xml"; + opts.setContentType(contentType); + opts.setHeader( "If-Match", eTag); + + ClientResponse res = client.get(providerURI, opts); + Assert.assertNotNull(res); + try { + String thisETag = res.getHeader("ETag"); + Assert.assertNotNull( thisETag ); + Date thisLastModified = res.getLastModified(); + Assert.assertNotNull( thisLastModified ); + + // Should return 200 - value since feed is changed + Assert.assertEquals(200, res.getStatus()); + Assert.assertEquals(ResponseType.SUCCESS, res.getType()); + + // AtomTestCaseUtils.printResponseHeaders( "Feed modified if-none-match response headers:", " ", res ); + // System.out.println("Feed response content:"); + // AtomTestCaseUtils.prettyPrint(abdera, res.getDocument()); + } finally { + res.release(); + } + } + + @Test + public void testModifiedGetIfUnModified() throws Exception { + System.out.println(">>>ProviderFeedEntityTagsTestCase.testFeedUnmodifiedGetIfUnModified"); + // Feed request with predicates + RequestOptions opts = new RequestOptions(); + final String contentType = "application/atom+xml"; + opts.setContentType(contentType); + opts.setHeader( "If-Unmodified-Since", dateFormat.format( new Date() )); + + ClientResponse res = client.get(providerURI, opts); + Assert.assertNotNull(res); + try { + // Should return 304 - Feed not provided since feed is modified since. + Assert.assertEquals(304, res.getStatus()); + } finally { + res.release(); + } + } + + @Test + public void testModifiedGetIfModified() throws Exception { + System.out.println(">>>ProviderFeedEntityTagsTestCase.testFeedUnmodifiedGetIfModified"); + // Feed request with predicates + RequestOptions opts = new RequestOptions(); + final String contentType = "application/atom+xml"; + opts.setContentType(contentType); + opts.setHeader( "If-Modified-Since", dateFormat.format( lastModified )); + + ClientResponse res = client.get(providerURI, opts); + Assert.assertNotNull(res); + try { + // Should return 200 - Feed provided since feed is changed. + Assert.assertEquals(200, res.getStatus()); + Assert.assertEquals(ResponseType.SUCCESS, res.getType()); + + String thisETag = res.getHeader("ETag"); + Assert.assertNotNull( thisETag ); + Date thisLastModified = res.getLastModified(); + Assert.assertNotNull( thisLastModified ); + } finally { + res.release(); + } + } + + + public static void printFeed( String title, String indent, Feed feed ) { + if ( feed == null ) { + System.out.println( title + " feed is null"); + return; + } + + System.out.println( title ); + System.out.println( indent + "id=" + feed.getId() ); + System.out.println( indent + "title=" + feed.getTitle() ); + System.out.println( indent + "updated=" + feed.getUpdated() ); + System.out.println( indent + "author=" + feed.getAuthor() ); + Collection collection = feed.getCollection(); + if ( collection == null ) { + System.out.println( indent + "collection=null" ); + } else { + System.out.println( indent + "collection=" + collection ); + } + // System.out.println( indent + "collection size=" + feed.getCollection() ); + // for (Collection collection : workspace.getCollections()) { + // if (collection.getTitle().equals("customers")) { + // String expected = uri + "customers"; + // String actual = collection.getResolvedHref().toString(); + // assertEquals(expected, actual); + // } + // } + + } + + /** + * Read response ream from the given socket. + * @param socket + * @return + * @throws IOException + */ + private static String read(InputStream inputStream) throws IOException { + BufferedReader reader = null; + try { + reader = new BufferedReader(new InputStreamReader( inputStream )); + StringBuffer sb = new StringBuffer(); + String str; + while ((str = reader.readLine()) != null) { + sb.append(str); + } + return sb.toString(); + } finally { + if (reader != null) { + reader.close(); + } + } + } +} diff --git a/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/ProviderServiceDocumentTestCase.java b/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/ProviderServiceDocumentTestCase.java new file mode 100644 index 0000000000..96ea508210 --- /dev/null +++ b/java/sca/contrib/modules/binding-atom-abdera/src/test/java/org/apache/tuscany/sca/binding/atom/ProviderServiceDocumentTestCase.java @@ -0,0 +1,209 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.atom; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; + +import junit.framework.Assert; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import org.apache.tuscany.sca.host.embedded.SCADomain; +import org.apache.tuscany.sca.binding.atom.collection.Collection; + +import org.apache.abdera.Abdera; +import org.apache.abdera.i18n.iri.IRI; +import org.apache.abdera.factory.Factory; +import org.apache.abdera.model.Content; +import org.apache.abdera.model.Entry; +import org.apache.abdera.model.Feed; +import org.apache.abdera.model.Document; +import org.apache.abdera.model.Service; +import org.apache.abdera.protocol.Response.ResponseType; +import org.apache.abdera.protocol.client.AbderaClient; +import org.apache.abdera.protocol.client.ClientResponse; +import org.apache.abdera.protocol.client.RequestOptions; +import org.apache.abdera.parser.Parser; + +/** + * Tests use of service documents provided by atom binding based collections. + * Uses the SCA provided Provider composite to act as a server. + * Uses the Abdera provided Client to act as a client. + */ +public class ProviderServiceDocumentTestCase { + public final static String providerURI = "http://localhost:8084/customer"; + protected static SCADomain scaProviderDomain; + protected static SCADomain scaConsumerDomain; + protected static CustomerClient testService; + protected static Abdera abdera; + protected static AbderaClient client; + protected static Parser abderaParser; + + @BeforeClass + public static void init() throws Exception { + scaProviderDomain = SCADomain.newInstance("org/apache/tuscany/sca/binding/atom/Provider.composite"); + scaConsumerDomain = SCADomain.newInstance("org/apache/tuscany/sca/binding/atom/Consumer.composite"); + testService = scaConsumerDomain.getService(CustomerClient.class, "CustomerClient"); + abdera = new Abdera(); + client = new AbderaClient(abdera); + abderaParser = Abdera.getNewParser(); + } + + @AfterClass + public static void destroy() throws Exception { + scaProviderDomain.close(); + } + + @Test + public void testPrelim() throws Exception { + Assert.assertNotNull(scaProviderDomain); + Assert.assertNotNull( client ); + } + + @Test + public void testFeedBasics() throws Exception { + // Normal feed request + ClientResponse res = client.get(providerURI); + Assert.assertNotNull(res); + try { + // Assert feed provided since no predicates + Assert.assertEquals(200, res.getStatus()); + Assert.assertEquals(ResponseType.SUCCESS, res.getType()); + // AtomTestCaseUtils.printResponseHeaders( "Feed response headers:", " ", res ); + // System.out.println("Feed response content:"); + // AtomTestCaseUtils.prettyPrint(abdera, res.getDocument()); + + // Perform other tests on feed. + // Warning. AbderaClient.getEntityTag is very particular on tag pattern. + // Document doc = res.getDocument(); + String body = read( res.getInputStream() ); + // RFC 4287 requires non-null id, title, updated elements + Assert.assertTrue( -1 != body.indexOf( "" )); + Assert.assertTrue( -1 != body.indexOf( "" )); + Assert.assertTrue( -1 != body.indexOf( "" )); + } finally { + res.release(); + } + } + + @Test + public void testServiceDocumentGet() throws Exception { + Collection resourceCollection = testService.getCustomerCollection(); + Assert.assertNotNull(resourceCollection); + + Entry postEntry = postEntry("Sponge Bob"); + Entry newEntry = resourceCollection.post(postEntry); + postEntry = postEntry("Austin Powers"); + newEntry = resourceCollection.post(postEntry); + postEntry = postEntry("Count Dracula"); + newEntry = resourceCollection.post(postEntry); + + // Service document + ClientResponse res = client.get(providerURI + "/atomsvc"); + Assert.assertNotNull(res); + try { + // Asser feed provided since no predicates + Assert.assertEquals(200, res.getStatus()); + Assert.assertEquals(ResponseType.SUCCESS, res.getType()); + + // Perform other tests on feed. + // AtomTestCaseUtils.prettyPrint(abdera, res.getDocument()); + Document serviceDoc = res.getDocument(); + Service service = serviceDoc.getRoot(); + Assert.assertNotNull( service ); + org.apache.abdera.model.Collection collection = service.getCollection( "workspace", "customers" ); + String title = collection.getTitle(); + Assert.assertEquals("customers", title); + String href = collection.getHref().toString(); + Assert.assertTrue( href.contains( "customer") ); + } finally { + res.release(); + } + } + + public static void printFeed( String title, String indent, Feed feed ) { + if ( feed == null ) { + System.out.println( title + " feed is null"); + return; + } + + System.out.println( title ); + System.out.println( indent + "id=" + feed.getId() ); + System.out.println( indent + "title=" + feed.getTitle() ); + System.out.println( indent + "updated=" + feed.getUpdated() ); + System.out.println( indent + "author=" + feed.getAuthor() ); + // Collection collection = feed.getCollection(); + // if ( collection == null ) { + // System.out.println( indent + "collection=null" ); + // } else { + // System.out.println( indent + "collection=" + collection ); + // } + // System.out.println( indent + "collection size=" + feed.getCollection() ); + // for (Collection collection : workspace.getCollections()) { + // if (collection.getTitle().equals("customers")) { + // String expected = uri + "customers"; + // String actual = collection.getResolvedHref().toString(); + // assertEquals(expected, actual); + // } + // } + + } + + private Entry postEntry(String value) { + Entry entry = abdera.newEntry(); + entry.setTitle("customer " + value); + + Content content = abdera.getFactory().newContent(); + content.setContentType(Content.Type.TEXT); + content.setValue(value); + entry.setContentElement(content); + + return entry; + } + + /** + * Read response ream from the given socket. + * @param socket + * @return + * @throws IOException + */ + private static String read(InputStream inputStream) throws IOException { + BufferedReader reader = null; + try { + reader = new BufferedReader(new InputStreamReader( inputStream )); + StringBuffer sb = new StringBuffer(); + String str; + while ((str = reader.readLine()) != null) { + sb.append(str); + } + return sb.toString(); + } finally { + if (reader != null) { + reader.close(); + } + } + } +} diff --git a/java/sca/contrib/modules/binding-atom-abdera/src/test/resources/org/apache/tuscany/sca/binding/atom/Consumer.composite b/java/sca/contrib/modules/binding-atom-abdera/src/test/resources/org/apache/tuscany/sca/binding/atom/Consumer.composite new file mode 100644 index 0000000000..a2c50f872e --- /dev/null +++ b/java/sca/contrib/modules/binding-atom-abdera/src/test/resources/org/apache/tuscany/sca/binding/atom/Consumer.composite @@ -0,0 +1,32 @@ + + + + + + + + + + + + diff --git a/java/sca/contrib/modules/binding-atom-abdera/src/test/resources/org/apache/tuscany/sca/binding/atom/Provider.composite b/java/sca/contrib/modules/binding-atom-abdera/src/test/resources/org/apache/tuscany/sca/binding/atom/Provider.composite new file mode 100644 index 0000000000..60097ee0f7 --- /dev/null +++ b/java/sca/contrib/modules/binding-atom-abdera/src/test/resources/org/apache/tuscany/sca/binding/atom/Provider.composite @@ -0,0 +1,33 @@ + + + + + + + + + + + + + diff --git a/java/sca/contrib/modules/binding-atom-abdera/src/test/resources/org/apache/tuscany/sca/binding/atom/ReceiptProvider.composite b/java/sca/contrib/modules/binding-atom-abdera/src/test/resources/org/apache/tuscany/sca/binding/atom/ReceiptProvider.composite new file mode 100644 index 0000000000..71aa932a12 --- /dev/null +++ b/java/sca/contrib/modules/binding-atom-abdera/src/test/resources/org/apache/tuscany/sca/binding/atom/ReceiptProvider.composite @@ -0,0 +1,33 @@ + + + + + + + + + + + + + diff --git a/java/sca/contrib/modules/binding-atom/LICENSE b/java/sca/contrib/modules/binding-atom/LICENSE new file mode 100644 index 0000000000..6e529a25c4 --- /dev/null +++ b/java/sca/contrib/modules/binding-atom/LICENSE @@ -0,0 +1,205 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + + diff --git a/java/sca/contrib/modules/binding-atom/META-INF/MANIFEST.MF b/java/sca/contrib/modules/binding-atom/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..ff7fe96475 --- /dev/null +++ b/java/sca/contrib/modules/binding-atom/META-INF/MANIFEST.MF @@ -0,0 +1,23 @@ +Manifest-Version: 1.0 +Export-Package: org.apache.tuscany.sca.binding.atom;uses:="org.apache. + tuscany.sca.assembly";version="2.0.0" +Private-Package: org.apache.tuscany.sca.binding.atom.impl;version="1.4 + " +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA Atom Feed Binding Extension +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397253156 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA Atom Feed Binding Extension +Import-Package: javax.xml.stream;resolution:=optional, + org.apache.tuscany.sca.assembly;version="2.0.0", + org.apache.tuscany.sca.binding.atom;version="2.0.0", + org.apache.tuscany.sca.core;version="2.0.0";resolution:=optional, + org.apache.tuscany.sca.monitor;version="2.0.0";resolution:=optional, + org.apache.tuscany.sca.policy;version="2.0.0" +Bundle-SymbolicName: org.apache.tuscany.sca.binding.atom +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/binding-atom/NOTICE b/java/sca/contrib/modules/binding-atom/NOTICE new file mode 100644 index 0000000000..51042eab05 --- /dev/null +++ b/java/sca/contrib/modules/binding-atom/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/binding-atom/pom.xml b/java/sca/contrib/modules/binding-atom/pom.xml new file mode 100644 index 0000000000..e5a7462228 --- /dev/null +++ b/java/sca/contrib/modules/binding-atom/pom.xml @@ -0,0 +1,62 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + + tuscany-binding-atom + Apache Tuscany SCA Atom Feed Binding Extension + + + + org.apache.tuscany.sca + tuscany-assembly + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-assembly-xml + 2.0-SNAPSHOT + test + + + + org.apache.tuscany.sca + tuscany-sca-api + 2.0-SNAPSHOT + test + + + + junit + junit + 4.5 + test + + + + + diff --git a/java/sca/contrib/modules/binding-atom/src/main/java/org/apache/tuscany/sca/binding/atom/AtomBinding.java b/java/sca/contrib/modules/binding-atom/src/main/java/org/apache/tuscany/sca/binding/atom/AtomBinding.java new file mode 100644 index 0000000000..807d6a8971 --- /dev/null +++ b/java/sca/contrib/modules/binding-atom/src/main/java/org/apache/tuscany/sca/binding/atom/AtomBinding.java @@ -0,0 +1,43 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.atom; + +import org.apache.tuscany.sca.assembly.Binding; + +/** + * Atom binding model. + * + * @version $Rev$ $Date$ + */ +public interface AtomBinding extends Binding { + + /** + * Returns the title of the Atom collection. + * @return + */ + String getTitle(); + + /** + * Sets the title of the Atom collection. + * @param title + */ + void setTitle(String title); + +} diff --git a/java/sca/contrib/modules/binding-atom/src/main/java/org/apache/tuscany/sca/binding/atom/AtomBindingFactory.java b/java/sca/contrib/modules/binding-atom/src/main/java/org/apache/tuscany/sca/binding/atom/AtomBindingFactory.java new file mode 100644 index 0000000000..6e5623e1a2 --- /dev/null +++ b/java/sca/contrib/modules/binding-atom/src/main/java/org/apache/tuscany/sca/binding/atom/AtomBindingFactory.java @@ -0,0 +1,35 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.atom; + +/** + * Factory for the Atom binding + * + * @version $Rev$ $Date$ + */ +public interface AtomBindingFactory { + + /** + * Creates a new Atom binding. + * @return the new Atom binding + */ + AtomBinding createAtomBinding(); + +} diff --git a/java/sca/contrib/modules/binding-atom/src/main/java/org/apache/tuscany/sca/binding/atom/impl/AtomBindingFactoryImpl.java b/java/sca/contrib/modules/binding-atom/src/main/java/org/apache/tuscany/sca/binding/atom/impl/AtomBindingFactoryImpl.java new file mode 100644 index 0000000000..ea06625d34 --- /dev/null +++ b/java/sca/contrib/modules/binding-atom/src/main/java/org/apache/tuscany/sca/binding/atom/impl/AtomBindingFactoryImpl.java @@ -0,0 +1,36 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.atom.impl; + +import org.apache.tuscany.sca.binding.atom.AtomBinding; +import org.apache.tuscany.sca.binding.atom.AtomBindingFactory; + +/** + * Factory for the Atom binding model. + * + * @version $Rev$ $Date$ + */ +public class AtomBindingFactoryImpl implements AtomBindingFactory { + + public AtomBinding createAtomBinding() { + return new AtomBindingImpl(); + } + +} diff --git a/java/sca/contrib/modules/binding-atom/src/main/java/org/apache/tuscany/sca/binding/atom/impl/AtomBindingImpl.java b/java/sca/contrib/modules/binding-atom/src/main/java/org/apache/tuscany/sca/binding/atom/impl/AtomBindingImpl.java new file mode 100644 index 0000000000..1c68ab5bc1 --- /dev/null +++ b/java/sca/contrib/modules/binding-atom/src/main/java/org/apache/tuscany/sca/binding/atom/impl/AtomBindingImpl.java @@ -0,0 +1,117 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.atom.impl; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.assembly.Component; +import org.apache.tuscany.sca.assembly.ComponentService; +import org.apache.tuscany.sca.assembly.OptimizableBinding; +import org.apache.tuscany.sca.binding.atom.AtomBinding; +import org.apache.tuscany.sca.policy.Intent; +import org.apache.tuscany.sca.policy.IntentAttachPointType; +import org.apache.tuscany.sca.policy.PolicySet; +import org.apache.tuscany.sca.policy.PolicySetAttachPoint; + +/** + * Implementation of the Atom Feed binding model. + * + * @version $Rev$ $Date$ + */ +class AtomBindingImpl implements AtomBinding, PolicySetAttachPoint { + + private String name; + private String uri; + private String title; + private List requiredIntents = new ArrayList(); + private List policySets = new ArrayList(); + private IntentAttachPointType intentAttachPointType; + private List applicablePolicySets = new ArrayList(); + + public String getName() { + return name; + } + + public String getURI() { + return uri; + } + + public void setName(String name) { + this.name = name; + } + + public void setURI(String uri) { + this.uri = uri; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public boolean isUnresolved() { + // The binding is always resolved + return false; + } + + public void setUnresolved(boolean unresolved) { + // The binding is always resolved + } + + //Policy related getters/setters + + public List getPolicySets() { + return policySets; + } + + public List getRequiredIntents() { + return requiredIntents; + } + + public IntentAttachPointType getType() { + return intentAttachPointType; + } + + public void setType(IntentAttachPointType intentAttachPointType) { + this.intentAttachPointType = intentAttachPointType; + } + + public void setPolicySets(List policySets) { + this.policySets = policySets; + } + + public void setRequiredIntents(List intents) { + this.requiredIntents = intents; + } + + public List getApplicablePolicySets() { + return applicablePolicySets; + } + + @Override + public Object clone() throws CloneNotSupportedException { + return super.clone(); + } +} diff --git a/java/sca/contrib/modules/binding-atom/src/main/resources/META-INF/services/org.apache.tuscany.sca.binding.atom.AtomBindingFactory b/java/sca/contrib/modules/binding-atom/src/main/resources/META-INF/services/org.apache.tuscany.sca.binding.atom.AtomBindingFactory new file mode 100644 index 0000000000..a8117db8f3 --- /dev/null +++ b/java/sca/contrib/modules/binding-atom/src/main/resources/META-INF/services/org.apache.tuscany.sca.binding.atom.AtomBindingFactory @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for the model factory +org.apache.tuscany.sca.binding.atom.impl.AtomBindingFactoryImpl \ No newline at end of file diff --git a/java/sca/contrib/modules/binding-atom/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor b/java/sca/contrib/modules/binding-atom/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor new file mode 100644 index 0000000000..52e0e916f5 --- /dev/null +++ b/java/sca/contrib/modules/binding-atom/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for the artifact processor extension +org.apache.tuscany.sca.assembly.xml.DefaultBeanModelProcessor;qname=http://tuscany.apache.org/xmlns/sca/1.0#binding.atom,model=org.apache.tuscany.sca.binding.atom.AtomBinding,factory=org.apache.tuscany.sca.binding.atom.AtomBindingFactory \ No newline at end of file diff --git a/java/sca/contrib/modules/binding-atom/src/test/java/org/apache/tuscany/sca/binding/atom/AtomBindingProcessorTestCase.java b/java/sca/contrib/modules/binding-atom/src/test/java/org/apache/tuscany/sca/binding/atom/AtomBindingProcessorTestCase.java new file mode 100644 index 0000000000..1477554cd1 --- /dev/null +++ b/java/sca/contrib/modules/binding-atom/src/test/java/org/apache/tuscany/sca/binding/atom/AtomBindingProcessorTestCase.java @@ -0,0 +1,91 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.atom; + +import java.io.StringReader; + +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sca.assembly.Composite; +import org.apache.tuscany.sca.contribution.processor.DefaultStAXArtifactProcessorExtensionPoint; +import org.apache.tuscany.sca.contribution.processor.ExtensibleStAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessorExtensionPoint; +import org.apache.tuscany.sca.core.DefaultExtensionPointRegistry; +import org.apache.tuscany.sca.core.UtilityExtensionPoint; +import org.apache.tuscany.sca.monitor.DefaultMonitorFactory; +import org.apache.tuscany.sca.monitor.Monitor; +import org.apache.tuscany.sca.monitor.MonitorFactory; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * @version $Rev$ $Date$ + */ +public class AtomBindingProcessorTestCase { + + private static final String COMPOSITE = + "" + + "" + + " " + + " " + + " " + + " " + + " " + + " " + + ""; + + private static XMLInputFactory inputFactory; + private static StAXArtifactProcessor staxProcessor; + private static Monitor monitor; + + @BeforeClass + public static void setUp() throws Exception { + DefaultExtensionPointRegistry extensionPoints = new DefaultExtensionPointRegistry(); + inputFactory = XMLInputFactory.newInstance(); + // Create a monitor + UtilityExtensionPoint utilities = extensionPoints.getExtensionPoint(UtilityExtensionPoint.class); + MonitorFactory monitorFactory = new DefaultMonitorFactory(); + if (monitorFactory != null) { + monitor = monitorFactory.createMonitor(); + utilities.addUtility(monitorFactory); + } + StAXArtifactProcessorExtensionPoint staxProcessors = new DefaultStAXArtifactProcessorExtensionPoint(extensionPoints); + staxProcessor = new ExtensibleStAXArtifactProcessor(staxProcessors, inputFactory, null, monitor); + } + + /** + * Test parsing valid composite definition. Valid composite populated with correct values expected. + * @throws Exception + */ + @Test + public void testLoadValidComposite() throws Exception { + XMLStreamReader reader = inputFactory.createXMLStreamReader(new StringReader(COMPOSITE)); + + Composite composite = (Composite)staxProcessor.read(reader); + AtomBinding binding = (AtomBinding) composite.getComponents().get(0).getServices().get(0).getBindings().get(0); + + Assert.assertNotNull(binding); + Assert.assertEquals("Feed Title", binding.getTitle()); + Assert.assertEquals("http://localhost:8080/feed", binding.getURI()); + } +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/LICENSE b/java/sca/contrib/modules/binding-corba-runtime/LICENSE new file mode 100644 index 0000000000..6e529a25c4 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/LICENSE @@ -0,0 +1,205 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + + diff --git a/java/sca/contrib/modules/binding-corba-runtime/META-INF/MANIFEST.MF b/java/sca/contrib/modules/binding-corba-runtime/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..45b1f17ec6 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/META-INF/MANIFEST.MF @@ -0,0 +1,64 @@ +Manifest-Version: 1.0 +Export-Package: org.apache.tuscany.sca.binding.corba.provider.service; + uses:="org.apache.tuscany.sca.runtime,org.apache.tuscany.sca.binding. + corba.provider.exceptions,org.omg.CORBA,org.omg.CORBA.portable,org.ap + ache.tuscany.sca.interfacedef,org.apache.tuscany.sca.binding.corba.pr + ovider.types";version="2.0.0",org.apache.tuscany.sca.binding.corba.prov + ider;uses:="org.apache.tuscany.sca.runtime,org.apache.tuscany.sca.ass + embly,org.apache.tuscany.sca.provider,org.apache.tuscany.sca.binding. + corba.provider.exceptions,org.omg.CORBA,org.apache.tuscany.sca.core,o + rg.apache.tuscany.sca.interfacedef.java,org.apache.tuscany.sca.bindin + g.corba,org.apache.tuscany.sca.interfacedef,org.apache.tuscany.sca.bi + nding.corba.provider.reference,org.apache.tuscany.sca.invocation,org. + apache.tuscany.sca.binding.corba.provider.service,org.apache.tuscany. + sca.host.corba,org.oasisopen.sca";version="2.0.0",org.apache.tuscany.sca.bin + ding.corba.provider.exceptions;version="2.0.0",org.apache.tuscany.sca.b + inding.corba.provider.types;uses:="org.apache.tuscany.sca.binding.cor + ba.provider.exceptions";version="2.0.0",org.apache.tuscany.sca.binding. + corba.provider.reference;uses:="net.sf.cglib.proxy,org.apache.tuscany + .sca.binding.corba.provider.exceptions,org.omg.CORBA,org.apache.tusca + ny.sca.binding.corba.provider.types,org.omg.CORBA.portable";version=" + 1.4" +Private-Package: org.apache.tuscany.sca.binding.corba.provider.meta;ve + rsion="1.4",org.apache.tuscany.sca.binding.corba.provider.types.util; + version="2.0.0",org.apache.tuscany.sca.binding.corba.provider.util;vers + ion="1.4" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA CORBA Binding Runtime +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397143078 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA CORBA Binding Runtime +Import-Package: javax.xml.namespace;resolution:=optional, + + net.sf.cglib.proxy, + org.apache.tuscany.sca.assembly;version="2.0.0", + org.apache.tuscany.sca.binding.corba;version="2.0.0", + org.apache.tuscany.sca.binding.corba.provider;version="2.0.0", + org.apache.tuscany.sca.binding.corba.provider.exceptions;version="2.0.0", + org.apache.tuscany.sca.binding.corba.provider.meta;resolution:=optional, + org.apache.tuscany.sca.binding.corba.provider.reference;version="2.0.0", + org.apache.tuscany.sca.binding.corba.provider.service;version="2.0.0", + org.apache.tuscany.sca.binding.corba.provider.types;version="2.0.0", + org.apache.tuscany.sca.binding.corba.provider.types.util;resolution:=optional, + org.apache.tuscany.sca.binding.corba.provider.util;resolution:=optional, + org.apache.tuscany.sca.core;version="2.0.0", + org.apache.tuscany.sca.host.corba;version="2.0.0", + org.apache.tuscany.sca.interfacedef;version="2.0.0", + org.apache.tuscany.sca.interfacedef.java;version="2.0.0", + org.apache.tuscany.sca.interfacedef.util;version="2.0.0";resolution:=optional, + org.apache.tuscany.sca.invocation;version="2.0.0", + org.apache.tuscany.sca.policy;version="2.0.0";resolution:=optional, + org.apache.tuscany.sca.provider;version="2.0.0", + org.apache.tuscany.sca.runtime;version="2.0.0", + + org.omg.CORBA, + org.omg.CORBA.portable, + org.omg.CosNaming;resolution:=optional, + org.oasisopen.sca;version="2.0.0" +Bundle-SymbolicName: org.apache.tuscany.sca.binding.corba.runtime +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/binding-corba-runtime/NOTICE b/java/sca/contrib/modules/binding-corba-runtime/NOTICE new file mode 100644 index 0000000000..51042eab05 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/binding-corba-runtime/pom.xml b/java/sca/contrib/modules/binding-corba-runtime/pom.xml new file mode 100644 index 0000000000..77b1a02b55 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/pom.xml @@ -0,0 +1,130 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + tuscany-binding-corba-runtime + Apache Tuscany SCA CORBA Binding Runtime + + + + org.apache.tuscany.sca + tuscany-interface-java + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-binding-corba + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-host-corba + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-host-corba-jse + 2.0-SNAPSHOT + test + + + + cglib + cglib-nodep + 2.2 + compile + + + + + + + + + + + + diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/CorbaBindingProviderFactory.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/CorbaBindingProviderFactory.java new file mode 100644 index 0000000000..aa1669045b --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/CorbaBindingProviderFactory.java @@ -0,0 +1,70 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.provider; + +import org.apache.tuscany.sca.binding.corba.CorbaBinding; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.host.corba.CorbaHostExtensionPoint; +import org.apache.tuscany.sca.host.corba.ExtensibleCorbaHost; +import org.apache.tuscany.sca.provider.BindingProviderFactory; +import org.apache.tuscany.sca.provider.ReferenceBindingProvider; +import org.apache.tuscany.sca.provider.ServiceBindingProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; + +/** + * @version $Rev$ $Date$ + */ +public class CorbaBindingProviderFactory implements BindingProviderFactory { + + private CorbaHostExtensionPoint chep; + private ExtensibleCorbaHost host; + + public CorbaBindingProviderFactory(ExtensionPointRegistry registry) { + chep = registry.getExtensionPoint(CorbaHostExtensionPoint.class); + host = new ExtensibleCorbaHost(chep); + } + /** + * @see org.apache.tuscany.sca.provider.BindingProviderFactory#createReferenceBindingProvider(org.apache.tuscany.sca.runtime.RuntimeComponent, org.apache.tuscany.sca.runtime.RuntimeComponentReference, org.apache.tuscany.sca.assembly.Binding) + */ + public ReferenceBindingProvider createReferenceBindingProvider(RuntimeComponent component, + RuntimeComponentReference reference, + CorbaBinding binding) { + return new CorbaReferenceBindingProvider(binding, host, reference); + } + + /** + * @see org.apache.tuscany.sca.provider.BindingProviderFactory#createServiceBindingProvider(org.apache.tuscany.sca.runtime.RuntimeComponent, org.apache.tuscany.sca.runtime.RuntimeComponentService, org.apache.tuscany.sca.assembly.Binding) + */ + public ServiceBindingProvider createServiceBindingProvider(RuntimeComponent component, + RuntimeComponentService service, + CorbaBinding binding) { + return new CorbaServiceBindingProvider(binding, host, service); + } + + /** + * @see org.apache.tuscany.sca.provider.ProviderFactory#getModelType() + */ + public Class getModelType() { + return CorbaBinding.class; + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/CorbaInvoker.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/CorbaInvoker.java new file mode 100644 index 0000000000..0ad3b2240e --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/CorbaInvoker.java @@ -0,0 +1,89 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.provider; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.util.Map; + +import org.apache.tuscany.sca.binding.corba.provider.exceptions.RequestConfigurationException; +import org.apache.tuscany.sca.binding.corba.provider.reference.DynaCorbaRequest; +import org.apache.tuscany.sca.binding.corba.provider.reference.DynaCorbaResponse; +import org.apache.tuscany.sca.binding.corba.provider.util.OperationMapper; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.omg.CORBA.Object; +import org.oasisopen.sca.ServiceRuntimeException; + +/** + * @version $Rev$ $Date$ + */ +public class CorbaInvoker implements Invoker { + + private Object remoteObject; + private Class referenceClass; + private Map operationsMap; + private Map operationMethodMapping; + + public CorbaInvoker(RuntimeComponentReference reference, Object remoteObject, Class referenceClass, Map operationsMap) { + this.remoteObject = remoteObject; + this.referenceClass = referenceClass; + this.operationsMap = operationsMap; + this.operationMethodMapping = OperationMapper.mapOperationToMethod(reference.getInterfaceContract().getInterface().getOperations(), referenceClass); + } + + /** + * @see org.apache.tuscany.sca.invocation.Invoker#invoke(org.apache.tuscany.sca.invocation.Message) + */ + public Message invoke(Message msg) { + try { + DynaCorbaRequest request = new DynaCorbaRequest(remoteObject, msg.getOperation().getName()); + request.setReferenceClass(referenceClass); + request.setOperationsMap(operationsMap); + if (msg.getOperation().getOutputType() != null) { + Annotation[] notes = operationMethodMapping.get(msg.getOperation()).getAnnotations(); + request.setOutputType(msg.getOperation().getOutputType().getPhysical(), notes); + } + java.lang.Object[] args = msg.getBody(); + if (args != null) { + Annotation[][] notes = operationMethodMapping.get(msg.getOperation()).getParameterAnnotations(); + for (int i = 0; i < args.length; i++) { + request.addArgument(args[i], notes[i]); + } + } + if (msg.getOperation().getFaultTypes() != null) { + for (DataType type : msg.getOperation().getFaultTypes()) { + request.addExceptionType(type.getPhysical()); + } + } + DynaCorbaResponse response = request.invoke(); + msg.setBody(response.getContent()); + } catch (RequestConfigurationException e) { + throw new ServiceRuntimeException(e); + } catch (Exception e) { + msg.setFaultBody(e); + } + return msg; + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/CorbaReferenceBindingProvider.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/CorbaReferenceBindingProvider.java new file mode 100644 index 0000000000..e177e1912f --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/CorbaReferenceBindingProvider.java @@ -0,0 +1,100 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.provider; + +import java.lang.reflect.Method; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.apache.tuscany.sca.binding.corba.CorbaBinding; +import org.apache.tuscany.sca.binding.corba.provider.util.OperationMapper; +import org.apache.tuscany.sca.host.corba.CorbaHost; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.interfacedef.java.JavaInterface; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.provider.ReferenceBindingProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.omg.CORBA.Object; + +/** + * @version $Rev$ $Date$ + */ +public class CorbaReferenceBindingProvider implements ReferenceBindingProvider { + + private static final Logger logger = Logger.getLogger(CorbaReferenceBindingProvider.class.getName()); + private CorbaBinding binding; + private CorbaHost host; + private RuntimeComponentReference reference; + private Object remoteObject; + private Class referenceClass; + private Map operationsMap = null; + + public CorbaReferenceBindingProvider(CorbaBinding binding, CorbaHost host, RuntimeComponentReference reference) { + this.binding = binding; + this.host = host; + this.reference = reference; + this.referenceClass = ((JavaInterface)reference.getInterfaceContract().getInterface()).getJavaClass(); + operationsMap = OperationMapper.mapMethodToOperationName(referenceClass); + } + + /** + * @see org.apache.tuscany.sca.provider.ReferenceBindingProvider#createInvoker(org.apache.tuscany.sca.interfacedef.Operation) + */ + public Invoker createInvoker(Operation operation) { + try { + if (remoteObject == null) { + remoteObject = host.lookup(binding.getCorbaname()); + } + return new CorbaInvoker(reference, remoteObject, referenceClass, operationsMap); + } catch (Exception e) { + logger.log(Level.WARNING, "Exception during creating CORBA invoker", e); + } + return null; + } + + /** + * @see org.apache.tuscany.sca.provider.ReferenceBindingProvider#getBindingInterfaceContract() + */ + public InterfaceContract getBindingInterfaceContract() { + return reference.getInterfaceContract(); + } + + /** + * @see org.apache.tuscany.sca.provider.ReferenceBindingProvider#start() + */ + public void start() { + } + + /** + * @see org.apache.tuscany.sca.provider.ReferenceBindingProvider#stop() + */ + public void stop() { + } + + /** + * @see org.apache.tuscany.sca.provider.ReferenceBindingProvider#supportsOneWayInvocation() + */ + public boolean supportsOneWayInvocation() { + return false; + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/CorbaServiceBindingProvider.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/CorbaServiceBindingProvider.java new file mode 100644 index 0000000000..a574c52703 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/CorbaServiceBindingProvider.java @@ -0,0 +1,92 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.provider; + +import org.apache.tuscany.sca.binding.corba.CorbaBinding; +import org.apache.tuscany.sca.binding.corba.provider.service.ComponentInvocationProxy; +import org.apache.tuscany.sca.binding.corba.provider.service.DynaCorbaServant; +import org.apache.tuscany.sca.binding.corba.provider.service.InvocationProxy; +import org.apache.tuscany.sca.binding.corba.provider.types.util.Utils; +import org.apache.tuscany.sca.host.corba.CorbaHost; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.interfacedef.java.JavaInterface; +import org.apache.tuscany.sca.provider.ServiceBindingProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; +import org.oasisopen.sca.ServiceRuntimeException; + +/** + * @version $Rev$ $Date$ + */ +public class CorbaServiceBindingProvider implements ServiceBindingProvider { + + private CorbaBinding binding; + private CorbaHost host; + private RuntimeComponentService service; + private DynaCorbaServant servant; + + public CorbaServiceBindingProvider(CorbaBinding binding, CorbaHost host, RuntimeComponentService service) { + this.binding = binding; + this.host = host; + this.service = service; + } + + /** + * @see org.apache.tuscany.sca.provider.ServiceBindingProvider#getBindingInterfaceContract() + */ + public InterfaceContract getBindingInterfaceContract() { + return service.getInterfaceContract(); + } + + /** + * @see org.apache.tuscany.sca.provider.ServiceBindingProvider#start() + */ + public void start() { + try { + Class javaClass = ((JavaInterface)service.getInterfaceContract().getInterface()).getJavaClass(); + InvocationProxy proxy = new ComponentInvocationProxy(service, service.getRuntimeWire(binding), javaClass); + servant = new DynaCorbaServant(proxy, Utils.getTypeId(javaClass)); + servant.setIds(new String[] {binding.getId()}); + host.registerServant(binding.getCorbaname(), servant); + } catch (Exception e) { + throw new ServiceRuntimeException(e); + } + + } + + /** + * @see org.apache.tuscany.sca.provider.ServiceBindingProvider#stop() + */ + public void stop() { + try { + host.unregisterServant(binding.getCorbaname()); + } catch (Exception e) { + throw new ServiceRuntimeException(e); + } + + } + + /** + * @see org.apache.tuscany.sca.provider.ServiceBindingProvider#supportsOneWayInvocation() + */ + public boolean supportsOneWayInvocation() { + return false; + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/exceptions/CorbaException.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/exceptions/CorbaException.java new file mode 100644 index 0000000000..b3569e43b9 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/exceptions/CorbaException.java @@ -0,0 +1,34 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.provider.exceptions; + +/** + * @version $Rev$ $Date$ + * Represents CORBA SystemException + */ +public class CorbaException extends Exception { + + private static final long serialVersionUID = 1L; + + public CorbaException(String message, Throwable cause) { + super(message, cause); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/exceptions/RequestConfigurationException.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/exceptions/RequestConfigurationException.java new file mode 100644 index 0000000000..a554f56035 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/exceptions/RequestConfigurationException.java @@ -0,0 +1,43 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.provider.exceptions; + +/** + * @version $Rev$ $Date$ + */ +public class RequestConfigurationException extends Exception { + + private static final long serialVersionUID = 1L; + private String objectId; + + public RequestConfigurationException(String message, String objectId) { + super(message + ", object id was: " + objectId); + this.objectId = objectId; + } + + public RequestConfigurationException(String message) { + super(message); + } + + public String getType() { + return objectId; + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/meta/CorbaArray.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/meta/CorbaArray.java new file mode 100644 index 0000000000..823db1e748 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/meta/CorbaArray.java @@ -0,0 +1,34 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.provider.meta; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +/** + * @version $Rev$ $Date$ + * Declares CORBA arrays lengths + */ +@Retention(RetentionPolicy.RUNTIME) +public @interface CorbaArray { + + int[] value(); + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/meta/CorbaUnionElement.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/meta/CorbaUnionElement.java new file mode 100644 index 0000000000..feb6627e25 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/meta/CorbaUnionElement.java @@ -0,0 +1,37 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.provider.meta; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +/** + * @version $Rev$ $Date$ Declares CORBA union object + */ +@Retention(RetentionPolicy.RUNTIME) +public @interface CorbaUnionElement { + + // number of option in switch clause + int optionNumber() default -1; + + // type of element + CorbaUnionElementType type(); + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/meta/CorbaUnionElementType.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/meta/CorbaUnionElementType.java new file mode 100644 index 0000000000..1e7a0087e0 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/meta/CorbaUnionElementType.java @@ -0,0 +1,28 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.provider.meta; + +/** + * @version $Rev$ $Date$ + * Types for union element + */ +public enum CorbaUnionElementType { + discriminator, defaultOption, option; +} \ No newline at end of file diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/reference/DynaCorbaRequest.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/reference/DynaCorbaRequest.java new file mode 100644 index 0000000000..e7d0b8b91b --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/reference/DynaCorbaRequest.java @@ -0,0 +1,253 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.provider.reference; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.tuscany.sca.binding.corba.provider.exceptions.CorbaException; +import org.apache.tuscany.sca.binding.corba.provider.exceptions.RequestConfigurationException; +import org.apache.tuscany.sca.binding.corba.provider.types.TypeTree; +import org.apache.tuscany.sca.binding.corba.provider.types.TypeTreeCreator; +import org.apache.tuscany.sca.binding.corba.provider.types.util.TypeHelpersProxy; +import org.apache.tuscany.sca.binding.corba.provider.types.util.Utils; +import org.apache.tuscany.sca.binding.corba.provider.util.MethodFinder; +import org.omg.CORBA.BAD_OPERATION; +import org.omg.CORBA.BAD_PARAM; +import org.omg.CORBA.Object; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.portable.ApplicationException; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.ObjectImpl; +import org.omg.CORBA.portable.OutputStream; + +/** + * @version $Rev$ $Date$ Represents single CORBA request + */ +public class DynaCorbaRequest { + + private TypeTree returnTree; + private Map exceptions = new HashMap(); + private InputStream inputStream; + private ObjectImpl remoteObject; + private String operation; + private List arguments = new ArrayList(); + private List argumentsTypes = new ArrayList(); + private Class referenceClass; + private Map operationsMap; + + /** + * Creates request. + * + * @param ObjectremoteObject remote object reference + * @param operation operation to invoke + * @param scaBindingRules apply SCA default binding mapping rules + */ + public DynaCorbaRequest(Object remoteObject, String operation) { + this.remoteObject = (ObjectImpl)remoteObject; + this.operation = operation; + } + + /** + * Sets class which will be backed by this reference request + * @param referenceClass + */ + public void setReferenceClass(Class referenceClass) { + this.referenceClass = referenceClass; + } + + /** + * Sets method to operation names mapping + * @param operationsMap + */ + public void setOperationsMap(Map operationsMap) { + this.operationsMap = operationsMap; + } + + /** + * Adds operation argument - stores arguments and caches its TypeTree. Annotations will be set to null by default. + * + * @param argument + */ + public void addArgument(java.lang.Object argument) throws RequestConfigurationException { + addArgument(argument, null); + } + + /** + * Adds operation argument - stores arguments and caches its TypeTree + * + * @param argument + */ + public void addArgument(java.lang.Object argument, Annotation[] notes) throws RequestConfigurationException { + TypeTree tree = TypeTreeCreator.createTypeTree(argument.getClass(), notes); + argumentsTypes.add(tree); + arguments.add(argument); + } + + /** + * Passing stored arguments to CORBA communication output stream + * + * @param outputStream + * @throws RequestConfigurationException + */ + private void passArguments(OutputStream outputStream) throws RequestConfigurationException { + for (int i = 0; i < arguments.size(); i++) { + TypeTree tree = argumentsTypes.get(i); + TypeHelpersProxy.write(tree.getRootNode(), outputStream, arguments.get(i)); + } + } + + /** + * Sets return type for operation. Annotations will be set to null by default. + * + * @param forClass + */ + public void setOutputType(Class forClass) throws RequestConfigurationException { + setOutputType(forClass, null); + } + + /** + * Sets return type for operation + * + * @param forClass + */ + public void setOutputType(Class forClass, Annotation[] notes) throws RequestConfigurationException { + returnTree = TypeTreeCreator.createTypeTree(forClass, notes); + } + + /** + * Configures possible exceptions + * + * @param forClass + */ + public void addExceptionType(Class forClass) throws RequestConfigurationException { + TypeTree tree = TypeTreeCreator.createTypeTree(forClass, null); + String exceptionId = Utils.getTypeId(forClass); + exceptions.put(exceptionId, tree); + } + + /** + * Handles application excpeition. + * + * @param ae occured exception + * @throws Exception + */ + private void handleApplicationException(ApplicationException ae) throws Exception { + try { + if (exceptions.size() == 0) { + RequestConfigurationException exception = + new RequestConfigurationException( + "ApplicationException occured, but no exception type was specified.", + ae.getId()); + throw exception; + } + InputStream is = ae.getInputStream(); + String exceptionId = is.read_string(); + TypeTree tree = exceptions.get(exceptionId); + if (tree == null) { + RequestConfigurationException exception = + new RequestConfigurationException( + "ApplicationException occured, but no such exception was defined", + ae.getId()); + throw exception; + } else { + Exception ex = (Exception)TypeHelpersProxy.read(tree.getRootNode(), is); + throw ex; + } + } catch (Exception e) { + throw e; + } + } + + /** + * Handles exceptions generated by CORBA API + * + * @param se + */ + private void handleSystemException(SystemException se) throws Exception { + if (se instanceof BAD_OPERATION) { + throw new CorbaException("Bad operation name: " + operation, se); + } else if (se instanceof BAD_PARAM) { + throw new CorbaException("Bad parameter", se); + } else { + // TODO: handle more system exception types + throw new CorbaException(se.getMessage(), se); + } + } + + /** + * Gets operation name which is includes mapping rules + * @return + */ + private String getFinalOperationName() { + String result = operation; + if (referenceClass != null) { + Class[] argumentTypes = new Class[arguments.size()]; + for (int i = 0; i < arguments.size(); i++) { + argumentTypes[i] = arguments.get(i).getClass(); + } + Method method = MethodFinder.findMethod(referenceClass, operation, argumentTypes); + String newOperation = (String)operationsMap.get(method); + if (newOperation != null) { + result = newOperation; + } + } + return result; + } + + /** + * Invokes previously configured request + * + * @return + */ + public DynaCorbaResponse invoke() throws Exception { + DynaCorbaResponse response = new DynaCorbaResponse(); + String finalOperationName = getFinalOperationName(); + OutputStream outputStream = ((ObjectImpl)remoteObject)._request(finalOperationName, true); + passArguments(outputStream); + try { + inputStream = remoteObject._invoke(outputStream); + if (inputStream != null && returnTree != null) { + response.setContent(TypeHelpersProxy.read(returnTree.getRootNode(), inputStream)); + } + } catch (ApplicationException ae) { + handleApplicationException(ae); + } catch (SystemException se) { + handleSystemException(se); + } catch (Exception e) { + throw e; + } finally { + release(); + } + return response; + } + + /** + * Releases request resources + */ + private void release() { + remoteObject._releaseReply(inputStream); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/reference/DynaCorbaResponse.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/reference/DynaCorbaResponse.java new file mode 100644 index 0000000000..6a01c70a38 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/reference/DynaCorbaResponse.java @@ -0,0 +1,39 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.provider.reference; + +/** + * @version $Rev$ $Date$ + * Holder for content returned from DynaCorbaRequest + * + */ +public class DynaCorbaResponse { + + private Object content; + + public Object getContent() { + return content; + } + + public void setContent(Object content) { + this.content = content; + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/reference/InterfaceInstanceCreator.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/reference/InterfaceInstanceCreator.java new file mode 100644 index 0000000000..2828e09cc7 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/reference/InterfaceInstanceCreator.java @@ -0,0 +1,70 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.provider.reference; + +import java.lang.reflect.Method; + +import net.sf.cglib.proxy.Callback; +import net.sf.cglib.proxy.CallbackFilter; +import net.sf.cglib.proxy.Enhancer; +import net.sf.cglib.proxy.MethodInterceptor; +import net.sf.cglib.proxy.NoOp; + +import org.omg.CORBA.Object; + +/** + * @version $Rev$ $Date$ + */ +public class InterfaceInstanceCreator { + + private static final CallbackFilter FILTER = new CallbackFilter() { + public int accept(Method method) { + return 1; + } + }; + + /** + * Dynamically creates instance of user defined interface. Instance is + * enhanced by RemoteMethodInterceptor + * + * @param reference + * CORBA reference + * @param forClass + * user defined interface + * @return dynamic implementation instance + */ + public static java.lang.Object createInstance(Object reference, Class forClass) { + java.lang.Object result = null; + try { + Enhancer enhancer = new Enhancer(); + enhancer.setInterfaces(new Class[] {forClass}); + enhancer.setCallbackFilter(FILTER); + enhancer.setCallbackTypes(new Class[] {NoOp.class, MethodInterceptor.class}); + Class newClass = enhancer.createClass(); + Enhancer.registerStaticCallbacks(newClass, new Callback[] {NoOp.INSTANCE, + new InterfaceMethodInterceptor(reference, forClass)}); + result = newClass.newInstance(); + } catch (Exception e) { + e.printStackTrace(); + } + return result; + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/reference/InterfaceMethodInterceptor.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/reference/InterfaceMethodInterceptor.java new file mode 100644 index 0000000000..c5c98ab27c --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/reference/InterfaceMethodInterceptor.java @@ -0,0 +1,65 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.provider.reference; + +import java.lang.reflect.Method; + +import net.sf.cglib.proxy.MethodInterceptor; +import net.sf.cglib.proxy.MethodProxy; + +import org.omg.CORBA.Object; + +/** + * @version $Rev$ $Date$ + * Interceptor for CORBA reference methods + */ +public class InterfaceMethodInterceptor implements MethodInterceptor { + + private Object reference; + private Class javaClass; + + public InterfaceMethodInterceptor(Object reference, Class javaClass) { + this.reference = reference; + this.javaClass = javaClass; + } + + /** + * Create and execute DynaCorbaRequest instance, basing on intercepted + * method arguments, return types, exceptions + */ + public java.lang.Object intercept(java.lang.Object object, + Method method, + java.lang.Object[] arguments, + MethodProxy arg3) throws Throwable { + DynaCorbaRequest request = new DynaCorbaRequest(reference, method.getName()); + request.setReferenceClass(javaClass); + for (int i = 0; i < arguments.length; i++) { + request.addArgument(arguments[i]); + } + request.setOutputType(method.getReturnType()); + Class[] exceptions = method.getExceptionTypes(); + for (int i = 0; i < exceptions.length; i++) { + request.addExceptionType(exceptions[i]); + } + DynaCorbaResponse response = request.invoke(); + return response.getContent(); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/service/ComponentInvocationProxy.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/service/ComponentInvocationProxy.java new file mode 100644 index 0000000000..b88c097008 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/service/ComponentInvocationProxy.java @@ -0,0 +1,120 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.provider.service; + +import java.lang.annotation.Annotation; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.tuscany.sca.binding.corba.provider.exceptions.RequestConfigurationException; +import org.apache.tuscany.sca.binding.corba.provider.types.TypeTree; +import org.apache.tuscany.sca.binding.corba.provider.types.TypeTreeCreator; +import org.apache.tuscany.sca.binding.corba.provider.util.OperationMapper; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; +import org.apache.tuscany.sca.runtime.RuntimeWire; + +/** + * @version $Rev$ $Date$ + * Invocation proxy for SCA components + */ +public class ComponentInvocationProxy implements InvocationProxy { + + private RuntimeWire wire; + private Map methodOperationMapping; + private Map operationMethodMapping; + private Map operationsMap; + private Map operationsCache = new HashMap(); + + public ComponentInvocationProxy(RuntimeComponentService service, RuntimeWire wire, Class javaClass) + throws RequestConfigurationException { + this.wire = wire; + operationsMap = OperationMapper.mapOperationNameToMethod(javaClass); + operationMethodMapping = OperationMapper.mapOperationToMethod(service.getInterfaceContract().getInterface().getOperations(), javaClass); + methodOperationMapping = OperationMapper.mapMethodToOperation(service.getInterfaceContract().getInterface().getOperations(), javaClass); + cacheOperationTypes(service.getInterfaceContract().getInterface().getOperations()); + } + + /** + * Caches TypeTree for every operation in backed component + * + * @param operations + * @throws RequestConfigurationException + */ + private void cacheOperationTypes(List operations) throws RequestConfigurationException { + for (Operation operation : operations) { + try { + OperationTypes operationTypes = new OperationTypes(); + List inputInstances = new ArrayList(); + // cache output type tree + if (operation.getOutputType() != null && operation.getOutputType().getPhysical() != null + && !operation.getOutputType().getPhysical().equals(void.class)) { + Annotation[] notes = operationMethodMapping.get(operation).getAnnotations(); + TypeTree outputType = + TypeTreeCreator.createTypeTree(operation.getOutputType().getPhysical(), notes); + operationTypes.setOutputType(outputType); + } + // cache input types trees + if (operation.getInputType() != null) { + Method method = operationMethodMapping.get(operation); + Annotation[][] notes = method.getParameterAnnotations(); + int i = 0; + for (DataType>> type : operation.getInputType().getLogical()) { + Class forClass = type.getPhysical(); + TypeTree inputType = TypeTreeCreator.createTypeTree(forClass, notes[i]); + inputInstances.add(inputType); + i++; + } + + } + operationTypes.setInputType(inputInstances); + operationsCache.put(operation, operationTypes); + } catch (RequestConfigurationException e) { + throw e; + } + } + } + + private Operation getOperation4Name(String operationName) { + Method method = operationsMap.get(operationName); + return methodOperationMapping.get(method); + } + + public OperationTypes getOperationTypes(String operationName) { + return operationsCache.get(getOperation4Name(operationName)); + } + + public Object invoke(String operationName, List arguments) throws InvocationException { + Object result = null; + try { + result = wire.invoke(getOperation4Name(operationName), arguments.toArray()); + } catch (InvocationTargetException e) { + InvocationException exception = new InvocationException(e.getCause()); + throw exception; + } + return result; + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/service/DynaCorbaServant.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/service/DynaCorbaServant.java new file mode 100644 index 0000000000..d8524eaee9 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/service/DynaCorbaServant.java @@ -0,0 +1,137 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.provider.service; + +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.apache.tuscany.sca.binding.corba.provider.exceptions.RequestConfigurationException; +import org.apache.tuscany.sca.binding.corba.provider.types.TypeTree; +import org.apache.tuscany.sca.binding.corba.provider.types.TypeTreeCreator; +import org.apache.tuscany.sca.binding.corba.provider.types.util.TypeHelpersProxy; +import org.apache.tuscany.sca.binding.corba.provider.types.util.Utils; +import org.omg.CORBA.MARSHAL; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.InvokeHandler; +import org.omg.CORBA.portable.ObjectImpl; +import org.omg.CORBA.portable.OutputStream; +import org.omg.CORBA.portable.ResponseHandler; + +/** + * @version $Rev$ $Date$ + * General servant which provides target component implementation via CORBA + */ +public class DynaCorbaServant extends ObjectImpl implements InvokeHandler { + + private static final Logger logger = Logger.getLogger(DynaCorbaServant.class.getName()); + + private String[] ids; + private InvocationProxy invocationProxy; + private String typeId; + + /** + * Creates servant object + * @param invocationProxy + * @param typeId + * @throws RequestConfigurationException + */ + public DynaCorbaServant(InvocationProxy invocationProxy, String typeId) throws RequestConfigurationException { + this.invocationProxy = invocationProxy; + this.typeId = typeId; + setDefaultIds(); + } + + /** + * Sets CORBA object ID + * @param ids + */ + public void setIds(String[] ids) { + for (int i = 0; i < ids.length; i++) { + if (ids[i] == null || ids[i].length() == 0) { + // if invalid id was passed then set to default + setDefaultIds(); + return; + } + } + this.ids = ids; + } + + public OutputStream _invoke(String operationName, InputStream in, ResponseHandler rh) { + OperationTypes types = invocationProxy.getOperationTypes(operationName); + if (types == null) { + // operation wasn't found + throw new org.omg.CORBA.BAD_OPERATION(0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE); + } else { + List inputInstances = new ArrayList(); + try { + // retrieving in arguments + for (TypeTree tree : types.getInputType()) { + Object o = TypeHelpersProxy.read(tree.getRootNode(), in); + inputInstances.add(o); + } + } catch (MARSHAL e) { + // parameter passed by user was not compatible with Java to + // Corba mapping + throw new org.omg.CORBA.BAD_PARAM(0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE); + } + try { + // invocation and sending result + Object result = invocationProxy.invoke(operationName, inputInstances); + OutputStream out = rh.createReply(); + if (types.getOutputType() != null) { + TypeTree tree = types.getOutputType(); + TypeHelpersProxy.write(tree.getRootNode(), out, result); + } + return out; + } catch (InvocationException ie) { + // handling user exception + try { + OutputStream out = rh.createExceptionReply(); + Class exceptionClass = ie.getTargetException().getClass(); + TypeTree tree = TypeTreeCreator.createTypeTree(exceptionClass, null); + String exceptionId = Utils.getTypeId(exceptionClass); + out.write_string(exceptionId); + TypeHelpersProxy.write(tree.getRootNode(), out, ie.getTargetException()); + return out; + } catch (Exception e) { + logger.log(Level.WARNING, "Exception during handling invocation exception", e); + } + } catch (Exception e) { + logger.log(Level.WARNING, "Unexpected exception during sending CORBA result to client", e); + } + } + return null; + } + + @Override + public String[] _ids() { + return ids; + } + + /** + * Sets servant ID to default, based on Java class name + */ + private void setDefaultIds() { + this.ids = new String[] {typeId}; + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/service/InvocationException.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/service/InvocationException.java new file mode 100644 index 0000000000..57e2fae9f4 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/service/InvocationException.java @@ -0,0 +1,43 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.provider.service; + +/** + * @version $Rev$ $Date$ + * Wrapper for exception thrown during target invocation + */ +public class InvocationException extends Exception { + + private static final long serialVersionUID = 1L; + private Throwable targetException; + + public InvocationException(Throwable targetException) { + this.targetException = targetException; + } + + public Throwable getTargetException() { + return targetException; + } + + public void setTargetException(Throwable target) { + this.targetException = target; + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/service/InvocationProxy.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/service/InvocationProxy.java new file mode 100644 index 0000000000..2e2066802a --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/service/InvocationProxy.java @@ -0,0 +1,46 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.provider.service; + +import java.util.List; + +/** + * @version $Rev$ $Date$ + * Target proxy interface for service bindings + */ +public interface InvocationProxy { + + /** + * Gets operations types for target + * @param operationName + * @return + */ + public OperationTypes getOperationTypes(String operationName); + + /** + * Invokes target operation + * @param operationName + * @param arguments + * @return + * @throws InvocationException + */ + public Object invoke(String operationName, List arguments) throws InvocationException; + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/service/OperationTypes.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/service/OperationTypes.java new file mode 100644 index 0000000000..766048ac64 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/service/OperationTypes.java @@ -0,0 +1,51 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.provider.service; + +import java.util.List; + +import org.apache.tuscany.sca.binding.corba.provider.types.TypeTree; + +/** + * @version $Rev$ $Date$ + * Holder for Java type trees for one method + */ +public class OperationTypes { + + private TypeTree outputType; + private List inputType; + + public TypeTree getOutputType() { + return outputType; + } + + public void setOutputType(TypeTree outputType) { + this.outputType = outputType; + } + + public List getInputType() { + return inputType; + } + + public void setInputType(List inputType) { + this.inputType = inputType; + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/AnnotationAttributes.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/AnnotationAttributes.java new file mode 100644 index 0000000000..ab7371bbe8 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/AnnotationAttributes.java @@ -0,0 +1,46 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.provider.types; + +/** + * Holds information retrieved from objects annotations + */ +public class AnnotationAttributes { + + private boolean corbaArray; + private int[] corbaArrayLength; + + public boolean isCorbaArray() { + return corbaArray; + } + + public void setCorbaArray(boolean isCorbaArray) { + this.corbaArray = isCorbaArray; + } + + public int[] getCorbaArrayLength() { + return corbaArrayLength; + } + + public void setCorbaArrayLength(int[] corbaArrayLength) { + this.corbaArrayLength = corbaArrayLength; + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/NodeType.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/NodeType.java new file mode 100644 index 0000000000..706a44406b --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/NodeType.java @@ -0,0 +1,28 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.provider.types; + +/** + * @version $Rev$ $Date$ + * Types of CORBA objects. + */ +public enum NodeType { + primitive, struct, union, array, sequence, reference, idl_enum, exception +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/TypeTree.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/TypeTree.java new file mode 100644 index 0000000000..d4207ab735 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/TypeTree.java @@ -0,0 +1,50 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.provider.types; + +/** + * @version $Rev$ $Date$ + * Helper tree for Java object hierarchy. It's closer to CORBA types + * structure than plain Java hierarchy - it helps reading and writing + * complex structures. + */ +public class TypeTree { + + private TypeTreeNode rootNode; + + /** + * Returns root node. + * + * @return root of type tree + */ + public TypeTreeNode getRootNode() { + return rootNode; + } + + /** + * Sets root of the type tree. + * + * @param rootNode root node. + */ + public void setRootNode(TypeTreeNode rootNode) { + this.rootNode = rootNode; + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/TypeTreeCreator.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/TypeTreeCreator.java new file mode 100644 index 0000000000..1ba4002303 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/TypeTreeCreator.java @@ -0,0 +1,497 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.provider.types; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.apache.tuscany.sca.binding.corba.provider.exceptions.RequestConfigurationException; +import org.apache.tuscany.sca.binding.corba.provider.meta.CorbaArray; +import org.apache.tuscany.sca.binding.corba.provider.meta.CorbaUnionElement; +import org.apache.tuscany.sca.binding.corba.provider.meta.CorbaUnionElementType; + +/** + * @version $Rev$ $Date$ + * Creator of types tree. + */ +public class TypeTreeCreator { + + /** + * Helps to determine if type is a primitive. + */ + private static List> primitives = new ArrayList>(); + + static { + primitives.add(boolean.class); + primitives.add(byte.class); + primitives.add(short.class); + primitives.add(int.class); + primitives.add(long.class); + primitives.add(double.class); + primitives.add(float.class); + primitives.add(char.class); + primitives.add(String.class); + primitives.add(Boolean.class); + primitives.add(Byte.class); + primitives.add(Short.class); + primitives.add(Integer.class); + primitives.add(Long.class); + primitives.add(Double.class); + primitives.add(Float.class); + primitives.add(Character.class); + } + + /** + * Creates class for given string argument. + * + * @param name name of type + * @return type + */ + private static Class createClassFromString(String name) { + Class result = null; + try { + if (name.length() == 1) { + // primitives + switch (name.charAt(0)) { + case 'Z': + result = boolean.class; + break; + case 'C': + result = char.class; + break; + case 'B': + result = byte.class; + break; + case 'S': + result = short.class; + break; + case 'I': + result = int.class; + break; + case 'J': + result = long.class; + break; + case 'F': + result = float.class; + break; + case 'D': + result = double.class; + break; + } + } else { + // class + name = name.substring(1, name.length() - 1); + result = Class.forName(name); + } + } catch (Exception e) { + e.printStackTrace(); + } + return result; + } + + /** + * Reduces dimension of array. + * + * @param forClass array class + * @return reduced array + */ + private static Class reduceArrayDimension(Class forClass) { + String name = forClass.getName(); + try { + String reduced = name.substring(1, name.length()); + if (reduced.startsWith("[")) { + // reduced class is still an array + return Class.forName(reduced); + } else { + // reduced class may be primitive or class + return createClassFromString(reduced); + } + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + return null; + } + + /** + * Return given array without first element + * + * @param array + * @return + */ + private static int[] removeFirstElement(int[] array) { + int[] result = new int[array.length - 1]; + System.arraycopy(array, 1, result, 0, result.length); + return result; + } + + /** + * Converts objects annotations to structure which will be used by this + * class + * + * @param notes + * @return + */ + private static AnnotationAttributes createAnnotationAttributes(Annotation[] notes) { + AnnotationAttributes attrs = new AnnotationAttributes(); + for (int i = 0; notes != null && i < notes.length; i++) { + if (notes[i].annotationType().equals(CorbaArray.class)) { + attrs.setCorbaArray(true); + attrs.setCorbaArrayLength(((CorbaArray)notes[i]).value()); + } + } + return attrs; + } + + /** + * Creates tree for given type. + * + * @param forClass + * @return type tree + */ + public static TypeTree createTypeTree(Class forClass, Annotation[] notes) throws RequestConfigurationException { + TypeTree tree = new TypeTree(); + TypeTreeNode rootNode = null; + AnnotationAttributes attrs = createAnnotationAttributes(notes); + rootNode = inspectClassHierarchy(forClass, attrs, tree); + tree.setRootNode(rootNode); + return tree; + + } + + /** + * Recurrent method which builds type tree. + * + * @param forClass + * @param tree + * @return + */ + private static TypeTreeNode inspectClassHierarchy(Class forClass, AnnotationAttributes attributes, TypeTree tree) + throws RequestConfigurationException { + + TypeTreeNode node = null; + node = createTypeNode(forClass, attributes); + + NodeType nodeType = node.getNodeType(); + TypeTreeNode[] children = null; + + if (nodeType.equals(NodeType.primitive)) { + // stop condition for recurrent method + } else if (nodeType.equals(NodeType.array)) { + Class reduced = reduceArrayDimension(node.getJavaClass()); + children = new TypeTreeNode[1]; + int[] newLengths = removeFirstElement(attributes.getCorbaArrayLength()); + attributes.setCorbaArrayLength(newLengths); + children[0] = inspectClassHierarchy(reduced, attributes, tree); + } else if (nodeType.equals(NodeType.sequence)) { + // reducing sequence dimension + Class reduced = reduceArrayDimension(node.getJavaClass()); + children = new TypeTreeNode[1]; + children[0] = inspectClassHierarchy(reduced, attributes, tree); + // System.arraycopy(src, srcPos, dest, destPos, length) + } else if (nodeType.equals(NodeType.struct) || nodeType.equals(NodeType.exception)) { + // inspect types for every structure member + Field[] fields = node.getJavaClass().getFields(); + children = new TypeTreeNode[fields.length]; + for (int i = 0; i < fields.length; i++) { + Class field = fields[i].getType(); + AnnotationAttributes fAttrs = createAnnotationAttributes(fields[i].getAnnotations()); + TypeTreeNode child = inspectClassHierarchy(field, fAttrs, tree); + child.setName(fields[i].getName()); + children[i] = child; + } + } else if (nodeType.equals(NodeType.idl_enum)) { + + } else if (nodeType.equals(NodeType.union)) { + // inspect types for every structure member + Field[] fields = node.getJavaClass().getDeclaredFields(); + children = new TypeTreeNode[fields.length]; + for (int i = 0; i < fields.length; i++) { + Class field = fields[i].getType(); + AnnotationAttributes fAttrs = createAnnotationAttributes(fields[i].getAnnotations()); + TypeTreeNode child = inspectClassHierarchy(field, fAttrs, tree); + child.setName(fields[i].getName()); + children[i] = child; + } + } else if (nodeType.equals(NodeType.reference)) { + // TODO: CORBA references + } + + node.setChildren(children); + return node; + } + + /** + * Creating and configuring TypeTreeNode for given class. + * + * @param forClass class + * @return node + * @throws RequestConfigurationException + */ + private static TypeTreeNode createTypeNode(Class forClass, AnnotationAttributes attributes) + throws RequestConfigurationException { + TypeTreeNode node = new TypeTreeNode(); + if (forClass.isArray() && !attributes.isCorbaArray()) { + node.setNodeType(NodeType.sequence); + node.setJavaClass(forClass); + } else if (forClass.isArray() && attributes.isCorbaArray()) { + node.setNodeType(NodeType.array); + node.setJavaClass(forClass); + try { + // set the actual array size for further use by ArrayTypeHelper + node.setAttributes(attributes.getCorbaArrayLength()[0]); + } catch (ArrayIndexOutOfBoundsException e) { + RequestConfigurationException exc = + new RequestConfigurationException("Annotated array size doesn't match declared arrays size"); + throw exc; + } + } else if (primitives.contains(forClass)) { + node.setNodeType(NodeType.primitive); + node.setJavaClass(forClass); + node.setChildren(null); + } else if (forClass.isInterface()) { + node.setNodeType(NodeType.reference); + node.setJavaClass(forClass); + node.setChildren(null); + } else if (isStructType(forClass)) { + node.setNodeType(NodeType.struct); + node.setJavaClass(forClass); + } else if (isEnumType(forClass)) { + node.setNodeType(NodeType.idl_enum); + node.setJavaClass(forClass); + } else if (isUserException(forClass)) { + node.setNodeType(NodeType.exception); + node.setJavaClass(forClass); + } else if (isUnionType(forClass)) { + node.setNodeType(NodeType.union); + node.setJavaClass(forClass); + node.setAttributes(getUnionAttributes(forClass)); + } else { + RequestConfigurationException e = + new RequestConfigurationException("User defined type which cannot be handled: " + forClass + .getCanonicalName()); + throw e; + } + return node; + } + + /** + * Tells whether given class is structure + * + * @param forClass + * @return + */ + private static boolean isStructType(Class forClass) { + int classMods = forClass.getModifiers(); + if (!Modifier.isFinal(classMods)) { + return false; + } + boolean areCtorsValid = false; + Class[] fieldsTypes = null; + Constructor[] ctors = forClass.getConstructors(); + /* + * Do we have 2 ctors and one of them is null ctor? + */ + if (ctors.length != 2) { + return false; + } + for (int i = 0; i < ctors.length; i++) { + Class[] params = ctors[i].getParameterTypes(); + if (params.length == 0) { + areCtorsValid = true; + } else { + fieldsTypes = params; + } + } + if (!areCtorsValid) { + return false; + } + /* + * Are constructor args declared as class fields? + */ + Field[] fields = forClass.getFields(); + Set> fieldsSet = new HashSet>(Arrays.asList(fieldsTypes)); + for (int i = 0; i < fields.length && !fieldsSet.isEmpty(); i++) { + int mods = fields[i].getModifiers(); + if (Modifier.isPublic(mods) && !Modifier.isStatic(mods) && !Modifier.isFinal(mods)) { + fieldsSet.remove(fields[i].getType()); + } + + } + return fieldsSet.isEmpty(); + } + + /** + * Tells whether given class is enum + * + * @param forClass + * @return + */ + private static boolean isEnumType(Class forClass) { + boolean isValueMethod = false; + boolean isFromIntMethod = false; + /* + * enum type should have value and from_int methods + */ + try { + Method valueMet = forClass.getMethod("value", new Class[] {}); + int modValueMet = valueMet.getModifiers(); + if (valueMet.getReturnType().equals(int.class) && Modifier.isPublic(modValueMet)) { + isValueMethod = true; + } + Method fromIntMet = forClass.getMethod("from_int", new Class[] {int.class}); + int modFromIntMet = fromIntMet.getModifiers(); + if ((fromIntMet.getReturnType().equals(forClass) && Modifier.isPublic(modFromIntMet) && Modifier + .isStatic(modFromIntMet))) { + isFromIntMethod = true; + } + } catch (NoSuchMethodException e) { + } + if (!isFromIntMethod || !isValueMethod) { + return false; + } + /* + * enum type should also contain minimum one pair of fields: EnumType + * field and int _field + */ + int enumCount = 0; + Field[] fields = forClass.getFields(); + for (int i = 0; i < fields.length; i++) { + if (fields[i].getType().equals(forClass)) { + int modifiers = fields[i].getModifiers(); + if (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers) && Modifier.isFinal(modifiers)) { + try { + Field field = forClass.getField("_" + fields[i].getName()); + if (field.getType().equals(int.class)) { + enumCount++; + } + } catch (NoSuchFieldException e) { + } + + } + } + } + return enumCount > 0; + } + + /** + * Tells whether given class is CORBA user exception + * + * @param forClass + * @return + */ + private static boolean isUserException(Class forClass) { + do { + if (forClass.equals(Exception.class)) { + return true; + } else { + forClass = forClass.getSuperclass(); + } + } while (forClass != null && !forClass.equals(Object.class)); + return false; + } + + /** + * Tells whether given class is CORBA union. This method validates usage of + * unions annotations. + * + * @param forClass + * @return + * @throws RequestConfigurationException + */ + private static boolean isUnionType(Class forClass) throws RequestConfigurationException { + int classMods = forClass.getModifiers(); + if (!Modifier.isFinal(classMods)) { + return false; + } + boolean atLeastOneOption = false; + boolean discriminatorPresent = false; + for (int i = 0; i < forClass.getDeclaredFields().length; i++) { + CorbaUnionElement note = forClass.getDeclaredFields()[i].getAnnotation(CorbaUnionElement.class); + if (note != null) { + int fieldMod = forClass.getDeclaredFields()[i].getModifiers(); + if (Modifier.isPrivate(fieldMod) && !Modifier.isFinal(fieldMod) && !Modifier.isStatic(fieldMod)) { + if (note.type().equals(CorbaUnionElementType.discriminator)) { + if (discriminatorPresent) { + throw new RequestConfigurationException( + "More than one discriminators declared on: " + forClass); + } + discriminatorPresent = true; + } else { + atLeastOneOption = true; + } + } else { + throw new RequestConfigurationException( + "Annotated union field should be private, not final and no static on class: " + forClass); + } + } + } + if (atLeastOneOption && !discriminatorPresent) { + throw new RequestConfigurationException("No discriminator annotation found on: " + forClass); + } else if (!atLeastOneOption && discriminatorPresent) { + throw new RequestConfigurationException("No union option found on: " + forClass); + } else if (discriminatorPresent && atLeastOneOption) { + return true; + } else { + return false; + } + } + + /** + * Gets union attributes - discriminator field name, option fields etc. This + * method relies that previously scanned class is valid (method isUnionType) + * + * @param forClass + * @return + * @throws RequestConfigurationException + */ + private static UnionAttributes getUnionAttributes(Class forClass) throws RequestConfigurationException { + UnionAttributes attributes = new UnionAttributes(); + for (int i = 0; i < forClass.getDeclaredFields().length; i++) { + CorbaUnionElement note = forClass.getDeclaredFields()[i].getAnnotation(CorbaUnionElement.class); + if (note != null) { + if (note.type().equals(CorbaUnionElementType.discriminator)) { + attributes.setDiscriminatorName(forClass.getDeclaredFields()[i].getName()); + } else if (note.type().equals(CorbaUnionElementType.defaultOption)) { + attributes.setDefaultOptionName(forClass.getDeclaredFields()[i].getName()); + } else if (note.type().equals(CorbaUnionElementType.option)) { + if (attributes.getOptionsMapping().containsKey(note.optionNumber())) { + throw new RequestConfigurationException("In " + forClass + + ": field \"" + + forClass.getDeclaredFields()[i].getName() + + "\" uses already used option id: " + + note.optionNumber()); + } else { + attributes.getOptionsMapping().put(note.optionNumber(), + forClass.getDeclaredFields()[i].getName()); + } + } + } + } + return attributes; + } +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/TypeTreeNode.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/TypeTreeNode.java new file mode 100644 index 0000000000..009eac3377 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/TypeTreeNode.java @@ -0,0 +1,75 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.provider.types; + +/** + * @version $Rev$ $Date$ + * Represents single tree node. + * + */ +public class TypeTreeNode { + + private NodeType nodeType; + private TypeTreeNode[] children; + private Class javaClass; + private String name; + private Object attributes; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public NodeType getNodeType() { + return nodeType; + } + + public void setNodeType(NodeType nodeType) { + this.nodeType = nodeType; + } + + public TypeTreeNode[] getChildren() { + return children; + } + + public void setChildren(TypeTreeNode[] children) { + this.children = children; + } + + public Class getJavaClass() { + return javaClass; + } + + public void setJavaClass(Class javaClass) { + this.javaClass = javaClass; + } + + public Object getAttributes() { + return attributes; + } + + public void setAttributes(Object attributes) { + this.attributes = attributes; + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/UnionAttributes.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/UnionAttributes.java new file mode 100644 index 0000000000..34bee2a0e4 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/UnionAttributes.java @@ -0,0 +1,59 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.provider.types; + +import java.util.HashMap; +import java.util.Map; + +/** + * @version $Rev$ $Date$ + * Stores attributes for previously scanned CORBA union type + */ +public class UnionAttributes { + + public String discriminatorName; + public String defaultOptionName; + public Map optionsMapping = new HashMap(); + + public String getDiscriminatorName() { + return discriminatorName; + } + + public void setDiscriminatorName(String discriminatorName) { + this.discriminatorName = discriminatorName; + } + + public String getDefaultOptionName() { + return defaultOptionName; + } + + public void setDefaultOptionName(String defaultOptionName) { + this.defaultOptionName = defaultOptionName; + } + + public Map getOptionsMapping() { + return optionsMapping; + } + + public void setOptionsMapping(Map optionsMapping) { + this.optionsMapping = optionsMapping; + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/ArrayTypeHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/ArrayTypeHelper.java new file mode 100644 index 0000000000..35a1e539d9 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/ArrayTypeHelper.java @@ -0,0 +1,53 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.provider.types.util; + +import java.lang.reflect.Array; + +import org.apache.tuscany.sca.binding.corba.provider.types.TypeTreeNode; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; + +/** + * @version $Rev$ $Date$ + */ +public class ArrayTypeHelper implements TypeHelper { + + public Object read(TypeTreeNode node, InputStream is) { + Object array = null; + try { + int size = (Integer)node.getAttributes(); + array = Array.newInstance(node.getChildren()[0].getJavaClass(), size); + for (int i = 0; i < size; i++) { + Array.set(array, i, TypeHelpersProxy.read(node.getChildren()[0], is)); + } + } catch (Exception e) { + e.printStackTrace(); + } + return array; + } + + public void write(TypeTreeNode node, OutputStream os, Object data) { + for (int i = 0; i < (Integer)node.getAttributes(); i++) { + TypeHelpersProxy.write(node.getChildren()[0], os, Array.get(data, i)); + } + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/BooleanTypeHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/BooleanTypeHelper.java new file mode 100644 index 0000000000..bbc2012a38 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/BooleanTypeHelper.java @@ -0,0 +1,39 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.provider.types.util; + +import org.apache.tuscany.sca.binding.corba.provider.types.TypeTreeNode; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; + +/** + * @version $Rev$ $Date$ + */ +public class BooleanTypeHelper implements TypeHelper { + + public Object read(TypeTreeNode node, InputStream is) { + return is.read_boolean(); + } + + public void write(TypeTreeNode node, OutputStream os, Object data) { + os.write_boolean((Boolean)data); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/ByteTypeHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/ByteTypeHelper.java new file mode 100644 index 0000000000..761cc5d62c --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/ByteTypeHelper.java @@ -0,0 +1,39 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.provider.types.util; + +import org.apache.tuscany.sca.binding.corba.provider.types.TypeTreeNode; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; + +/** + * @version $Rev$ $Date$ + */ +public class ByteTypeHelper implements TypeHelper { + + public Object read(TypeTreeNode node, InputStream is) { + return is.read_octet(); + } + + public void write(TypeTreeNode node, OutputStream os, Object data) { + os.write_octet((Byte)data); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/CharTypeHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/CharTypeHelper.java new file mode 100644 index 0000000000..b2d2afd011 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/CharTypeHelper.java @@ -0,0 +1,39 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.provider.types.util; + +import org.apache.tuscany.sca.binding.corba.provider.types.TypeTreeNode; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; + +/** + * @version $Rev$ $Date$ + */ +public class CharTypeHelper implements TypeHelper { + + public Object read(TypeTreeNode node, InputStream is) { + return is.read_char(); + } + + public void write(TypeTreeNode node, OutputStream os, Object data) { + os.write_char((Character)data); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/DoubleTypeHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/DoubleTypeHelper.java new file mode 100644 index 0000000000..f667123bb7 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/DoubleTypeHelper.java @@ -0,0 +1,39 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.provider.types.util; + +import org.apache.tuscany.sca.binding.corba.provider.types.TypeTreeNode; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; + +/** + * @version $Rev$ $Date$ + */ +public class DoubleTypeHelper implements TypeHelper { + + public Object read(TypeTreeNode node, InputStream is) { + return is.read_double(); + } + + public void write(TypeTreeNode node, OutputStream os, Object data) { + os.write_double((Double)data); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/EnumTypeHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/EnumTypeHelper.java new file mode 100644 index 0000000000..5661232e1e --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/EnumTypeHelper.java @@ -0,0 +1,41 @@ +package org.apache.tuscany.sca.binding.corba.provider.types.util; + +import java.lang.reflect.Method; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.apache.tuscany.sca.binding.corba.provider.types.TypeTreeNode; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; + +/** + * @version $Rev$ $Date$ + */ +public class EnumTypeHelper implements TypeHelper { + + private static final Logger logger = Logger.getLogger(EnumTypeHelper.class.getName()); + + public Object read(TypeTreeNode node, InputStream is) { + int value = is.read_long(); + Object result = null; + try { + Method method = node.getJavaClass().getMethod("from_int", new Class[] {int.class}); + result = method.invoke(null, new Object[] {value}); + } catch (Exception e) { + logger.log(Level.WARNING, "Exception during reading CORBA enum data", e); + e.printStackTrace(); + } + return result; + } + + public void write(TypeTreeNode node, OutputStream os, Object data) { + int value = 0; + try { + Method method = data.getClass().getMethod("value", new Class[] {}); + value = (Integer)method.invoke(data, new Object[] {}); + } catch (Exception e) { + logger.log(Level.WARNING, "Exception during writing CORBA enum data", e); + } + os.write_long(value); + } +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/FloatTypeHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/FloatTypeHelper.java new file mode 100644 index 0000000000..7c39725012 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/FloatTypeHelper.java @@ -0,0 +1,39 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.provider.types.util; + +import org.apache.tuscany.sca.binding.corba.provider.types.TypeTreeNode; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; + +/** + * @version $Rev$ $Date$ + */ +public class FloatTypeHelper implements TypeHelper { + + public Object read(TypeTreeNode node, InputStream is) { + return is.read_float(); + } + + public void write(TypeTreeNode node, OutputStream os, Object data) { + os.write_float((Float)data); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/IntTypeHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/IntTypeHelper.java new file mode 100644 index 0000000000..e903b59e50 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/IntTypeHelper.java @@ -0,0 +1,39 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.provider.types.util; + +import org.apache.tuscany.sca.binding.corba.provider.types.TypeTreeNode; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; + +/** + * @version $Rev$ $Date$ + */ +public class IntTypeHelper implements TypeHelper { + + public Object read(TypeTreeNode node, InputStream is) { + return is.read_long(); + } + + public void write(TypeTreeNode node, OutputStream os, Object data) { + os.write_long((Integer)data); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/LongTypeHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/LongTypeHelper.java new file mode 100644 index 0000000000..79d3c0cbc8 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/LongTypeHelper.java @@ -0,0 +1,39 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.provider.types.util; + +import org.apache.tuscany.sca.binding.corba.provider.types.TypeTreeNode; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; + +/** + * @version $Rev$ $Date$ + */ +public class LongTypeHelper implements TypeHelper { + + public Object read(TypeTreeNode node, InputStream is) { + return is.read_longlong(); + } + + public void write(TypeTreeNode node, OutputStream os, Object data) { + os.write_longlong((Long)data); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/ReferenceTypeHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/ReferenceTypeHelper.java new file mode 100644 index 0000000000..c89a25401d --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/ReferenceTypeHelper.java @@ -0,0 +1,42 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.provider.types.util; + +import org.apache.tuscany.sca.binding.corba.provider.reference.InterfaceInstanceCreator; +import org.apache.tuscany.sca.binding.corba.provider.types.TypeTreeNode; +import org.omg.CORBA.Object; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; + +/** + * @version $Rev$ $Date$ + */ +public class ReferenceTypeHelper implements TypeHelper { + + public java.lang.Object read(TypeTreeNode node, InputStream is) { + Object reference = is.read_Object(); + return (java.lang.Object)InterfaceInstanceCreator.createInstance(reference, node.getJavaClass()); + } + + public void write(TypeTreeNode node, OutputStream os, java.lang.Object data) { + os.write_Object((Object)data); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/SequenceTypeHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/SequenceTypeHelper.java new file mode 100644 index 0000000000..911c787b11 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/SequenceTypeHelper.java @@ -0,0 +1,70 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.provider.types.util; + +import java.lang.reflect.Array; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.apache.tuscany.sca.binding.corba.provider.types.TypeTreeNode; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; + +/** + * @version $Rev$ $Date$ + */ +public class SequenceTypeHelper implements TypeHelper { + + public Object read(TypeTreeNode node, InputStream is) { + Object sequence = null; + try { + int size = is.read_long(); + sequence = Array.newInstance(node.getChildren()[0].getJavaClass(), size); + for (int i = 0; i < size; i++) { + Array.set(sequence, i, TypeHelpersProxy.read(node.getChildren()[0], is)); + } + } catch (Exception e) { + e.printStackTrace(); + } + return sequence; + } + + public void write(TypeTreeNode node, OutputStream os, Object data) { + int sum = 0; + // determine length of array + List array = new ArrayList(); + while (true) { + try { + array.add(Array.get(data, sum)); + sum++; + } catch (ArrayIndexOutOfBoundsException e) { + break; + } + } + os.write_long(sum); + Iterator iter = array.iterator(); + while (iter.hasNext()) { + Object elem = iter.next(); + TypeHelpersProxy.write(node.getChildren()[0], os, elem); + } + + } +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/ShortTypeHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/ShortTypeHelper.java new file mode 100644 index 0000000000..f4cdabc8e2 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/ShortTypeHelper.java @@ -0,0 +1,39 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.provider.types.util; + +import org.apache.tuscany.sca.binding.corba.provider.types.TypeTreeNode; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; + +/** + * @version $Rev$ $Date$ + */ +public class ShortTypeHelper implements TypeHelper { + + public Object read(TypeTreeNode node, InputStream is) { + return is.read_short(); + } + + public void write(TypeTreeNode node, OutputStream os, Object data) { + os.write_short((Short)data); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/StringTypeHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/StringTypeHelper.java new file mode 100644 index 0000000000..5a4fcba221 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/StringTypeHelper.java @@ -0,0 +1,39 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.provider.types.util; + +import org.apache.tuscany.sca.binding.corba.provider.types.TypeTreeNode; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; + +/** + * @version $Rev$ $Date$ + */ +public class StringTypeHelper implements TypeHelper { + + public Object read(TypeTreeNode node, InputStream is) { + return is.read_string(); + } + + public void write(TypeTreeNode node, OutputStream os, Object data) { + os.write_string((String)data); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/StructTypeHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/StructTypeHelper.java new file mode 100644 index 0000000000..1fc729b926 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/StructTypeHelper.java @@ -0,0 +1,69 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.provider.types.util; + +import java.lang.reflect.Field; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.apache.tuscany.sca.binding.corba.provider.types.TypeTreeNode; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; + +/** + * @version $Rev$ $Date$ + */ +public class StructTypeHelper implements TypeHelper { + + private static final Logger logger = Logger.getLogger(StructTypeHelper.class.getName()); + + public Object read(TypeTreeNode node, InputStream is) { + TypeTreeNode[] children = node.getChildren(); + Object result = null; + if (children != null) { + try { + result = node.getJavaClass().newInstance(); + for (int i = 0; i < children.length; i++) { + Object childResult = TypeHelpersProxy.read(children[i], is); + Field childField = result.getClass().getField(children[i].getName()); + childField.set(result, childResult); + } + } catch (Exception e) { + logger.log(Level.WARNING, "Exception during reading CORBA struct data", e); + } + } + return result; + } + + public void write(TypeTreeNode node, OutputStream os, Object data) { + TypeTreeNode[] children = node.getChildren(); + if (children != null) { + try { + for (int i = 0; i < children.length; i++) { + Field childField = node.getJavaClass().getField(children[i].getName()); + TypeHelpersProxy.write(children[i], os, childField.get(data)); + } + } catch (Exception e) { + logger.log(Level.WARNING, "Exception during writing CORBA struct data", e); + } + } + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/TypeHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/TypeHelper.java new file mode 100644 index 0000000000..0f1f973f49 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/TypeHelper.java @@ -0,0 +1,47 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.provider.types.util; + +import org.apache.tuscany.sca.binding.corba.provider.types.TypeTreeNode; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; + +/** + * @version $Rev$ $Date$ + */ +public interface TypeHelper { + + /** + * Reads CORBA object + * @param node + * @param is + * @return + */ + Object read(TypeTreeNode node, InputStream is); + + /** + * Writes CORBA object + * @param node + * @param os + * @param data + */ + void write(TypeTreeNode node, OutputStream os, Object data); + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/TypeHelpersProxy.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/TypeHelpersProxy.java new file mode 100644 index 0000000000..ded82bf12e --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/TypeHelpersProxy.java @@ -0,0 +1,119 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.provider.types.util; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.tuscany.sca.binding.corba.provider.types.NodeType; +import org.apache.tuscany.sca.binding.corba.provider.types.TypeTreeNode; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; + +/** + * @version $Rev$ $Date$ + * Proxies getType(), write(), read() methods to appropriate TypeHelper implementation. + */ +public class TypeHelpersProxy { + + /** + * Maps primitive types to its TypeHelper implementations + */ + private static Map, TypeHelper> primitiveTypes = null; + + /** + * Maps other types to its TypeHelper implementations + */ + private static Map complexTypes = null; + + static { + // initiate type helpers + primitiveTypes = new HashMap, TypeHelper>(); + complexTypes = new HashMap(); + + primitiveTypes.put(boolean.class, new BooleanTypeHelper()); + primitiveTypes.put(char.class, new CharTypeHelper()); + primitiveTypes.put(byte.class, new ByteTypeHelper()); + primitiveTypes.put(short.class, new ShortTypeHelper()); + primitiveTypes.put(int.class, new IntTypeHelper()); + primitiveTypes.put(long.class, new LongTypeHelper()); + primitiveTypes.put(float.class, new FloatTypeHelper()); + primitiveTypes.put(double.class, new DoubleTypeHelper()); + primitiveTypes.put(String.class, new StringTypeHelper()); + primitiveTypes.put(Boolean.class, primitiveTypes.get(boolean.class)); + primitiveTypes.put(Character.class, primitiveTypes.get(char.class)); + primitiveTypes.put(Byte.class, primitiveTypes.get(byte.class)); + primitiveTypes.put(Short.class, primitiveTypes.get(short.class)); + primitiveTypes.put(Integer.class, primitiveTypes.get(int.class)); + primitiveTypes.put(Long.class, primitiveTypes.get(long.class)); + primitiveTypes.put(Float.class, primitiveTypes.get(float.class)); + primitiveTypes.put(Double.class, primitiveTypes.get(double.class)); + primitiveTypes.put(String.class, primitiveTypes.get(String.class)); + complexTypes.put(NodeType.array, new ArrayTypeHelper()); + complexTypes.put(NodeType.struct, new StructTypeHelper()); + complexTypes.put(NodeType.reference, new ReferenceTypeHelper()); + complexTypes.put(NodeType.sequence, new SequenceTypeHelper()); + complexTypes.put(NodeType.idl_enum, new EnumTypeHelper()); + complexTypes.put(NodeType.exception, new StructTypeHelper()); + complexTypes.put(NodeType.union, new UnionTypeHelper()); + } + + /** + * Gets type helper basing on given type + * + * @param node + * @return + */ + private static TypeHelper getTypeHelper(TypeTreeNode node) { + TypeHelper typeHelper = null; + NodeType type = node.getNodeType(); + if (type.equals(NodeType.primitive)) { + typeHelper = primitiveTypes.get(node.getJavaClass()); + } else { + typeHelper = complexTypes.get(type); + } + return typeHelper; + } + + /** + * Proxies read method invocation to appropriate TypeHelper implementation. + * + * @param node + * @param is + * @return + */ + public static final Object read(TypeTreeNode node, InputStream is) { + TypeHelper helper = getTypeHelper(node); + return helper.read(node, is); + } + + /** + * Proxies write method invocation to appropriate TypeHelper implementation. + * + * @param node + * @param os + * @param data + */ + public static final void write(TypeTreeNode node, OutputStream os, Object data) { + TypeHelper helper = getTypeHelper(node); + helper.write(node, os, data); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/UnionTypeHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/UnionTypeHelper.java new file mode 100644 index 0000000000..df2e833fcd --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/UnionTypeHelper.java @@ -0,0 +1,92 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.provider.types.util; + +import java.lang.reflect.Field; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.apache.tuscany.sca.binding.corba.provider.types.TypeTreeNode; +import org.apache.tuscany.sca.binding.corba.provider.types.UnionAttributes; +import org.omg.CORBA.portable.InputStream; +import org.omg.CORBA.portable.OutputStream; + +/** + * @version $Rev$ $Date$ + */ +public class UnionTypeHelper implements TypeHelper { + + private static final Logger logger = Logger.getLogger(UnionTypeHelper.class.getName()); + + public Object read(TypeTreeNode node, InputStream is) { + Object result = null; + try { + int discriminator = is.read_long(); + UnionAttributes attrs = (UnionAttributes)node.getAttributes(); + String childName = attrs.getOptionsMapping().get(discriminator); + if (childName == null) { + // get default if option numbers field not found + childName = attrs.getDefaultOptionName(); + } + result = node.getJavaClass().newInstance(); + Field discField = result.getClass().getDeclaredField(attrs.getDiscriminatorName()); + discField.setAccessible(true); + discField.set(result, discriminator); + for (int i = 0; i < node.getChildren().length; i++) { + if (node.getChildren()[i].getName().equals(childName)) { + Object unionValue = TypeHelpersProxy.read(node.getChildren()[i], is); + Field childField = result.getClass().getDeclaredField(childName); + childField.setAccessible(true); + childField.set(result, unionValue); + break; + } + } + } catch (Exception e) { + logger.log(Level.WARNING, "Exception during reading CORBA union data", e); + } + return result; + } + + public void write(TypeTreeNode node, OutputStream os, Object data) { + try { + UnionAttributes attrs = (UnionAttributes)node.getAttributes(); + Field discriminatorField = data.getClass().getDeclaredField(attrs.getDiscriminatorName()); + discriminatorField.setAccessible(true); + int discriminator = discriminatorField.getInt(data); + os.write_long(discriminator); + String childName = attrs.getOptionsMapping().get(discriminator); + if (childName == null) { + // get default if option numbers field not found + childName = attrs.getDefaultOptionName(); + } + for (int i = 0; i < node.getChildren().length; i++) { + if (node.getChildren()[i].getName().equals(childName)) { + Field childField = data.getClass().getDeclaredField(childName); + childField.setAccessible(true); + TypeHelpersProxy.write(node.getChildren()[i], os, childField.get(data)); + break; + } + } + } catch (Exception e) { + logger.log(Level.WARNING, "Exception during writing CORBA union data", e); + } + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/Utils.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/Utils.java new file mode 100644 index 0000000000..7ccd70f69e --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/types/util/Utils.java @@ -0,0 +1,40 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.provider.types.util; + +/** + * @version $Rev$ $Date$ + * Class for type utilities + */ +public class Utils { + + /** + * Creates CORBA id for Java class + * @param forClass + * @return + */ + public static String getTypeId(Class forClass) { + String result = forClass.getName().replace('.', '/'); + result = result.replaceAll("Package", ""); + result = "IDL:" + result + ":1.0"; + return result; + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/util/MethodFinder.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/util/MethodFinder.java new file mode 100644 index 0000000000..f9facac0cc --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/util/MethodFinder.java @@ -0,0 +1,97 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.provider.util; + +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; + +/** + * @version $Rev$ $Date$ + * Utility for finding method in given class. + */ +public class MethodFinder { + + private static Map, Class> boxingMapping; + + static { + boxingMapping = new HashMap, Class>(); + boxingMapping.put(boolean.class, Boolean.class); + boxingMapping.put(byte.class, Byte.class); + boxingMapping.put(short.class, Short.class); + boxingMapping.put(char.class, Character.class); + boxingMapping.put(int.class, Integer.class); + boxingMapping.put(long.class, Long.class); + boxingMapping.put(float.class, Float.class); + boxingMapping.put(double.class, Double.class); + } + + /** + * Converts primitive class to its object equivalent. + * + * @param parameter class to convert + * @return object equivalent for primitive type. If parameter wasn't + * primitive then returns parameter. + */ + private static Class normalizePrimitive(Class parameter) { + Class result = boxingMapping.get(parameter); + if (result != null) { + return result; + } else { + // not a primitive - no need to normalize + return parameter; + } + } + + /** + * Finds appropriate method. This method ignores difference between + * primitive types and theirs object equivalents. Ie. if we want to find + * method "get" in java.util.List with only one parameter, which type is + * Integer then we'll obtain method get(int). + * + * @param forClass class which possibly contains desired method + * @param methodName desired methods name + * @param parameterTypes desired methods parameter types + * @return desired method, if no method was found then null will be returned + */ + public static Method findMethod(Class forClass, String methodName, Class[] parameterTypes) { + Method[] methods = forClass.getMethods(); + for (int i = 0; i < methods.length; i++) { + if (methods[i].getName().equals(methodName)) { + Class[] methodPTypes = methods[i].getParameterTypes(); + if (methodPTypes.length == parameterTypes.length) { + boolean parameterMatch = true; + for (int j = 0; j < methodPTypes.length; j++) { + Class nMethodPType = normalizePrimitive(methodPTypes[j]); + Class nParameterType = normalizePrimitive(parameterTypes[j]); + if (!nMethodPType.equals(nParameterType)) { + parameterMatch = false; + break; + } + } + if (parameterMatch) { + return methods[i]; + } + } + } + } + return null; + } +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/util/OperationMapper.java b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/util/OperationMapper.java new file mode 100644 index 0000000000..414e50abf4 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/java/org/apache/tuscany/sca/binding/corba/provider/util/OperationMapper.java @@ -0,0 +1,578 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.corba.provider.util; + +import java.lang.reflect.Method; +import java.rmi.RemoteException; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.omg.CORBA.portable.IDLEntity; + +/** + * @version $Rev$ $Date$ + */ +public final class OperationMapper { + + private static Set> getAllInterfaces(Class intfClass) { + Set> allInterfaces = new LinkedHashSet>(); + + LinkedList> stack = new LinkedList>(); + stack.addFirst(intfClass); + + while (!stack.isEmpty()) { + Class intf = stack.removeFirst(); + allInterfaces.add(intf); + for (Class i : intf.getInterfaces()) { + stack.add(0, i); + } + } + + return allInterfaces; + } + + /** + * Maps Java methods to operation names + * @param intfClass + * @return + */ + @SuppressWarnings("unchecked") + public static Map mapMethodToOperationName(Class intfClass) { + return iiopMap(intfClass, false); + } + + /** + * Maps operation names to Java methods + * @param intfClass + * @return + */ + @SuppressWarnings("unchecked") + public static Map mapOperationNameToMethod(Class intfClass) { + return iiopMap(intfClass, true); + } + + @SuppressWarnings("unchecked") + private static Map iiopMap(Class intfClass, boolean operationToMethod) { + Method[] methods = getAllMethods(intfClass); + + // find every valid getter + Map getterByMethod = new HashMap(methods.length); + Map getterByName = new HashMap(methods.length); + for (int i = 0; i < methods.length; i++) { + Method method = methods[i]; + String methodName = method.getName(); + + // no arguments allowed + if (method.getParameterTypes().length != 0) { + continue; + } + + // must start with get or is + String verb; + if (methodName.startsWith("get") && methodName.length() > 3 && method.getReturnType() != void.class) { + verb = "get"; + } else if (methodName.startsWith("is") && methodName.length() > 2 && method.getReturnType() == boolean.class) { + verb = "is"; + } else { + continue; + } + + // must only throw Remote or Runtime Exceptions + boolean exceptionsValid = true; + Class[] exceptionTypes = method.getExceptionTypes(); + for (int j = 0; j < exceptionTypes.length; j++) { + Class exceptionType = exceptionTypes[j]; + if (!RemoteException.class.isAssignableFrom(exceptionType) && + !RuntimeException.class.isAssignableFrom(exceptionType) && + !Error.class.isAssignableFrom(exceptionType)) { + exceptionsValid = false; + break; + } + } + if (!exceptionsValid) { + continue; + } + + String propertyName; + if (methodName.length() > verb.length() + 1 && Character.isUpperCase(methodName.charAt(verb.length() + 1))) { + propertyName = methodName.substring(verb.length()); + } else { + propertyName = Character.toLowerCase(methodName.charAt(verb.length())) + methodName.substring(verb.length() + 1); + } + getterByMethod.put(method, propertyName); + getterByName.put(propertyName, method); + } + + Map setterByMethod = new HashMap(methods.length); + for (int i = 0; i < methods.length; i++) { + Method method = methods[i]; + String methodName = method.getName(); + + // must have exactally one arg + if (method.getParameterTypes().length != 1) { + continue; + } + + // must return non void + if (method.getReturnType() != void.class) { + continue; + } + + // must start with set + if (!methodName.startsWith("set") || methodName.length() <= 3) { + continue; + } + + // must only throw Remote or Runtime Exceptions + boolean exceptionsValid = true; + Class[] exceptionTypes = method.getExceptionTypes(); + for (int j = 0; j < exceptionTypes.length; j++) { + Class exceptionType = exceptionTypes[j]; + if (!RemoteException.class.isAssignableFrom(exceptionType) && + !RuntimeException.class.isAssignableFrom(exceptionType) && + !Error.class.isAssignableFrom(exceptionType)) { + exceptionsValid = false; + break; + } + } + if (!exceptionsValid) { + continue; + } + + String propertyName; + if (methodName.length() > 4 && Character.isUpperCase(methodName.charAt(4))) { + propertyName = methodName.substring(3); + } else { + propertyName = Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4); + } + + // must have a matching getter + Method getter = (Method) getterByName.get(propertyName); + if (getter == null) { + continue; + } + + // setter property must match getter return value + if (!method.getParameterTypes()[0].equals(getter.getReturnType())) { + continue; + } + setterByMethod.put(method, propertyName); + } + + // index the methods by name... used to determine which methods are overloaded + HashMap> overloadedMethods = new HashMap>(methods.length); + for (int i = 0; i < methods.length; i++) { + Method method = methods[i]; + if (getterByMethod.containsKey(method) || setterByMethod.containsKey(method)) { + continue; + } + String methodName = method.getName(); + List methodList = overloadedMethods.get(methodName); + if (methodList == null) { + methodList = new LinkedList(); + overloadedMethods.put(methodName, methodList); + } + methodList.add(method); + } + + // index the methods by lower case name... used to determine which methods differ only by case + Map> caseCollisionMethods = new HashMap>(methods.length); + for (int i = 0; i < methods.length; i++) { + Method method = methods[i]; + if (getterByMethod.containsKey(method) || setterByMethod.containsKey(method)) { + continue; + } + String lowerCaseMethodName = method.getName().toLowerCase(); + Set methodSet = caseCollisionMethods.get(lowerCaseMethodName); + if (methodSet == null) { + methodSet = new HashSet(); + caseCollisionMethods.put(lowerCaseMethodName, methodSet); + } + methodSet.add(method.getName()); + } + + String className = getClassName(intfClass); + Map iiopMap = new HashMap(methods.length); + for (int i = 0; i < methods.length; i++) { + Method method = methods[i]; + + String iiopName = (String) getterByMethod.get(method); + if (iiopName != null) { + // if we have a leading underscore prepend with J + if (iiopName.charAt(0) == '_') { + iiopName = "J_get_" + iiopName.substring(1); + } else { + iiopName = "_get_" + iiopName; + } + } else { + iiopName = (String) setterByMethod.get(method); + if (iiopName != null) { + // if we have a leading underscore prepend with J + if (iiopName.charAt(0) == '_') { + iiopName = "J_set_" + iiopName.substring(1); + } else { + iiopName = "_set_" + iiopName; + } + } else { + iiopName = method.getName(); + + // if we have a leading underscore prepend with J + if (iiopName.charAt(0) == '_') { + iiopName = "J" + iiopName; + } + } + } + + // if this name only differs by case add the case index to the end + Set caseCollisions = caseCollisionMethods.get(method.getName().toLowerCase()); + if (caseCollisions != null && caseCollisions.size() > 1) { + iiopName += upperCaseIndexString(iiopName); + } + + // if this is an overloaded method append the parameter string + List overloads = overloadedMethods.get(method.getName()); + if (overloads != null && overloads.size() > 1) { + iiopName += buildOverloadParameterString(method.getParameterTypes()); + } + + // if we have a leading underscore prepend with J + iiopName = replace(iiopName, '$', "U0024"); + + // if we have matched a keyword prepend with an underscore + if (keywords.contains(iiopName.toLowerCase())) { + iiopName = "_" + iiopName; + } + + // if the name is the same as the class name, append an underscore + if (iiopName.equalsIgnoreCase(className)) { + iiopName += "_"; + } + + if (operationToMethod) { + iiopMap.put(iiopName, method); + } else { + iiopMap.put(method, iiopName); + } + } + + return iiopMap; + } + + private static Method[] getAllMethods(Class intfClass) { + List methods = new LinkedList(); + for (Iterator> iterator = getAllInterfaces(intfClass).iterator(); iterator.hasNext();) { + Class intf = iterator.next(); + methods.addAll(Arrays.asList(intf.getDeclaredMethods())); + } + + return (Method[]) methods.toArray(new Method[methods.size()]); + } + + /** + * Return the a string containing an underscore '_' index of each uppercase + * character in the IIOP name. This is used for distinction of names that + * only differ by case, since CORBA does not support case sensitive names. + */ + private static String upperCaseIndexString(String iiopName) { + StringBuffer stringBuffer = new StringBuffer(); + for (int i = 0; i < iiopName.length(); i++) { + char c = iiopName.charAt(i); + if (Character.isUpperCase(c)) { + stringBuffer.append('_').append(i); + } + } + return stringBuffer.toString(); + } + + /** + * Replaces any occurances of the specified "oldChar" with the new string. + * This is used to replace occurances if '$' in CORBA names since '$' is a + * special character + */ + private static String replace(String source, char oldChar, String newString) { + StringBuffer stringBuffer = new StringBuffer(source.length()); + for (int i = 0; i < source.length(); i++) { + char c = source.charAt(i); + if (c == oldChar) { + stringBuffer.append(newString); + } else { + stringBuffer.append(c); + } + } + return stringBuffer.toString(); + } + + /** + * Return the a string containing a double underscore '__' list of parameter + * types encoded using the Java to IDL rules. This is used for distinction + * of methods that only differ by parameter lists. + */ + private static String buildOverloadParameterString(Class[] parameterTypes) { + String name = ""; + if (parameterTypes.length == 0) { + name += "__"; + } else { + for (int i = 0; i < parameterTypes.length; i++) { + Class parameterType = parameterTypes[i]; + name += buildOverloadParameterString(parameterType); + } + } + return name.replace('.', '_'); + } + + /** + * Returns a single parameter type encoded using the Java to IDL rules. + */ + private static String buildOverloadParameterString(Class parameterType) { + String name = "_"; + + int arrayDimensions = 0; + while (parameterType.isArray()) { + arrayDimensions++; + parameterType = parameterType.getComponentType(); + } + + // arrays start with org_omg_boxedRMI_ + if (arrayDimensions > 0) { + name += "_org_omg_boxedRMI"; + } + + // IDLEntity types must be prefixed with org_omg_boxedIDL_ + if (IDLEntity.class.isAssignableFrom(parameterType)) { + name += "_org_omg_boxedIDL"; + } + + // add package... some types have special mappings in corba + String packageName = (String)specialTypePackages.get(parameterType.getName()); + if (packageName == null) { + packageName = getPackageName(parameterType.getName()); + } + if (packageName.length() > 0) { + name += "_" + packageName; + } + + // arrays now contain a dimension indicator + if (arrayDimensions > 0) { + name += "_" + "seq" + arrayDimensions; + } + + // add the class name + String className = (String)specialTypeNames.get(parameterType.getName()); + if (className == null) { + className = buildClassName(parameterType); + } + name += "_" + className; + + return name; + } + + /** + * Returns a string containing an encoded class name. + */ + private static String buildClassName(Class type) { + if (type.isArray()) { + throw new IllegalArgumentException("type is an array: " + type); + } + + // get the classname + String typeName = type.getName(); + int endIndex = typeName.lastIndexOf('.'); + if (endIndex < 0) { + return typeName; + } + StringBuffer className = new StringBuffer(typeName.substring(endIndex + 1)); + + // for innerclasses replace the $ separator with two underscores + // we can't just blindly replace all $ characters since class names can + // contain the $ character + if (type.getDeclaringClass() != null) { + String declaringClassName = getClassName(type.getDeclaringClass()); + assert className.toString().startsWith(declaringClassName + "$"); + className.replace(declaringClassName.length(), declaringClassName.length() + 1, "__"); + } + + // if we have a leading underscore prepend with J + if (className.charAt(0) == '_') { + className.insert(0, "J"); + } + return className.toString(); + } + + private static String getClassName(Class type) { + if (type.isArray()) { + throw new IllegalArgumentException("type is an array: " + type); + } + + // get the classname + String typeName = type.getName(); + int endIndex = typeName.lastIndexOf('.'); + if (endIndex < 0) { + return typeName; + } + return typeName.substring(endIndex + 1); + } + + private static String getPackageName(String interfaceName) { + int endIndex = interfaceName.lastIndexOf('.'); + if (endIndex < 0) { + return ""; + } + return interfaceName.substring(0, endIndex); + } + + private static final Map specialTypeNames; + private static final Map specialTypePackages; + private static final Set keywords; + + static { + specialTypeNames = new HashMap(); + specialTypeNames.put("boolean", "boolean"); + specialTypeNames.put("char", "wchar"); + specialTypeNames.put("byte", "octet"); + specialTypeNames.put("short", "short"); + specialTypeNames.put("int", "long"); + specialTypeNames.put("long", "long_long"); + specialTypeNames.put("float", "float"); + specialTypeNames.put("double", "double"); + specialTypeNames.put("java.lang.Class", "ClassDesc"); + specialTypeNames.put("java.lang.String", "WStringValue"); + specialTypeNames.put("org.omg.CORBA.Object", "Object"); + + specialTypePackages = new HashMap(); + specialTypePackages.put("boolean", ""); + specialTypePackages.put("char", ""); + specialTypePackages.put("byte", ""); + specialTypePackages.put("short", ""); + specialTypePackages.put("int", ""); + specialTypePackages.put("long", ""); + specialTypePackages.put("float", ""); + specialTypePackages.put("double", ""); + specialTypePackages.put("java.lang.Class", "javax.rmi.CORBA"); + specialTypePackages.put("java.lang.String", "CORBA"); + specialTypePackages.put("org.omg.CORBA.Object", ""); + + keywords = new HashSet(); + keywords.add("abstract"); + keywords.add("any"); + keywords.add("attribute"); + keywords.add("boolean"); + keywords.add("case"); + keywords.add("char"); + keywords.add("const"); + keywords.add("context"); + keywords.add("custom"); + keywords.add("default"); + keywords.add("double"); + keywords.add("enum"); + keywords.add("exception"); + keywords.add("factory"); + keywords.add("false"); + keywords.add("fixed"); + keywords.add("float"); + keywords.add("in"); + keywords.add("inout"); + keywords.add("interface"); + keywords.add("long"); + keywords.add("module"); + keywords.add("native"); + keywords.add("object"); + keywords.add("octet"); + keywords.add("oneway"); + keywords.add("out"); + keywords.add("private"); + keywords.add("public"); + keywords.add("raises"); + keywords.add("readonly"); + keywords.add("sequence"); + keywords.add("short"); + keywords.add("string"); + keywords.add("struct"); + keywords.add("supports"); + keywords.add("switch"); + keywords.add("true"); + keywords.add("truncatable"); + keywords.add("typedef"); + keywords.add("union"); + keywords.add("unsigned"); + keywords.add("valuebase"); + keywords.add("valuetype"); + keywords.add("void"); + keywords.add("wchar"); + keywords.add("wstring"); + } + + @SuppressWarnings("unchecked") + public static Map mapOperationToMethod(List operations, Class forClass) { + return (Map)createMethod2OperationMapping(operations, forClass, false); + } + + @SuppressWarnings("unchecked") + public static Map mapMethodToOperation(List operations, Class forClass) { + return (Map)createMethod2OperationMapping(operations, forClass, true); + } + + /** + * Maps Java methods to Tuscany operations + */ + @SuppressWarnings("unchecked") + private static Map createMethod2OperationMapping(List operations, Class forClass, boolean method2operation) { + // for every operation find all methods with the same name, then + // compare operations and methods parameters + Map mapping = new HashMap(); + for (Operation operation : operations) { + List inputTypes = operation.getInputType().getLogical(); + Method[] methods = forClass.getMethods(); + for (int i = 0; i < methods.length; i++) { + if (methods[i].getName().equals(operation.getName()) && inputTypes.size() == methods[i] + .getParameterTypes().length) { + Class[] parameterTypes = methods[i].getParameterTypes(); + int j = 0; + boolean parameterMatch = true; + for (DataType dataType : inputTypes) { + if (!dataType.getPhysical().equals(parameterTypes[j])) { + parameterMatch = false; + break; + } + j++; + } + if (parameterMatch) { + // match found + if (method2operation) { + mapping.put(methods[i], operation); + } else { + mapping.put(operation, methods[i]); + } + break; + } + } + } + } + return mapping; + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.BindingProviderFactory b/java/sca/contrib/modules/binding-corba-runtime/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.BindingProviderFactory new file mode 100644 index 0000000000..9855dec8af --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.BindingProviderFactory @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for the binding extension +org.apache.tuscany.sca.binding.corba.provider.CorbaBindingProviderFactory;model=org.apache.tuscany.sca.binding.corba.CorbaBinding diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/CorbaServantTestCase.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/CorbaServantTestCase.java new file mode 100644 index 0000000000..38891340f9 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/CorbaServantTestCase.java @@ -0,0 +1,564 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing; + +import static junit.framework.Assert.fail; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.lang.reflect.Array; + +import junit.framework.Assert; + +import org.apache.tuscany.sca.binding.corba.provider.exceptions.CorbaException; +import org.apache.tuscany.sca.binding.corba.provider.exceptions.RequestConfigurationException; +import org.apache.tuscany.sca.binding.corba.provider.reference.DynaCorbaRequest; +import org.apache.tuscany.sca.binding.corba.provider.reference.DynaCorbaResponse; +import org.apache.tuscany.sca.binding.corba.provider.service.ComponentInvocationProxy; +import org.apache.tuscany.sca.binding.corba.provider.service.DynaCorbaServant; +import org.apache.tuscany.sca.binding.corba.provider.service.InvocationProxy; +import org.apache.tuscany.sca.binding.corba.provider.types.util.Utils; +import org.apache.tuscany.sca.binding.corba.testing.arrays_unions.ArraysUnionsTests; +import org.apache.tuscany.sca.binding.corba.testing.arrays_unions.ArraysUnionsTestsHelper; +import org.apache.tuscany.sca.binding.corba.testing.arrays_unions.TestStruct; +import org.apache.tuscany.sca.binding.corba.testing.enums.Color; +import org.apache.tuscany.sca.binding.corba.testing.enums.EnumManager; +import org.apache.tuscany.sca.binding.corba.testing.enums.EnumManagerHelper; +import org.apache.tuscany.sca.binding.corba.testing.exceptions.Calc; +import org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcHelper; +import org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.DivByZero; +import org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.NotSupported; +import org.apache.tuscany.sca.binding.corba.testing.generated.ArraysSetter; +import org.apache.tuscany.sca.binding.corba.testing.generated.ArraysSetterHelper; +import org.apache.tuscany.sca.binding.corba.testing.generated.PrimitivesSetter; +import org.apache.tuscany.sca.binding.corba.testing.generated.PrimitivesSetterHelper; +import org.apache.tuscany.sca.binding.corba.testing.generated.SimpleStruct; +import org.apache.tuscany.sca.binding.corba.testing.generated.SomeStruct; +import org.apache.tuscany.sca.binding.corba.testing.generated.TestObject; +import org.apache.tuscany.sca.binding.corba.testing.generated.TestObjectHelper; +import org.apache.tuscany.sca.binding.corba.testing.hierarchy.NonCorbaException; +import org.apache.tuscany.sca.binding.corba.testing.servants.ArraysSetterServant; +import org.apache.tuscany.sca.binding.corba.testing.servants.ArraysUnionsTuscanyServant; +import org.apache.tuscany.sca.binding.corba.testing.servants.CalcServant; +import org.apache.tuscany.sca.binding.corba.testing.servants.EnumManagerServant; +import org.apache.tuscany.sca.binding.corba.testing.servants.InvalidTestObjectServant; +import org.apache.tuscany.sca.binding.corba.testing.servants.InvalidTypesServant; +import org.apache.tuscany.sca.binding.corba.testing.servants.NonCorbaServant; +import org.apache.tuscany.sca.binding.corba.testing.servants.PrimitivesSetterServant; +import org.apache.tuscany.sca.binding.corba.testing.servants.TestObjectServant; +import org.apache.tuscany.sca.binding.corba.testing.service.mocks.TestRuntimeComponentService; +import org.apache.tuscany.sca.host.corba.naming.TransientNameServer; +import org.apache.tuscany.sca.host.corba.naming.TransientNameService; +import org.apache.tuscany.sca.interfacedef.java.JavaInterface; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.omg.CORBA.BAD_OPERATION; +import org.omg.CORBA.ORB; +import org.omg.CORBA.Object; +import org.omg.CosNaming.NameComponent; +import org.omg.CosNaming.NamingContext; +import org.omg.CosNaming.NamingContextHelper; + +/** + * @version $Rev$ $Date$ + * Tests API for dynamic CORBA servants + */ +public class CorbaServantTestCase { + + private static ORB orb; + private static TransientNameServer server; + + @BeforeClass + public static void start() { + try { + server = + new TransientNameServer(TestConstants.TEST2_HOST, TestConstants.TEST2_PORT, + TransientNameService.DEFAULT_SERVICE_NAME); + Thread t = server.start(); + if (t == null) { + Assert.fail("The naming server cannot be started"); + } + orb = server.getORB(); + } catch (Throwable e) { + e.printStackTrace(); + Assert.fail(e.getMessage()); + } + } + + @AfterClass + public static void stop() { + server.stop(); + } + + /** + * Binds servant implementation to name + */ + private void bindServant(DynaCorbaServant servant, String name) { + try { + Object nameService = orb.resolve_initial_references("NameService"); + NamingContext namingContext = NamingContextHelper.narrow(nameService); + + NameComponent nc = new NameComponent(name, ""); + NameComponent[] path = new NameComponent[] {nc}; + namingContext.rebind(path, servant); + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * Returns object reference which is binded to given name + * + * @param name + * @return + */ + private org.omg.CORBA.Object bindReference(String name) { + try { + org.omg.CORBA.Object objRef = orb.resolve_initial_references("NameService"); + NamingContext ncRef = NamingContextHelper.narrow(objRef); + NameComponent nc = new NameComponent(name, ""); + NameComponent path[] = {nc}; + return ncRef.resolve(path); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + /** + * Tests primitives (arguments, return types) + */ + @Test + public void test_primitivesSetter() { + try { + PrimitivesSetter primitivesSetter = new PrimitivesSetterServant(); + TestRuntimeComponentService service = new TestRuntimeComponentService(primitivesSetter); + Class javaClass = ((JavaInterface)service.getInterfaceContract().getInterface()).getJavaClass(); + InvocationProxy proxy = new ComponentInvocationProxy(service, service.getRuntimeWire(null), javaClass); + DynaCorbaServant servant = new DynaCorbaServant(proxy, Utils.getTypeId(javaClass)); + String[] ids = + new String[] {"IDL:org/apache/tuscany/sca/binding/corba/testing/generated/PrimitivesSetter:1.0"}; + servant.setIds(ids); + bindServant(servant, "PrimitivesSetter"); + PrimitivesSetter psClient = PrimitivesSetterHelper.narrow(bindReference("PrimitivesSetter")); + assertTrue(psClient.setBoolean(true) == true); + assertTrue(psClient.setChar('A') == 'A'); + assertTrue(psClient.setString("SomeTest").equals("SomeTest")); + assertTrue(psClient.setDouble(2d) == 2d); + assertTrue(psClient.setFloat(3f) == 3f); + assertTrue(psClient.setLong(1) == 1); + assertTrue(psClient.setLongLong(0L) == 0L); + assertTrue(psClient.setOctet((byte)8) == (byte)8); + assertTrue(psClient.setShort((short)6) == (short)6); + assertTrue(psClient.setUnsignedLong(9) == 9); + assertTrue(psClient.setUnsignedLongLong(11L) == 11L); + assertTrue(psClient.setUnsignedShort((short)15) == (short)15); + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + } + + /** + * Tests if array values are equal + */ + private boolean areArraysEqual(java.lang.Object arr1, java.lang.Object arr2, int arrLen) { + try { + for (int i = 0; i < arrLen; i++) { + if (!Array.get(arr1, i).equals(Array.get(arr2, i))) { + return false; + } + } + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return false; + } + + /** + * Tests arrays (arguments, return types) + */ + @Test + public void test_arraysSetter() { + try { + ArraysSetter arraysSetter = new ArraysSetterServant(); + TestRuntimeComponentService service = new TestRuntimeComponentService(arraysSetter); + Class javaClass = ((JavaInterface)service.getInterfaceContract().getInterface()).getJavaClass(); + InvocationProxy proxy = new ComponentInvocationProxy(service, service.getRuntimeWire(null), javaClass); + DynaCorbaServant servant = new DynaCorbaServant(proxy, Utils.getTypeId(javaClass)); + String[] ids = new String[] {"IDL:org/apache/tuscany/sca/binding/corba/testing/generated/ArraysSetter:1.0"}; + servant.setIds(ids); + java.lang.Object result = null; + bindServant(servant, "ArraysSetter"); + ArraysSetter asClient = ArraysSetterHelper.narrow(bindReference("ArraysSetter")); + + boolean[] bArr = new boolean[] {true, false}; + result = (java.lang.Object)asClient.setBoolean(bArr); + assertTrue(areArraysEqual(bArr, result, bArr.length)); + + byte[] byArr = new byte[] {1, 2}; + result = (java.lang.Object)asClient.setOctet(byArr); + assertTrue(areArraysEqual(byArr, result, byArr.length)); + + short[] shArr = new short[] {1, 2}; + result = (java.lang.Object)asClient.setShort(shArr); + assertTrue(areArraysEqual(shArr, result, shArr.length)); + + int[] iArr = new int[] {1, 2}; + result = (java.lang.Object)asClient.setLong(iArr); + assertTrue(areArraysEqual(iArr, result, iArr.length)); + + long[] lArr = new long[] {1, 2}; + result = (java.lang.Object)asClient.setLongLong(lArr); + assertTrue(areArraysEqual(lArr, result, lArr.length)); + + String[] strArr = new String[] {"Some", "Test"}; + result = (java.lang.Object)asClient.setString(strArr); + assertTrue(areArraysEqual(strArr, result, strArr.length)); + + char[] chArr = new char[] {'A', 'B'}; + result = (java.lang.Object)asClient.setChar(chArr); + assertTrue(areArraysEqual(chArr, result, chArr.length)); + + float[] flArr = new float[] {1, 2}; + result = (java.lang.Object)asClient.setFloat(flArr); + assertTrue(areArraysEqual(flArr, result, flArr.length)); + + double[] dbArr = new double[] {1, 2}; + result = (java.lang.Object)asClient.setDouble(dbArr); + assertTrue(areArraysEqual(dbArr, result, dbArr.length)); + + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + } + + /** + * Tests structures (arguments, return types) + */ + @Test + public void test_TestObject_setStruct() { + try { + TestObject to = new TestObjectServant(); + TestRuntimeComponentService service = new TestRuntimeComponentService(to); + Class javaClass = ((JavaInterface)service.getInterfaceContract().getInterface()).getJavaClass(); + InvocationProxy proxy = new ComponentInvocationProxy(service, service.getRuntimeWire(null), javaClass); + DynaCorbaServant servant = new DynaCorbaServant(proxy, Utils.getTypeId(javaClass)); + String[] ids = new String[] {"IDL:org/apache/tuscany/sca/binding/corba/testing/generated/TestObject:1.0"}; + servant.setIds(ids); + bindServant(servant, "TestObject"); + TestObject testObject = TestObjectHelper.narrow(bindReference("TestObject")); + SomeStruct ss = new SomeStruct(); + SimpleStruct inner = new SimpleStruct(); + inner.field1 = TestConstants.STR_1; + inner.field2 = TestConstants.INT_1; + ss.innerStruct = inner; + ss.str = TestConstants.STR_2; + ss.str_list = TestConstants.STR_ARR_1; + ss.threeDimSeq = TestConstants.INT_ARRAY_3_DIM; + ss.twoDimSeq = TestConstants.INT_ARRAY_2_DIM; + SomeStruct result = testObject.setStruct(ss); + assertTrue(TestConstants.are2DimArraysEqual(result.twoDimSeq, TestConstants.INT_ARRAY_2_DIM)); + assertTrue(TestConstants.are3DimArraysEqual(result.threeDimSeq, TestConstants.INT_ARRAY_3_DIM)); + assertTrue(result.str.equals(ss.str)); + assertTrue(result.innerStruct.field1.equals(ss.innerStruct.field1)); + assertTrue(result.innerStruct.field2 == ss.innerStruct.field2); + assertTrue(areArraysEqual(result.str_list, ss.str_list, ss.str_list.length)); + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + } + + /** + * Tests handling BAD_OPERATION system exception + */ + @Test + public void test_systemException_BAD_OPERATION() { + try { + TestObjectServant tos = new TestObjectServant(); + TestRuntimeComponentService service = new TestRuntimeComponentService(tos); + Class javaClass = ((JavaInterface)service.getInterfaceContract().getInterface()).getJavaClass(); + InvocationProxy proxy = new ComponentInvocationProxy(service, service.getRuntimeWire(null), javaClass); + DynaCorbaServant servant = new DynaCorbaServant(proxy, Utils.getTypeId(javaClass)); + String[] ids = new String[] {"IDL:org/apache/tuscany/sca/binding/corba/testing/generated/TestObject:1.0"}; + servant.setIds(ids); + bindServant(servant, "TestObject"); + DynaCorbaRequest request = + new DynaCorbaRequest(bindReference("TestObject"), "methodThatSurelyDoesNotExist"); + request.invoke(); + fail(); + } catch (Exception e) { + if (e instanceof CorbaException) { + assertTrue(true); + } else { + e.printStackTrace(); + } + } + + try { + InvalidTestObjectServant tos = new InvalidTestObjectServant(); + TestRuntimeComponentService service = new TestRuntimeComponentService(tos); + Class javaClass = ((JavaInterface)service.getInterfaceContract().getInterface()).getJavaClass(); + InvocationProxy proxy = new ComponentInvocationProxy(service, service.getRuntimeWire(null), javaClass); + DynaCorbaServant servant = new DynaCorbaServant(proxy, Utils.getTypeId(javaClass)); + String[] ids = new String[] {"IDL:org/apache/tuscany/sca/binding/corba/testing/generated/TestObject:1.0"}; + servant.setIds(ids); + bindServant(servant, "InvalidTestObject"); + TestObject to = TestObjectHelper.narrow(bindReference("InvalidTestObject")); + SomeStruct str = new SomeStruct(); + str.innerStruct = new SimpleStruct(); + str.innerStruct.field1 = "Whatever"; + str.str = "Whatever"; + str.str_list = new String[] {}; + str.threeDimSeq = new int[][][] {}; + str.twoDimSeq = new int[][] {}; + to.setStruct(str); + } catch (Exception e) { + if (e instanceof BAD_OPERATION) { + assertTrue(true); + } else { + e.printStackTrace(); + } + } + } + + /** + * Tests handling user exceptions + */ + @Test + public void test_userExceptions() { + try { + CalcServant calc = new CalcServant(); + TestRuntimeComponentService service = new TestRuntimeComponentService(calc); + Class javaClass = ((JavaInterface)service.getInterfaceContract().getInterface()).getJavaClass(); + InvocationProxy proxy = new ComponentInvocationProxy(service, service.getRuntimeWire(null), javaClass); + DynaCorbaServant servant = new DynaCorbaServant(proxy, Utils.getTypeId(javaClass)); + String[] ids = {"IDL:org/apache/tuscany/sca/binding/corba/testing/exceptions/Calc:1.0"}; + servant.setIds(ids); + bindServant(servant, "Calc"); + Calc calcClient = CalcHelper.narrow(bindReference("Calc")); + calcClient.div(1, 0); + fail(); + } catch (Exception e) { + if (e instanceof DivByZero) { + assertTrue(true); + } else { + e.printStackTrace(); + fail(); + } + } + + try { + CalcServant calc = new CalcServant(); + TestRuntimeComponentService service = new TestRuntimeComponentService(calc); + Class javaClass = ((JavaInterface)service.getInterfaceContract().getInterface()).getJavaClass(); + InvocationProxy proxy = new ComponentInvocationProxy(service, service.getRuntimeWire(null), javaClass); + DynaCorbaServant servant = new DynaCorbaServant(proxy, Utils.getTypeId(javaClass)); + String[] ids = {"IDL:org/apache/tuscany/sca/binding/corba/testing/exceptions/Calc:1.0"}; + servant.setIds(ids); + bindServant(servant, "Calc"); + Calc calcClient = CalcHelper.narrow(bindReference("Calc")); + calcClient.divForSmallArgs(255, 255); + fail(); + } catch (Exception e) { + if (e instanceof NotSupported) { + assertTrue(true); + } else { + e.printStackTrace(); + fail(); + } + } + } + + /** + * Tests enums (arguments, return types) + */ + @Test + public void test_enums() { + try { + EnumManagerServant ems = new EnumManagerServant(); + TestRuntimeComponentService service = new TestRuntimeComponentService(ems); + Class javaClass = ((JavaInterface)service.getInterfaceContract().getInterface()).getJavaClass(); + InvocationProxy proxy = new ComponentInvocationProxy(service, service.getRuntimeWire(null), javaClass); + DynaCorbaServant servant = new DynaCorbaServant(proxy, Utils.getTypeId(javaClass)); + String[] ids = {"IDL:org/apache/tuscany/sca/binding/corba/testing/enums/EnumManager:1.0"}; + servant.setIds(ids); + bindServant(servant, "Enum"); + EnumManager em = EnumManagerHelper.narrow(bindReference("Enum")); + Color color = Color.red; + assertTrue(em.getColor(color).value() == color.value()); + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + } + + @Test + public void test_nonCorbaServants() { + try { + NonCorbaServant ncs = new NonCorbaServant(); + TestRuntimeComponentService service = new TestRuntimeComponentService(ncs); + Class javaClass = ((JavaInterface)service.getInterfaceContract().getInterface()).getJavaClass(); + InvocationProxy proxy = new ComponentInvocationProxy(service, service.getRuntimeWire(null), javaClass); + DynaCorbaServant servant = new DynaCorbaServant(proxy, Utils.getTypeId(javaClass)); + bindServant(servant, "NonCorbaServant"); + // it's non corba servant so we don't have stubs to test them + DynaCorbaRequest request = new DynaCorbaRequest(bindReference("NonCorbaServant"), "setString"); + request.addArgument(TestConstants.STR_1); + request.setOutputType(String.class); + DynaCorbaResponse response = request.invoke(); + assertTrue(response.getContent().equals(TestConstants.STR_1)); + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + + try { + NonCorbaServant ncs = new NonCorbaServant(); + TestRuntimeComponentService service = new TestRuntimeComponentService(ncs); + Class javaClass = ((JavaInterface)service.getInterfaceContract().getInterface()).getJavaClass(); + InvocationProxy proxy = new ComponentInvocationProxy(service, service.getRuntimeWire(null), javaClass); + DynaCorbaServant servant = new DynaCorbaServant(proxy, Utils.getTypeId(javaClass)); + bindServant(servant, "NonCorbaServant"); + // it's non corba servant so we don't have stubs to test them + DynaCorbaRequest request = new DynaCorbaRequest(bindReference("NonCorbaServant"), "throwException"); + request.addExceptionType(NonCorbaException.class); + request.invoke(); + fail(); + } catch (Exception e) { + if (e instanceof NonCorbaException) { + assertTrue(true); + } else { + e.printStackTrace(); + fail(); + } + } + } + + /** + * Tests handling BAD_PARAM system exception + */ + @Test + public void test_systemException_BAD_PARAM() { + try { + CalcServant calc = new CalcServant(); + TestRuntimeComponentService service = new TestRuntimeComponentService(calc); + Class javaClass = ((JavaInterface)service.getInterfaceContract().getInterface()).getJavaClass(); + InvocationProxy proxy = new ComponentInvocationProxy(service, service.getRuntimeWire(null), javaClass); + DynaCorbaServant servant = new DynaCorbaServant(proxy, Utils.getTypeId(javaClass)); + String[] ids = new String[] {"IDL:org/apache/tuscany/sca/binding/corba/testing/generated/TestObject:1.0"}; + servant.setIds(ids); + bindServant(servant, "Calc"); + DynaCorbaRequest request = new DynaCorbaRequest(bindReference("Calc"), "div"); + request.addArgument(2d); + request.setOutputType(double.class); + request.invoke(); + fail(); + } catch (Exception e) { + if (e instanceof CorbaException) { + assertTrue(true); + } else { + e.printStackTrace(); + fail(); + } + } + } + + /** + * Tests handling BAD_PARAM system exception + */ + @Test + public void test_invalidServantConfiguraion() { + try { + InvalidTypesServant its = new InvalidTypesServant(); + TestRuntimeComponentService service = new TestRuntimeComponentService(its); + //expecting exception... + Class javaClass = ((JavaInterface)service.getInterfaceContract().getInterface()).getJavaClass(); + InvocationProxy proxy = new ComponentInvocationProxy(service, service.getRuntimeWire(null), javaClass); + new DynaCorbaServant(proxy, Utils.getTypeId(javaClass)); + fail(); + } catch (Exception e) { + if (e instanceof RequestConfigurationException) { + assertTrue(true); + } else { + e.printStackTrace(); + fail(); + } + } + } + + /** + * Tests serving CORBA arrays by Tuscany CORBA servants + */ + @Test + public void test_arraysPassing() { + try { + ArraysUnionsTuscanyServant arraysUnions = new ArraysUnionsTuscanyServant(); + TestRuntimeComponentService service = new TestRuntimeComponentService(arraysUnions); + Class javaClass = ((JavaInterface)service.getInterfaceContract().getInterface()).getJavaClass(); + InvocationProxy proxy = new ComponentInvocationProxy(service, service.getRuntimeWire(null), javaClass); + DynaCorbaServant servant = new DynaCorbaServant(proxy, Utils.getTypeId(javaClass)); + String[] ids = new String[] {"IDL:org/apache/tuscany/sca/binding/corba/testing/arrays_unions/ArraysUnionsTests:1.0"}; + servant.setIds(ids); + bindServant(servant, "ArraysUnions"); + Object reference = bindReference("ArraysUnions"); + ArraysUnionsTests objRef = ArraysUnionsTestsHelper.narrow(reference); + String[][] stringArray = {{"Hello", "World"}, {"Hi", "Again"}}; + String[][] result = objRef.passStringArray(stringArray); + for (int i = 0; i < stringArray.length; i++) { + for (int j = 0; j < stringArray[i].length; j++) { + assertEquals(stringArray[i][j], result[i][j]); + } + } + TestStruct struct = new TestStruct(); + String[] field1 = {"Hello", "World"}; + int[][] field2 = { {4, 2, 2, 5}, {6, 12, 5, 8}}; + float[][][] field3 = { { {2, 6}, {2, 7}, {9, 3}, {4, 6}}, { {3, 7}, {6, 6}, {3, 5}, {6, 2}}}; + struct.oneDimArray = field1; + struct.twoDimArray = field2; + struct.threeDimArray = field3; + + TestStruct structResult = objRef.passTestStruct(struct); + for (int i = 0; i < struct.oneDimArray.length; i++) { + assertEquals(struct.oneDimArray[i], structResult.oneDimArray[i]); + } + for (int i = 0; i < struct.twoDimArray.length; i++) { + for (int j = 0; j < struct.twoDimArray[i].length; j++) { + assertEquals(struct.twoDimArray[i][j], structResult.twoDimArray[i][j]); + } + } + for (int i = 0; i < struct.threeDimArray.length; i++) { + for (int j = 0; j < struct.threeDimArray[i].length; j++) { + for (int k = 0; k < struct.threeDimArray[i][j].length; k++) { + assertEquals(struct.threeDimArray[i][j][k], structResult.threeDimArray[i][j][k], 0.0); + } + } + } + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/CorbaTypesTestCase.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/CorbaTypesTestCase.java new file mode 100644 index 0000000000..1b1754f347 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/CorbaTypesTestCase.java @@ -0,0 +1,841 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Array; + +import junit.framework.Assert; + +import org.apache.tuscany.sca.binding.corba.provider.exceptions.CorbaException; +import org.apache.tuscany.sca.binding.corba.provider.exceptions.RequestConfigurationException; +import org.apache.tuscany.sca.binding.corba.provider.reference.DynaCorbaRequest; +import org.apache.tuscany.sca.binding.corba.provider.reference.DynaCorbaResponse; +import org.apache.tuscany.sca.binding.corba.testing.enums.Color; +import org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.DivByZero; +import org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.NotSupported; +import org.apache.tuscany.sca.binding.corba.testing.generated.SimpleStruct; +import org.apache.tuscany.sca.binding.corba.testing.generated.SomeStruct; +import org.apache.tuscany.sca.binding.corba.testing.hierarchy.ArraysTestStruct; +import org.apache.tuscany.sca.binding.corba.testing.hierarchy.DummyObject; +import org.apache.tuscany.sca.binding.corba.testing.hierarchy.InnerUnion; +import org.apache.tuscany.sca.binding.corba.testing.hierarchy.InvalidCorbaArray; +import org.apache.tuscany.sca.binding.corba.testing.hierarchy.InvalidEnum1; +import org.apache.tuscany.sca.binding.corba.testing.hierarchy.InvalidEnum2; +import org.apache.tuscany.sca.binding.corba.testing.hierarchy.InvalidEnum3; +import org.apache.tuscany.sca.binding.corba.testing.hierarchy.InvalidStruct1; +import org.apache.tuscany.sca.binding.corba.testing.hierarchy.InvalidStruct2; +import org.apache.tuscany.sca.binding.corba.testing.hierarchy.InvalidStruct3; +import org.apache.tuscany.sca.binding.corba.testing.hierarchy.InvalidUnion1; +import org.apache.tuscany.sca.binding.corba.testing.hierarchy.InvalidUnion2; +import org.apache.tuscany.sca.binding.corba.testing.hierarchy.InvalidUnion3; +import org.apache.tuscany.sca.binding.corba.testing.hierarchy.InvalidUnion4; +import org.apache.tuscany.sca.binding.corba.testing.hierarchy.InvalidUnion5; +import org.apache.tuscany.sca.binding.corba.testing.hierarchy.RichUnion; +import org.apache.tuscany.sca.binding.corba.testing.servants.ArraysSetterServant; +import org.apache.tuscany.sca.binding.corba.testing.servants.ArraysUnionsServant; +import org.apache.tuscany.sca.binding.corba.testing.servants.ArraysUnionsTuscanyServant; +import org.apache.tuscany.sca.binding.corba.testing.servants.CalcServant; +import org.apache.tuscany.sca.binding.corba.testing.servants.EnumManagerServant; +import org.apache.tuscany.sca.binding.corba.testing.servants.ObjectManagerServant; +import org.apache.tuscany.sca.binding.corba.testing.servants.PrimitivesSetterServant; +import org.apache.tuscany.sca.binding.corba.testing.servants.TestObjectServant; +import org.apache.tuscany.sca.host.corba.naming.TransientNameServer; +import org.apache.tuscany.sca.host.corba.naming.TransientNameService; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.omg.CORBA.ORB; +import org.omg.CORBA.Object; +import org.omg.CosNaming.NameComponent; +import org.omg.CosNaming.NamingContext; +import org.omg.CosNaming.NamingContextExt; +import org.omg.CosNaming.NamingContextExtHelper; +import org.omg.CosNaming.NamingContextHelper; + +/** + * @version $Rev$ $Date$ + * Tests API for dynamic CORBA requests. Tests handling various Java + * types. + */ +public class CorbaTypesTestCase { + private static TransientNameServer server; + private static ORB orb; + + private static Object refPrimitivesSetter; + private static Object refArraysSetter; + private static Object refTestObject; + private static Object refCalcObject; + private static Object refObjectManager; + private static Object refEnumManager; + private static Object refArraysUnions; + + /** + * Spawns tnameserv process (must be in PATH). Initializes test servants and + * stores it's references so tests can use it. + */ + @BeforeClass + public static void setUp() { + try { + try { + server = + new TransientNameServer(TestConstants.TEST1_HOST, TestConstants.TEST1_PORT, + TransientNameService.DEFAULT_SERVICE_NAME); + Thread t = server.start(); + if (t == null) { + Assert.fail("The naming server cannot be started"); + } + orb = server.getORB(); + } catch (Throwable e) { + e.printStackTrace(); + Assert.fail(e.getMessage()); + } + + Object nameService = orb.resolve_initial_references("NameService"); + NamingContext namingContext = NamingContextHelper.narrow(nameService); + + PrimitivesSetterServant singleSetter = new PrimitivesSetterServant(); + ArraysSetterServant arraysSetter = new ArraysSetterServant(); + TestObjectServant complexObject = new TestObjectServant(); + CalcServant calcObject = new CalcServant(); + ObjectManagerServant objectManager = new ObjectManagerServant(); + EnumManagerServant enumManager = new EnumManagerServant(); + ArraysUnionsServant arraysUnions = new ArraysUnionsServant(); + + orb.connect(singleSetter); + orb.connect(arraysSetter); + + NameComponent nc; + NameComponent[] path; + + nc = new NameComponent("PrimitivesSetter", ""); + path = new NameComponent[] {nc}; + namingContext.rebind(path, singleSetter); + + nc = new NameComponent("ArraysSetter", ""); + path = new NameComponent[] {nc}; + namingContext.rebind(path, arraysSetter); + + nc = new NameComponent("TestObject", ""); + path = new NameComponent[] {nc}; + namingContext.rebind(path, complexObject); + + nc = new NameComponent("CalcObject", ""); + path = new NameComponent[] {nc}; + namingContext.rebind(path, calcObject); + + nc = new NameComponent("ObjectManager", ""); + path = new NameComponent[] {nc}; + namingContext.rebind(path, objectManager); + + nc = new NameComponent("EnumManager", ""); + path = new NameComponent[] {nc}; + namingContext.rebind(path, enumManager); + + nc = new NameComponent("ArraysUnions", ""); + path = new NameComponent[] {nc}; + namingContext.rebind(path, arraysUnions); + + NamingContextExt nce = NamingContextExtHelper.narrow(orb.resolve_initial_references("NameService")); + + refArraysSetter = nce.resolve(nce.to_name("ArraysSetter")); + refPrimitivesSetter = nce.resolve(nce.to_name("PrimitivesSetter")); + refTestObject = nce.resolve(nce.to_name("TestObject")); + refCalcObject = nce.resolve(nce.to_name("CalcObject")); + refObjectManager = nce.resolve(nce.to_name("ObjectManager")); + refEnumManager = nce.resolve(nce.to_name("EnumManager")); + refArraysUnions = nce.resolve(nce.to_name("ArraysUnions")); + + } catch (Exception e) { + e.printStackTrace(); + } + } + + @AfterClass + public static void stop() { + server.stop(); + } + + /** + * Tests remote operation, basing on given reference, operation name, + * arguments, expected return type and content + * + * @param ref remote object + * @param operationName operation to invoke + * @param clazz expected return type + * @param arguments array of operation arguments + * @param equalTo expected return content + */ + private void dynaTestInvoker(Object ref, + String operationName, + Class clazz, + java.lang.Object[] arguments, + java.lang.Object equalTo) { + + try { + DynaCorbaRequest request = new DynaCorbaRequest(ref, operationName); + request.setOutputType(clazz); + for (int i = 0; arguments != null && i < arguments.length; i++) { + request.addArgument(arguments[i]); + } + + DynaCorbaResponse response = request.invoke(); + java.lang.Object content = (java.lang.Object)response.getContent(); + assertTrue(content.getClass().equals(clazz)); + if (equalTo != null && equalTo.getClass().isArray()) { + for (int i = 0; i < Array.getLength(equalTo); i++) { + assertTrue(Array.get(content, i).equals(Array.get(equalTo, i))); + } + } else { + assertTrue(content.equals(equalTo)); + } + } catch (Exception e) { + e.printStackTrace(); + fail("Error while invoking " + operationName); + } + } + + /** + * Tests passing (and getting as result) varied primitives + */ + @Test + public void test_setPrimitives() { + + dynaTestInvoker(refPrimitivesSetter, "setBoolean", Boolean.class, new Boolean[] {true}, true); + dynaTestInvoker(refPrimitivesSetter, "setOctet", Byte.class, new Byte[] {1}, (byte)1); + dynaTestInvoker(refPrimitivesSetter, "setChar", Character.class, new Character[] {'A'}, 'A'); + dynaTestInvoker(refPrimitivesSetter, "setShort", Short.class, new Short[] {1}, (short)1); + dynaTestInvoker(refPrimitivesSetter, "setLong", Integer.class, new Integer[] {1}, (int)1); + dynaTestInvoker(refPrimitivesSetter, "setLongLong", Long.class, new Long[] {(long)1}, (long)1); + dynaTestInvoker(refPrimitivesSetter, "setFloat", Float.class, new Float[] {(float)1}, (float)1); + dynaTestInvoker(refPrimitivesSetter, "setDouble", Double.class, new Double[] {(double)1}, (double)1); + dynaTestInvoker(refPrimitivesSetter, "setString", String.class, new String[] {"1"}, "1"); + + } + + /** + * Tests passing (and getting as result) varied types sequences + */ + @Test + public void test_setArrays() { + + dynaTestInvoker(refArraysSetter, + "setBoolean", + Boolean[].class, + new Boolean[][] {new Boolean[] {false, true}}, + new Boolean[] {false, true}); + + dynaTestInvoker(refArraysSetter, + "setChar", + Character[].class, + new Character[][] {new Character[] {'A', 'B'}}, + new Character[] {'A', 'B'}); + + dynaTestInvoker(refArraysSetter, "setOctet", Byte[].class, new Byte[][] {new Byte[] {1, 2}}, new Byte[] {1, 2}); + + dynaTestInvoker(refArraysSetter, "setShort", Short[].class, new Short[][] {new Short[] {1, 2}}, new Short[] {1, + 2}); + + dynaTestInvoker(refArraysSetter, + "setLong", + Integer[].class, + new Integer[][] {new Integer[] {1, 2}}, + new Integer[] {1, 2}); + + dynaTestInvoker(refArraysSetter, + "setLongLong", + Long[].class, + new Long[][] {new Long[] {new Long(1), new Long(2)}}, + new Long[] {new Long(1), new Long(2)}); + + dynaTestInvoker(refArraysSetter, + "setFloat", + Float[].class, + new Float[][] {new Float[] {new Float(1.0), new Float(2.0)}}, + new Float[] {new Float(1.0), new Float(2.0)}); + + dynaTestInvoker(refArraysSetter, + "setDouble", + Double[].class, + new Double[][] {new Double[] {new Double(1.0), new Double(2.0)}}, + new Double[] {new Double(1.0), new Double(2.0)}); + + dynaTestInvoker(refArraysSetter, + "setString", + String[].class, + new String[][] {new String[] {"A", "B"}}, + new String[] {"A", "B"}); + + } + + /** + * Tests passing (and getting as result) complex structure + */ + @Test + public void test_TestObject_setStruct() { + DynaCorbaRequest request = new DynaCorbaRequest(refTestObject, "setStruct"); + + SomeStruct struct = new SomeStruct(); + SimpleStruct inner = new SimpleStruct(); + inner.field1 = TestConstants.STR_1; + inner.field2 = TestConstants.INT_1; + struct.innerStruct = inner; + struct.str_list = TestConstants.STR_ARR_2; + struct.twoDimSeq = TestConstants.INT_ARRAY_2_DIM; + struct.threeDimSeq = TestConstants.INT_ARRAY_3_DIM; + struct.str = TestConstants.STR_1; + + try { + request.addArgument(struct); + request.setOutputType(SomeStruct.class); + DynaCorbaResponse response = request.invoke(); + SomeStruct result = (SomeStruct)response.getContent(); + assertTrue(TestConstants.are2DimArraysEqual(result.twoDimSeq, TestConstants.INT_ARRAY_2_DIM)); + assertTrue(TestConstants.are3DimArraysEqual(result.threeDimSeq, TestConstants.INT_ARRAY_3_DIM)); + assertEquals(TestConstants.STR_1, result.str); + assertEquals(TestConstants.STR_ARR_2[0], result.str_list[0]); + assertEquals(TestConstants.STR_ARR_2[1], result.str_list[1]); + assertEquals(TestConstants.STR_1, result.innerStruct.field1); + assertEquals(TestConstants.INT_1, result.innerStruct.field2); + } catch (Exception e) { + e.printStackTrace(); + fail("Exception occured during tests: " + e); + } + } + + /** + * Test passing (and getting as result) simple two-field structure + */ + @Test + public void test_TestObject_setSimpleStruct() { + SimpleStruct struct = new SimpleStruct(); + struct.field1 = TestConstants.STR_1; + struct.field2 = TestConstants.INT_1; + DynaCorbaRequest request = new DynaCorbaRequest(refTestObject, "setSimpleStruct"); + try { + request.setOutputType(SimpleStruct.class); + request.addArgument(struct); + DynaCorbaResponse response = request.invoke(); + SimpleStruct retStruct = (SimpleStruct)response.getContent(); + assertTrue(retStruct.field1.equals(struct.field1) && retStruct.field2 == struct.field2); + } catch (Exception e) { + e.printStackTrace(); + fail("Exception occured during tests: " + e); + } + } + + /** + * Tests passing (and getting as result) two dim. sequence of long. + */ + @Test + public void test_TestObject_setLongSeq2() { + int[][] arr1 = new int[2][2]; + for (int i = 0; i < 2; i++) { + for (int j = 0; j < 2; j++) { + arr1[i][j] = (int)(Math.random() * 1000); + } + } + DynaCorbaRequest request = new DynaCorbaRequest(refTestObject, "setLongSeq2"); + try { + request.setOutputType(arr1.getClass()); + request.addArgument(arr1); + DynaCorbaResponse response = request.invoke(); + int[][] arr2 = (int[][])response.getContent(); + for (int i = 0; i < 2; i++) { + for (int j = 0; j < 2; j++) { + assertEquals(arr1[i][j], arr2[i][j]); + } + } + } catch (Exception e) { + e.printStackTrace(); + fail("Exception occured during tests: " + e); + } + } + + /** + * Tests passing multiple complex attributes. + */ + @Test + public void test_TestObject_pickStructFromArgs() { + SomeStruct arg1 = new SomeStruct(); + SomeStruct arg2 = new SomeStruct(); + SomeStruct arg3 = new SomeStruct(); + + SimpleStruct inner = new SimpleStruct(); + inner.field1 = TestConstants.STR_1; + inner.field2 = TestConstants.INT_1; + + arg1.innerStruct = inner; + arg2.innerStruct = inner; + arg3.innerStruct = inner; + + arg1.str = TestConstants.STR_1; + arg2.str = TestConstants.STR_2; + arg3.str = TestConstants.STR_3; + + arg1.str_list = TestConstants.STR_ARR_1; + arg2.str_list = TestConstants.STR_ARR_2; + arg3.str_list = TestConstants.STR_ARR_2; + + arg1.threeDimSeq = TestConstants.INT_ARRAY_3_DIM; + arg2.threeDimSeq = TestConstants.INT_ARRAY_3_DIM; + arg3.threeDimSeq = TestConstants.INT_ARRAY_3_DIM; + + arg1.twoDimSeq = TestConstants.INT_ARRAY_2_DIM; + arg2.twoDimSeq = TestConstants.INT_ARRAY_2_DIM; + arg3.twoDimSeq = TestConstants.INT_ARRAY_2_DIM; + + DynaCorbaRequest request = new DynaCorbaRequest(refTestObject, "pickStructFromArgs"); + try { + + request.setOutputType(SomeStruct.class); + request.addArgument(arg1); + request.addArgument(arg2); + request.addArgument(arg3); + request.addArgument(1); + DynaCorbaResponse response = request.invoke(); + SomeStruct result = (SomeStruct)response.getContent(); + + // just make sure that servant returned right structure + assertTrue(result.str.equals(TestConstants.STR_1)); + } catch (Exception e) { + fail("Exception occured during tests " + e); + e.printStackTrace(); + } + + } + + /** + * Tests handling user defined remote exception (single declared) + */ + @Test + public void test_singleException() { + DynaCorbaRequest request1 = new DynaCorbaRequest(refCalcObject, "div"); + try { + request1.addArgument(2d); + request1.addArgument(2d); + request1.setOutputType(Double.class); + request1.addExceptionType(DivByZero.class); + request1.invoke(); + } catch (Exception e) { + fail(); + } + + DynaCorbaRequest request2 = new DynaCorbaRequest(refCalcObject, "div"); + try { + request2.addArgument(2d); + request2.addArgument(0d); + request2.setOutputType(Double.class); + request2.addExceptionType(DivByZero.class); + request2.invoke(); + } catch (DivByZero e) { + assertTrue(e.info != null && e.arguments != null && e.arguments.arg1 == 2 && e.arguments.arg2 == 0); + } catch (Exception exc) { + exc.printStackTrace(); + fail(); + } + } + + /** + * Tests handling user defined multiple exceptions + */ + @Test + public void test_multipleExceptions() { + DynaCorbaRequest request = new DynaCorbaRequest(refCalcObject, "divForSmallArgs"); + try { + request.addArgument(101d); + request.addArgument(101d); + request.setOutputType(Double.class); + request.addExceptionType(DivByZero.class); + request.addExceptionType(NotSupported.class); + request.invoke(); + } catch (Exception e) { + assertTrue(e instanceof NotSupported); + } + } + + /** + * Tests handling exceptions while user defined no exceptions + */ + @Test + public void test_noExceptionsDeclared() { + DynaCorbaRequest request = new DynaCorbaRequest(refCalcObject, "div"); + try { + request.addArgument(1d); + request.addArgument(0d); + request.setOutputType(Double.class); + request.invoke(); + fail(); + } catch (Exception e) { + assertTrue(e instanceof RequestConfigurationException); + } + } + + /** + * Tests handling exceptions while user defined no such exception + */ + @Test + public void test_noSuchExceptionDeclared() { + DynaCorbaRequest request = new DynaCorbaRequest(refCalcObject, "div"); + try { + request.addArgument(1d); + request.addArgument(0d); + request.addExceptionType(NotSupported.class); + request.setOutputType(Double.class); + request.invoke(); + fail(); + } catch (Exception e) { + assertTrue(e instanceof RequestConfigurationException); + } + } + + /** + * Tests handling non existing operation situation + */ + @Test + public void test_systemException_BAD_OPERATION() { + DynaCorbaRequest request = new DynaCorbaRequest(refCalcObject, "thisOperationSurelyDoesNotExist"); + try { + request.invoke(); + fail(); + } catch (Exception e) { + assertTrue(e instanceof CorbaException); + } + } + + /** + * Tests obtaining references to other objects and using them with specified + * user interface + */ + @Test + @Ignore("Cause of tnameservice hang on stop") + public void test_enchancedReferences() { + DynaCorbaRequest request = null; + try { + request = new DynaCorbaRequest(refObjectManager, "getDummyObject"); + request.setOutputType(DummyObject.class); + DynaCorbaResponse response = request.invoke(); + DummyObject dummy = (DummyObject)response.getContent(); + DummyObject dummy2 = dummy.cloneObject(); + dummy2.cloneObject(); + assertNotSame(dummy.getLong(), dummy2.getLong()); + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + } + + /** + * Test passing enums as arguments and retrieving them as a result + */ + @Test + public void test_enums() { + try { + DynaCorbaRequest request = new DynaCorbaRequest(refEnumManager, "getColor"); + Color color = Color.green; + request.addArgument(color); + request.setOutputType(Color.class); + DynaCorbaResponse response = request.invoke(); + Color result = (Color)response.getContent(); + assertEquals(color.value(), result.value()); + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + } + + /** + * Tests recognizing structures + */ + @Test + public void test_structValidation() { + DynaCorbaRequest request = null; + try { + request = new DynaCorbaRequest(refArraysSetter, "whatever"); + request.setOutputType(InvalidStruct1.class); + fail(); + } catch (Exception e) { + assertTrue(e instanceof RequestConfigurationException); + } + + try { + request = new DynaCorbaRequest(refArraysSetter, "whatever"); + request.setOutputType(InvalidStruct2.class); + fail(); + } catch (Exception e) { + assertTrue(e instanceof RequestConfigurationException); + } + + try { + request = new DynaCorbaRequest(refArraysSetter, "whatever"); + request.setOutputType(InvalidStruct3.class); + fail(); + } catch (Exception e) { + assertTrue(e instanceof RequestConfigurationException); + } + + try { + request = new DynaCorbaRequest(refArraysSetter, "whatever"); + request.setOutputType(SomeStruct.class); + } catch (Exception e) { + fail(); + } + } + + /** + * Tests recognizing enums + */ + @Test + public void test_enumValidation() { + DynaCorbaRequest request = null; + try { + request = new DynaCorbaRequest(refArraysSetter, "whatever"); + request.setOutputType(InvalidEnum1.class); + fail(); + } catch (Exception e) { + assertTrue(e instanceof RequestConfigurationException); + } + + try { + request = new DynaCorbaRequest(refArraysSetter, "whatever"); + request.setOutputType(InvalidEnum2.class); + fail(); + } catch (Exception e) { + assertTrue(e instanceof RequestConfigurationException); + } + + try { + request = new DynaCorbaRequest(refArraysSetter, "whatever"); + request.setOutputType(InvalidEnum3.class); + fail(); + } catch (Exception e) { + assertTrue(e instanceof RequestConfigurationException); + } + + try { + request = new DynaCorbaRequest(refArraysSetter, "whatever"); + request.setOutputType(Color.class); + } catch (Exception e) { + fail(); + } + } + + /** + * Tests handling passing wrong params + */ + @Test + public void test_systemException_BAD_PARAM() { + try { + DynaCorbaRequest request = new DynaCorbaRequest(refCalcObject, "div"); + request.setOutputType(Double.class); + request.addArgument(3d); + request.invoke(); + fail(); + } catch (Exception e) { + if (e instanceof CorbaException) { + assertTrue(true); + } else { + e.printStackTrace(); + fail(); + } + } + } + + /** + * Tests passing CORBA arrays + */ + @Test + public void test_arraysPassing() { + try { + DynaCorbaRequest request = new DynaCorbaRequest(refArraysUnions, "passStringArray"); + Annotation[] notes = + ArraysUnionsTuscanyServant.class.getMethod("passStringArray", new Class[] {String[][].class}) + .getAnnotations(); + request.setOutputType(String[][].class, notes); + String[][] argument = { {"Hello", "World"}, {"Hi", "again"}}; + request.addArgument(argument, notes); + DynaCorbaResponse response = request.invoke(); + String[][] result = (String[][])response.getContent(); + for (int i = 0; i < argument.length; i++) { + for (int j = 0; j < argument[i].length; j++) { + assertEquals(argument[i][j], result[i][j]); + } + } + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + + try { + DynaCorbaRequest request = new DynaCorbaRequest(refArraysUnions, "passTestStruct"); + ArraysTestStruct arg = new ArraysTestStruct(); + String[] field1 = {"Hello", "World"}; + arg.field1 = field1; + int[][] field2 = { {4, 2, 2, 5}, {6, 12, 5, 8}}; + arg.field2 = field2; + float[][][] field3 = { { {2, 6}, {2, 7}, {9, 3}, {4, 6}}, { {3, 7}, {6, 6}, {3, 5}, {6, 2}}}; + arg.field3 = field3; + request.addArgument(arg); + request.setOutputType(ArraysTestStruct.class); + DynaCorbaResponse response = request.invoke(); + ArraysTestStruct result = (ArraysTestStruct)response.getContent(); + for (int i = 0; i < arg.field1.length; i++) { + assertEquals(arg.field1[i], result.field1[i]); + } + for (int i = 0; i < arg.field2.length; i++) { + for (int j = 0; j < arg.field2[i].length; j++) { + assertEquals(arg.field2[i][j], result.field2[i][j]); + } + } + for (int i = 0; i < arg.field2.length; i++) { + for (int j = 0; j < arg.field2[i].length; j++) { + for (int k = 0; k < arg.field3[i][j].length; k++) { + assertEquals(arg.field3[i][j][k], result.field3[i][j][k], 0.0); + } + } + } + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + } + + /** + * Tests situation when CORBA array dimension size doesn't match + * CORBA array annotation arguments (which sets dimension lengths) + */ + @Test + public void test_invalidArrayAnnotationSize() { + try { + DynaCorbaRequest request = new DynaCorbaRequest(refArraysUnions, "passStringArray"); + Annotation[] notes = + ArraysUnionsTuscanyServant.class.getMethod("passStringArray", new Class[] {String[][].class}) + .getAnnotations(); + request.setOutputType(String[][][].class, notes); + fail(); + } catch (RequestConfigurationException e) { + // expected + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + try { + DynaCorbaRequest request = new DynaCorbaRequest(refArraysUnions, "passStringArray"); + Annotation[] notes = + ArraysUnionsTuscanyServant.class.getMethod("passStringArray", new Class[] {String[][].class}) + .getAnnotations(); + request.addArgument(new String[0][0][0], notes); + fail(); + } catch (RequestConfigurationException e) { + // expected + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + try { + DynaCorbaRequest request = new DynaCorbaRequest(refArraysUnions, "passStringArray"); + request.addArgument(new InvalidCorbaArray(), null); + fail(); + } catch (RequestConfigurationException e) { + // expected + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + } + + /** + * Tests passing CORBA unions + */ + @Test + public void test_passingUnions() { + try { + DynaCorbaRequest request = new DynaCorbaRequest(refArraysUnions, "passRichUnion"); + request.setOutputType(RichUnion.class); + RichUnion arg = new RichUnion(); + InnerUnion argIu = new InnerUnion(); + argIu.setX(10); + arg.setIu(argIu); + request.addArgument(arg); + DynaCorbaResponse response = request.invoke(); + RichUnion result = (RichUnion)response.getContent(); + assertEquals(arg.getIu().getX(), result.getIu().getX()); + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + try { + DynaCorbaRequest request = new DynaCorbaRequest(refArraysUnions, "passRichUnion"); + request.setOutputType(RichUnion.class); + RichUnion arg = new RichUnion(); + arg.setDef(true); + request.addArgument(arg); + DynaCorbaResponse response = request.invoke(); + RichUnion result = (RichUnion)response.getContent(); + assertEquals(arg.isDef(), result.isDef()); + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + } + + /** + * Tests handling invalid union declarations + */ + @Test + public void test_testInvalidUnionClasses() { + try { + DynaCorbaRequest request = new DynaCorbaRequest(refArraysUnions, "whatever"); + request.setOutputType(InvalidUnion1.class); + } catch (Exception e) { + assertEquals(RequestConfigurationException.class, e.getClass()); + } + try { + DynaCorbaRequest request = new DynaCorbaRequest(refArraysUnions, "whatever"); + request.setOutputType(InvalidUnion2.class); + } catch (Exception e) { + assertEquals(RequestConfigurationException.class, e.getClass()); + } + try { + DynaCorbaRequest request = new DynaCorbaRequest(refArraysUnions, "whatever"); + request.setOutputType(InvalidUnion3.class); + } catch (Exception e) { + assertEquals(RequestConfigurationException.class, e.getClass()); + } + try { + DynaCorbaRequest request = new DynaCorbaRequest(refArraysUnions, "whatever"); + request.setOutputType(InvalidUnion4.class); + } catch (Exception e) { + assertEquals(RequestConfigurationException.class, e.getClass()); + } + try { + DynaCorbaRequest request = new DynaCorbaRequest(refArraysUnions, "whatever"); + request.setOutputType(InvalidUnion5.class); + } catch (Exception e) { + assertEquals(RequestConfigurationException.class, e.getClass()); + } + } +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/MappingTestInterface.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/MappingTestInterface.java new file mode 100644 index 0000000000..f0dccd9e7e --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/MappingTestInterface.java @@ -0,0 +1,46 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing; + +/** + * @version $Rev$ $Date$ + * Interface that can be tested for operations mapping + */ +public interface MappingTestInterface { + + int getIntField(); + + void setIntField(int intField); + + boolean isBoolField(); + + void setBoolField(boolean boolField); + + void overloadedName(); + + void overloadedName(String arg1); + + void overloadedName(String arg1, int arg2); + + void caseCollision(); + + void CaseCollision(); + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/MethodFinderTestCase.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/MethodFinderTestCase.java new file mode 100644 index 0000000000..6975c62ddb --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/MethodFinderTestCase.java @@ -0,0 +1,70 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import java.lang.reflect.Method; + +import org.apache.tuscany.sca.binding.corba.provider.util.MethodFinder; +import org.junit.Test; + +/** + * @version $Rev$ $Date$ + * Various tests for MethodFinder + */ +public class MethodFinderTestCase { + + /** + * Tests finding existing methods + */ + @Test + public void test_findExistingMethod() { + try { + String methodName = "rotateLeft"; + Method sample = Integer.class.getMethod(methodName, new Class[] {int.class, int.class}); + Method m1 = MethodFinder.findMethod(Integer.class, methodName, new Class[] {int.class, int.class}); + Method m2 = + MethodFinder.findMethod(Integer.class, methodName, new Class[] {Integer.class, Integer.class}); + assertEquals(sample, m1); + assertEquals(sample, m2); + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + } + + /** + * Tests null result value for not existing method + */ + @Test + public void test_findNotExistingMethod() { + try { + String methodName = "rotateLeft"; + Method method = MethodFinder.findMethod(Integer.class, methodName, new Class[] {}); + assertEquals(null, method); + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/OperationMappingTestCase.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/OperationMappingTestCase.java new file mode 100644 index 0000000000..4767728db7 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/OperationMappingTestCase.java @@ -0,0 +1,67 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing; + +import static org.junit.Assert.assertEquals; + +import java.lang.reflect.Method; +import java.util.Map; + +import org.apache.tuscany.sca.binding.corba.provider.util.OperationMapper; +import org.junit.Test; + +/** + * @version $Rev$ $Date$ + * Various tests for OperationsMapping + */ +public class OperationMappingTestCase { + + /** + * Tests if Java2IDLUtil maps methods to operations correctly + */ + @Test + public void test_mappingRules() { + Map met2op = OperationMapper.mapMethodToOperationName(MappingTestInterface.class); + for (Method method : met2op.keySet()) { + String name = method.getName(); + String translatedName = met2op.get(method); + if (name.equals("getIntField")) { + assertEquals("_get_intField", translatedName); + } else if (name.equals("setIntField")) { + assertEquals("_set_intField", translatedName); + } else if (name.equals("isBoolField")) { + assertEquals("_get_boolField", translatedName); + } else if (name.equals("setBoolField")) { + assertEquals("_set_boolField", translatedName); + } else if (name.equals("overloadedName") && method.getParameterTypes().length == 0) { + assertEquals("overloadedName__", translatedName); + } else if (name.equals("overloadedName") && method.getParameterTypes().length == 1) { + assertEquals("overloadedName__CORBA_WStringValue", translatedName); + } else if (name.equals("overloadedName") && method.getParameterTypes().length == 2) { + assertEquals("overloadedName__CORBA_WStringValue__long", translatedName); + } else if (name.equals("caseCollision")) { + assertEquals("caseCollision_4", translatedName); + } else if (name.equals("CaseCollision")) { + assertEquals("CaseCollision_0_4", translatedName); + } + } + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/TestConstants.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/TestConstants.java new file mode 100644 index 0000000000..962a00d002 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/TestConstants.java @@ -0,0 +1,87 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing; + +/** + * Some constants and utilities for module tests + * @version $Rev$ $Date$ + */ +public class TestConstants { + + public static final String STR_1 = "Hello world!"; + public static final String STR_2 = "2nd string"; + public static final String STR_3 = "Other string"; + public static final String[] STR_ARR_1 = {"Hello", "World"}; + public static final String[] STR_ARR_2 = {"Another", "string", "array"}; + public static final int INT_1 = 0; + + public static final int TEST1_PORT = 11100; + public static final String TEST1_HOST = "localhost"; + + public static final int TEST2_PORT = 11101; + public static final String TEST2_HOST = "localhost"; + + public static final int[][] INT_ARRAY_2_DIM = { {1, 2}, {3, 4}}; + public static final int[][][] INT_ARRAY_3_DIM = { { {1, 2}, {3, 4}}, { {5, 6}, {7, 8}}}; + + public static final long TNAMESERV_SPAWN_WAIT = 300; + + /** + * Tests if given 2D arrays values are equal + * @param arr1 + * @param arr2 + * @return + */ + public static boolean are2DimArraysEqual(int[][] arr1, int[][] arr2) { + int sum = 0; + int expSum = 0; + for (int i = 0; i < arr1.length; i++) { + for (int j = 0; j < arr1[i].length; j++) { + expSum++; + if (arr1[i][j] == arr2[i][j]) { + sum++; + } + } + } + return sum == expSum; + } + + /** + * Tests if given 3D arrays values are equal + * @param arr1 + * @param arr2 + * @return + */ + public static boolean are3DimArraysEqual(int[][][] arr1, int[][][] arr2) { + int sum = 0; + int expSum = 0; + for (int i = 0; i < arr1.length; i++) { + for (int j = 0; j < arr1[i].length; j++) { + for (int k = 0; k < arr1[i][j].length; k++) { + expSum++; + if (arr1[i][j][k] == arr2[i][j][k]) { + sum++; + } + } + } + } + return sum == expSum; + } +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/ArraysUnionsTests.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/ArraysUnionsTests.java new file mode 100644 index 0000000000..f4ca1577f5 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/ArraysUnionsTests.java @@ -0,0 +1,13 @@ +package org.apache.tuscany.sca.binding.corba.testing.arrays_unions; + + +/** +* org/apache/tuscany/sca/binding/corba/testing/arrays_unions/ArraysUnionsTests.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from arrays_unions.idl +* niedziela, 17 sierpieñ 2008 15:45:39 CEST +*/ + +public interface ArraysUnionsTests extends ArraysUnionsTestsOperations, org.omg.CORBA.Object, org.omg.CORBA.portable.IDLEntity +{ +} // interface ArraysUnionsTests diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/ArraysUnionsTestsHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/ArraysUnionsTestsHelper.java new file mode 100644 index 0000000000..d10bc498b7 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/ArraysUnionsTestsHelper.java @@ -0,0 +1,85 @@ +package org.apache.tuscany.sca.binding.corba.testing.arrays_unions; + + +/** +* org/apache/tuscany/sca/binding/corba/testing/arrays_unions/ArraysUnionsTestsHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from arrays_unions.idl +* niedziela, 17 sierpieñ 2008 15:45:39 CEST +*/ + +abstract public class ArraysUnionsTestsHelper +{ + private static String _id = "IDL:org/apache/tuscany/sca/binding/corba/testing/arrays_unions/ArraysUnionsTests:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.apache.tuscany.sca.binding.corba.testing.arrays_unions.ArraysUnionsTests that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.apache.tuscany.sca.binding.corba.testing.arrays_unions.ArraysUnionsTests extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_interface_tc (org.apache.tuscany.sca.binding.corba.testing.arrays_unions.ArraysUnionsTestsHelper.id (), "ArraysUnionsTests"); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.apache.tuscany.sca.binding.corba.testing.arrays_unions.ArraysUnionsTests read (org.omg.CORBA.portable.InputStream istream) + { + return narrow (istream.read_Object (_ArraysUnionsTestsStub.class)); + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.apache.tuscany.sca.binding.corba.testing.arrays_unions.ArraysUnionsTests value) + { + ostream.write_Object ((org.omg.CORBA.Object) value); + } + + public static org.apache.tuscany.sca.binding.corba.testing.arrays_unions.ArraysUnionsTests narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.apache.tuscany.sca.binding.corba.testing.arrays_unions.ArraysUnionsTests) + return (org.apache.tuscany.sca.binding.corba.testing.arrays_unions.ArraysUnionsTests)obj; + else if (!obj._is_a (id ())) + throw new org.omg.CORBA.BAD_PARAM (); + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.apache.tuscany.sca.binding.corba.testing.arrays_unions._ArraysUnionsTestsStub stub = new org.apache.tuscany.sca.binding.corba.testing.arrays_unions._ArraysUnionsTestsStub (); + stub._set_delegate(delegate); + return stub; + } + } + + public static org.apache.tuscany.sca.binding.corba.testing.arrays_unions.ArraysUnionsTests unchecked_narrow (org.omg.CORBA.Object obj) + { + if (obj == null) + return null; + else if (obj instanceof org.apache.tuscany.sca.binding.corba.testing.arrays_unions.ArraysUnionsTests) + return (org.apache.tuscany.sca.binding.corba.testing.arrays_unions.ArraysUnionsTests)obj; + else + { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate (); + org.apache.tuscany.sca.binding.corba.testing.arrays_unions._ArraysUnionsTestsStub stub = new org.apache.tuscany.sca.binding.corba.testing.arrays_unions._ArraysUnionsTestsStub (); + stub._set_delegate(delegate); + return stub; + } + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/ArraysUnionsTestsHolder.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/ArraysUnionsTestsHolder.java new file mode 100644 index 0000000000..98987c1252 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/ArraysUnionsTestsHolder.java @@ -0,0 +1,38 @@ +package org.apache.tuscany.sca.binding.corba.testing.arrays_unions; + +/** +* org/apache/tuscany/sca/binding/corba/testing/arrays_unions/ArraysUnionsTestsHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from arrays_unions.idl +* niedziela, 17 sierpieñ 2008 15:45:39 CEST +*/ + +public final class ArraysUnionsTestsHolder implements org.omg.CORBA.portable.Streamable +{ + public org.apache.tuscany.sca.binding.corba.testing.arrays_unions.ArraysUnionsTests value = null; + + public ArraysUnionsTestsHolder () + { + } + + public ArraysUnionsTestsHolder (org.apache.tuscany.sca.binding.corba.testing.arrays_unions.ArraysUnionsTests initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.apache.tuscany.sca.binding.corba.testing.arrays_unions.ArraysUnionsTestsHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.apache.tuscany.sca.binding.corba.testing.arrays_unions.ArraysUnionsTestsHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.apache.tuscany.sca.binding.corba.testing.arrays_unions.ArraysUnionsTestsHelper.type (); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/ArraysUnionsTestsOperations.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/ArraysUnionsTestsOperations.java new file mode 100644 index 0000000000..d80adb476a --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/ArraysUnionsTestsOperations.java @@ -0,0 +1,16 @@ +package org.apache.tuscany.sca.binding.corba.testing.arrays_unions; + + +/** +* org/apache/tuscany/sca/binding/corba/testing/arrays_unions/ArraysUnionsTestsOperations.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from arrays_unions.idl +* niedziela, 17 sierpieñ 2008 15:45:39 CEST +*/ + +public interface ArraysUnionsTestsOperations +{ + org.apache.tuscany.sca.binding.corba.testing.arrays_unions.TestStruct passTestStruct (org.apache.tuscany.sca.binding.corba.testing.arrays_unions.TestStruct arg); + String[][] passStringArray (String[][] arg); + org.apache.tuscany.sca.binding.corba.testing.arrays_unions.RichUnion passRichUnion (org.apache.tuscany.sca.binding.corba.testing.arrays_unions.RichUnion arg); +} // interface ArraysUnionsTestsOperations diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/InnerUnion.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/InnerUnion.java new file mode 100644 index 0000000000..9f520f3c5d --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/InnerUnion.java @@ -0,0 +1,112 @@ +package org.apache.tuscany.sca.binding.corba.testing.arrays_unions; + + +/** +* org/apache/tuscany/sca/binding/corba/testing/arrays_unions/InnerUnion.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from arrays_unions.idl +* niedziela, 17 sierpieñ 2008 15:45:39 CEST +*/ + +public final class InnerUnion implements org.omg.CORBA.portable.IDLEntity +{ + private int ___x; + private float ___y; + private int __discriminator; + private boolean __uninitialized = true; + + public InnerUnion () + { + } + + public int discriminator () + { + if (__uninitialized) + throw new org.omg.CORBA.BAD_OPERATION (); + return __discriminator; + } + + public int x () + { + if (__uninitialized) + throw new org.omg.CORBA.BAD_OPERATION (); + verifyx (__discriminator); + return ___x; + } + + public void x (int value) + { + __discriminator = 1; + ___x = value; + __uninitialized = false; + } + + public void x (int discriminator, int value) + { + verifyx (discriminator); + __discriminator = discriminator; + ___x = value; + __uninitialized = false; + } + + private void verifyx (int discriminator) + { + if (discriminator != 1) + throw new org.omg.CORBA.BAD_OPERATION (); + } + + public float y () + { + if (__uninitialized) + throw new org.omg.CORBA.BAD_OPERATION (); + verifyy (__discriminator); + return ___y; + } + + public void y (float value) + { + __discriminator = 2; + ___y = value; + __uninitialized = false; + } + + public void y (int discriminator, float value) + { + verifyy (discriminator); + __discriminator = discriminator; + ___y = value; + __uninitialized = false; + } + + private void verifyy (int discriminator) + { + if (discriminator != 2) + throw new org.omg.CORBA.BAD_OPERATION (); + } + + public void _default () + { + __discriminator = -2147483648; + __uninitialized = false; + } + + public void _default (int discriminator) + { + verifyDefault( discriminator ) ; + __discriminator = discriminator ; + __uninitialized = false; + } + + private void verifyDefault( int value ) + { + switch (value) { + case 1: + case 2: + throw new org.omg.CORBA.BAD_OPERATION() ; + + default: + return; + } + } + +} // class InnerUnion diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/InnerUnionHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/InnerUnionHelper.java new file mode 100644 index 0000000000..11c22f1d72 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/InnerUnionHelper.java @@ -0,0 +1,106 @@ +package org.apache.tuscany.sca.binding.corba.testing.arrays_unions; + + +/** +* org/apache/tuscany/sca/binding/corba/testing/arrays_unions/InnerUnionHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from arrays_unions.idl +* niedziela, 17 sierpieñ 2008 15:45:39 CEST +*/ + +abstract public class InnerUnionHelper +{ + private static String _id = "IDL:org/apache/tuscany/sca/binding/corba/testing/arrays_unions/InnerUnion/InnerUnion:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.apache.tuscany.sca.binding.corba.testing.arrays_unions.InnerUnion that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.apache.tuscany.sca.binding.corba.testing.arrays_unions.InnerUnion extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + org.omg.CORBA.TypeCode _disTypeCode0; + _disTypeCode0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_long); + org.omg.CORBA.UnionMember[] _members0 = new org.omg.CORBA.UnionMember [2]; + org.omg.CORBA.TypeCode _tcOf_members0; + org.omg.CORBA.Any _anyOf_members0; + + // Branch for x (case label 1) + _anyOf_members0 = org.omg.CORBA.ORB.init ().create_any (); + _anyOf_members0.insert_long ((int)1); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_long); + _members0[0] = new org.omg.CORBA.UnionMember ( + "x", + _anyOf_members0, + _tcOf_members0, + null); + + // Branch for y (case label 2) + _anyOf_members0 = org.omg.CORBA.ORB.init ().create_any (); + _anyOf_members0.insert_long ((int)2); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_float); + _members0[1] = new org.omg.CORBA.UnionMember ( + "y", + _anyOf_members0, + _tcOf_members0, + null); + __typeCode = org.omg.CORBA.ORB.init ().create_union_tc (org.apache.tuscany.sca.binding.corba.testing.arrays_unions.InnerUnionHelper.id (), "InnerUnion", _disTypeCode0, _members0); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.apache.tuscany.sca.binding.corba.testing.arrays_unions.InnerUnion read (org.omg.CORBA.portable.InputStream istream) + { + org.apache.tuscany.sca.binding.corba.testing.arrays_unions.InnerUnion value = new org.apache.tuscany.sca.binding.corba.testing.arrays_unions.InnerUnion (); + int _dis0 = (int)0; + _dis0 = istream.read_long (); + switch (_dis0) + { + case 1: + int _x = (int)0; + _x = istream.read_long (); + value.x (_x); + break; + case 2: + float _y = (float)0; + _y = istream.read_float (); + value.y (_y); + break; + default: + value._default( _dis0 ) ; + break; + } + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.apache.tuscany.sca.binding.corba.testing.arrays_unions.InnerUnion value) + { + ostream.write_long (value.discriminator ()); + switch (value.discriminator ()) + { + case 1: + ostream.write_long (value.x ()); + break; + case 2: + ostream.write_float (value.y ()); + break; + } + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/InnerUnionHolder.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/InnerUnionHolder.java new file mode 100644 index 0000000000..ca9233c77f --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/InnerUnionHolder.java @@ -0,0 +1,38 @@ +package org.apache.tuscany.sca.binding.corba.testing.arrays_unions; + +/** +* org/apache/tuscany/sca/binding/corba/testing/arrays_unions/InnerUnionHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from arrays_unions.idl +* niedziela, 17 sierpieñ 2008 15:45:39 CEST +*/ + +public final class InnerUnionHolder implements org.omg.CORBA.portable.Streamable +{ + public org.apache.tuscany.sca.binding.corba.testing.arrays_unions.InnerUnion value = null; + + public InnerUnionHolder () + { + } + + public InnerUnionHolder (org.apache.tuscany.sca.binding.corba.testing.arrays_unions.InnerUnion initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.apache.tuscany.sca.binding.corba.testing.arrays_unions.InnerUnionHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.apache.tuscany.sca.binding.corba.testing.arrays_unions.InnerUnionHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.apache.tuscany.sca.binding.corba.testing.arrays_unions.InnerUnionHelper.type (); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/RichUnion.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/RichUnion.java new file mode 100644 index 0000000000..1a1a36fd16 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/RichUnion.java @@ -0,0 +1,177 @@ +package org.apache.tuscany.sca.binding.corba.testing.arrays_unions; + + +/** +* org/apache/tuscany/sca/binding/corba/testing/arrays_unions/RichUnion.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from arrays_unions.idl +* niedziela, 17 sierpieñ 2008 15:45:39 CEST +*/ + +public final class RichUnion implements org.omg.CORBA.portable.IDLEntity +{ + private int ___x; + private float ___y; + private String ___z; + private org.apache.tuscany.sca.binding.corba.testing.arrays_unions.InnerUnion ___iu; + private boolean ___a; + private int __discriminator; + private boolean __uninitialized = true; + + public RichUnion () + { + } + + public int discriminator () + { + if (__uninitialized) + throw new org.omg.CORBA.BAD_OPERATION (); + return __discriminator; + } + + public int x () + { + if (__uninitialized) + throw new org.omg.CORBA.BAD_OPERATION (); + verifyx (__discriminator); + return ___x; + } + + public void x (int value) + { + __discriminator = 1; + ___x = value; + __uninitialized = false; + } + + public void x (int discriminator, int value) + { + verifyx (discriminator); + __discriminator = discriminator; + ___x = value; + __uninitialized = false; + } + + private void verifyx (int discriminator) + { + if (discriminator != 1) + throw new org.omg.CORBA.BAD_OPERATION (); + } + + public float y () + { + if (__uninitialized) + throw new org.omg.CORBA.BAD_OPERATION (); + verifyy (__discriminator); + return ___y; + } + + public void y (float value) + { + __discriminator = 2; + ___y = value; + __uninitialized = false; + } + + public void y (int discriminator, float value) + { + verifyy (discriminator); + __discriminator = discriminator; + ___y = value; + __uninitialized = false; + } + + private void verifyy (int discriminator) + { + if (discriminator != 2) + throw new org.omg.CORBA.BAD_OPERATION (); + } + + public String z () + { + if (__uninitialized) + throw new org.omg.CORBA.BAD_OPERATION (); + verifyz (__discriminator); + return ___z; + } + + public void z (String value) + { + __discriminator = 3; + ___z = value; + __uninitialized = false; + } + + public void z (int discriminator, String value) + { + verifyz (discriminator); + __discriminator = discriminator; + ___z = value; + __uninitialized = false; + } + + private void verifyz (int discriminator) + { + if (discriminator != 3) + throw new org.omg.CORBA.BAD_OPERATION (); + } + + public org.apache.tuscany.sca.binding.corba.testing.arrays_unions.InnerUnion iu () + { + if (__uninitialized) + throw new org.omg.CORBA.BAD_OPERATION (); + verifyiu (__discriminator); + return ___iu; + } + + public void iu (org.apache.tuscany.sca.binding.corba.testing.arrays_unions.InnerUnion value) + { + __discriminator = 4; + ___iu = value; + __uninitialized = false; + } + + public void iu (int discriminator, org.apache.tuscany.sca.binding.corba.testing.arrays_unions.InnerUnion value) + { + verifyiu (discriminator); + __discriminator = discriminator; + ___iu = value; + __uninitialized = false; + } + + private void verifyiu (int discriminator) + { + if (discriminator != 4) + throw new org.omg.CORBA.BAD_OPERATION (); + } + + public boolean a () + { + if (__uninitialized) + throw new org.omg.CORBA.BAD_OPERATION (); + verifya (__discriminator); + return ___a; + } + + public void a (boolean value) + { + __discriminator = -2147483648; + ___a = value; + __uninitialized = false; + } + + public void a (int discriminator, boolean value) + { + verifya (discriminator); + __discriminator = discriminator; + ___a = value; + __uninitialized = false; + } + + private void verifya (int discriminator) + { + if (discriminator == 1 || discriminator == 2 || discriminator == 3 || discriminator == 4) + throw new org.omg.CORBA.BAD_OPERATION (); + } + +} // class RichUnion diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/RichUnionHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/RichUnionHelper.java new file mode 100644 index 0000000000..7cef0ea189 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/RichUnionHelper.java @@ -0,0 +1,157 @@ +package org.apache.tuscany.sca.binding.corba.testing.arrays_unions; + + +/** +* org/apache/tuscany/sca/binding/corba/testing/arrays_unions/RichUnionHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from arrays_unions.idl +* niedziela, 17 sierpieñ 2008 15:45:39 CEST +*/ + +abstract public class RichUnionHelper +{ + private static String _id = "IDL:org/apache/tuscany/sca/binding/corba/testing/arrays_unions/RichUnion/RichUnion:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.apache.tuscany.sca.binding.corba.testing.arrays_unions.RichUnion that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.apache.tuscany.sca.binding.corba.testing.arrays_unions.RichUnion extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + org.omg.CORBA.TypeCode _disTypeCode0; + _disTypeCode0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_long); + org.omg.CORBA.UnionMember[] _members0 = new org.omg.CORBA.UnionMember [5]; + org.omg.CORBA.TypeCode _tcOf_members0; + org.omg.CORBA.Any _anyOf_members0; + + // Branch for x (case label 1) + _anyOf_members0 = org.omg.CORBA.ORB.init ().create_any (); + _anyOf_members0.insert_long ((int)1); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_long); + _members0[0] = new org.omg.CORBA.UnionMember ( + "x", + _anyOf_members0, + _tcOf_members0, + null); + + // Branch for y (case label 2) + _anyOf_members0 = org.omg.CORBA.ORB.init ().create_any (); + _anyOf_members0.insert_long ((int)2); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_float); + _members0[1] = new org.omg.CORBA.UnionMember ( + "y", + _anyOf_members0, + _tcOf_members0, + null); + + // Branch for z (case label 3) + _anyOf_members0 = org.omg.CORBA.ORB.init ().create_any (); + _anyOf_members0.insert_long ((int)3); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _members0[2] = new org.omg.CORBA.UnionMember ( + "z", + _anyOf_members0, + _tcOf_members0, + null); + + // Branch for iu (case label 4) + _anyOf_members0 = org.omg.CORBA.ORB.init ().create_any (); + _anyOf_members0.insert_long ((int)4); + _tcOf_members0 = org.apache.tuscany.sca.binding.corba.testing.arrays_unions.InnerUnionHelper.type (); + _members0[3] = new org.omg.CORBA.UnionMember ( + "iu", + _anyOf_members0, + _tcOf_members0, + null); + + // Branch for a (Default case) + _anyOf_members0 = org.omg.CORBA.ORB.init ().create_any (); + _anyOf_members0.insert_octet ((byte)0); // default member label + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_boolean); + _members0[4] = new org.omg.CORBA.UnionMember ( + "a", + _anyOf_members0, + _tcOf_members0, + null); + __typeCode = org.omg.CORBA.ORB.init ().create_union_tc (org.apache.tuscany.sca.binding.corba.testing.arrays_unions.RichUnionHelper.id (), "RichUnion", _disTypeCode0, _members0); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.apache.tuscany.sca.binding.corba.testing.arrays_unions.RichUnion read (org.omg.CORBA.portable.InputStream istream) + { + org.apache.tuscany.sca.binding.corba.testing.arrays_unions.RichUnion value = new org.apache.tuscany.sca.binding.corba.testing.arrays_unions.RichUnion (); + int _dis0 = (int)0; + _dis0 = istream.read_long (); + switch (_dis0) + { + case 1: + int _x = (int)0; + _x = istream.read_long (); + value.x (_x); + break; + case 2: + float _y = (float)0; + _y = istream.read_float (); + value.y (_y); + break; + case 3: + String _z = null; + _z = istream.read_string (); + value.z (_z); + break; + case 4: + org.apache.tuscany.sca.binding.corba.testing.arrays_unions.InnerUnion _iu = null; + _iu = org.apache.tuscany.sca.binding.corba.testing.arrays_unions.InnerUnionHelper.read (istream); + value.iu (_iu); + break; + default: + boolean _a = false; + _a = istream.read_boolean (); + value.a (_dis0, _a); + break; + } + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.apache.tuscany.sca.binding.corba.testing.arrays_unions.RichUnion value) + { + ostream.write_long (value.discriminator ()); + switch (value.discriminator ()) + { + case 1: + ostream.write_long (value.x ()); + break; + case 2: + ostream.write_float (value.y ()); + break; + case 3: + ostream.write_string (value.z ()); + break; + case 4: + org.apache.tuscany.sca.binding.corba.testing.arrays_unions.InnerUnionHelper.write (ostream, value.iu ()); + break; + default: + ostream.write_boolean (value.a ()); + break; + } + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/RichUnionHolder.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/RichUnionHolder.java new file mode 100644 index 0000000000..5498104905 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/RichUnionHolder.java @@ -0,0 +1,38 @@ +package org.apache.tuscany.sca.binding.corba.testing.arrays_unions; + +/** +* org/apache/tuscany/sca/binding/corba/testing/arrays_unions/RichUnionHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from arrays_unions.idl +* niedziela, 17 sierpieñ 2008 15:45:39 CEST +*/ + +public final class RichUnionHolder implements org.omg.CORBA.portable.Streamable +{ + public org.apache.tuscany.sca.binding.corba.testing.arrays_unions.RichUnion value = null; + + public RichUnionHolder () + { + } + + public RichUnionHolder (org.apache.tuscany.sca.binding.corba.testing.arrays_unions.RichUnion initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.apache.tuscany.sca.binding.corba.testing.arrays_unions.RichUnionHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.apache.tuscany.sca.binding.corba.testing.arrays_unions.RichUnionHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.apache.tuscany.sca.binding.corba.testing.arrays_unions.RichUnionHelper.type (); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/StringArrayHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/StringArrayHelper.java new file mode 100644 index 0000000000..72beff0537 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/StringArrayHelper.java @@ -0,0 +1,76 @@ +package org.apache.tuscany.sca.binding.corba.testing.arrays_unions; + + +/** +* org/apache/tuscany/sca/binding/corba/testing/arrays_unions/StringArrayHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from arrays_unions.idl +* niedziela, 17 sierpieñ 2008 15:45:39 CEST +*/ + +abstract public class StringArrayHelper +{ + private static String _id = "IDL:org/apache/tuscany/sca/binding/corba/testing/arrays_unions/StringArray:1.0"; + + public static void insert (org.omg.CORBA.Any a, String[][] that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static String[][] extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + __typeCode = org.omg.CORBA.ORB.init ().create_string_tc (0); + __typeCode = org.omg.CORBA.ORB.init ().create_array_tc (2, __typeCode ); + __typeCode = org.omg.CORBA.ORB.init ().create_array_tc (2, __typeCode ); + __typeCode = org.omg.CORBA.ORB.init ().create_alias_tc (org.apache.tuscany.sca.binding.corba.testing.arrays_unions.StringArrayHelper.id (), "StringArray", __typeCode); + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static String[][] read (org.omg.CORBA.portable.InputStream istream) + { + String value[][] = null; + value = new String[2][]; + for (int _o0 = 0;_o0 < (2); ++_o0) + { + value[_o0] = new String[2]; + for (int _o1 = 0;_o1 < (2); ++_o1) + { + value[_o0][_o1] = istream.read_string (); + } + } + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, String[][] value) + { + if (value.length != (2)) + throw new org.omg.CORBA.MARSHAL (0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE); + for (int _i0 = 0;_i0 < (2); ++_i0) + { + if (value[_i0].length != (2)) + throw new org.omg.CORBA.MARSHAL (0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE); + for (int _i1 = 0;_i1 < (2); ++_i1) + { + ostream.write_string (value[_i0][_i1]); + } + } + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/StringArrayHolder.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/StringArrayHolder.java new file mode 100644 index 0000000000..747337597c --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/StringArrayHolder.java @@ -0,0 +1,39 @@ +package org.apache.tuscany.sca.binding.corba.testing.arrays_unions; + + +/** +* org/apache/tuscany/sca/binding/corba/testing/arrays_unions/StringArrayHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from arrays_unions.idl +* niedziela, 17 sierpieñ 2008 15:45:39 CEST +*/ + +public final class StringArrayHolder implements org.omg.CORBA.portable.Streamable +{ + public String value[][] = null; + + public StringArrayHolder () + { + } + + public StringArrayHolder (String[][] initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.apache.tuscany.sca.binding.corba.testing.arrays_unions.StringArrayHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.apache.tuscany.sca.binding.corba.testing.arrays_unions.StringArrayHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.apache.tuscany.sca.binding.corba.testing.arrays_unions.StringArrayHelper.type (); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/TestStruct.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/TestStruct.java new file mode 100644 index 0000000000..2b239deadc --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/TestStruct.java @@ -0,0 +1,28 @@ +package org.apache.tuscany.sca.binding.corba.testing.arrays_unions; + + +/** +* org/apache/tuscany/sca/binding/corba/testing/arrays_unions/TestStruct.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from arrays_unions.idl +* niedziela, 17 sierpieñ 2008 15:45:39 CEST +*/ + +public final class TestStruct implements org.omg.CORBA.portable.IDLEntity +{ + public String oneDimArray[] = null; + public int twoDimArray[][] = null; + public float threeDimArray[][][] = null; + + public TestStruct () + { + } // ctor + + public TestStruct (String[] _oneDimArray, int[][] _twoDimArray, float[][][] _threeDimArray) + { + oneDimArray = _oneDimArray; + twoDimArray = _twoDimArray; + threeDimArray = _threeDimArray; + } // ctor + +} // class TestStruct diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/TestStructHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/TestStructHelper.java new file mode 100644 index 0000000000..6427d9d200 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/TestStructHelper.java @@ -0,0 +1,149 @@ +package org.apache.tuscany.sca.binding.corba.testing.arrays_unions; + + +/** +* org/apache/tuscany/sca/binding/corba/testing/arrays_unions/TestStructHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from arrays_unions.idl +* niedziela, 17 sierpieñ 2008 15:45:39 CEST +*/ + +abstract public class TestStructHelper +{ + private static String _id = "IDL:org/apache/tuscany/sca/binding/corba/testing/arrays_unions/TestStruct/TestStruct:1.0"; + + public static void insert (org.omg.CORBA.Any a, org.apache.tuscany.sca.binding.corba.testing.arrays_unions.TestStruct that) + { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream (); + a.type (type ()); + write (out, that); + a.read_value (out.create_input_stream (), type ()); + } + + public static org.apache.tuscany.sca.binding.corba.testing.arrays_unions.TestStruct extract (org.omg.CORBA.Any a) + { + return read (a.create_input_stream ()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + synchronized public static org.omg.CORBA.TypeCode type () + { + if (__typeCode == null) + { + synchronized (org.omg.CORBA.TypeCode.class) + { + if (__typeCode == null) + { + if (__active) + { + return org.omg.CORBA.ORB.init().create_recursive_tc ( _id ); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [3]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_string_tc (0); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_array_tc (2, _tcOf_members0 ); + _members0[0] = new org.omg.CORBA.StructMember ( + "oneDimArray", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_long); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_array_tc (2, _tcOf_members0 ); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_array_tc (4, _tcOf_members0 ); + _members0[1] = new org.omg.CORBA.StructMember ( + "twoDimArray", + _tcOf_members0, + null); + _tcOf_members0 = org.omg.CORBA.ORB.init ().get_primitive_tc (org.omg.CORBA.TCKind.tk_float); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_array_tc (2, _tcOf_members0 ); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_array_tc (4, _tcOf_members0 ); + _tcOf_members0 = org.omg.CORBA.ORB.init ().create_array_tc (2, _tcOf_members0 ); + _members0[2] = new org.omg.CORBA.StructMember ( + "threeDimArray", + _tcOf_members0, + null); + __typeCode = org.omg.CORBA.ORB.init ().create_struct_tc (org.apache.tuscany.sca.binding.corba.testing.arrays_unions.TestStructHelper.id (), "TestStruct", _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id () + { + return _id; + } + + public static org.apache.tuscany.sca.binding.corba.testing.arrays_unions.TestStruct read (org.omg.CORBA.portable.InputStream istream) + { + org.apache.tuscany.sca.binding.corba.testing.arrays_unions.TestStruct value = new org.apache.tuscany.sca.binding.corba.testing.arrays_unions.TestStruct (); + value.oneDimArray = new String[2]; + for (int _o0 = 0;_o0 < (2); ++_o0) + { + value.oneDimArray[_o0] = istream.read_string (); + } + value.twoDimArray = new int[2][]; + for (int _o1 = 0;_o1 < (2); ++_o1) + { + value.twoDimArray[_o1] = new int[4]; + for (int _o2 = 0;_o2 < (4); ++_o2) + { + value.twoDimArray[_o1][_o2] = istream.read_long (); + } + } + value.threeDimArray = new float[2][][]; + for (int _o3 = 0;_o3 < (2); ++_o3) + { + value.threeDimArray[_o3] = new float[4][]; + for (int _o4 = 0;_o4 < (4); ++_o4) + { + value.threeDimArray[_o3][_o4] = new float[2]; + for (int _o5 = 0;_o5 < (2); ++_o5) + { + value.threeDimArray[_o3][_o4][_o5] = istream.read_float (); + } + } + } + return value; + } + + public static void write (org.omg.CORBA.portable.OutputStream ostream, org.apache.tuscany.sca.binding.corba.testing.arrays_unions.TestStruct value) + { + if (value.oneDimArray.length != (2)) + throw new org.omg.CORBA.MARSHAL (0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE); + for (int _i0 = 0;_i0 < (2); ++_i0) + { + ostream.write_string (value.oneDimArray[_i0]); + } + if (value.twoDimArray.length != (2)) + throw new org.omg.CORBA.MARSHAL (0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE); + for (int _i1 = 0;_i1 < (2); ++_i1) + { + if (value.twoDimArray[_i1].length != (4)) + throw new org.omg.CORBA.MARSHAL (0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE); + for (int _i2 = 0;_i2 < (4); ++_i2) + { + ostream.write_long (value.twoDimArray[_i1][_i2]); + } + } + if (value.threeDimArray.length != (2)) + throw new org.omg.CORBA.MARSHAL (0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE); + for (int _i3 = 0;_i3 < (2); ++_i3) + { + if (value.threeDimArray[_i3].length != (4)) + throw new org.omg.CORBA.MARSHAL (0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE); + for (int _i4 = 0;_i4 < (4); ++_i4) + { + if (value.threeDimArray[_i3][_i4].length != (2)) + throw new org.omg.CORBA.MARSHAL (0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE); + for (int _i5 = 0;_i5 < (2); ++_i5) + { + ostream.write_float (value.threeDimArray[_i3][_i4][_i5]); + } + } + } + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/TestStructHolder.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/TestStructHolder.java new file mode 100644 index 0000000000..94683e0327 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/TestStructHolder.java @@ -0,0 +1,38 @@ +package org.apache.tuscany.sca.binding.corba.testing.arrays_unions; + +/** +* org/apache/tuscany/sca/binding/corba/testing/arrays_unions/TestStructHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from arrays_unions.idl +* niedziela, 17 sierpieñ 2008 15:45:39 CEST +*/ + +public final class TestStructHolder implements org.omg.CORBA.portable.Streamable +{ + public org.apache.tuscany.sca.binding.corba.testing.arrays_unions.TestStruct value = null; + + public TestStructHolder () + { + } + + public TestStructHolder (org.apache.tuscany.sca.binding.corba.testing.arrays_unions.TestStruct initialValue) + { + value = initialValue; + } + + public void _read (org.omg.CORBA.portable.InputStream i) + { + value = org.apache.tuscany.sca.binding.corba.testing.arrays_unions.TestStructHelper.read (i); + } + + public void _write (org.omg.CORBA.portable.OutputStream o) + { + org.apache.tuscany.sca.binding.corba.testing.arrays_unions.TestStructHelper.write (o, value); + } + + public org.omg.CORBA.TypeCode _type () + { + return org.apache.tuscany.sca.binding.corba.testing.arrays_unions.TestStructHelper.type (); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/_ArraysUnionsTestsImplBase.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/_ArraysUnionsTestsImplBase.java new file mode 100644 index 0000000000..e4cac28e4f --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/_ArraysUnionsTestsImplBase.java @@ -0,0 +1,86 @@ +package org.apache.tuscany.sca.binding.corba.testing.arrays_unions; + + +/** +* org/apache/tuscany/sca/binding/corba/testing/arrays_unions/_ArraysUnionsTestsImplBase.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from arrays_unions.idl +* niedziela, 17 sierpieñ 2008 15:45:39 CEST +*/ + +public abstract class _ArraysUnionsTestsImplBase extends org.omg.CORBA.portable.ObjectImpl + implements org.apache.tuscany.sca.binding.corba.testing.arrays_unions.ArraysUnionsTests, org.omg.CORBA.portable.InvokeHandler +{ + + // Constructors + public _ArraysUnionsTestsImplBase () + { + } + + private static java.util.Hashtable _methods = new java.util.Hashtable (); + static + { + _methods.put ("passTestStruct", new java.lang.Integer (0)); + _methods.put ("passStringArray", new java.lang.Integer (1)); + _methods.put ("passRichUnion", new java.lang.Integer (2)); + } + + public org.omg.CORBA.portable.OutputStream _invoke (String $method, + org.omg.CORBA.portable.InputStream in, + org.omg.CORBA.portable.ResponseHandler $rh) + { + org.omg.CORBA.portable.OutputStream out = null; + java.lang.Integer __method = (java.lang.Integer)_methods.get ($method); + if (__method == null) + throw new org.omg.CORBA.BAD_OPERATION (0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE); + + switch (__method.intValue ()) + { + case 0: // org/apache/tuscany/sca/binding/corba/testing/arrays_unions/ArraysUnionsTests/passTestStruct + { + org.apache.tuscany.sca.binding.corba.testing.arrays_unions.TestStruct arg = org.apache.tuscany.sca.binding.corba.testing.arrays_unions.TestStructHelper.read (in); + org.apache.tuscany.sca.binding.corba.testing.arrays_unions.TestStruct $result = null; + $result = this.passTestStruct (arg); + out = $rh.createReply(); + org.apache.tuscany.sca.binding.corba.testing.arrays_unions.TestStructHelper.write (out, $result); + break; + } + + case 1: // org/apache/tuscany/sca/binding/corba/testing/arrays_unions/ArraysUnionsTests/passStringArray + { + String arg[][] = org.apache.tuscany.sca.binding.corba.testing.arrays_unions.StringArrayHelper.read (in); + String $result[][] = null; + $result = this.passStringArray (arg); + out = $rh.createReply(); + org.apache.tuscany.sca.binding.corba.testing.arrays_unions.StringArrayHelper.write (out, $result); + break; + } + + case 2: // org/apache/tuscany/sca/binding/corba/testing/arrays_unions/ArraysUnionsTests/passRichUnion + { + org.apache.tuscany.sca.binding.corba.testing.arrays_unions.RichUnion arg = org.apache.tuscany.sca.binding.corba.testing.arrays_unions.RichUnionHelper.read (in); + org.apache.tuscany.sca.binding.corba.testing.arrays_unions.RichUnion $result = null; + $result = this.passRichUnion (arg); + out = $rh.createReply(); + org.apache.tuscany.sca.binding.corba.testing.arrays_unions.RichUnionHelper.write (out, $result); + break; + } + + default: + throw new org.omg.CORBA.BAD_OPERATION (0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE); + } + + return out; + } // _invoke + + // Type-specific CORBA::Object operations + private static String[] __ids = { + "IDL:org/apache/tuscany/sca/binding/corba/testing/arrays_unions/ArraysUnionsTests:1.0"}; + + public String[] _ids () + { + return (String[])__ids.clone (); + } + + +} // class _ArraysUnionsTestsImplBase diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/_ArraysUnionsTestsStub.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/_ArraysUnionsTestsStub.java new file mode 100644 index 0000000000..38e29c0d63 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/arrays_unions/_ArraysUnionsTestsStub.java @@ -0,0 +1,100 @@ +package org.apache.tuscany.sca.binding.corba.testing.arrays_unions; + + +/** +* org/apache/tuscany/sca/binding/corba/testing/arrays_unions/_ArraysUnionsTestsStub.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from arrays_unions.idl +* niedziela, 17 sierpieñ 2008 15:45:39 CEST +*/ + +public class _ArraysUnionsTestsStub extends org.omg.CORBA.portable.ObjectImpl implements org.apache.tuscany.sca.binding.corba.testing.arrays_unions.ArraysUnionsTests +{ + + public org.apache.tuscany.sca.binding.corba.testing.arrays_unions.TestStruct passTestStruct (org.apache.tuscany.sca.binding.corba.testing.arrays_unions.TestStruct arg) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("passTestStruct", true); + org.apache.tuscany.sca.binding.corba.testing.arrays_unions.TestStructHelper.write ($out, arg); + $in = _invoke ($out); + org.apache.tuscany.sca.binding.corba.testing.arrays_unions.TestStruct $result = org.apache.tuscany.sca.binding.corba.testing.arrays_unions.TestStructHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return passTestStruct (arg ); + } finally { + _releaseReply ($in); + } + } // passTestStruct + + public String[][] passStringArray (String[][] arg) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("passStringArray", true); + org.apache.tuscany.sca.binding.corba.testing.arrays_unions.StringArrayHelper.write ($out, arg); + $in = _invoke ($out); + String $result[][] = org.apache.tuscany.sca.binding.corba.testing.arrays_unions.StringArrayHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return passStringArray (arg ); + } finally { + _releaseReply ($in); + } + } // passStringArray + + public org.apache.tuscany.sca.binding.corba.testing.arrays_unions.RichUnion passRichUnion (org.apache.tuscany.sca.binding.corba.testing.arrays_unions.RichUnion arg) + { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request ("passRichUnion", true); + org.apache.tuscany.sca.binding.corba.testing.arrays_unions.RichUnionHelper.write ($out, arg); + $in = _invoke ($out); + org.apache.tuscany.sca.binding.corba.testing.arrays_unions.RichUnion $result = org.apache.tuscany.sca.binding.corba.testing.arrays_unions.RichUnionHelper.read ($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream (); + String _id = $ex.getId (); + throw new org.omg.CORBA.MARSHAL (_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return passRichUnion (arg ); + } finally { + _releaseReply ($in); + } + } // passRichUnion + + // Type-specific CORBA::Object operations + private static String[] __ids = { + "IDL:org/apache/tuscany/sca/binding/corba/testing/arrays_unions/ArraysUnionsTests:1.0"}; + + public String[] _ids () + { + return (String[])__ids.clone (); + } + + private void readObject (java.io.ObjectInputStream s) throws java.io.IOException + { + String str = s.readUTF (); + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.Object obj = org.omg.CORBA.ORB.init (args, props).string_to_object (str); + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl) obj)._get_delegate (); + _set_delegate (delegate); + } + + private void writeObject (java.io.ObjectOutputStream s) throws java.io.IOException + { + String[] args = null; + java.util.Properties props = null; + String str = org.omg.CORBA.ORB.init (args, props).object_to_string (this); + s.writeUTF (str); + } +} // class _ArraysUnionsTestsStub diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/enums/Color.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/enums/Color.java new file mode 100644 index 0000000000..e3c28f8b91 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/enums/Color.java @@ -0,0 +1,60 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.enums; + +/** +* org/apache/tuscany/sca/binding/corba/testing/enums/Color.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from enums.idl +* czwartek, 19 czerwiec 2008 15:46:10 CEST +*/ + +public class Color implements org.omg.CORBA.portable.IDLEntity { + private int __value; + private static int __size = 3; + private static org.apache.tuscany.sca.binding.corba.testing.enums.Color[] __array = + new org.apache.tuscany.sca.binding.corba.testing.enums.Color[__size]; + + public static final int _red = 0; + public static final org.apache.tuscany.sca.binding.corba.testing.enums.Color red = + new org.apache.tuscany.sca.binding.corba.testing.enums.Color(_red); + public static final int _yellow = 1; + public static final org.apache.tuscany.sca.binding.corba.testing.enums.Color yellow = + new org.apache.tuscany.sca.binding.corba.testing.enums.Color(_yellow); + public static final int _green = 2; + public static final org.apache.tuscany.sca.binding.corba.testing.enums.Color green = + new org.apache.tuscany.sca.binding.corba.testing.enums.Color(_green); + + public int value() { + return __value; + } + + public static org.apache.tuscany.sca.binding.corba.testing.enums.Color from_int(int value) { + if (value >= 0 && value < __size) + return __array[value]; + else + throw new org.omg.CORBA.BAD_PARAM(); + } + + protected Color(int value) { + __value = value; + __array[__value] = this; + } +} // class Color diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/enums/ColorHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/enums/ColorHelper.java new file mode 100644 index 0000000000..775cac8e16 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/enums/ColorHelper.java @@ -0,0 +1,69 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.enums; + +/** +* org/apache/tuscany/sca/binding/corba/testing/enums/ColorHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from enums.idl +* czwartek, 19 czerwiec 2008 15:46:10 CEST +*/ + +abstract public class ColorHelper { + private static String _id = "IDL:org/apache/tuscany/sca/binding/corba/testing/enums/Color:1.0"; + + public static void insert(org.omg.CORBA.Any a, org.apache.tuscany.sca.binding.corba.testing.enums.Color that) { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream(); + a.type(type()); + write(out, that); + a.read_value(out.create_input_stream(), type()); + } + + public static org.apache.tuscany.sca.binding.corba.testing.enums.Color extract(org.omg.CORBA.Any a) { + return read(a.create_input_stream()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + + synchronized public static org.omg.CORBA.TypeCode type() { + if (__typeCode == null) { + __typeCode = + org.omg.CORBA.ORB.init().create_enum_tc(org.apache.tuscany.sca.binding.corba.testing.enums.ColorHelper + .id(), + "Color", + new String[] {"red", "yellow", "green"}); + } + return __typeCode; + } + + public static String id() { + return _id; + } + + public static org.apache.tuscany.sca.binding.corba.testing.enums.Color read(org.omg.CORBA.portable.InputStream istream) { + return org.apache.tuscany.sca.binding.corba.testing.enums.Color.from_int(istream.read_long()); + } + + public static void write(org.omg.CORBA.portable.OutputStream ostream, + org.apache.tuscany.sca.binding.corba.testing.enums.Color value) { + ostream.write_long(value.value()); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/enums/ColorHolder.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/enums/ColorHolder.java new file mode 100644 index 0000000000..32cd9c8df6 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/enums/ColorHolder.java @@ -0,0 +1,51 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.enums; + +/** +* org/apache/tuscany/sca/binding/corba/testing/enums/ColorHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from enums.idl +* czwartek, 19 czerwiec 2008 15:46:10 CEST +*/ + +public final class ColorHolder implements org.omg.CORBA.portable.Streamable { + public org.apache.tuscany.sca.binding.corba.testing.enums.Color value = null; + + public ColorHolder() { + } + + public ColorHolder(org.apache.tuscany.sca.binding.corba.testing.enums.Color initialValue) { + value = initialValue; + } + + public void _read(org.omg.CORBA.portable.InputStream i) { + value = org.apache.tuscany.sca.binding.corba.testing.enums.ColorHelper.read(i); + } + + public void _write(org.omg.CORBA.portable.OutputStream o) { + org.apache.tuscany.sca.binding.corba.testing.enums.ColorHelper.write(o, value); + } + + public org.omg.CORBA.TypeCode _type() { + return org.apache.tuscany.sca.binding.corba.testing.enums.ColorHelper.type(); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/enums/EnumManager.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/enums/EnumManager.java new file mode 100644 index 0000000000..3f73557952 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/enums/EnumManager.java @@ -0,0 +1,30 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.enums; + +/** +* org/apache/tuscany/sca/binding/corba/testing/enums/EnumManager.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from enums.idl +* czwartek, 19 czerwiec 2008 15:46:10 CEST +*/ + +public interface EnumManager extends EnumManagerOperations, org.omg.CORBA.Object, org.omg.CORBA.portable.IDLEntity { +} // interface EnumManager diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/enums/EnumManagerHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/enums/EnumManagerHelper.java new file mode 100644 index 0000000000..a6160a7643 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/enums/EnumManagerHelper.java @@ -0,0 +1,98 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.enums; + +/** +* org/apache/tuscany/sca/binding/corba/testing/enums/EnumManagerHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from enums.idl +* czwartek, 19 czerwiec 2008 15:46:10 CEST +*/ + +abstract public class EnumManagerHelper { + private static String _id = "IDL:org/apache/tuscany/sca/binding/corba/testing/enums/EnumManager:1.0"; + + public static void insert(org.omg.CORBA.Any a, org.apache.tuscany.sca.binding.corba.testing.enums.EnumManager that) { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream(); + a.type(type()); + write(out, that); + a.read_value(out.create_input_stream(), type()); + } + + public static org.apache.tuscany.sca.binding.corba.testing.enums.EnumManager extract(org.omg.CORBA.Any a) { + return read(a.create_input_stream()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + + synchronized public static org.omg.CORBA.TypeCode type() { + if (__typeCode == null) { + __typeCode = + org.omg.CORBA.ORB.init() + .create_interface_tc(org.apache.tuscany.sca.binding.corba.testing.enums.EnumManagerHelper.id(), + "EnumManager"); + } + return __typeCode; + } + + public static String id() { + return _id; + } + + public static org.apache.tuscany.sca.binding.corba.testing.enums.EnumManager read(org.omg.CORBA.portable.InputStream istream) { + return narrow(istream.read_Object(_EnumManagerStub.class)); + } + + public static void write(org.omg.CORBA.portable.OutputStream ostream, + org.apache.tuscany.sca.binding.corba.testing.enums.EnumManager value) { + ostream.write_Object((org.omg.CORBA.Object)value); + } + + public static org.apache.tuscany.sca.binding.corba.testing.enums.EnumManager narrow(org.omg.CORBA.Object obj) { + if (obj == null) + return null; + else if (obj instanceof org.apache.tuscany.sca.binding.corba.testing.enums.EnumManager) + return (org.apache.tuscany.sca.binding.corba.testing.enums.EnumManager)obj; + else if (!obj._is_a(id())) + throw new org.omg.CORBA.BAD_PARAM(); + else { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate(); + org.apache.tuscany.sca.binding.corba.testing.enums._EnumManagerStub stub = + new org.apache.tuscany.sca.binding.corba.testing.enums._EnumManagerStub(); + stub._set_delegate(delegate); + return stub; + } + } + + public static org.apache.tuscany.sca.binding.corba.testing.enums.EnumManager unchecked_narrow(org.omg.CORBA.Object obj) { + if (obj == null) + return null; + else if (obj instanceof org.apache.tuscany.sca.binding.corba.testing.enums.EnumManager) + return (org.apache.tuscany.sca.binding.corba.testing.enums.EnumManager)obj; + else { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate(); + org.apache.tuscany.sca.binding.corba.testing.enums._EnumManagerStub stub = + new org.apache.tuscany.sca.binding.corba.testing.enums._EnumManagerStub(); + stub._set_delegate(delegate); + return stub; + } + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/enums/EnumManagerHolder.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/enums/EnumManagerHolder.java new file mode 100644 index 0000000000..6afa6bc806 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/enums/EnumManagerHolder.java @@ -0,0 +1,51 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.enums; + +/** +* org/apache/tuscany/sca/binding/corba/testing/enums/EnumManagerHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from enums.idl +* czwartek, 19 czerwiec 2008 15:46:10 CEST +*/ + +public final class EnumManagerHolder implements org.omg.CORBA.portable.Streamable { + public org.apache.tuscany.sca.binding.corba.testing.enums.EnumManager value = null; + + public EnumManagerHolder() { + } + + public EnumManagerHolder(org.apache.tuscany.sca.binding.corba.testing.enums.EnumManager initialValue) { + value = initialValue; + } + + public void _read(org.omg.CORBA.portable.InputStream i) { + value = org.apache.tuscany.sca.binding.corba.testing.enums.EnumManagerHelper.read(i); + } + + public void _write(org.omg.CORBA.portable.OutputStream o) { + org.apache.tuscany.sca.binding.corba.testing.enums.EnumManagerHelper.write(o, value); + } + + public org.omg.CORBA.TypeCode _type() { + return org.apache.tuscany.sca.binding.corba.testing.enums.EnumManagerHelper.type(); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/enums/EnumManagerOperations.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/enums/EnumManagerOperations.java new file mode 100644 index 0000000000..bab0c27f77 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/enums/EnumManagerOperations.java @@ -0,0 +1,32 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.enums; + +/** +* org/apache/tuscany/sca/binding/corba/testing/enums/EnumManagerOperations.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from enums.idl +* czwartek, 19 czerwiec 2008 15:46:10 CEST +*/ + +public interface EnumManagerOperations { + + org.apache.tuscany.sca.binding.corba.testing.enums.Color getColor(org.apache.tuscany.sca.binding.corba.testing.enums.Color color); +} // interface EnumManagerOperations diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/enums/_EnumManagerImplBase.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/enums/_EnumManagerImplBase.java new file mode 100644 index 0000000000..514627ff4b --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/enums/_EnumManagerImplBase.java @@ -0,0 +1,76 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.enums; + +/** +* org/apache/tuscany/sca/binding/corba/testing/enums/_EnumManagerImplBase.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from enums.idl +* czwartek, 19 czerwiec 2008 15:46:10 CEST +*/ + +public abstract class _EnumManagerImplBase extends org.omg.CORBA.portable.ObjectImpl implements + org.apache.tuscany.sca.binding.corba.testing.enums.EnumManager, org.omg.CORBA.portable.InvokeHandler { + + // Constructors + public _EnumManagerImplBase() { + } + + private static java.util.Hashtable _methods = new java.util.Hashtable(); + static { + _methods.put("getColor", new java.lang.Integer(0)); + } + + public org.omg.CORBA.portable.OutputStream _invoke(String $method, + org.omg.CORBA.portable.InputStream in, + org.omg.CORBA.portable.ResponseHandler $rh) { + org.omg.CORBA.portable.OutputStream out = null; + java.lang.Integer __method = (java.lang.Integer)_methods.get($method); + if (__method == null) + throw new org.omg.CORBA.BAD_OPERATION(0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE); + + switch (__method.intValue()) { + case 0: // org/apache/tuscany/sca/binding/corba/testing/enums/EnumManager/getColor + { + org.apache.tuscany.sca.binding.corba.testing.enums.Color color = + org.apache.tuscany.sca.binding.corba.testing.enums.ColorHelper.read(in); + org.apache.tuscany.sca.binding.corba.testing.enums.Color $result = null; + $result = this.getColor(color); + out = $rh.createReply(); + org.apache.tuscany.sca.binding.corba.testing.enums.ColorHelper.write(out, $result); + break; + } + + default: + throw new org.omg.CORBA.BAD_OPERATION(0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE); + } + + return out; + } // _invoke + + // Type-specific CORBA::Object operations + private static String[] __ids = {"IDL:org/apache/tuscany/sca/binding/corba/testing/enums/EnumManager:1.0"}; + + @Override + public String[] _ids() { + return (String[])__ids.clone(); + } + +} // class _EnumManagerImplBase diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/enums/_EnumManagerStub.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/enums/_EnumManagerStub.java new file mode 100644 index 0000000000..4629ca9cff --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/enums/_EnumManagerStub.java @@ -0,0 +1,75 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.enums; + +/** +* org/apache/tuscany/sca/binding/corba/testing/enums/_EnumManagerStub.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from enums.idl +* czwartek, 19 czerwiec 2008 15:46:10 CEST +*/ + +public class _EnumManagerStub extends org.omg.CORBA.portable.ObjectImpl implements + org.apache.tuscany.sca.binding.corba.testing.enums.EnumManager { + + public org.apache.tuscany.sca.binding.corba.testing.enums.Color getColor(org.apache.tuscany.sca.binding.corba.testing.enums.Color color) { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("getColor", true); + org.apache.tuscany.sca.binding.corba.testing.enums.ColorHelper.write($out, color); + $in = _invoke($out); + org.apache.tuscany.sca.binding.corba.testing.enums.Color $result = + org.apache.tuscany.sca.binding.corba.testing.enums.ColorHelper.read($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return getColor(color); + } finally { + _releaseReply($in); + } + } // getColor + + // Type-specific CORBA::Object operations + private static String[] __ids = {"IDL:org/apache/tuscany/sca/binding/corba/testing/enums/EnumManager:1.0"}; + + @Override + public String[] _ids() { + return (String[])__ids.clone(); + } + + private void readObject(java.io.ObjectInputStream s) throws java.io.IOException { + String str = s.readUTF(); + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.Object obj = org.omg.CORBA.ORB.init(args, props).string_to_object(str); + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate(); + _set_delegate(delegate); + } + + private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { + String[] args = null; + java.util.Properties props = null; + String str = org.omg.CORBA.ORB.init(args, props).object_to_string(this); + s.writeUTF(str); + } +} // class _EnumManagerStub diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/Calc.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/Calc.java new file mode 100644 index 0000000000..aa480f93ac --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/Calc.java @@ -0,0 +1,30 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.exceptions; + +/** +* org/apache/tuscany/sca/binding/corba/testing/exceptions/Calc.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from exceptions.idl +* sobota, 7 czerwiec 2008 16:12:31 CEST +*/ + +public interface Calc extends CalcOperations, org.omg.CORBA.Object, org.omg.CORBA.portable.IDLEntity { +} // interface Calc diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcHelper.java new file mode 100644 index 0000000000..5ed36ca19b --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcHelper.java @@ -0,0 +1,98 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.exceptions; + +/** +* org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from exceptions.idl +* sobota, 7 czerwiec 2008 16:12:31 CEST +*/ + +abstract public class CalcHelper { + private static String _id = "IDL:org/apache/tuscany/sca/binding/corba/testing/exceptions/Calc:1.0"; + + public static void insert(org.omg.CORBA.Any a, org.apache.tuscany.sca.binding.corba.testing.exceptions.Calc that) { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream(); + a.type(type()); + write(out, that); + a.read_value(out.create_input_stream(), type()); + } + + public static org.apache.tuscany.sca.binding.corba.testing.exceptions.Calc extract(org.omg.CORBA.Any a) { + return read(a.create_input_stream()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + + synchronized public static org.omg.CORBA.TypeCode type() { + if (__typeCode == null) { + __typeCode = + org.omg.CORBA.ORB.init() + .create_interface_tc(org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcHelper.id(), + "Calc"); + } + return __typeCode; + } + + public static String id() { + return _id; + } + + public static org.apache.tuscany.sca.binding.corba.testing.exceptions.Calc read(org.omg.CORBA.portable.InputStream istream) { + return narrow(istream.read_Object(_CalcStub.class)); + } + + public static void write(org.omg.CORBA.portable.OutputStream ostream, + org.apache.tuscany.sca.binding.corba.testing.exceptions.Calc value) { + ostream.write_Object((org.omg.CORBA.Object)value); + } + + public static org.apache.tuscany.sca.binding.corba.testing.exceptions.Calc narrow(org.omg.CORBA.Object obj) { + if (obj == null) + return null; + else if (obj instanceof org.apache.tuscany.sca.binding.corba.testing.exceptions.Calc) + return (org.apache.tuscany.sca.binding.corba.testing.exceptions.Calc)obj; + else if (!obj._is_a(id())) + throw new org.omg.CORBA.BAD_PARAM(); + else { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate(); + org.apache.tuscany.sca.binding.corba.testing.exceptions._CalcStub stub = + new org.apache.tuscany.sca.binding.corba.testing.exceptions._CalcStub(); + stub._set_delegate(delegate); + return stub; + } + } + + public static org.apache.tuscany.sca.binding.corba.testing.exceptions.Calc unchecked_narrow(org.omg.CORBA.Object obj) { + if (obj == null) + return null; + else if (obj instanceof org.apache.tuscany.sca.binding.corba.testing.exceptions.Calc) + return (org.apache.tuscany.sca.binding.corba.testing.exceptions.Calc)obj; + else { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate(); + org.apache.tuscany.sca.binding.corba.testing.exceptions._CalcStub stub = + new org.apache.tuscany.sca.binding.corba.testing.exceptions._CalcStub(); + stub._set_delegate(delegate); + return stub; + } + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcHolder.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcHolder.java new file mode 100644 index 0000000000..ec1cfadd1e --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcHolder.java @@ -0,0 +1,51 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.exceptions; + +/** +* org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from exceptions.idl +* sobota, 7 czerwiec 2008 16:12:31 CEST +*/ + +public final class CalcHolder implements org.omg.CORBA.portable.Streamable { + public org.apache.tuscany.sca.binding.corba.testing.exceptions.Calc value = null; + + public CalcHolder() { + } + + public CalcHolder(org.apache.tuscany.sca.binding.corba.testing.exceptions.Calc initialValue) { + value = initialValue; + } + + public void _read(org.omg.CORBA.portable.InputStream i) { + value = org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcHelper.read(i); + } + + public void _write(org.omg.CORBA.portable.OutputStream o) { + org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcHelper.write(o, value); + } + + public org.omg.CORBA.TypeCode _type() { + return org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcHelper.type(); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcOperations.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcOperations.java new file mode 100644 index 0000000000..29865ace06 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcOperations.java @@ -0,0 +1,36 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.exceptions; + +/** +* org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcOperations.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from exceptions.idl +* sobota, 7 czerwiec 2008 16:12:31 CEST +*/ + +public interface CalcOperations { + double div(double arg1, double arg2) + throws org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.DivByZero; + + double divForSmallArgs(double arg1, double arg2) + throws org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.DivByZero, + org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.NotSupported; +} // interface CalcOperations diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/Arguments.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/Arguments.java new file mode 100644 index 0000000000..d7839ec4db --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/Arguments.java @@ -0,0 +1,41 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage; + +/** +* org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/Arguments.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from exceptions.idl +* sobota, 7 czerwiec 2008 16:12:31 CEST +*/ + +public final class Arguments implements org.omg.CORBA.portable.IDLEntity { + public double arg1 = (double)0; + public double arg2 = (double)0; + + public Arguments() { + } // ctor + + public Arguments(double _arg1, double _arg2) { + arg1 = _arg1; + arg2 = _arg2; + } // ctor + +} // class Arguments diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/ArgumentsHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/ArgumentsHelper.java new file mode 100644 index 0000000000..c47d63208f --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/ArgumentsHelper.java @@ -0,0 +1,94 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage; + +/** +* org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/ArgumentsHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from exceptions.idl +* sobota, 7 czerwiec 2008 16:12:31 CEST +*/ + +abstract public class ArgumentsHelper { + private static String _id = + "IDL:org/apache/tuscany/sca/binding/corba/testing/exceptions/Calc/Arguments/Arguments:1.0"; + + public static void insert(org.omg.CORBA.Any a, + org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.Arguments that) { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream(); + a.type(type()); + write(out, that); + a.read_value(out.create_input_stream(), type()); + } + + public static org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.Arguments extract(org.omg.CORBA.Any a) { + return read(a.create_input_stream()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + + synchronized public static org.omg.CORBA.TypeCode type() { + if (__typeCode == null) { + synchronized (org.omg.CORBA.TypeCode.class) { + if (__typeCode == null) { + if (__active) { + return org.omg.CORBA.ORB.init().create_recursive_tc(_id); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember[2]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + _tcOf_members0 = org.omg.CORBA.ORB.init().get_primitive_tc(org.omg.CORBA.TCKind.tk_double); + _members0[0] = new org.omg.CORBA.StructMember("arg1", _tcOf_members0, null); + _tcOf_members0 = org.omg.CORBA.ORB.init().get_primitive_tc(org.omg.CORBA.TCKind.tk_double); + _members0[1] = new org.omg.CORBA.StructMember("arg2", _tcOf_members0, null); + __typeCode = + org.omg.CORBA.ORB + .init() + .create_struct_tc(org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.ArgumentsHelper + .id(), + "Arguments", + _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id() { + return _id; + } + + public static org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.Arguments read(org.omg.CORBA.portable.InputStream istream) { + org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.Arguments value = + new org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.Arguments(); + value.arg1 = istream.read_double(); + value.arg2 = istream.read_double(); + return value; + } + + public static void write(org.omg.CORBA.portable.OutputStream ostream, + org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.Arguments value) { + ostream.write_double(value.arg1); + ostream.write_double(value.arg2); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/ArgumentsHolder.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/ArgumentsHolder.java new file mode 100644 index 0000000000..f767e8c11a --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/ArgumentsHolder.java @@ -0,0 +1,51 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage; + +/** +* org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/ArgumentsHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from exceptions.idl +* sobota, 7 czerwiec 2008 16:12:31 CEST +*/ + +public final class ArgumentsHolder implements org.omg.CORBA.portable.Streamable { + public org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.Arguments value = null; + + public ArgumentsHolder() { + } + + public ArgumentsHolder(org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.Arguments initialValue) { + value = initialValue; + } + + public void _read(org.omg.CORBA.portable.InputStream i) { + value = org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.ArgumentsHelper.read(i); + } + + public void _write(org.omg.CORBA.portable.OutputStream o) { + org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.ArgumentsHelper.write(o, value); + } + + public org.omg.CORBA.TypeCode _type() { + return org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.ArgumentsHelper.type(); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/DivByZero.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/DivByZero.java new file mode 100644 index 0000000000..e7cbb4b8ca --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/DivByZero.java @@ -0,0 +1,52 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage; + +/** +* org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/DivByZero.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from exceptions.idl +* sobota, 7 czerwiec 2008 16:12:31 CEST +*/ + +public final class DivByZero extends org.omg.CORBA.UserException { + public org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.Arguments arguments = null; + public String info = null; + + public DivByZero() { + super(DivByZeroHelper.id()); + } // ctor + + public DivByZero(org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.Arguments _arguments, + String _info) { + super(DivByZeroHelper.id()); + arguments = _arguments; + info = _info; + } // ctor + + public DivByZero(String $reason, + org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.Arguments _arguments, + String _info) { + super(DivByZeroHelper.id() + " " + $reason); + arguments = _arguments; + info = _info; + } // ctor + +} // class DivByZero diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/DivByZeroHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/DivByZeroHelper.java new file mode 100644 index 0000000000..5d27f9969c --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/DivByZeroHelper.java @@ -0,0 +1,100 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage; + +/** +* org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/DivByZeroHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from exceptions.idl +* sobota, 7 czerwiec 2008 16:12:31 CEST +*/ + +abstract public class DivByZeroHelper { + private static String _id = "IDL:org/apache/tuscany/sca/binding/corba/testing/exceptions/Calc/DivByZero:1.0"; + + public static void insert(org.omg.CORBA.Any a, + org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.DivByZero that) { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream(); + a.type(type()); + write(out, that); + a.read_value(out.create_input_stream(), type()); + } + + public static org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.DivByZero extract(org.omg.CORBA.Any a) { + return read(a.create_input_stream()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + + synchronized public static org.omg.CORBA.TypeCode type() { + if (__typeCode == null) { + synchronized (org.omg.CORBA.TypeCode.class) { + if (__typeCode == null) { + if (__active) { + return org.omg.CORBA.ORB.init().create_recursive_tc(_id); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember[2]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + _tcOf_members0 = + org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.ArgumentsHelper.type(); + _members0[0] = new org.omg.CORBA.StructMember("arguments", _tcOf_members0, null); + _tcOf_members0 = org.omg.CORBA.ORB.init().create_string_tc(0); + _members0[1] = new org.omg.CORBA.StructMember("info", _tcOf_members0, null); + __typeCode = + org.omg.CORBA.ORB + .init() + .create_exception_tc(org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.DivByZeroHelper + .id(), + "DivByZero", + _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id() { + return _id; + } + + public static org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.DivByZero read(org.omg.CORBA.portable.InputStream istream) { + org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.DivByZero value = + new org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.DivByZero(); + // read and discard the repository ID + istream.read_string(); + value.arguments = + org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.ArgumentsHelper.read(istream); + value.info = istream.read_string(); + return value; + } + + public static void write(org.omg.CORBA.portable.OutputStream ostream, + org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.DivByZero value) { + // write the repository ID + ostream.write_string(id()); + org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.ArgumentsHelper.write(ostream, + value.arguments); + ostream.write_string(value.info); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/DivByZeroHolder.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/DivByZeroHolder.java new file mode 100644 index 0000000000..ab01c66675 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/DivByZeroHolder.java @@ -0,0 +1,51 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage; + +/** +* org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/DivByZeroHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from exceptions.idl +* sobota, 7 czerwiec 2008 16:12:31 CEST +*/ + +public final class DivByZeroHolder implements org.omg.CORBA.portable.Streamable { + public org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.DivByZero value = null; + + public DivByZeroHolder() { + } + + public DivByZeroHolder(org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.DivByZero initialValue) { + value = initialValue; + } + + public void _read(org.omg.CORBA.portable.InputStream i) { + value = org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.DivByZeroHelper.read(i); + } + + public void _write(org.omg.CORBA.portable.OutputStream o) { + org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.DivByZeroHelper.write(o, value); + } + + public org.omg.CORBA.TypeCode _type() { + return org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.DivByZeroHelper.type(); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/NotSupported.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/NotSupported.java new file mode 100644 index 0000000000..f4ea58e55e --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/NotSupported.java @@ -0,0 +1,46 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage; + +/** +* org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/NotSupported.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from exceptions.idl +* sobota, 7 czerwiec 2008 16:12:31 CEST +*/ + +public final class NotSupported extends org.omg.CORBA.UserException { + public String info = null; + + public NotSupported() { + super(NotSupportedHelper.id()); + } // ctor + + public NotSupported(String _info) { + super(NotSupportedHelper.id()); + info = _info; + } // ctor + + public NotSupported(String $reason, String _info) { + super(NotSupportedHelper.id() + " " + $reason); + info = _info; + } // ctor + +} // class NotSupported diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/NotSupportedHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/NotSupportedHelper.java new file mode 100644 index 0000000000..82609a36c1 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/NotSupportedHelper.java @@ -0,0 +1,93 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage; + +/** +* org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/NotSupportedHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from exceptions.idl +* sobota, 7 czerwiec 2008 16:12:31 CEST +*/ + +abstract public class NotSupportedHelper { + private static String _id = "IDL:org/apache/tuscany/sca/binding/corba/testing/exceptions/Calc/NotSupported:1.0"; + + public static void insert(org.omg.CORBA.Any a, + org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.NotSupported that) { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream(); + a.type(type()); + write(out, that); + a.read_value(out.create_input_stream(), type()); + } + + public static org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.NotSupported extract(org.omg.CORBA.Any a) { + return read(a.create_input_stream()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + + synchronized public static org.omg.CORBA.TypeCode type() { + if (__typeCode == null) { + synchronized (org.omg.CORBA.TypeCode.class) { + if (__typeCode == null) { + if (__active) { + return org.omg.CORBA.ORB.init().create_recursive_tc(_id); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember[1]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + _tcOf_members0 = org.omg.CORBA.ORB.init().create_string_tc(0); + _members0[0] = new org.omg.CORBA.StructMember("info", _tcOf_members0, null); + __typeCode = + org.omg.CORBA.ORB + .init() + .create_exception_tc(org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.NotSupportedHelper + .id(), + "NotSupported", + _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id() { + return _id; + } + + public static org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.NotSupported read(org.omg.CORBA.portable.InputStream istream) { + org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.NotSupported value = + new org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.NotSupported(); + // read and discard the repository ID + istream.read_string(); + value.info = istream.read_string(); + return value; + } + + public static void write(org.omg.CORBA.portable.OutputStream ostream, + org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.NotSupported value) { + // write the repository ID + ostream.write_string(id()); + ostream.write_string(value.info); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/NotSupportedHolder.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/NotSupportedHolder.java new file mode 100644 index 0000000000..1389bd33d9 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/NotSupportedHolder.java @@ -0,0 +1,51 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage; + +/** +* org/apache/tuscany/sca/binding/corba/testing/exceptions/CalcPackage/NotSupportedHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from exceptions.idl +* sobota, 7 czerwiec 2008 16:12:31 CEST +*/ + +public final class NotSupportedHolder implements org.omg.CORBA.portable.Streamable { + public org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.NotSupported value = null; + + public NotSupportedHolder() { + } + + public NotSupportedHolder(org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.NotSupported initialValue) { + value = initialValue; + } + + public void _read(org.omg.CORBA.portable.InputStream i) { + value = org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.NotSupportedHelper.read(i); + } + + public void _write(org.omg.CORBA.portable.OutputStream o) { + org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.NotSupportedHelper.write(o, value); + } + + public org.omg.CORBA.TypeCode _type() { + return org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.NotSupportedHelper.type(); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/_CalcImplBase.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/_CalcImplBase.java new file mode 100644 index 0000000000..a73e252129 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/_CalcImplBase.java @@ -0,0 +1,102 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.exceptions; + +/** +* org/apache/tuscany/sca/binding/corba/testing/exceptions/_CalcImplBase.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from exceptions.idl +* sobota, 7 czerwiec 2008 16:12:31 CEST +*/ + +public abstract class _CalcImplBase extends org.omg.CORBA.portable.ObjectImpl implements + org.apache.tuscany.sca.binding.corba.testing.exceptions.Calc, org.omg.CORBA.portable.InvokeHandler { + + // Constructors + public _CalcImplBase() { + } + + private static java.util.Hashtable _methods = new java.util.Hashtable(); + static { + _methods.put("div", new java.lang.Integer(0)); + _methods.put("divForSmallArgs", new java.lang.Integer(1)); + } + + public org.omg.CORBA.portable.OutputStream _invoke(String $method, + org.omg.CORBA.portable.InputStream in, + org.omg.CORBA.portable.ResponseHandler $rh) { + org.omg.CORBA.portable.OutputStream out = null; + java.lang.Integer __method = (java.lang.Integer)_methods.get($method); + if (__method == null) + throw new org.omg.CORBA.BAD_OPERATION(0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE); + + switch (__method.intValue()) { + case 0: // org/apache/tuscany/sca/binding/corba/testing/exceptions/Calc/div + { + try { + double arg1 = in.read_double(); + double arg2 = in.read_double(); + double $result = (double)0; + $result = this.div(arg1, arg2); + out = $rh.createReply(); + out.write_double($result); + } catch (org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.DivByZero $ex) { + out = $rh.createExceptionReply(); + org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.DivByZeroHelper.write(out, $ex); + } + break; + } + + case 1: // org/apache/tuscany/sca/binding/corba/testing/exceptions/Calc/divForSmallArgs + { + try { + double arg1 = in.read_double(); + double arg2 = in.read_double(); + double $result = (double)0; + $result = this.divForSmallArgs(arg1, arg2); + out = $rh.createReply(); + out.write_double($result); + } catch (org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.DivByZero $ex) { + out = $rh.createExceptionReply(); + org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.DivByZeroHelper.write(out, $ex); + } catch (org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.NotSupported $ex) { + out = $rh.createExceptionReply(); + org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.NotSupportedHelper.write(out, + $ex); + } + break; + } + + default: + throw new org.omg.CORBA.BAD_OPERATION(0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE); + } + + return out; + } // _invoke + + // Type-specific CORBA::Object operations + private static String[] __ids = {"IDL:org/apache/tuscany/sca/binding/corba/testing/exceptions/Calc:1.0"}; + + @Override + public String[] _ids() { + return (String[])__ids.clone(); + } + +} // class _CalcImplBase diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/_CalcStub.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/_CalcStub.java new file mode 100644 index 0000000000..65ce051129 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/exceptions/_CalcStub.java @@ -0,0 +1,106 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.exceptions; + +/** +* org/apache/tuscany/sca/binding/corba/testing/exceptions/_CalcStub.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from exceptions.idl +* sobota, 7 czerwiec 2008 16:12:31 CEST +*/ + +public class _CalcStub extends org.omg.CORBA.portable.ObjectImpl implements + org.apache.tuscany.sca.binding.corba.testing.exceptions.Calc { + + public double div(double arg1, double arg2) + throws org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.DivByZero { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("div", true); + $out.write_double(arg1); + $out.write_double(arg2); + $in = _invoke($out); + double $result = $in.read_double(); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + if (_id.equals("IDL:org/apache/tuscany/sca/binding/corba/testing/exceptions/Calc/DivByZero:1.0")) + throw org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.DivByZeroHelper.read($in); + else + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return div(arg1, arg2); + } finally { + _releaseReply($in); + } + } // div + + public double divForSmallArgs(double arg1, double arg2) + throws org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.DivByZero, + org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.NotSupported { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("divForSmallArgs", true); + $out.write_double(arg1); + $out.write_double(arg2); + $in = _invoke($out); + double $result = $in.read_double(); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + if (_id.equals("IDL:org/apache/tuscany/sca/binding/corba/testing/exceptions/Calc/DivByZero:1.0")) + throw org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.DivByZeroHelper.read($in); + else if (_id.equals("IDL:org/apache/tuscany/sca/binding/corba/testing/exceptions/Calc/NotSupported:1.0")) + throw org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.NotSupportedHelper.read($in); + else + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return divForSmallArgs(arg1, arg2); + } finally { + _releaseReply($in); + } + } // divForSmallArgs + + // Type-specific CORBA::Object operations + private static String[] __ids = {"IDL:org/apache/tuscany/sca/binding/corba/testing/exceptions/Calc:1.0"}; + + @Override + public String[] _ids() { + return (String[])__ids.clone(); + } + + private void readObject(java.io.ObjectInputStream s) throws java.io.IOException { + String str = s.readUTF(); + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.Object obj = org.omg.CORBA.ORB.init(args, props).string_to_object(str); + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate(); + _set_delegate(delegate); + } + + private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { + String[] args = null; + java.util.Properties props = null; + String str = org.omg.CORBA.ORB.init(args, props).object_to_string(this); + s.writeUTF(str); + } +} // class _CalcStub diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/ArraysSetter.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/ArraysSetter.java new file mode 100644 index 0000000000..fde204edf8 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/ArraysSetter.java @@ -0,0 +1,30 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/ArraysSetter.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 14:12:28 CEST +*/ + +public interface ArraysSetter extends ArraysSetterOperations, org.omg.CORBA.Object, org.omg.CORBA.portable.IDLEntity { +} // interface ArraysSetter diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/ArraysSetterHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/ArraysSetterHelper.java new file mode 100644 index 0000000000..71b4fbbdb6 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/ArraysSetterHelper.java @@ -0,0 +1,100 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/ArraysSetterHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 14:12:28 CEST +*/ + +abstract public class ArraysSetterHelper { + private static String _id = "IDL:org/apache/tuscany/sca/binding/corba/testing/generated/ArraysSetter:1.0"; + + public static void insert(org.omg.CORBA.Any a, + org.apache.tuscany.sca.binding.corba.testing.generated.ArraysSetter that) { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream(); + a.type(type()); + write(out, that); + a.read_value(out.create_input_stream(), type()); + } + + public static org.apache.tuscany.sca.binding.corba.testing.generated.ArraysSetter extract(org.omg.CORBA.Any a) { + return read(a.create_input_stream()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + + synchronized public static org.omg.CORBA.TypeCode type() { + if (__typeCode == null) { + __typeCode = + org.omg.CORBA.ORB + .init() + .create_interface_tc(org.apache.tuscany.sca.binding.corba.testing.generated.ArraysSetterHelper.id(), + "ArraysSetter"); + } + return __typeCode; + } + + public static String id() { + return _id; + } + + public static org.apache.tuscany.sca.binding.corba.testing.generated.ArraysSetter read(org.omg.CORBA.portable.InputStream istream) { + return narrow(istream.read_Object(_ArraysSetterStub.class)); + } + + public static void write(org.omg.CORBA.portable.OutputStream ostream, + org.apache.tuscany.sca.binding.corba.testing.generated.ArraysSetter value) { + ostream.write_Object((org.omg.CORBA.Object)value); + } + + public static org.apache.tuscany.sca.binding.corba.testing.generated.ArraysSetter narrow(org.omg.CORBA.Object obj) { + if (obj == null) + return null; + else if (obj instanceof org.apache.tuscany.sca.binding.corba.testing.generated.ArraysSetter) + return (org.apache.tuscany.sca.binding.corba.testing.generated.ArraysSetter)obj; + else if (!obj._is_a(id())) + throw new org.omg.CORBA.BAD_PARAM(); + else { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate(); + org.apache.tuscany.sca.binding.corba.testing.generated._ArraysSetterStub stub = + new org.apache.tuscany.sca.binding.corba.testing.generated._ArraysSetterStub(); + stub._set_delegate(delegate); + return stub; + } + } + + public static org.apache.tuscany.sca.binding.corba.testing.generated.ArraysSetter unchecked_narrow(org.omg.CORBA.Object obj) { + if (obj == null) + return null; + else if (obj instanceof org.apache.tuscany.sca.binding.corba.testing.generated.ArraysSetter) + return (org.apache.tuscany.sca.binding.corba.testing.generated.ArraysSetter)obj; + else { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate(); + org.apache.tuscany.sca.binding.corba.testing.generated._ArraysSetterStub stub = + new org.apache.tuscany.sca.binding.corba.testing.generated._ArraysSetterStub(); + stub._set_delegate(delegate); + return stub; + } + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/ArraysSetterHolder.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/ArraysSetterHolder.java new file mode 100644 index 0000000000..d758a560a9 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/ArraysSetterHolder.java @@ -0,0 +1,51 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/ArraysSetterHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 14:12:28 CEST +*/ + +public final class ArraysSetterHolder implements org.omg.CORBA.portable.Streamable { + public org.apache.tuscany.sca.binding.corba.testing.generated.ArraysSetter value = null; + + public ArraysSetterHolder() { + } + + public ArraysSetterHolder(org.apache.tuscany.sca.binding.corba.testing.generated.ArraysSetter initialValue) { + value = initialValue; + } + + public void _read(org.omg.CORBA.portable.InputStream i) { + value = org.apache.tuscany.sca.binding.corba.testing.generated.ArraysSetterHelper.read(i); + } + + public void _write(org.omg.CORBA.portable.OutputStream o) { + org.apache.tuscany.sca.binding.corba.testing.generated.ArraysSetterHelper.write(o, value); + } + + public org.omg.CORBA.TypeCode _type() { + return org.apache.tuscany.sca.binding.corba.testing.generated.ArraysSetterHelper.type(); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/ArraysSetterOperations.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/ArraysSetterOperations.java new file mode 100644 index 0000000000..464c2ccbc3 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/ArraysSetterOperations.java @@ -0,0 +1,59 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/ArraysSetterOperations.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 14:12:28 CEST +*/ + +public interface ArraysSetterOperations { + boolean[] setBoolean(boolean[] arg); + + char[] setChar(char[] arg); + + char[] setWchar(char[] arg); + + byte[] setOctet(byte[] arg); + + short[] setShort(short[] arg); + + short[] setUnsignedShort(short[] arg); + + int[] setLong(int[] arg); + + int[] setUnsignedLong(int[] arg); + + long[] setLongLong(long[] arg); + + long[] setUnsignedLongLong(long[] arg); + + float[] setFloat(float[] arg); + + double[] setDouble(double[] arg); + + String[] setString(String[] arg); + + String[] setWstring(String[] arg); + + org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObject[] setRemoteObject(org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObject[] obj); +} // interface ArraysSetterOperations diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/PrimitivesSetter.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/PrimitivesSetter.java new file mode 100644 index 0000000000..c053f12a02 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/PrimitivesSetter.java @@ -0,0 +1,31 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/PrimitivesSetter.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 2008 14:12:28 CEST +*/ + +public interface PrimitivesSetter extends PrimitivesSetterOperations, org.omg.CORBA.Object, + org.omg.CORBA.portable.IDLEntity { +} // interface PrimitivesSetter diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/PrimitivesSetterHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/PrimitivesSetterHelper.java new file mode 100644 index 0000000000..566689960e --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/PrimitivesSetterHelper.java @@ -0,0 +1,100 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/PrimitivesSetterHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 2008 14:12:28 CEST +*/ + +abstract public class PrimitivesSetterHelper { + private static String _id = "IDL:org/apache/tuscany/sca/binding/corba/testing/generated/PrimitivesSetter:1.0"; + + public static void insert(org.omg.CORBA.Any a, + org.apache.tuscany.sca.binding.corba.testing.generated.PrimitivesSetter that) { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream(); + a.type(type()); + write(out, that); + a.read_value(out.create_input_stream(), type()); + } + + public static org.apache.tuscany.sca.binding.corba.testing.generated.PrimitivesSetter extract(org.omg.CORBA.Any a) { + return read(a.create_input_stream()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + + synchronized public static org.omg.CORBA.TypeCode type() { + if (__typeCode == null) { + __typeCode = + org.omg.CORBA.ORB.init() + .create_interface_tc(org.apache.tuscany.sca.binding.corba.testing.generated.PrimitivesSetterHelper + .id(), + "PrimitivesSetter"); + } + return __typeCode; + } + + public static String id() { + return _id; + } + + public static org.apache.tuscany.sca.binding.corba.testing.generated.PrimitivesSetter read(org.omg.CORBA.portable.InputStream istream) { + return narrow(istream.read_Object(_PrimitivesSetterStub.class)); + } + + public static void write(org.omg.CORBA.portable.OutputStream ostream, + org.apache.tuscany.sca.binding.corba.testing.generated.PrimitivesSetter value) { + ostream.write_Object((org.omg.CORBA.Object)value); + } + + public static org.apache.tuscany.sca.binding.corba.testing.generated.PrimitivesSetter narrow(org.omg.CORBA.Object obj) { + if (obj == null) + return null; + else if (obj instanceof org.apache.tuscany.sca.binding.corba.testing.generated.PrimitivesSetter) + return (org.apache.tuscany.sca.binding.corba.testing.generated.PrimitivesSetter)obj; + else if (!obj._is_a(id())) + throw new org.omg.CORBA.BAD_PARAM(); + else { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate(); + org.apache.tuscany.sca.binding.corba.testing.generated._PrimitivesSetterStub stub = + new org.apache.tuscany.sca.binding.corba.testing.generated._PrimitivesSetterStub(); + stub._set_delegate(delegate); + return stub; + } + } + + public static org.apache.tuscany.sca.binding.corba.testing.generated.PrimitivesSetter unchecked_narrow(org.omg.CORBA.Object obj) { + if (obj == null) + return null; + else if (obj instanceof org.apache.tuscany.sca.binding.corba.testing.generated.PrimitivesSetter) + return (org.apache.tuscany.sca.binding.corba.testing.generated.PrimitivesSetter)obj; + else { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate(); + org.apache.tuscany.sca.binding.corba.testing.generated._PrimitivesSetterStub stub = + new org.apache.tuscany.sca.binding.corba.testing.generated._PrimitivesSetterStub(); + stub._set_delegate(delegate); + return stub; + } + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/PrimitivesSetterHolder.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/PrimitivesSetterHolder.java new file mode 100644 index 0000000000..6564957081 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/PrimitivesSetterHolder.java @@ -0,0 +1,51 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/PrimitivesSetterHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 2008 14:12:28 CEST +*/ + +public final class PrimitivesSetterHolder implements org.omg.CORBA.portable.Streamable { + public org.apache.tuscany.sca.binding.corba.testing.generated.PrimitivesSetter value = null; + + public PrimitivesSetterHolder() { + } + + public PrimitivesSetterHolder(org.apache.tuscany.sca.binding.corba.testing.generated.PrimitivesSetter initialValue) { + value = initialValue; + } + + public void _read(org.omg.CORBA.portable.InputStream i) { + value = org.apache.tuscany.sca.binding.corba.testing.generated.PrimitivesSetterHelper.read(i); + } + + public void _write(org.omg.CORBA.portable.OutputStream o) { + org.apache.tuscany.sca.binding.corba.testing.generated.PrimitivesSetterHelper.write(o, value); + } + + public org.omg.CORBA.TypeCode _type() { + return org.apache.tuscany.sca.binding.corba.testing.generated.PrimitivesSetterHelper.type(); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/PrimitivesSetterOperations.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/PrimitivesSetterOperations.java new file mode 100644 index 0000000000..26669de95a --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/PrimitivesSetterOperations.java @@ -0,0 +1,59 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/PrimitivesSetterOperations.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 2008 14:12:28 CEST +*/ + +public interface PrimitivesSetterOperations { + boolean setBoolean(boolean arg); + + char setChar(char arg); + + char setWchar(char arg); + + byte setOctet(byte arg); + + short setShort(short arg); + + short setUnsignedShort(short arg); + + int setLong(int arg); + + int setUnsignedLong(int arg); + + long setLongLong(long arg); + + long setUnsignedLongLong(long arg); + + float setFloat(float arg); + + double setDouble(double arg); + + String setString(String arg); + + String setWstring(String arg); + + org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObject setRemoteObject(org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObject obj); +} // interface PrimitivesSetterOperations diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/RemoteObject.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/RemoteObject.java new file mode 100644 index 0000000000..5a140f5ecc --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/RemoteObject.java @@ -0,0 +1,30 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/RemoteObject.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 2008 14:12:28 CEST +*/ + +public interface RemoteObject extends RemoteObjectOperations, org.omg.CORBA.Object, org.omg.CORBA.portable.IDLEntity { +} // interface RemoteObject diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/RemoteObjectHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/RemoteObjectHelper.java new file mode 100644 index 0000000000..2a8fe73417 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/RemoteObjectHelper.java @@ -0,0 +1,100 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/RemoteObjectHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 2008 14:12:28 CEST +*/ + +abstract public class RemoteObjectHelper { + private static String _id = "IDL:org/apache/tuscany/sca/binding/corba/testing/generated/RemoteObject:1.0"; + + public static void insert(org.omg.CORBA.Any a, + org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObject that) { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream(); + a.type(type()); + write(out, that); + a.read_value(out.create_input_stream(), type()); + } + + public static org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObject extract(org.omg.CORBA.Any a) { + return read(a.create_input_stream()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + + synchronized public static org.omg.CORBA.TypeCode type() { + if (__typeCode == null) { + __typeCode = + org.omg.CORBA.ORB + .init() + .create_interface_tc(org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObjectHelper.id(), + "RemoteObject"); + } + return __typeCode; + } + + public static String id() { + return _id; + } + + public static org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObject read(org.omg.CORBA.portable.InputStream istream) { + return narrow(istream.read_Object(_RemoteObjectStub.class)); + } + + public static void write(org.omg.CORBA.portable.OutputStream ostream, + org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObject value) { + ostream.write_Object((org.omg.CORBA.Object)value); + } + + public static org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObject narrow(org.omg.CORBA.Object obj) { + if (obj == null) + return null; + else if (obj instanceof org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObject) + return (org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObject)obj; + else if (!obj._is_a(id())) + throw new org.omg.CORBA.BAD_PARAM(); + else { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate(); + org.apache.tuscany.sca.binding.corba.testing.generated._RemoteObjectStub stub = + new org.apache.tuscany.sca.binding.corba.testing.generated._RemoteObjectStub(); + stub._set_delegate(delegate); + return stub; + } + } + + public static org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObject unchecked_narrow(org.omg.CORBA.Object obj) { + if (obj == null) + return null; + else if (obj instanceof org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObject) + return (org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObject)obj; + else { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate(); + org.apache.tuscany.sca.binding.corba.testing.generated._RemoteObjectStub stub = + new org.apache.tuscany.sca.binding.corba.testing.generated._RemoteObjectStub(); + stub._set_delegate(delegate); + return stub; + } + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/RemoteObjectHolder.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/RemoteObjectHolder.java new file mode 100644 index 0000000000..63e3926dd2 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/RemoteObjectHolder.java @@ -0,0 +1,51 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/RemoteObjectHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 2008 14:12:28 CEST +*/ + +public final class RemoteObjectHolder implements org.omg.CORBA.portable.Streamable { + public org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObject value = null; + + public RemoteObjectHolder() { + } + + public RemoteObjectHolder(org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObject initialValue) { + value = initialValue; + } + + public void _read(org.omg.CORBA.portable.InputStream i) { + value = org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObjectHelper.read(i); + } + + public void _write(org.omg.CORBA.portable.OutputStream o) { + org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObjectHelper.write(o, value); + } + + public org.omg.CORBA.TypeCode _type() { + return org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObjectHelper.type(); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/RemoteObjectOperations.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/RemoteObjectOperations.java new file mode 100644 index 0000000000..a8231236eb --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/RemoteObjectOperations.java @@ -0,0 +1,30 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/RemoteObjectOperations.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 2008 14:12:28 CEST +*/ + +public interface RemoteObjectOperations { +} // interface RemoteObjectOperations diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/SimpleStruct.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/SimpleStruct.java new file mode 100644 index 0000000000..ca86420240 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/SimpleStruct.java @@ -0,0 +1,41 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/SimpleStruct.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 2008 14:12:28 CEST +*/ + +public final class SimpleStruct implements org.omg.CORBA.portable.IDLEntity { + public String field1 = null; + public int field2 = (int)0; + + public SimpleStruct() { + } // ctor + + public SimpleStruct(String _field1, int _field2) { + field1 = _field1; + field2 = _field2; + } // ctor + +} // class SimpleStruct diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/SimpleStructHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/SimpleStructHelper.java new file mode 100644 index 0000000000..2a8898d38f --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/SimpleStructHelper.java @@ -0,0 +1,93 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/SimpleStructHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 2008 14:12:28 CEST +*/ + +abstract public class SimpleStructHelper { + private static String _id = + "IDL:org/apache/tuscany/sca/binding/corba/testing/generated/SimpleStruct/SimpleStruct:1.0"; + + public static void insert(org.omg.CORBA.Any a, + org.apache.tuscany.sca.binding.corba.testing.generated.SimpleStruct that) { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream(); + a.type(type()); + write(out, that); + a.read_value(out.create_input_stream(), type()); + } + + public static org.apache.tuscany.sca.binding.corba.testing.generated.SimpleStruct extract(org.omg.CORBA.Any a) { + return read(a.create_input_stream()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + + synchronized public static org.omg.CORBA.TypeCode type() { + if (__typeCode == null) { + synchronized (org.omg.CORBA.TypeCode.class) { + if (__typeCode == null) { + if (__active) { + return org.omg.CORBA.ORB.init().create_recursive_tc(_id); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember[2]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + _tcOf_members0 = org.omg.CORBA.ORB.init().create_string_tc(0); + _members0[0] = new org.omg.CORBA.StructMember("field1", _tcOf_members0, null); + _tcOf_members0 = org.omg.CORBA.ORB.init().get_primitive_tc(org.omg.CORBA.TCKind.tk_long); + _members0[1] = new org.omg.CORBA.StructMember("field2", _tcOf_members0, null); + __typeCode = + org.omg.CORBA.ORB.init() + .create_struct_tc(org.apache.tuscany.sca.binding.corba.testing.generated.SimpleStructHelper + .id(), + "SimpleStruct", + _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id() { + return _id; + } + + public static org.apache.tuscany.sca.binding.corba.testing.generated.SimpleStruct read(org.omg.CORBA.portable.InputStream istream) { + org.apache.tuscany.sca.binding.corba.testing.generated.SimpleStruct value = + new org.apache.tuscany.sca.binding.corba.testing.generated.SimpleStruct(); + value.field1 = istream.read_string(); + value.field2 = istream.read_long(); + return value; + } + + public static void write(org.omg.CORBA.portable.OutputStream ostream, + org.apache.tuscany.sca.binding.corba.testing.generated.SimpleStruct value) { + ostream.write_string(value.field1); + ostream.write_long(value.field2); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/SimpleStructHolder.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/SimpleStructHolder.java new file mode 100644 index 0000000000..bed30e00ca --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/SimpleStructHolder.java @@ -0,0 +1,51 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/SimpleStructHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 2008 14:12:28 CEST +*/ + +public final class SimpleStructHolder implements org.omg.CORBA.portable.Streamable { + public org.apache.tuscany.sca.binding.corba.testing.generated.SimpleStruct value = null; + + public SimpleStructHolder() { + } + + public SimpleStructHolder(org.apache.tuscany.sca.binding.corba.testing.generated.SimpleStruct initialValue) { + value = initialValue; + } + + public void _read(org.omg.CORBA.portable.InputStream i) { + value = org.apache.tuscany.sca.binding.corba.testing.generated.SimpleStructHelper.read(i); + } + + public void _write(org.omg.CORBA.portable.OutputStream o) { + org.apache.tuscany.sca.binding.corba.testing.generated.SimpleStructHelper.write(o, value); + } + + public org.omg.CORBA.TypeCode _type() { + return org.apache.tuscany.sca.binding.corba.testing.generated.SimpleStructHelper.type(); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/SomeStruct.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/SomeStruct.java new file mode 100644 index 0000000000..73dbd6c198 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/SomeStruct.java @@ -0,0 +1,51 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/SomeStruct.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 2008 14:12:28 CEST +*/ + +public final class SomeStruct implements org.omg.CORBA.portable.IDLEntity { + public org.apache.tuscany.sca.binding.corba.testing.generated.SimpleStruct innerStruct = null; + public String str = null; + public String str_list[] = null; + public int twoDimSeq[][] = null; + public int threeDimSeq[][][] = null; + + public SomeStruct() { + } // ctor + + public SomeStruct(org.apache.tuscany.sca.binding.corba.testing.generated.SimpleStruct _innerStruct, + String _str, + String[] _str_list, + int[][] _twoDimSeq, + int[][][] _threeDimSeq) { + innerStruct = _innerStruct; + str = _str; + str_list = _str_list; + twoDimSeq = _twoDimSeq; + threeDimSeq = _threeDimSeq; + } // ctor + +} // class SomeStruct diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/SomeStructHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/SomeStructHelper.java new file mode 100644 index 0000000000..8f524ffeb1 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/SomeStructHelper.java @@ -0,0 +1,146 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/SomeStructHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 2008 14:12:28 CEST +*/ + +abstract public class SomeStructHelper { + private static String _id = "IDL:org/apache/tuscany/sca/binding/corba/testing/generated/SomeStruct/SomeStruct:1.0"; + + public static void insert(org.omg.CORBA.Any a, + org.apache.tuscany.sca.binding.corba.testing.generated.SomeStruct that) { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream(); + a.type(type()); + write(out, that); + a.read_value(out.create_input_stream(), type()); + } + + public static org.apache.tuscany.sca.binding.corba.testing.generated.SomeStruct extract(org.omg.CORBA.Any a) { + return read(a.create_input_stream()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + private static boolean __active = false; + + synchronized public static org.omg.CORBA.TypeCode type() { + if (__typeCode == null) { + synchronized (org.omg.CORBA.TypeCode.class) { + if (__typeCode == null) { + if (__active) { + return org.omg.CORBA.ORB.init().create_recursive_tc(_id); + } + __active = true; + org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember[5]; + org.omg.CORBA.TypeCode _tcOf_members0 = null; + _tcOf_members0 = org.apache.tuscany.sca.binding.corba.testing.generated.SimpleStructHelper.type(); + _members0[0] = new org.omg.CORBA.StructMember("innerStruct", _tcOf_members0, null); + _tcOf_members0 = org.omg.CORBA.ORB.init().create_string_tc(0); + _members0[1] = new org.omg.CORBA.StructMember("str", _tcOf_members0, null); + _tcOf_members0 = org.omg.CORBA.ORB.init().create_string_tc(0); + _tcOf_members0 = org.omg.CORBA.ORB.init().create_sequence_tc(0, _tcOf_members0); + _tcOf_members0 = + org.omg.CORBA.ORB.init() + .create_alias_tc(org.apache.tuscany.sca.binding.corba.testing.generated.string_listHelper + .id(), + "string_list", + _tcOf_members0); + _members0[2] = new org.omg.CORBA.StructMember("str_list", _tcOf_members0, null); + _tcOf_members0 = org.omg.CORBA.ORB.init().get_primitive_tc(org.omg.CORBA.TCKind.tk_long); + _tcOf_members0 = org.omg.CORBA.ORB.init().create_sequence_tc(0, _tcOf_members0); + _tcOf_members0 = + org.omg.CORBA.ORB.init() + .create_alias_tc(org.apache.tuscany.sca.binding.corba.testing.generated.long_seq1Helper + .id(), + "long_seq1", + _tcOf_members0); + _tcOf_members0 = org.omg.CORBA.ORB.init().create_sequence_tc(0, _tcOf_members0); + _tcOf_members0 = + org.omg.CORBA.ORB.init() + .create_alias_tc(org.apache.tuscany.sca.binding.corba.testing.generated.long_seq2Helper + .id(), + "long_seq2", + _tcOf_members0); + _members0[3] = new org.omg.CORBA.StructMember("twoDimSeq", _tcOf_members0, null); + _tcOf_members0 = org.omg.CORBA.ORB.init().get_primitive_tc(org.omg.CORBA.TCKind.tk_long); + _tcOf_members0 = org.omg.CORBA.ORB.init().create_sequence_tc(0, _tcOf_members0); + _tcOf_members0 = + org.omg.CORBA.ORB.init() + .create_alias_tc(org.apache.tuscany.sca.binding.corba.testing.generated.long_seq1Helper + .id(), + "long_seq1", + _tcOf_members0); + _tcOf_members0 = org.omg.CORBA.ORB.init().create_sequence_tc(0, _tcOf_members0); + _tcOf_members0 = + org.omg.CORBA.ORB.init() + .create_alias_tc(org.apache.tuscany.sca.binding.corba.testing.generated.long_seq2Helper + .id(), + "long_seq2", + _tcOf_members0); + _tcOf_members0 = org.omg.CORBA.ORB.init().create_sequence_tc(0, _tcOf_members0); + _tcOf_members0 = + org.omg.CORBA.ORB.init() + .create_alias_tc(org.apache.tuscany.sca.binding.corba.testing.generated.long_seq3Helper + .id(), + "long_seq3", + _tcOf_members0); + _members0[4] = new org.omg.CORBA.StructMember("threeDimSeq", _tcOf_members0, null); + __typeCode = + org.omg.CORBA.ORB.init() + .create_struct_tc(org.apache.tuscany.sca.binding.corba.testing.generated.SomeStructHelper + .id(), + "SomeStruct", + _members0); + __active = false; + } + } + } + return __typeCode; + } + + public static String id() { + return _id; + } + + public static org.apache.tuscany.sca.binding.corba.testing.generated.SomeStruct read(org.omg.CORBA.portable.InputStream istream) { + org.apache.tuscany.sca.binding.corba.testing.generated.SomeStruct value = + new org.apache.tuscany.sca.binding.corba.testing.generated.SomeStruct(); + value.innerStruct = org.apache.tuscany.sca.binding.corba.testing.generated.SimpleStructHelper.read(istream); + value.str = istream.read_string(); + value.str_list = org.apache.tuscany.sca.binding.corba.testing.generated.string_listHelper.read(istream); + value.twoDimSeq = org.apache.tuscany.sca.binding.corba.testing.generated.long_seq2Helper.read(istream); + value.threeDimSeq = org.apache.tuscany.sca.binding.corba.testing.generated.long_seq3Helper.read(istream); + return value; + } + + public static void write(org.omg.CORBA.portable.OutputStream ostream, + org.apache.tuscany.sca.binding.corba.testing.generated.SomeStruct value) { + org.apache.tuscany.sca.binding.corba.testing.generated.SimpleStructHelper.write(ostream, value.innerStruct); + ostream.write_string(value.str); + org.apache.tuscany.sca.binding.corba.testing.generated.string_listHelper.write(ostream, value.str_list); + org.apache.tuscany.sca.binding.corba.testing.generated.long_seq2Helper.write(ostream, value.twoDimSeq); + org.apache.tuscany.sca.binding.corba.testing.generated.long_seq3Helper.write(ostream, value.threeDimSeq); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/SomeStructHolder.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/SomeStructHolder.java new file mode 100644 index 0000000000..3231a136dc --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/SomeStructHolder.java @@ -0,0 +1,51 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/SomeStructHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 2008 14:12:28 CEST +*/ + +public final class SomeStructHolder implements org.omg.CORBA.portable.Streamable { + public org.apache.tuscany.sca.binding.corba.testing.generated.SomeStruct value = null; + + public SomeStructHolder() { + } + + public SomeStructHolder(org.apache.tuscany.sca.binding.corba.testing.generated.SomeStruct initialValue) { + value = initialValue; + } + + public void _read(org.omg.CORBA.portable.InputStream i) { + value = org.apache.tuscany.sca.binding.corba.testing.generated.SomeStructHelper.read(i); + } + + public void _write(org.omg.CORBA.portable.OutputStream o) { + org.apache.tuscany.sca.binding.corba.testing.generated.SomeStructHelper.write(o, value); + } + + public org.omg.CORBA.TypeCode _type() { + return org.apache.tuscany.sca.binding.corba.testing.generated.SomeStructHelper.type(); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/TestObject.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/TestObject.java new file mode 100644 index 0000000000..28d3ecdc91 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/TestObject.java @@ -0,0 +1,30 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/TestObject.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 2008 14:12:28 CEST +*/ + +public interface TestObject extends TestObjectOperations, org.omg.CORBA.Object, org.omg.CORBA.portable.IDLEntity { +} // interface TestObject diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/TestObjectHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/TestObjectHelper.java new file mode 100644 index 0000000000..29ff2edfd2 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/TestObjectHelper.java @@ -0,0 +1,99 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/TestObjectHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 2008 14:12:28 CEST +*/ + +abstract public class TestObjectHelper { + private static String _id = "IDL:org/apache/tuscany/sca/binding/corba/testing/generated/TestObject:1.0"; + + public static void insert(org.omg.CORBA.Any a, + org.apache.tuscany.sca.binding.corba.testing.generated.TestObject that) { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream(); + a.type(type()); + write(out, that); + a.read_value(out.create_input_stream(), type()); + } + + public static org.apache.tuscany.sca.binding.corba.testing.generated.TestObject extract(org.omg.CORBA.Any a) { + return read(a.create_input_stream()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + + synchronized public static org.omg.CORBA.TypeCode type() { + if (__typeCode == null) { + __typeCode = + org.omg.CORBA.ORB.init() + .create_interface_tc(org.apache.tuscany.sca.binding.corba.testing.generated.TestObjectHelper.id(), + "TestObject"); + } + return __typeCode; + } + + public static String id() { + return _id; + } + + public static org.apache.tuscany.sca.binding.corba.testing.generated.TestObject read(org.omg.CORBA.portable.InputStream istream) { + return narrow(istream.read_Object(_TestObjectStub.class)); + } + + public static void write(org.omg.CORBA.portable.OutputStream ostream, + org.apache.tuscany.sca.binding.corba.testing.generated.TestObject value) { + ostream.write_Object((org.omg.CORBA.Object)value); + } + + public static org.apache.tuscany.sca.binding.corba.testing.generated.TestObject narrow(org.omg.CORBA.Object obj) { + if (obj == null) + return null; + else if (obj instanceof org.apache.tuscany.sca.binding.corba.testing.generated.TestObject) + return (org.apache.tuscany.sca.binding.corba.testing.generated.TestObject)obj; + else if (!obj._is_a(id())) + throw new org.omg.CORBA.BAD_PARAM(); + else { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate(); + org.apache.tuscany.sca.binding.corba.testing.generated._TestObjectStub stub = + new org.apache.tuscany.sca.binding.corba.testing.generated._TestObjectStub(); + stub._set_delegate(delegate); + return stub; + } + } + + public static org.apache.tuscany.sca.binding.corba.testing.generated.TestObject unchecked_narrow(org.omg.CORBA.Object obj) { + if (obj == null) + return null; + else if (obj instanceof org.apache.tuscany.sca.binding.corba.testing.generated.TestObject) + return (org.apache.tuscany.sca.binding.corba.testing.generated.TestObject)obj; + else { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate(); + org.apache.tuscany.sca.binding.corba.testing.generated._TestObjectStub stub = + new org.apache.tuscany.sca.binding.corba.testing.generated._TestObjectStub(); + stub._set_delegate(delegate); + return stub; + } + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/TestObjectHolder.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/TestObjectHolder.java new file mode 100644 index 0000000000..b8aea13c8d --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/TestObjectHolder.java @@ -0,0 +1,51 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/TestObjectHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 2008 14:12:28 CEST +*/ + +public final class TestObjectHolder implements org.omg.CORBA.portable.Streamable { + public org.apache.tuscany.sca.binding.corba.testing.generated.TestObject value = null; + + public TestObjectHolder() { + } + + public TestObjectHolder(org.apache.tuscany.sca.binding.corba.testing.generated.TestObject initialValue) { + value = initialValue; + } + + public void _read(org.omg.CORBA.portable.InputStream i) { + value = org.apache.tuscany.sca.binding.corba.testing.generated.TestObjectHelper.read(i); + } + + public void _write(org.omg.CORBA.portable.OutputStream o) { + org.apache.tuscany.sca.binding.corba.testing.generated.TestObjectHelper.write(o, value); + } + + public org.omg.CORBA.TypeCode _type() { + return org.apache.tuscany.sca.binding.corba.testing.generated.TestObjectHelper.type(); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/TestObjectOperations.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/TestObjectOperations.java new file mode 100644 index 0000000000..0bacb6746a --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/TestObjectOperations.java @@ -0,0 +1,44 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/TestObjectOperations.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 2008 14:12:28 CEST +*/ + +public interface TestObjectOperations { + org.apache.tuscany.sca.binding.corba.testing.generated.SomeStruct pickStructFromArgs(org.apache.tuscany.sca.binding.corba.testing.generated.SomeStruct arg1, + org.apache.tuscany.sca.binding.corba.testing.generated.SomeStruct arg2, + org.apache.tuscany.sca.binding.corba.testing.generated.SomeStruct arg3, + int structNumber); + + org.apache.tuscany.sca.binding.corba.testing.generated.SomeStruct setStruct(org.apache.tuscany.sca.binding.corba.testing.generated.SomeStruct arg); + + org.apache.tuscany.sca.binding.corba.testing.generated.SimpleStruct setSimpleStruct(org.apache.tuscany.sca.binding.corba.testing.generated.SimpleStructHolder arg); + + int[] setLongSeq1(org.apache.tuscany.sca.binding.corba.testing.generated.long_seq1Holder arg); + + int[][] setLongSeq2(org.apache.tuscany.sca.binding.corba.testing.generated.long_seq2Holder arg); + + int[][][] setLongSeq3(org.apache.tuscany.sca.binding.corba.testing.generated.long_seq3Holder arg); +} // interface TestObjectOperations diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/_ArraysSetterImplBase.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/_ArraysSetterImplBase.java new file mode 100644 index 0000000000..c6e8c2a4e0 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/_ArraysSetterImplBase.java @@ -0,0 +1,232 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/_ArraysSetterImplBase.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 14:12:28 CEST +*/ + +public abstract class _ArraysSetterImplBase extends org.omg.CORBA.portable.ObjectImpl implements + org.apache.tuscany.sca.binding.corba.testing.generated.ArraysSetter, org.omg.CORBA.portable.InvokeHandler { + + // Constructors + public _ArraysSetterImplBase() { + } + + private static java.util.Hashtable _methods = new java.util.Hashtable(); + static { + _methods.put("setBoolean", new java.lang.Integer(0)); + _methods.put("setChar", new java.lang.Integer(1)); + _methods.put("setWchar", new java.lang.Integer(2)); + _methods.put("setOctet", new java.lang.Integer(3)); + _methods.put("setShort", new java.lang.Integer(4)); + _methods.put("setUnsignedShort", new java.lang.Integer(5)); + _methods.put("setLong", new java.lang.Integer(6)); + _methods.put("setUnsignedLong", new java.lang.Integer(7)); + _methods.put("setLongLong", new java.lang.Integer(8)); + _methods.put("setUnsignedLongLong", new java.lang.Integer(9)); + _methods.put("setFloat", new java.lang.Integer(10)); + _methods.put("setDouble", new java.lang.Integer(11)); + _methods.put("setString", new java.lang.Integer(12)); + _methods.put("setWstring", new java.lang.Integer(13)); + _methods.put("setRemoteObject", new java.lang.Integer(14)); + } + + public org.omg.CORBA.portable.OutputStream _invoke(String $method, + org.omg.CORBA.portable.InputStream in, + org.omg.CORBA.portable.ResponseHandler $rh) { + org.omg.CORBA.portable.OutputStream out = null; + java.lang.Integer __method = (java.lang.Integer)_methods.get($method); + if (__method == null) + throw new org.omg.CORBA.BAD_OPERATION(0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE); + + switch (__method.intValue()) { + case 0: // org/apache/tuscany/sca/binding/corba/testing/generated/ArraysSetter/setBoolean + { + boolean arg[] = org.apache.tuscany.sca.binding.corba.testing.generated.boolean_listHelper.read(in); + boolean $result[] = null; + $result = this.setBoolean(arg); + out = $rh.createReply(); + org.apache.tuscany.sca.binding.corba.testing.generated.boolean_listHelper.write(out, $result); + break; + } + + case 1: // org/apache/tuscany/sca/binding/corba/testing/generated/ArraysSetter/setChar + { + char arg[] = org.apache.tuscany.sca.binding.corba.testing.generated.char_listHelper.read(in); + char $result[] = null; + $result = this.setChar(arg); + out = $rh.createReply(); + org.apache.tuscany.sca.binding.corba.testing.generated.char_listHelper.write(out, $result); + break; + } + + case 2: // org/apache/tuscany/sca/binding/corba/testing/generated/ArraysSetter/setWchar + { + char arg[] = org.apache.tuscany.sca.binding.corba.testing.generated.wchar_listHelper.read(in); + char $result[] = null; + $result = this.setWchar(arg); + out = $rh.createReply(); + org.apache.tuscany.sca.binding.corba.testing.generated.wchar_listHelper.write(out, $result); + break; + } + + case 3: // org/apache/tuscany/sca/binding/corba/testing/generated/ArraysSetter/setOctet + { + byte arg[] = org.apache.tuscany.sca.binding.corba.testing.generated.octet_listHelper.read(in); + byte $result[] = null; + $result = this.setOctet(arg); + out = $rh.createReply(); + org.apache.tuscany.sca.binding.corba.testing.generated.octet_listHelper.write(out, $result); + break; + } + + case 4: // org/apache/tuscany/sca/binding/corba/testing/generated/ArraysSetter/setShort + { + short arg[] = org.apache.tuscany.sca.binding.corba.testing.generated.short_listHelper.read(in); + short $result[] = null; + $result = this.setShort(arg); + out = $rh.createReply(); + org.apache.tuscany.sca.binding.corba.testing.generated.short_listHelper.write(out, $result); + break; + } + + case 5: // org/apache/tuscany/sca/binding/corba/testing/generated/ArraysSetter/setUnsignedShort + { + short arg[] = org.apache.tuscany.sca.binding.corba.testing.generated.unsigned_short_listHelper.read(in); + short $result[] = null; + $result = this.setUnsignedShort(arg); + out = $rh.createReply(); + org.apache.tuscany.sca.binding.corba.testing.generated.unsigned_short_listHelper.write(out, $result); + break; + } + + case 6: // org/apache/tuscany/sca/binding/corba/testing/generated/ArraysSetter/setLong + { + int arg[] = org.apache.tuscany.sca.binding.corba.testing.generated.long_listHelper.read(in); + int $result[] = null; + $result = this.setLong(arg); + out = $rh.createReply(); + org.apache.tuscany.sca.binding.corba.testing.generated.long_listHelper.write(out, $result); + break; + } + + case 7: // org/apache/tuscany/sca/binding/corba/testing/generated/ArraysSetter/setUnsignedLong + { + int arg[] = org.apache.tuscany.sca.binding.corba.testing.generated.unsigned_long_listHelper.read(in); + int $result[] = null; + $result = this.setUnsignedLong(arg); + out = $rh.createReply(); + org.apache.tuscany.sca.binding.corba.testing.generated.unsigned_long_listHelper.write(out, $result); + break; + } + + case 8: // org/apache/tuscany/sca/binding/corba/testing/generated/ArraysSetter/setLongLong + { + long arg[] = org.apache.tuscany.sca.binding.corba.testing.generated.long_long_listHelper.read(in); + long $result[] = null; + $result = this.setLongLong(arg); + out = $rh.createReply(); + org.apache.tuscany.sca.binding.corba.testing.generated.long_long_listHelper.write(out, $result); + break; + } + + case 9: // org/apache/tuscany/sca/binding/corba/testing/generated/ArraysSetter/setUnsignedLongLong + { + long arg[] = + org.apache.tuscany.sca.binding.corba.testing.generated.unsigned_long_long_listHelper.read(in); + long $result[] = null; + $result = this.setUnsignedLongLong(arg); + out = $rh.createReply(); + org.apache.tuscany.sca.binding.corba.testing.generated.unsigned_long_long_listHelper + .write(out, $result); + break; + } + + case 10: // org/apache/tuscany/sca/binding/corba/testing/generated/ArraysSetter/setFloat + { + float arg[] = org.apache.tuscany.sca.binding.corba.testing.generated.float_listHelper.read(in); + float $result[] = null; + $result = this.setFloat(arg); + out = $rh.createReply(); + org.apache.tuscany.sca.binding.corba.testing.generated.float_listHelper.write(out, $result); + break; + } + + case 11: // org/apache/tuscany/sca/binding/corba/testing/generated/ArraysSetter/setDouble + { + double arg[] = org.apache.tuscany.sca.binding.corba.testing.generated.double_listHelper.read(in); + double $result[] = null; + $result = this.setDouble(arg); + out = $rh.createReply(); + org.apache.tuscany.sca.binding.corba.testing.generated.double_listHelper.write(out, $result); + break; + } + + case 12: // org/apache/tuscany/sca/binding/corba/testing/generated/ArraysSetter/setString + { + String arg[] = org.apache.tuscany.sca.binding.corba.testing.generated.string_listHelper.read(in); + String $result[] = null; + $result = this.setString(arg); + out = $rh.createReply(); + org.apache.tuscany.sca.binding.corba.testing.generated.string_listHelper.write(out, $result); + break; + } + + case 13: // org/apache/tuscany/sca/binding/corba/testing/generated/ArraysSetter/setWstring + { + String arg[] = org.apache.tuscany.sca.binding.corba.testing.generated.wstring_listHelper.read(in); + String $result[] = null; + $result = this.setWstring(arg); + out = $rh.createReply(); + org.apache.tuscany.sca.binding.corba.testing.generated.wstring_listHelper.write(out, $result); + break; + } + + case 14: // org/apache/tuscany/sca/binding/corba/testing/generated/ArraysSetter/setRemoteObject + { + org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObject obj[] = + org.apache.tuscany.sca.binding.corba.testing.generated.remote_object_listHelper.read(in); + org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObject $result[] = null; + $result = this.setRemoteObject(obj); + out = $rh.createReply(); + org.apache.tuscany.sca.binding.corba.testing.generated.remote_object_listHelper.write(out, $result); + break; + } + + default: + throw new org.omg.CORBA.BAD_OPERATION(0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE); + } + + return out; + } // _invoke + + // Type-specific CORBA::Object operations + private static String[] __ids = {"IDL:org/apache/tuscany/sca/binding/corba/testing/generated/ArraysSetter:1.0"}; + + @Override + public String[] _ids() { + return (String[])__ids.clone(); + } + +} // class _ArraysSetterImplBase diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/_ArraysSetterStub.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/_ArraysSetterStub.java new file mode 100644 index 0000000000..079cc6e899 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/_ArraysSetterStub.java @@ -0,0 +1,343 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/_ArraysSetterStub.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 14:12:28 CEST +*/ + +public class _ArraysSetterStub extends org.omg.CORBA.portable.ObjectImpl implements + org.apache.tuscany.sca.binding.corba.testing.generated.ArraysSetter { + + public boolean[] setBoolean(boolean[] arg) { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("setBoolean", true); + org.apache.tuscany.sca.binding.corba.testing.generated.boolean_listHelper.write($out, arg); + $in = _invoke($out); + boolean $result[] = org.apache.tuscany.sca.binding.corba.testing.generated.boolean_listHelper.read($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return setBoolean(arg); + } finally { + _releaseReply($in); + } + } // setBoolean + + public char[] setChar(char[] arg) { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("setChar", true); + org.apache.tuscany.sca.binding.corba.testing.generated.char_listHelper.write($out, arg); + $in = _invoke($out); + char $result[] = org.apache.tuscany.sca.binding.corba.testing.generated.char_listHelper.read($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return setChar(arg); + } finally { + _releaseReply($in); + } + } // setChar + + public char[] setWchar(char[] arg) { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("setWchar", true); + org.apache.tuscany.sca.binding.corba.testing.generated.wchar_listHelper.write($out, arg); + $in = _invoke($out); + char $result[] = org.apache.tuscany.sca.binding.corba.testing.generated.wchar_listHelper.read($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return setWchar(arg); + } finally { + _releaseReply($in); + } + } // setWchar + + public byte[] setOctet(byte[] arg) { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("setOctet", true); + org.apache.tuscany.sca.binding.corba.testing.generated.octet_listHelper.write($out, arg); + $in = _invoke($out); + byte $result[] = org.apache.tuscany.sca.binding.corba.testing.generated.octet_listHelper.read($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return setOctet(arg); + } finally { + _releaseReply($in); + } + } // setOctet + + public short[] setShort(short[] arg) { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("setShort", true); + org.apache.tuscany.sca.binding.corba.testing.generated.short_listHelper.write($out, arg); + $in = _invoke($out); + short $result[] = org.apache.tuscany.sca.binding.corba.testing.generated.short_listHelper.read($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return setShort(arg); + } finally { + _releaseReply($in); + } + } // setShort + + public short[] setUnsignedShort(short[] arg) { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("setUnsignedShort", true); + org.apache.tuscany.sca.binding.corba.testing.generated.unsigned_short_listHelper.write($out, arg); + $in = _invoke($out); + short $result[] = + org.apache.tuscany.sca.binding.corba.testing.generated.unsigned_short_listHelper.read($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return setUnsignedShort(arg); + } finally { + _releaseReply($in); + } + } // setUnsignedShort + + public int[] setLong(int[] arg) { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("setLong", true); + org.apache.tuscany.sca.binding.corba.testing.generated.long_listHelper.write($out, arg); + $in = _invoke($out); + int $result[] = org.apache.tuscany.sca.binding.corba.testing.generated.long_listHelper.read($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return setLong(arg); + } finally { + _releaseReply($in); + } + } // setLong + + public int[] setUnsignedLong(int[] arg) { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("setUnsignedLong", true); + org.apache.tuscany.sca.binding.corba.testing.generated.unsigned_long_listHelper.write($out, arg); + $in = _invoke($out); + int $result[] = org.apache.tuscany.sca.binding.corba.testing.generated.unsigned_long_listHelper.read($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return setUnsignedLong(arg); + } finally { + _releaseReply($in); + } + } // setUnsignedLong + + public long[] setLongLong(long[] arg) { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("setLongLong", true); + org.apache.tuscany.sca.binding.corba.testing.generated.long_long_listHelper.write($out, arg); + $in = _invoke($out); + long $result[] = org.apache.tuscany.sca.binding.corba.testing.generated.long_long_listHelper.read($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return setLongLong(arg); + } finally { + _releaseReply($in); + } + } // setLongLong + + public long[] setUnsignedLongLong(long[] arg) { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("setUnsignedLongLong", true); + org.apache.tuscany.sca.binding.corba.testing.generated.unsigned_long_long_listHelper.write($out, arg); + $in = _invoke($out); + long $result[] = + org.apache.tuscany.sca.binding.corba.testing.generated.unsigned_long_long_listHelper.read($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return setUnsignedLongLong(arg); + } finally { + _releaseReply($in); + } + } // setUnsignedLongLong + + public float[] setFloat(float[] arg) { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("setFloat", true); + org.apache.tuscany.sca.binding.corba.testing.generated.float_listHelper.write($out, arg); + $in = _invoke($out); + float $result[] = org.apache.tuscany.sca.binding.corba.testing.generated.float_listHelper.read($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return setFloat(arg); + } finally { + _releaseReply($in); + } + } // setFloat + + public double[] setDouble(double[] arg) { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("setDouble", true); + org.apache.tuscany.sca.binding.corba.testing.generated.double_listHelper.write($out, arg); + $in = _invoke($out); + double $result[] = org.apache.tuscany.sca.binding.corba.testing.generated.double_listHelper.read($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return setDouble(arg); + } finally { + _releaseReply($in); + } + } // setDouble + + public String[] setString(String[] arg) { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("setString", true); + org.apache.tuscany.sca.binding.corba.testing.generated.string_listHelper.write($out, arg); + $in = _invoke($out); + String $result[] = org.apache.tuscany.sca.binding.corba.testing.generated.string_listHelper.read($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return setString(arg); + } finally { + _releaseReply($in); + } + } // setString + + public String[] setWstring(String[] arg) { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("setWstring", true); + org.apache.tuscany.sca.binding.corba.testing.generated.wstring_listHelper.write($out, arg); + $in = _invoke($out); + String $result[] = org.apache.tuscany.sca.binding.corba.testing.generated.wstring_listHelper.read($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return setWstring(arg); + } finally { + _releaseReply($in); + } + } // setWstring + + public org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObject[] setRemoteObject(org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObject[] obj) { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("setRemoteObject", true); + org.apache.tuscany.sca.binding.corba.testing.generated.remote_object_listHelper.write($out, obj); + $in = _invoke($out); + org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObject $result[] = + org.apache.tuscany.sca.binding.corba.testing.generated.remote_object_listHelper.read($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return setRemoteObject(obj); + } finally { + _releaseReply($in); + } + } // setRemoteObject + + // Type-specific CORBA::Object operations + private static String[] __ids = {"IDL:org/apache/tuscany/sca/binding/corba/testing/generated/ArraysSetter:1.0"}; + + @Override + public String[] _ids() { + return (String[])__ids.clone(); + } + + private void readObject(java.io.ObjectInputStream s) throws java.io.IOException { + String str = s.readUTF(); + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.Object obj = org.omg.CORBA.ORB.init(args, props).string_to_object(str); + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate(); + _set_delegate(delegate); + } + + private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { + String[] args = null; + java.util.Properties props = null; + String str = org.omg.CORBA.ORB.init(args, props).object_to_string(this); + s.writeUTF(str); + } +} // class _ArraysSetterStub diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/_PrimitivesSetterImplBase.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/_PrimitivesSetterImplBase.java new file mode 100644 index 0000000000..b444ce68d8 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/_PrimitivesSetterImplBase.java @@ -0,0 +1,230 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/_PrimitivesSetterImplBase.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 14:12:28 CEST +*/ + +public abstract class _PrimitivesSetterImplBase extends org.omg.CORBA.portable.ObjectImpl implements + org.apache.tuscany.sca.binding.corba.testing.generated.PrimitivesSetter, org.omg.CORBA.portable.InvokeHandler { + + // Constructors + public _PrimitivesSetterImplBase() { + } + + private static java.util.Hashtable _methods = new java.util.Hashtable(); + static { + _methods.put("setBoolean", new java.lang.Integer(0)); + _methods.put("setChar", new java.lang.Integer(1)); + _methods.put("setWchar", new java.lang.Integer(2)); + _methods.put("setOctet", new java.lang.Integer(3)); + _methods.put("setShort", new java.lang.Integer(4)); + _methods.put("setUnsignedShort", new java.lang.Integer(5)); + _methods.put("setLong", new java.lang.Integer(6)); + _methods.put("setUnsignedLong", new java.lang.Integer(7)); + _methods.put("setLongLong", new java.lang.Integer(8)); + _methods.put("setUnsignedLongLong", new java.lang.Integer(9)); + _methods.put("setFloat", new java.lang.Integer(10)); + _methods.put("setDouble", new java.lang.Integer(11)); + _methods.put("setString", new java.lang.Integer(12)); + _methods.put("setWstring", new java.lang.Integer(13)); + _methods.put("setRemoteObject", new java.lang.Integer(14)); + } + + public org.omg.CORBA.portable.OutputStream _invoke(String $method, + org.omg.CORBA.portable.InputStream in, + org.omg.CORBA.portable.ResponseHandler $rh) { + org.omg.CORBA.portable.OutputStream out = null; + java.lang.Integer __method = (java.lang.Integer)_methods.get($method); + if (__method == null) + throw new org.omg.CORBA.BAD_OPERATION(0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE); + + switch (__method.intValue()) { + case 0: // org/apache/tuscany/sca/binding/corba/testing/generated/PrimitivesSetter/setBoolean + { + boolean arg = in.read_boolean(); + boolean $result = false; + $result = this.setBoolean(arg); + out = $rh.createReply(); + out.write_boolean($result); + break; + } + + case 1: // org/apache/tuscany/sca/binding/corba/testing/generated/PrimitivesSetter/setChar + { + char arg = in.read_char(); + char $result = (char)0; + $result = this.setChar(arg); + out = $rh.createReply(); + out.write_char($result); + break; + } + + case 2: // org/apache/tuscany/sca/binding/corba/testing/generated/PrimitivesSetter/setWchar + { + char arg = in.read_wchar(); + char $result = (char)0; + $result = this.setWchar(arg); + out = $rh.createReply(); + out.write_wchar($result); + break; + } + + case 3: // org/apache/tuscany/sca/binding/corba/testing/generated/PrimitivesSetter/setOctet + { + byte arg = in.read_octet(); + byte $result = (byte)0; + $result = this.setOctet(arg); + out = $rh.createReply(); + out.write_octet($result); + break; + } + + case 4: // org/apache/tuscany/sca/binding/corba/testing/generated/PrimitivesSetter/setShort + { + short arg = in.read_short(); + short $result = (short)0; + $result = this.setShort(arg); + out = $rh.createReply(); + out.write_short($result); + break; + } + + case 5: // org/apache/tuscany/sca/binding/corba/testing/generated/PrimitivesSetter/setUnsignedShort + { + short arg = in.read_ushort(); + short $result = (short)0; + $result = this.setUnsignedShort(arg); + out = $rh.createReply(); + out.write_ushort($result); + break; + } + + case 6: // org/apache/tuscany/sca/binding/corba/testing/generated/PrimitivesSetter/setLong + { + int arg = in.read_long(); + int $result = (int)0; + $result = this.setLong(arg); + out = $rh.createReply(); + out.write_long($result); + break; + } + + case 7: // org/apache/tuscany/sca/binding/corba/testing/generated/PrimitivesSetter/setUnsignedLong + { + int arg = in.read_ulong(); + int $result = (int)0; + $result = this.setUnsignedLong(arg); + out = $rh.createReply(); + out.write_ulong($result); + break; + } + + case 8: // org/apache/tuscany/sca/binding/corba/testing/generated/PrimitivesSetter/setLongLong + { + long arg = in.read_longlong(); + long $result = (long)0; + $result = this.setLongLong(arg); + out = $rh.createReply(); + out.write_longlong($result); + break; + } + + case 9: // org/apache/tuscany/sca/binding/corba/testing/generated/PrimitivesSetter/setUnsignedLongLong + { + long arg = in.read_ulonglong(); + long $result = (long)0; + $result = this.setUnsignedLongLong(arg); + out = $rh.createReply(); + out.write_ulonglong($result); + break; + } + + case 10: // org/apache/tuscany/sca/binding/corba/testing/generated/PrimitivesSetter/setFloat + { + float arg = in.read_float(); + float $result = (float)0; + $result = this.setFloat(arg); + out = $rh.createReply(); + out.write_float($result); + break; + } + + case 11: // org/apache/tuscany/sca/binding/corba/testing/generated/PrimitivesSetter/setDouble + { + double arg = in.read_double(); + double $result = (double)0; + $result = this.setDouble(arg); + out = $rh.createReply(); + out.write_double($result); + break; + } + + case 12: // org/apache/tuscany/sca/binding/corba/testing/generated/PrimitivesSetter/setString + { + String arg = in.read_string(); + String $result = null; + $result = this.setString(arg); + out = $rh.createReply(); + out.write_string($result); + break; + } + + case 13: // org/apache/tuscany/sca/binding/corba/testing/generated/PrimitivesSetter/setWstring + { + String arg = in.read_wstring(); + String $result = null; + $result = this.setWstring(arg); + out = $rh.createReply(); + out.write_wstring($result); + break; + } + + case 14: // org/apache/tuscany/sca/binding/corba/testing/generated/PrimitivesSetter/setRemoteObject + { + org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObject obj = + org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObjectHelper.read(in); + org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObject $result = null; + $result = this.setRemoteObject(obj); + out = $rh.createReply(); + org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObjectHelper.write(out, $result); + break; + } + + default: + throw new org.omg.CORBA.BAD_OPERATION(0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE); + } + + return out; + } // _invoke + + // Type-specific CORBA::Object operations + private static String[] __ids = {"IDL:org/apache/tuscany/sca/binding/corba/testing/generated/PrimitivesSetter:1.0"}; + + @Override + public String[] _ids() { + return (String[])__ids.clone(); + } + +} // class _PrimitivesSetterImplBase diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/_PrimitivesSetterStub.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/_PrimitivesSetterStub.java new file mode 100644 index 0000000000..0b08e1fb67 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/_PrimitivesSetterStub.java @@ -0,0 +1,341 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/_PrimitivesSetterStub.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 14:12:28 CEST +*/ + +public class _PrimitivesSetterStub extends org.omg.CORBA.portable.ObjectImpl implements + org.apache.tuscany.sca.binding.corba.testing.generated.PrimitivesSetter { + + public boolean setBoolean(boolean arg) { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("setBoolean", true); + $out.write_boolean(arg); + $in = _invoke($out); + boolean $result = $in.read_boolean(); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return setBoolean(arg); + } finally { + _releaseReply($in); + } + } // setBoolean + + public char setChar(char arg) { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("setChar", true); + $out.write_char(arg); + $in = _invoke($out); + char $result = $in.read_char(); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return setChar(arg); + } finally { + _releaseReply($in); + } + } // setChar + + public char setWchar(char arg) { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("setWchar", true); + $out.write_wchar(arg); + $in = _invoke($out); + char $result = $in.read_wchar(); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return setWchar(arg); + } finally { + _releaseReply($in); + } + } // setWchar + + public byte setOctet(byte arg) { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("setOctet", true); + $out.write_octet(arg); + $in = _invoke($out); + byte $result = $in.read_octet(); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return setOctet(arg); + } finally { + _releaseReply($in); + } + } // setOctet + + public short setShort(short arg) { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("setShort", true); + $out.write_short(arg); + $in = _invoke($out); + short $result = $in.read_short(); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return setShort(arg); + } finally { + _releaseReply($in); + } + } // setShort + + public short setUnsignedShort(short arg) { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("setUnsignedShort", true); + $out.write_ushort(arg); + $in = _invoke($out); + short $result = $in.read_ushort(); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return setUnsignedShort(arg); + } finally { + _releaseReply($in); + } + } // setUnsignedShort + + public int setLong(int arg) { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("setLong", true); + $out.write_long(arg); + $in = _invoke($out); + int $result = $in.read_long(); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return setLong(arg); + } finally { + _releaseReply($in); + } + } // setLong + + public int setUnsignedLong(int arg) { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("setUnsignedLong", true); + $out.write_ulong(arg); + $in = _invoke($out); + int $result = $in.read_ulong(); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return setUnsignedLong(arg); + } finally { + _releaseReply($in); + } + } // setUnsignedLong + + public long setLongLong(long arg) { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("setLongLong", true); + $out.write_longlong(arg); + $in = _invoke($out); + long $result = $in.read_longlong(); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return setLongLong(arg); + } finally { + _releaseReply($in); + } + } // setLongLong + + public long setUnsignedLongLong(long arg) { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("setUnsignedLongLong", true); + $out.write_ulonglong(arg); + $in = _invoke($out); + long $result = $in.read_ulonglong(); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return setUnsignedLongLong(arg); + } finally { + _releaseReply($in); + } + } // setUnsignedLongLong + + public float setFloat(float arg) { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("setFloat", true); + $out.write_float(arg); + $in = _invoke($out); + float $result = $in.read_float(); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return setFloat(arg); + } finally { + _releaseReply($in); + } + } // setFloat + + public double setDouble(double arg) { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("setDouble", true); + $out.write_double(arg); + $in = _invoke($out); + double $result = $in.read_double(); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return setDouble(arg); + } finally { + _releaseReply($in); + } + } // setDouble + + public String setString(String arg) { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("setString", true); + $out.write_string(arg); + $in = _invoke($out); + String $result = $in.read_string(); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return setString(arg); + } finally { + _releaseReply($in); + } + } // setString + + public String setWstring(String arg) { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("setWstring", true); + $out.write_wstring(arg); + $in = _invoke($out); + String $result = $in.read_wstring(); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return setWstring(arg); + } finally { + _releaseReply($in); + } + } // setWstring + + public org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObject setRemoteObject(org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObject obj) { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("setRemoteObject", true); + org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObjectHelper.write($out, obj); + $in = _invoke($out); + org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObject $result = + org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObjectHelper.read($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return setRemoteObject(obj); + } finally { + _releaseReply($in); + } + } // setRemoteObject + + // Type-specific CORBA::Object operations + private static String[] __ids = {"IDL:org/apache/tuscany/sca/binding/corba/testing/generated/PrimitivesSetter:1.0"}; + + @Override + public String[] _ids() { + return (String[])__ids.clone(); + } + + private void readObject(java.io.ObjectInputStream s) throws java.io.IOException { + String str = s.readUTF(); + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.Object obj = org.omg.CORBA.ORB.init(args, props).string_to_object(str); + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate(); + _set_delegate(delegate); + } + + private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { + String[] args = null; + java.util.Properties props = null; + String str = org.omg.CORBA.ORB.init(args, props).object_to_string(this); + s.writeUTF(str); + } +} // class _PrimitivesSetterStub diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/_RemoteObjectImplBase.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/_RemoteObjectImplBase.java new file mode 100644 index 0000000000..a87534f88b --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/_RemoteObjectImplBase.java @@ -0,0 +1,59 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/_RemoteObjectImplBase.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 14:12:28 CEST +*/ + +public abstract class _RemoteObjectImplBase extends org.omg.CORBA.portable.ObjectImpl implements + org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObject, org.omg.CORBA.portable.InvokeHandler { + + // Constructors + public _RemoteObjectImplBase() { + } + + private static java.util.Hashtable _methods = new java.util.Hashtable(); + static { + } + + public org.omg.CORBA.portable.OutputStream _invoke(String $method, + org.omg.CORBA.portable.InputStream in, + org.omg.CORBA.portable.ResponseHandler $rh) { + org.omg.CORBA.portable.OutputStream out = null; + java.lang.Integer __method = (java.lang.Integer)_methods.get($method); + if (__method == null) + throw new org.omg.CORBA.BAD_OPERATION(0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE); + + return out; + } // _invoke + + // Type-specific CORBA::Object operations + private static String[] __ids = {"IDL:org/apache/tuscany/sca/binding/corba/testing/generated/RemoteObject:1.0"}; + + @Override + public String[] _ids() { + return (String[])__ids.clone(); + } + +} // class _RemoteObjectImplBase diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/_RemoteObjectStub.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/_RemoteObjectStub.java new file mode 100644 index 0000000000..e219dfa338 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/_RemoteObjectStub.java @@ -0,0 +1,55 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/_RemoteObjectStub.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 14:12:28 CEST +*/ + +public class _RemoteObjectStub extends org.omg.CORBA.portable.ObjectImpl implements + org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObject { + + // Type-specific CORBA::Object operations + private static String[] __ids = {"IDL:org/apache/tuscany/sca/binding/corba/testing/generated/RemoteObject:1.0"}; + + @Override + public String[] _ids() { + return (String[])__ids.clone(); + } + + private void readObject(java.io.ObjectInputStream s) throws java.io.IOException { + String str = s.readUTF(); + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.Object obj = org.omg.CORBA.ORB.init(args, props).string_to_object(str); + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate(); + _set_delegate(delegate); + } + + private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { + String[] args = null; + java.util.Properties props = null; + String str = org.omg.CORBA.ORB.init(args, props).object_to_string(this); + s.writeUTF(str); + } +} // class _RemoteObjectStub diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/_TestObjectImplBase.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/_TestObjectImplBase.java new file mode 100644 index 0000000000..c0bc0d6ebd --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/_TestObjectImplBase.java @@ -0,0 +1,149 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/_TestObjectImplBase.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 14:12:28 CEST +*/ + +public abstract class _TestObjectImplBase extends org.omg.CORBA.portable.ObjectImpl implements + org.apache.tuscany.sca.binding.corba.testing.generated.TestObject, org.omg.CORBA.portable.InvokeHandler { + + // Constructors + public _TestObjectImplBase() { + } + + private static java.util.Hashtable _methods = new java.util.Hashtable(); + static { + _methods.put("pickStructFromArgs", new java.lang.Integer(0)); + _methods.put("setStruct", new java.lang.Integer(1)); + _methods.put("setSimpleStruct", new java.lang.Integer(2)); + _methods.put("setLongSeq1", new java.lang.Integer(3)); + _methods.put("setLongSeq2", new java.lang.Integer(4)); + _methods.put("setLongSeq3", new java.lang.Integer(5)); + } + + public org.omg.CORBA.portable.OutputStream _invoke(String $method, + org.omg.CORBA.portable.InputStream in, + org.omg.CORBA.portable.ResponseHandler $rh) { + org.omg.CORBA.portable.OutputStream out = null; + java.lang.Integer __method = (java.lang.Integer)_methods.get($method); + if (__method == null) + throw new org.omg.CORBA.BAD_OPERATION(0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE); + + switch (__method.intValue()) { + case 0: // org/apache/tuscany/sca/binding/corba/testing/generated/TestObject/pickStructFromArgs + { + org.apache.tuscany.sca.binding.corba.testing.generated.SomeStruct arg1 = + org.apache.tuscany.sca.binding.corba.testing.generated.SomeStructHelper.read(in); + org.apache.tuscany.sca.binding.corba.testing.generated.SomeStruct arg2 = + org.apache.tuscany.sca.binding.corba.testing.generated.SomeStructHelper.read(in); + org.apache.tuscany.sca.binding.corba.testing.generated.SomeStruct arg3 = + org.apache.tuscany.sca.binding.corba.testing.generated.SomeStructHelper.read(in); + int structNumber = in.read_long(); + org.apache.tuscany.sca.binding.corba.testing.generated.SomeStruct $result = null; + $result = this.pickStructFromArgs(arg1, arg2, arg3, structNumber); + out = $rh.createReply(); + org.apache.tuscany.sca.binding.corba.testing.generated.SomeStructHelper.write(out, $result); + break; + } + + case 1: // org/apache/tuscany/sca/binding/corba/testing/generated/TestObject/setStruct + { + org.apache.tuscany.sca.binding.corba.testing.generated.SomeStruct arg = + org.apache.tuscany.sca.binding.corba.testing.generated.SomeStructHelper.read(in); + org.apache.tuscany.sca.binding.corba.testing.generated.SomeStruct $result = null; + $result = this.setStruct(arg); + out = $rh.createReply(); + org.apache.tuscany.sca.binding.corba.testing.generated.SomeStructHelper.write(out, $result); + break; + } + + case 2: // org/apache/tuscany/sca/binding/corba/testing/generated/TestObject/setSimpleStruct + { + org.apache.tuscany.sca.binding.corba.testing.generated.SimpleStructHolder arg = + new org.apache.tuscany.sca.binding.corba.testing.generated.SimpleStructHolder(); + arg.value = org.apache.tuscany.sca.binding.corba.testing.generated.SimpleStructHelper.read(in); + org.apache.tuscany.sca.binding.corba.testing.generated.SimpleStruct $result = null; + $result = this.setSimpleStruct(arg); + out = $rh.createReply(); + org.apache.tuscany.sca.binding.corba.testing.generated.SimpleStructHelper.write(out, $result); + org.apache.tuscany.sca.binding.corba.testing.generated.SimpleStructHelper.write(out, arg.value); + break; + } + + case 3: // org/apache/tuscany/sca/binding/corba/testing/generated/TestObject/setLongSeq1 + { + org.apache.tuscany.sca.binding.corba.testing.generated.long_seq1Holder arg = + new org.apache.tuscany.sca.binding.corba.testing.generated.long_seq1Holder(); + arg.value = org.apache.tuscany.sca.binding.corba.testing.generated.long_seq1Helper.read(in); + int $result[] = null; + $result = this.setLongSeq1(arg); + out = $rh.createReply(); + org.apache.tuscany.sca.binding.corba.testing.generated.long_seq1Helper.write(out, $result); + org.apache.tuscany.sca.binding.corba.testing.generated.long_seq1Helper.write(out, arg.value); + break; + } + + case 4: // org/apache/tuscany/sca/binding/corba/testing/generated/TestObject/setLongSeq2 + { + org.apache.tuscany.sca.binding.corba.testing.generated.long_seq2Holder arg = + new org.apache.tuscany.sca.binding.corba.testing.generated.long_seq2Holder(); + arg.value = org.apache.tuscany.sca.binding.corba.testing.generated.long_seq2Helper.read(in); + int $result[][] = null; + $result = this.setLongSeq2(arg); + out = $rh.createReply(); + org.apache.tuscany.sca.binding.corba.testing.generated.long_seq2Helper.write(out, $result); + org.apache.tuscany.sca.binding.corba.testing.generated.long_seq2Helper.write(out, arg.value); + break; + } + + case 5: // org/apache/tuscany/sca/binding/corba/testing/generated/TestObject/setLongSeq3 + { + org.apache.tuscany.sca.binding.corba.testing.generated.long_seq3Holder arg = + new org.apache.tuscany.sca.binding.corba.testing.generated.long_seq3Holder(); + arg.value = org.apache.tuscany.sca.binding.corba.testing.generated.long_seq3Helper.read(in); + int $result[][][] = null; + $result = this.setLongSeq3(arg); + out = $rh.createReply(); + org.apache.tuscany.sca.binding.corba.testing.generated.long_seq3Helper.write(out, $result); + org.apache.tuscany.sca.binding.corba.testing.generated.long_seq3Helper.write(out, arg.value); + break; + } + + default: + throw new org.omg.CORBA.BAD_OPERATION(0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE); + } + + return out; + } // _invoke + + // Type-specific CORBA::Object operations + private static String[] __ids = {"IDL:org/apache/tuscany/sca/binding/corba/testing/generated/TestObject:1.0"}; + + @Override + public String[] _ids() { + return (String[])__ids.clone(); + } + +} // class _TestObjectImplBase diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/_TestObjectStub.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/_TestObjectStub.java new file mode 100644 index 0000000000..ad47595ddf --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/_TestObjectStub.java @@ -0,0 +1,182 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/_TestObjectStub.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 14:12:28 CEST +*/ + +public class _TestObjectStub extends org.omg.CORBA.portable.ObjectImpl implements + org.apache.tuscany.sca.binding.corba.testing.generated.TestObject { + + public org.apache.tuscany.sca.binding.corba.testing.generated.SomeStruct pickStructFromArgs(org.apache.tuscany.sca.binding.corba.testing.generated.SomeStruct arg1, + org.apache.tuscany.sca.binding.corba.testing.generated.SomeStruct arg2, + org.apache.tuscany.sca.binding.corba.testing.generated.SomeStruct arg3, + int structNumber) { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("pickStructFromArgs", true); + org.apache.tuscany.sca.binding.corba.testing.generated.SomeStructHelper.write($out, arg1); + org.apache.tuscany.sca.binding.corba.testing.generated.SomeStructHelper.write($out, arg2); + org.apache.tuscany.sca.binding.corba.testing.generated.SomeStructHelper.write($out, arg3); + $out.write_long(structNumber); + $in = _invoke($out); + org.apache.tuscany.sca.binding.corba.testing.generated.SomeStruct $result = + org.apache.tuscany.sca.binding.corba.testing.generated.SomeStructHelper.read($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return pickStructFromArgs(arg1, arg2, arg3, structNumber); + } finally { + _releaseReply($in); + } + } // pickStructFromArgs + + public org.apache.tuscany.sca.binding.corba.testing.generated.SomeStruct setStruct(org.apache.tuscany.sca.binding.corba.testing.generated.SomeStruct arg) { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("setStruct", true); + org.apache.tuscany.sca.binding.corba.testing.generated.SomeStructHelper.write($out, arg); + $in = _invoke($out); + org.apache.tuscany.sca.binding.corba.testing.generated.SomeStruct $result = + org.apache.tuscany.sca.binding.corba.testing.generated.SomeStructHelper.read($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return setStruct(arg); + } finally { + _releaseReply($in); + } + } // setStruct + + public org.apache.tuscany.sca.binding.corba.testing.generated.SimpleStruct setSimpleStruct(org.apache.tuscany.sca.binding.corba.testing.generated.SimpleStructHolder arg) { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("setSimpleStruct", true); + org.apache.tuscany.sca.binding.corba.testing.generated.SimpleStructHelper.write($out, arg.value); + $in = _invoke($out); + org.apache.tuscany.sca.binding.corba.testing.generated.SimpleStruct $result = + org.apache.tuscany.sca.binding.corba.testing.generated.SimpleStructHelper.read($in); + arg.value = org.apache.tuscany.sca.binding.corba.testing.generated.SimpleStructHelper.read($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return setSimpleStruct(arg); + } finally { + _releaseReply($in); + } + } // setSimpleStruct + + public int[] setLongSeq1(org.apache.tuscany.sca.binding.corba.testing.generated.long_seq1Holder arg) { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("setLongSeq1", true); + org.apache.tuscany.sca.binding.corba.testing.generated.long_seq1Helper.write($out, arg.value); + $in = _invoke($out); + int $result[] = org.apache.tuscany.sca.binding.corba.testing.generated.long_seq1Helper.read($in); + arg.value = org.apache.tuscany.sca.binding.corba.testing.generated.long_seq1Helper.read($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return setLongSeq1(arg); + } finally { + _releaseReply($in); + } + } // setLongSeq1 + + public int[][] setLongSeq2(org.apache.tuscany.sca.binding.corba.testing.generated.long_seq2Holder arg) { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("setLongSeq2", true); + org.apache.tuscany.sca.binding.corba.testing.generated.long_seq2Helper.write($out, arg.value); + $in = _invoke($out); + int $result[][] = org.apache.tuscany.sca.binding.corba.testing.generated.long_seq2Helper.read($in); + arg.value = org.apache.tuscany.sca.binding.corba.testing.generated.long_seq2Helper.read($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return setLongSeq2(arg); + } finally { + _releaseReply($in); + } + } // setLongSeq2 + + public int[][][] setLongSeq3(org.apache.tuscany.sca.binding.corba.testing.generated.long_seq3Holder arg) { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("setLongSeq3", true); + org.apache.tuscany.sca.binding.corba.testing.generated.long_seq3Helper.write($out, arg.value); + $in = _invoke($out); + int $result[][][] = org.apache.tuscany.sca.binding.corba.testing.generated.long_seq3Helper.read($in); + arg.value = org.apache.tuscany.sca.binding.corba.testing.generated.long_seq3Helper.read($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return setLongSeq3(arg); + } finally { + _releaseReply($in); + } + } // setLongSeq3 + + // Type-specific CORBA::Object operations + private static String[] __ids = {"IDL:org/apache/tuscany/sca/binding/corba/testing/generated/TestObject:1.0"}; + + @Override + public String[] _ids() { + return (String[])__ids.clone(); + } + + private void readObject(java.io.ObjectInputStream s) throws java.io.IOException { + String str = s.readUTF(); + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.Object obj = org.omg.CORBA.ORB.init(args, props).string_to_object(str); + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate(); + _set_delegate(delegate); + } + + private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { + String[] args = null; + java.util.Properties props = null; + String str = org.omg.CORBA.ORB.init(args, props).object_to_string(this); + s.writeUTF(str); + } +} // class _TestObjectStub diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/boolean_listHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/boolean_listHelper.java new file mode 100644 index 0000000000..f3d96e8fd7 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/boolean_listHelper.java @@ -0,0 +1,75 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/boolean_listHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 14:12:28 CEST +*/ + +abstract public class boolean_listHelper { + private static String _id = "IDL:org/apache/tuscany/sca/binding/corba/testing/generated/boolean_list:1.0"; + + public static void insert(org.omg.CORBA.Any a, boolean[] that) { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream(); + a.type(type()); + write(out, that); + a.read_value(out.create_input_stream(), type()); + } + + public static boolean[] extract(org.omg.CORBA.Any a) { + return read(a.create_input_stream()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + + synchronized public static org.omg.CORBA.TypeCode type() { + if (__typeCode == null) { + __typeCode = org.omg.CORBA.ORB.init().get_primitive_tc(org.omg.CORBA.TCKind.tk_boolean); + __typeCode = org.omg.CORBA.ORB.init().create_sequence_tc(0, __typeCode); + __typeCode = + org.omg.CORBA.ORB.init() + .create_alias_tc(org.apache.tuscany.sca.binding.corba.testing.generated.boolean_listHelper.id(), + "boolean_list", + __typeCode); + } + return __typeCode; + } + + public static String id() { + return _id; + } + + public static boolean[] read(org.omg.CORBA.portable.InputStream istream) { + boolean value[] = null; + int _len0 = istream.read_long(); + value = new boolean[_len0]; + istream.read_boolean_array(value, 0, _len0); + return value; + } + + public static void write(org.omg.CORBA.portable.OutputStream ostream, boolean[] value) { + ostream.write_long(value.length); + ostream.write_boolean_array(value, 0, value.length); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/boolean_listHolder.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/boolean_listHolder.java new file mode 100644 index 0000000000..cb0ab8bcfd --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/boolean_listHolder.java @@ -0,0 +1,51 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/boolean_listHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 14:12:28 CEST +*/ + +public final class boolean_listHolder implements org.omg.CORBA.portable.Streamable { + public boolean value[] = null; + + public boolean_listHolder() { + } + + public boolean_listHolder(boolean[] initialValue) { + value = initialValue; + } + + public void _read(org.omg.CORBA.portable.InputStream i) { + value = org.apache.tuscany.sca.binding.corba.testing.generated.boolean_listHelper.read(i); + } + + public void _write(org.omg.CORBA.portable.OutputStream o) { + org.apache.tuscany.sca.binding.corba.testing.generated.boolean_listHelper.write(o, value); + } + + public org.omg.CORBA.TypeCode _type() { + return org.apache.tuscany.sca.binding.corba.testing.generated.boolean_listHelper.type(); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/char_listHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/char_listHelper.java new file mode 100644 index 0000000000..0bde1e701c --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/char_listHelper.java @@ -0,0 +1,75 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/char_listHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 14:12:28 CEST +*/ + +abstract public class char_listHelper { + private static String _id = "IDL:org/apache/tuscany/sca/binding/corba/testing/generated/char_list:1.0"; + + public static void insert(org.omg.CORBA.Any a, char[] that) { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream(); + a.type(type()); + write(out, that); + a.read_value(out.create_input_stream(), type()); + } + + public static char[] extract(org.omg.CORBA.Any a) { + return read(a.create_input_stream()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + + synchronized public static org.omg.CORBA.TypeCode type() { + if (__typeCode == null) { + __typeCode = org.omg.CORBA.ORB.init().get_primitive_tc(org.omg.CORBA.TCKind.tk_char); + __typeCode = org.omg.CORBA.ORB.init().create_sequence_tc(0, __typeCode); + __typeCode = + org.omg.CORBA.ORB.init() + .create_alias_tc(org.apache.tuscany.sca.binding.corba.testing.generated.char_listHelper.id(), + "char_list", + __typeCode); + } + return __typeCode; + } + + public static String id() { + return _id; + } + + public static char[] read(org.omg.CORBA.portable.InputStream istream) { + char value[] = null; + int _len0 = istream.read_long(); + value = new char[_len0]; + istream.read_char_array(value, 0, _len0); + return value; + } + + public static void write(org.omg.CORBA.portable.OutputStream ostream, char[] value) { + ostream.write_long(value.length); + ostream.write_char_array(value, 0, value.length); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/char_listHolder.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/char_listHolder.java new file mode 100644 index 0000000000..19b2942cfe --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/char_listHolder.java @@ -0,0 +1,51 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/char_listHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 14:12:28 CEST +*/ + +public final class char_listHolder implements org.omg.CORBA.portable.Streamable { + public char value[] = null; + + public char_listHolder() { + } + + public char_listHolder(char[] initialValue) { + value = initialValue; + } + + public void _read(org.omg.CORBA.portable.InputStream i) { + value = org.apache.tuscany.sca.binding.corba.testing.generated.char_listHelper.read(i); + } + + public void _write(org.omg.CORBA.portable.OutputStream o) { + org.apache.tuscany.sca.binding.corba.testing.generated.char_listHelper.write(o, value); + } + + public org.omg.CORBA.TypeCode _type() { + return org.apache.tuscany.sca.binding.corba.testing.generated.char_listHelper.type(); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/double_listHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/double_listHelper.java new file mode 100644 index 0000000000..8bb5a9c69d --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/double_listHelper.java @@ -0,0 +1,75 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/double_listHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 14:12:28 CEST +*/ + +abstract public class double_listHelper { + private static String _id = "IDL:org/apache/tuscany/sca/binding/corba/testing/generated/double_list:1.0"; + + public static void insert(org.omg.CORBA.Any a, double[] that) { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream(); + a.type(type()); + write(out, that); + a.read_value(out.create_input_stream(), type()); + } + + public static double[] extract(org.omg.CORBA.Any a) { + return read(a.create_input_stream()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + + synchronized public static org.omg.CORBA.TypeCode type() { + if (__typeCode == null) { + __typeCode = org.omg.CORBA.ORB.init().get_primitive_tc(org.omg.CORBA.TCKind.tk_double); + __typeCode = org.omg.CORBA.ORB.init().create_sequence_tc(0, __typeCode); + __typeCode = + org.omg.CORBA.ORB.init() + .create_alias_tc(org.apache.tuscany.sca.binding.corba.testing.generated.double_listHelper.id(), + "double_list", + __typeCode); + } + return __typeCode; + } + + public static String id() { + return _id; + } + + public static double[] read(org.omg.CORBA.portable.InputStream istream) { + double value[] = null; + int _len0 = istream.read_long(); + value = new double[_len0]; + istream.read_double_array(value, 0, _len0); + return value; + } + + public static void write(org.omg.CORBA.portable.OutputStream ostream, double[] value) { + ostream.write_long(value.length); + ostream.write_double_array(value, 0, value.length); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/double_listHolder.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/double_listHolder.java new file mode 100644 index 0000000000..dc89e71092 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/double_listHolder.java @@ -0,0 +1,51 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/double_listHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 14:12:28 CEST +*/ + +public final class double_listHolder implements org.omg.CORBA.portable.Streamable { + public double value[] = null; + + public double_listHolder() { + } + + public double_listHolder(double[] initialValue) { + value = initialValue; + } + + public void _read(org.omg.CORBA.portable.InputStream i) { + value = org.apache.tuscany.sca.binding.corba.testing.generated.double_listHelper.read(i); + } + + public void _write(org.omg.CORBA.portable.OutputStream o) { + org.apache.tuscany.sca.binding.corba.testing.generated.double_listHelper.write(o, value); + } + + public org.omg.CORBA.TypeCode _type() { + return org.apache.tuscany.sca.binding.corba.testing.generated.double_listHelper.type(); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/float_listHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/float_listHelper.java new file mode 100644 index 0000000000..7b71aa0a9f --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/float_listHelper.java @@ -0,0 +1,75 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/float_listHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 14:12:28 CEST +*/ + +abstract public class float_listHelper { + private static String _id = "IDL:org/apache/tuscany/sca/binding/corba/testing/generated/float_list:1.0"; + + public static void insert(org.omg.CORBA.Any a, float[] that) { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream(); + a.type(type()); + write(out, that); + a.read_value(out.create_input_stream(), type()); + } + + public static float[] extract(org.omg.CORBA.Any a) { + return read(a.create_input_stream()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + + synchronized public static org.omg.CORBA.TypeCode type() { + if (__typeCode == null) { + __typeCode = org.omg.CORBA.ORB.init().get_primitive_tc(org.omg.CORBA.TCKind.tk_float); + __typeCode = org.omg.CORBA.ORB.init().create_sequence_tc(0, __typeCode); + __typeCode = + org.omg.CORBA.ORB.init() + .create_alias_tc(org.apache.tuscany.sca.binding.corba.testing.generated.float_listHelper.id(), + "float_list", + __typeCode); + } + return __typeCode; + } + + public static String id() { + return _id; + } + + public static float[] read(org.omg.CORBA.portable.InputStream istream) { + float value[] = null; + int _len0 = istream.read_long(); + value = new float[_len0]; + istream.read_float_array(value, 0, _len0); + return value; + } + + public static void write(org.omg.CORBA.portable.OutputStream ostream, float[] value) { + ostream.write_long(value.length); + ostream.write_float_array(value, 0, value.length); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/float_listHolder.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/float_listHolder.java new file mode 100644 index 0000000000..513bab37cc --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/float_listHolder.java @@ -0,0 +1,51 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/float_listHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 14:12:28 CEST +*/ + +public final class float_listHolder implements org.omg.CORBA.portable.Streamable { + public float value[] = null; + + public float_listHolder() { + } + + public float_listHolder(float[] initialValue) { + value = initialValue; + } + + public void _read(org.omg.CORBA.portable.InputStream i) { + value = org.apache.tuscany.sca.binding.corba.testing.generated.float_listHelper.read(i); + } + + public void _write(org.omg.CORBA.portable.OutputStream o) { + org.apache.tuscany.sca.binding.corba.testing.generated.float_listHelper.write(o, value); + } + + public org.omg.CORBA.TypeCode _type() { + return org.apache.tuscany.sca.binding.corba.testing.generated.float_listHelper.type(); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/long_listHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/long_listHelper.java new file mode 100644 index 0000000000..c1d06e2ba9 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/long_listHelper.java @@ -0,0 +1,75 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/long_listHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 14:12:28 CEST +*/ + +abstract public class long_listHelper { + private static String _id = "IDL:org/apache/tuscany/sca/binding/corba/testing/generated/long_list:1.0"; + + public static void insert(org.omg.CORBA.Any a, int[] that) { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream(); + a.type(type()); + write(out, that); + a.read_value(out.create_input_stream(), type()); + } + + public static int[] extract(org.omg.CORBA.Any a) { + return read(a.create_input_stream()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + + synchronized public static org.omg.CORBA.TypeCode type() { + if (__typeCode == null) { + __typeCode = org.omg.CORBA.ORB.init().get_primitive_tc(org.omg.CORBA.TCKind.tk_long); + __typeCode = org.omg.CORBA.ORB.init().create_sequence_tc(0, __typeCode); + __typeCode = + org.omg.CORBA.ORB.init() + .create_alias_tc(org.apache.tuscany.sca.binding.corba.testing.generated.long_listHelper.id(), + "long_list", + __typeCode); + } + return __typeCode; + } + + public static String id() { + return _id; + } + + public static int[] read(org.omg.CORBA.portable.InputStream istream) { + int value[] = null; + int _len0 = istream.read_long(); + value = new int[_len0]; + istream.read_long_array(value, 0, _len0); + return value; + } + + public static void write(org.omg.CORBA.portable.OutputStream ostream, int[] value) { + ostream.write_long(value.length); + ostream.write_long_array(value, 0, value.length); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/long_listHolder.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/long_listHolder.java new file mode 100644 index 0000000000..f9ad7b77ac --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/long_listHolder.java @@ -0,0 +1,51 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/long_listHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 14:12:28 CEST +*/ + +public final class long_listHolder implements org.omg.CORBA.portable.Streamable { + public int value[] = null; + + public long_listHolder() { + } + + public long_listHolder(int[] initialValue) { + value = initialValue; + } + + public void _read(org.omg.CORBA.portable.InputStream i) { + value = org.apache.tuscany.sca.binding.corba.testing.generated.long_listHelper.read(i); + } + + public void _write(org.omg.CORBA.portable.OutputStream o) { + org.apache.tuscany.sca.binding.corba.testing.generated.long_listHelper.write(o, value); + } + + public org.omg.CORBA.TypeCode _type() { + return org.apache.tuscany.sca.binding.corba.testing.generated.long_listHelper.type(); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/long_long_listHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/long_long_listHelper.java new file mode 100644 index 0000000000..cfb292fc01 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/long_long_listHelper.java @@ -0,0 +1,75 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/long_long_listHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 14:12:28 CEST +*/ + +abstract public class long_long_listHelper { + private static String _id = "IDL:org/apache/tuscany/sca/binding/corba/testing/generated/long_long_list:1.0"; + + public static void insert(org.omg.CORBA.Any a, long[] that) { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream(); + a.type(type()); + write(out, that); + a.read_value(out.create_input_stream(), type()); + } + + public static long[] extract(org.omg.CORBA.Any a) { + return read(a.create_input_stream()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + + synchronized public static org.omg.CORBA.TypeCode type() { + if (__typeCode == null) { + __typeCode = org.omg.CORBA.ORB.init().get_primitive_tc(org.omg.CORBA.TCKind.tk_longlong); + __typeCode = org.omg.CORBA.ORB.init().create_sequence_tc(0, __typeCode); + __typeCode = + org.omg.CORBA.ORB.init() + .create_alias_tc(org.apache.tuscany.sca.binding.corba.testing.generated.long_long_listHelper.id(), + "long_long_list", + __typeCode); + } + return __typeCode; + } + + public static String id() { + return _id; + } + + public static long[] read(org.omg.CORBA.portable.InputStream istream) { + long value[] = null; + int _len0 = istream.read_long(); + value = new long[_len0]; + istream.read_longlong_array(value, 0, _len0); + return value; + } + + public static void write(org.omg.CORBA.portable.OutputStream ostream, long[] value) { + ostream.write_long(value.length); + ostream.write_longlong_array(value, 0, value.length); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/long_long_listHolder.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/long_long_listHolder.java new file mode 100644 index 0000000000..02f46a7d85 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/long_long_listHolder.java @@ -0,0 +1,51 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/long_long_listHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 14:12:28 CEST +*/ + +public final class long_long_listHolder implements org.omg.CORBA.portable.Streamable { + public long value[] = null; + + public long_long_listHolder() { + } + + public long_long_listHolder(long[] initialValue) { + value = initialValue; + } + + public void _read(org.omg.CORBA.portable.InputStream i) { + value = org.apache.tuscany.sca.binding.corba.testing.generated.long_long_listHelper.read(i); + } + + public void _write(org.omg.CORBA.portable.OutputStream o) { + org.apache.tuscany.sca.binding.corba.testing.generated.long_long_listHelper.write(o, value); + } + + public org.omg.CORBA.TypeCode _type() { + return org.apache.tuscany.sca.binding.corba.testing.generated.long_long_listHelper.type(); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/long_seq1Helper.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/long_seq1Helper.java new file mode 100644 index 0000000000..505aa3f026 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/long_seq1Helper.java @@ -0,0 +1,75 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/long_seq1Helper.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 2008 14:12:28 CEST +*/ + +abstract public class long_seq1Helper { + private static String _id = "IDL:org/apache/tuscany/sca/binding/corba/testing/generated/long_seq1:1.0"; + + public static void insert(org.omg.CORBA.Any a, int[] that) { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream(); + a.type(type()); + write(out, that); + a.read_value(out.create_input_stream(), type()); + } + + public static int[] extract(org.omg.CORBA.Any a) { + return read(a.create_input_stream()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + + synchronized public static org.omg.CORBA.TypeCode type() { + if (__typeCode == null) { + __typeCode = org.omg.CORBA.ORB.init().get_primitive_tc(org.omg.CORBA.TCKind.tk_long); + __typeCode = org.omg.CORBA.ORB.init().create_sequence_tc(0, __typeCode); + __typeCode = + org.omg.CORBA.ORB.init() + .create_alias_tc(org.apache.tuscany.sca.binding.corba.testing.generated.long_seq1Helper.id(), + "long_seq1", + __typeCode); + } + return __typeCode; + } + + public static String id() { + return _id; + } + + public static int[] read(org.omg.CORBA.portable.InputStream istream) { + int value[] = null; + int _len0 = istream.read_long(); + value = new int[_len0]; + istream.read_long_array(value, 0, _len0); + return value; + } + + public static void write(org.omg.CORBA.portable.OutputStream ostream, int[] value) { + ostream.write_long(value.length); + ostream.write_long_array(value, 0, value.length); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/long_seq1Holder.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/long_seq1Holder.java new file mode 100644 index 0000000000..5cbaa109ee --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/long_seq1Holder.java @@ -0,0 +1,51 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/long_seq1Holder.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 2008 14:12:28 CEST +*/ + +public final class long_seq1Holder implements org.omg.CORBA.portable.Streamable { + public int value[] = null; + + public long_seq1Holder() { + } + + public long_seq1Holder(int[] initialValue) { + value = initialValue; + } + + public void _read(org.omg.CORBA.portable.InputStream i) { + value = org.apache.tuscany.sca.binding.corba.testing.generated.long_seq1Helper.read(i); + } + + public void _write(org.omg.CORBA.portable.OutputStream o) { + org.apache.tuscany.sca.binding.corba.testing.generated.long_seq1Helper.write(o, value); + } + + public org.omg.CORBA.TypeCode _type() { + return org.apache.tuscany.sca.binding.corba.testing.generated.long_seq1Helper.type(); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/long_seq2Helper.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/long_seq2Helper.java new file mode 100644 index 0000000000..2f792888fb --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/long_seq2Helper.java @@ -0,0 +1,83 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/long_seq2Helper.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 2008 14:12:28 CEST +*/ + +abstract public class long_seq2Helper { + private static String _id = "IDL:org/apache/tuscany/sca/binding/corba/testing/generated/long_seq2:1.0"; + + public static void insert(org.omg.CORBA.Any a, int[][] that) { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream(); + a.type(type()); + write(out, that); + a.read_value(out.create_input_stream(), type()); + } + + public static int[][] extract(org.omg.CORBA.Any a) { + return read(a.create_input_stream()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + + synchronized public static org.omg.CORBA.TypeCode type() { + if (__typeCode == null) { + __typeCode = org.omg.CORBA.ORB.init().get_primitive_tc(org.omg.CORBA.TCKind.tk_long); + __typeCode = org.omg.CORBA.ORB.init().create_sequence_tc(0, __typeCode); + __typeCode = + org.omg.CORBA.ORB.init() + .create_alias_tc(org.apache.tuscany.sca.binding.corba.testing.generated.long_seq1Helper.id(), + "long_seq1", + __typeCode); + __typeCode = org.omg.CORBA.ORB.init().create_sequence_tc(0, __typeCode); + __typeCode = + org.omg.CORBA.ORB.init() + .create_alias_tc(org.apache.tuscany.sca.binding.corba.testing.generated.long_seq2Helper.id(), + "long_seq2", + __typeCode); + } + return __typeCode; + } + + public static String id() { + return _id; + } + + public static int[][] read(org.omg.CORBA.portable.InputStream istream) { + int value[][] = null; + int _len0 = istream.read_long(); + value = new int[_len0][]; + for (int _o1 = 0; _o1 < value.length; ++_o1) + value[_o1] = org.apache.tuscany.sca.binding.corba.testing.generated.long_seq1Helper.read(istream); + return value; + } + + public static void write(org.omg.CORBA.portable.OutputStream ostream, int[][] value) { + ostream.write_long(value.length); + for (int _i0 = 0; _i0 < value.length; ++_i0) + org.apache.tuscany.sca.binding.corba.testing.generated.long_seq1Helper.write(ostream, value[_i0]); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/long_seq2Holder.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/long_seq2Holder.java new file mode 100644 index 0000000000..8b2ccc1f73 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/long_seq2Holder.java @@ -0,0 +1,51 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/long_seq2Holder.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 2008 14:12:28 CEST +*/ + +public final class long_seq2Holder implements org.omg.CORBA.portable.Streamable { + public int value[][] = null; + + public long_seq2Holder() { + } + + public long_seq2Holder(int[][] initialValue) { + value = initialValue; + } + + public void _read(org.omg.CORBA.portable.InputStream i) { + value = org.apache.tuscany.sca.binding.corba.testing.generated.long_seq2Helper.read(i); + } + + public void _write(org.omg.CORBA.portable.OutputStream o) { + org.apache.tuscany.sca.binding.corba.testing.generated.long_seq2Helper.write(o, value); + } + + public org.omg.CORBA.TypeCode _type() { + return org.apache.tuscany.sca.binding.corba.testing.generated.long_seq2Helper.type(); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/long_seq3Helper.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/long_seq3Helper.java new file mode 100644 index 0000000000..67e224f0be --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/long_seq3Helper.java @@ -0,0 +1,89 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/long_seq3Helper.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 2008 14:12:28 CEST +*/ + +abstract public class long_seq3Helper { + private static String _id = "IDL:org/apache/tuscany/sca/binding/corba/testing/generated/long_seq3:1.0"; + + public static void insert(org.omg.CORBA.Any a, int[][][] that) { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream(); + a.type(type()); + write(out, that); + a.read_value(out.create_input_stream(), type()); + } + + public static int[][][] extract(org.omg.CORBA.Any a) { + return read(a.create_input_stream()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + + synchronized public static org.omg.CORBA.TypeCode type() { + if (__typeCode == null) { + __typeCode = org.omg.CORBA.ORB.init().get_primitive_tc(org.omg.CORBA.TCKind.tk_long); + __typeCode = org.omg.CORBA.ORB.init().create_sequence_tc(0, __typeCode); + __typeCode = + org.omg.CORBA.ORB.init() + .create_alias_tc(org.apache.tuscany.sca.binding.corba.testing.generated.long_seq1Helper.id(), + "long_seq1", + __typeCode); + __typeCode = org.omg.CORBA.ORB.init().create_sequence_tc(0, __typeCode); + __typeCode = + org.omg.CORBA.ORB.init() + .create_alias_tc(org.apache.tuscany.sca.binding.corba.testing.generated.long_seq2Helper.id(), + "long_seq2", + __typeCode); + __typeCode = org.omg.CORBA.ORB.init().create_sequence_tc(0, __typeCode); + __typeCode = + org.omg.CORBA.ORB.init() + .create_alias_tc(org.apache.tuscany.sca.binding.corba.testing.generated.long_seq3Helper.id(), + "long_seq3", + __typeCode); + } + return __typeCode; + } + + public static String id() { + return _id; + } + + public static int[][][] read(org.omg.CORBA.portable.InputStream istream) { + int value[][][] = null; + int _len0 = istream.read_long(); + value = new int[_len0][][]; + for (int _o1 = 0; _o1 < value.length; ++_o1) + value[_o1] = org.apache.tuscany.sca.binding.corba.testing.generated.long_seq2Helper.read(istream); + return value; + } + + public static void write(org.omg.CORBA.portable.OutputStream ostream, int[][][] value) { + ostream.write_long(value.length); + for (int _i0 = 0; _i0 < value.length; ++_i0) + org.apache.tuscany.sca.binding.corba.testing.generated.long_seq2Helper.write(ostream, value[_i0]); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/long_seq3Holder.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/long_seq3Holder.java new file mode 100644 index 0000000000..5d4adfba2d --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/long_seq3Holder.java @@ -0,0 +1,51 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/long_seq3Holder.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 2008 14:12:28 CEST +*/ + +public final class long_seq3Holder implements org.omg.CORBA.portable.Streamable { + public int value[][][] = null; + + public long_seq3Holder() { + } + + public long_seq3Holder(int[][][] initialValue) { + value = initialValue; + } + + public void _read(org.omg.CORBA.portable.InputStream i) { + value = org.apache.tuscany.sca.binding.corba.testing.generated.long_seq3Helper.read(i); + } + + public void _write(org.omg.CORBA.portable.OutputStream o) { + org.apache.tuscany.sca.binding.corba.testing.generated.long_seq3Helper.write(o, value); + } + + public org.omg.CORBA.TypeCode _type() { + return org.apache.tuscany.sca.binding.corba.testing.generated.long_seq3Helper.type(); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/octet_listHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/octet_listHelper.java new file mode 100644 index 0000000000..c7d86d9179 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/octet_listHelper.java @@ -0,0 +1,75 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/octet_listHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 2008 14:12:28 CEST +*/ + +abstract public class octet_listHelper { + private static String _id = "IDL:org/apache/tuscany/sca/binding/corba/testing/generated/octet_list:1.0"; + + public static void insert(org.omg.CORBA.Any a, byte[] that) { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream(); + a.type(type()); + write(out, that); + a.read_value(out.create_input_stream(), type()); + } + + public static byte[] extract(org.omg.CORBA.Any a) { + return read(a.create_input_stream()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + + synchronized public static org.omg.CORBA.TypeCode type() { + if (__typeCode == null) { + __typeCode = org.omg.CORBA.ORB.init().get_primitive_tc(org.omg.CORBA.TCKind.tk_octet); + __typeCode = org.omg.CORBA.ORB.init().create_sequence_tc(0, __typeCode); + __typeCode = + org.omg.CORBA.ORB.init() + .create_alias_tc(org.apache.tuscany.sca.binding.corba.testing.generated.octet_listHelper.id(), + "octet_list", + __typeCode); + } + return __typeCode; + } + + public static String id() { + return _id; + } + + public static byte[] read(org.omg.CORBA.portable.InputStream istream) { + byte value[] = null; + int _len0 = istream.read_long(); + value = new byte[_len0]; + istream.read_octet_array(value, 0, _len0); + return value; + } + + public static void write(org.omg.CORBA.portable.OutputStream ostream, byte[] value) { + ostream.write_long(value.length); + ostream.write_octet_array(value, 0, value.length); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/octet_listHolder.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/octet_listHolder.java new file mode 100644 index 0000000000..09b2b85c6a --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/octet_listHolder.java @@ -0,0 +1,51 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/octet_listHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 2008 14:12:28 CEST +*/ + +public final class octet_listHolder implements org.omg.CORBA.portable.Streamable { + public byte value[] = null; + + public octet_listHolder() { + } + + public octet_listHolder(byte[] initialValue) { + value = initialValue; + } + + public void _read(org.omg.CORBA.portable.InputStream i) { + value = org.apache.tuscany.sca.binding.corba.testing.generated.octet_listHelper.read(i); + } + + public void _write(org.omg.CORBA.portable.OutputStream o) { + org.apache.tuscany.sca.binding.corba.testing.generated.octet_listHelper.write(o, value); + } + + public org.omg.CORBA.TypeCode _type() { + return org.apache.tuscany.sca.binding.corba.testing.generated.octet_listHelper.type(); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/remote_object_listHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/remote_object_listHelper.java new file mode 100644 index 0000000000..e88b1e06c4 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/remote_object_listHelper.java @@ -0,0 +1,80 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/remote_object_listHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 2008 14:12:28 CEST +*/ + +abstract public class remote_object_listHelper { + private static String _id = "IDL:org/apache/tuscany/sca/binding/corba/testing/generated/remote_object_list:1.0"; + + public static void insert(org.omg.CORBA.Any a, + org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObject[] that) { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream(); + a.type(type()); + write(out, that); + a.read_value(out.create_input_stream(), type()); + } + + public static org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObject[] extract(org.omg.CORBA.Any a) { + return read(a.create_input_stream()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + + synchronized public static org.omg.CORBA.TypeCode type() { + if (__typeCode == null) { + __typeCode = org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObjectHelper.type(); + __typeCode = org.omg.CORBA.ORB.init().create_sequence_tc(0, __typeCode); + __typeCode = + org.omg.CORBA.ORB.init() + .create_alias_tc(org.apache.tuscany.sca.binding.corba.testing.generated.remote_object_listHelper + .id(), + "remote_object_list", + __typeCode); + } + return __typeCode; + } + + public static String id() { + return _id; + } + + public static org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObject[] read(org.omg.CORBA.portable.InputStream istream) { + org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObject value[] = null; + int _len0 = istream.read_long(); + value = new org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObject[_len0]; + for (int _o1 = 0; _o1 < value.length; ++_o1) + value[_o1] = org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObjectHelper.read(istream); + return value; + } + + public static void write(org.omg.CORBA.portable.OutputStream ostream, + org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObject[] value) { + ostream.write_long(value.length); + for (int _i0 = 0; _i0 < value.length; ++_i0) + org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObjectHelper.write(ostream, value[_i0]); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/remote_object_listHolder.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/remote_object_listHolder.java new file mode 100644 index 0000000000..d3f996c5b4 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/remote_object_listHolder.java @@ -0,0 +1,51 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/remote_object_listHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 2008 14:12:28 CEST +*/ + +public final class remote_object_listHolder implements org.omg.CORBA.portable.Streamable { + public org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObject value[] = null; + + public remote_object_listHolder() { + } + + public remote_object_listHolder(org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObject[] initialValue) { + value = initialValue; + } + + public void _read(org.omg.CORBA.portable.InputStream i) { + value = org.apache.tuscany.sca.binding.corba.testing.generated.remote_object_listHelper.read(i); + } + + public void _write(org.omg.CORBA.portable.OutputStream o) { + org.apache.tuscany.sca.binding.corba.testing.generated.remote_object_listHelper.write(o, value); + } + + public org.omg.CORBA.TypeCode _type() { + return org.apache.tuscany.sca.binding.corba.testing.generated.remote_object_listHelper.type(); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/short_listHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/short_listHelper.java new file mode 100644 index 0000000000..7c58d47f7c --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/short_listHelper.java @@ -0,0 +1,75 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/short_listHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 2008 14:12:28 CEST +*/ + +abstract public class short_listHelper { + private static String _id = "IDL:org/apache/tuscany/sca/binding/corba/testing/generated/short_list:1.0"; + + public static void insert(org.omg.CORBA.Any a, short[] that) { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream(); + a.type(type()); + write(out, that); + a.read_value(out.create_input_stream(), type()); + } + + public static short[] extract(org.omg.CORBA.Any a) { + return read(a.create_input_stream()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + + synchronized public static org.omg.CORBA.TypeCode type() { + if (__typeCode == null) { + __typeCode = org.omg.CORBA.ORB.init().get_primitive_tc(org.omg.CORBA.TCKind.tk_short); + __typeCode = org.omg.CORBA.ORB.init().create_sequence_tc(0, __typeCode); + __typeCode = + org.omg.CORBA.ORB.init() + .create_alias_tc(org.apache.tuscany.sca.binding.corba.testing.generated.short_listHelper.id(), + "short_list", + __typeCode); + } + return __typeCode; + } + + public static String id() { + return _id; + } + + public static short[] read(org.omg.CORBA.portable.InputStream istream) { + short value[] = null; + int _len0 = istream.read_long(); + value = new short[_len0]; + istream.read_short_array(value, 0, _len0); + return value; + } + + public static void write(org.omg.CORBA.portable.OutputStream ostream, short[] value) { + ostream.write_long(value.length); + ostream.write_short_array(value, 0, value.length); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/short_listHolder.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/short_listHolder.java new file mode 100644 index 0000000000..5be5a65c43 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/short_listHolder.java @@ -0,0 +1,51 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/short_listHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 2008 14:12:28 CEST +*/ + +public final class short_listHolder implements org.omg.CORBA.portable.Streamable { + public short value[] = null; + + public short_listHolder() { + } + + public short_listHolder(short[] initialValue) { + value = initialValue; + } + + public void _read(org.omg.CORBA.portable.InputStream i) { + value = org.apache.tuscany.sca.binding.corba.testing.generated.short_listHelper.read(i); + } + + public void _write(org.omg.CORBA.portable.OutputStream o) { + org.apache.tuscany.sca.binding.corba.testing.generated.short_listHelper.write(o, value); + } + + public org.omg.CORBA.TypeCode _type() { + return org.apache.tuscany.sca.binding.corba.testing.generated.short_listHelper.type(); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/string_listHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/string_listHelper.java new file mode 100644 index 0000000000..a40d5fa8de --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/string_listHelper.java @@ -0,0 +1,77 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/string_listHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 2008 14:12:28 CEST +*/ + +abstract public class string_listHelper { + private static String _id = "IDL:org/apache/tuscany/sca/binding/corba/testing/generated/string_list:1.0"; + + public static void insert(org.omg.CORBA.Any a, String[] that) { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream(); + a.type(type()); + write(out, that); + a.read_value(out.create_input_stream(), type()); + } + + public static String[] extract(org.omg.CORBA.Any a) { + return read(a.create_input_stream()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + + synchronized public static org.omg.CORBA.TypeCode type() { + if (__typeCode == null) { + __typeCode = org.omg.CORBA.ORB.init().create_string_tc(0); + __typeCode = org.omg.CORBA.ORB.init().create_sequence_tc(0, __typeCode); + __typeCode = + org.omg.CORBA.ORB.init() + .create_alias_tc(org.apache.tuscany.sca.binding.corba.testing.generated.string_listHelper.id(), + "string_list", + __typeCode); + } + return __typeCode; + } + + public static String id() { + return _id; + } + + public static String[] read(org.omg.CORBA.portable.InputStream istream) { + String value[] = null; + int _len0 = istream.read_long(); + value = new String[_len0]; + for (int _o1 = 0; _o1 < value.length; ++_o1) + value[_o1] = istream.read_string(); + return value; + } + + public static void write(org.omg.CORBA.portable.OutputStream ostream, String[] value) { + ostream.write_long(value.length); + for (int _i0 = 0; _i0 < value.length; ++_i0) + ostream.write_string(value[_i0]); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/string_listHolder.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/string_listHolder.java new file mode 100644 index 0000000000..76f99408f2 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/string_listHolder.java @@ -0,0 +1,51 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/string_listHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 2008 14:12:28 CEST +*/ + +public final class string_listHolder implements org.omg.CORBA.portable.Streamable { + public String value[] = null; + + public string_listHolder() { + } + + public string_listHolder(String[] initialValue) { + value = initialValue; + } + + public void _read(org.omg.CORBA.portable.InputStream i) { + value = org.apache.tuscany.sca.binding.corba.testing.generated.string_listHelper.read(i); + } + + public void _write(org.omg.CORBA.portable.OutputStream o) { + org.apache.tuscany.sca.binding.corba.testing.generated.string_listHelper.write(o, value); + } + + public org.omg.CORBA.TypeCode _type() { + return org.apache.tuscany.sca.binding.corba.testing.generated.string_listHelper.type(); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/unsigned_long_listHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/unsigned_long_listHelper.java new file mode 100644 index 0000000000..d7594b0815 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/unsigned_long_listHelper.java @@ -0,0 +1,76 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/unsigned_long_listHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 2008 14:12:28 CEST +*/ + +abstract public class unsigned_long_listHelper { + private static String _id = "IDL:org/apache/tuscany/sca/binding/corba/testing/generated/unsigned_long_list:1.0"; + + public static void insert(org.omg.CORBA.Any a, int[] that) { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream(); + a.type(type()); + write(out, that); + a.read_value(out.create_input_stream(), type()); + } + + public static int[] extract(org.omg.CORBA.Any a) { + return read(a.create_input_stream()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + + synchronized public static org.omg.CORBA.TypeCode type() { + if (__typeCode == null) { + __typeCode = org.omg.CORBA.ORB.init().get_primitive_tc(org.omg.CORBA.TCKind.tk_ulong); + __typeCode = org.omg.CORBA.ORB.init().create_sequence_tc(0, __typeCode); + __typeCode = + org.omg.CORBA.ORB.init() + .create_alias_tc(org.apache.tuscany.sca.binding.corba.testing.generated.unsigned_long_listHelper + .id(), + "unsigned_long_list", + __typeCode); + } + return __typeCode; + } + + public static String id() { + return _id; + } + + public static int[] read(org.omg.CORBA.portable.InputStream istream) { + int value[] = null; + int _len0 = istream.read_long(); + value = new int[_len0]; + istream.read_ulong_array(value, 0, _len0); + return value; + } + + public static void write(org.omg.CORBA.portable.OutputStream ostream, int[] value) { + ostream.write_long(value.length); + ostream.write_ulong_array(value, 0, value.length); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/unsigned_long_listHolder.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/unsigned_long_listHolder.java new file mode 100644 index 0000000000..e9fbcccc36 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/unsigned_long_listHolder.java @@ -0,0 +1,51 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/unsigned_long_listHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 2008 14:12:28 CEST +*/ + +public final class unsigned_long_listHolder implements org.omg.CORBA.portable.Streamable { + public int value[] = null; + + public unsigned_long_listHolder() { + } + + public unsigned_long_listHolder(int[] initialValue) { + value = initialValue; + } + + public void _read(org.omg.CORBA.portable.InputStream i) { + value = org.apache.tuscany.sca.binding.corba.testing.generated.unsigned_long_listHelper.read(i); + } + + public void _write(org.omg.CORBA.portable.OutputStream o) { + org.apache.tuscany.sca.binding.corba.testing.generated.unsigned_long_listHelper.write(o, value); + } + + public org.omg.CORBA.TypeCode _type() { + return org.apache.tuscany.sca.binding.corba.testing.generated.unsigned_long_listHelper.type(); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/unsigned_long_long_listHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/unsigned_long_long_listHelper.java new file mode 100644 index 0000000000..6ef187c4e5 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/unsigned_long_long_listHelper.java @@ -0,0 +1,78 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/unsigned_long_long_listHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 2008 14:12:28 CEST +*/ + +abstract public class unsigned_long_long_listHelper { + private static String _id = + "IDL:org/apache/tuscany/sca/binding/corba/testing/generated/unsigned_long_long_list:1.0"; + + public static void insert(org.omg.CORBA.Any a, long[] that) { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream(); + a.type(type()); + write(out, that); + a.read_value(out.create_input_stream(), type()); + } + + public static long[] extract(org.omg.CORBA.Any a) { + return read(a.create_input_stream()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + + synchronized public static org.omg.CORBA.TypeCode type() { + if (__typeCode == null) { + __typeCode = org.omg.CORBA.ORB.init().get_primitive_tc(org.omg.CORBA.TCKind.tk_ulonglong); + __typeCode = org.omg.CORBA.ORB.init().create_sequence_tc(0, __typeCode); + __typeCode = + org.omg.CORBA.ORB + .init() + .create_alias_tc(org.apache.tuscany.sca.binding.corba.testing.generated.unsigned_long_long_listHelper + .id(), + "unsigned_long_long_list", + __typeCode); + } + return __typeCode; + } + + public static String id() { + return _id; + } + + public static long[] read(org.omg.CORBA.portable.InputStream istream) { + long value[] = null; + int _len0 = istream.read_long(); + value = new long[_len0]; + istream.read_ulonglong_array(value, 0, _len0); + return value; + } + + public static void write(org.omg.CORBA.portable.OutputStream ostream, long[] value) { + ostream.write_long(value.length); + ostream.write_ulonglong_array(value, 0, value.length); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/unsigned_long_long_listHolder.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/unsigned_long_long_listHolder.java new file mode 100644 index 0000000000..59bc015c38 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/unsigned_long_long_listHolder.java @@ -0,0 +1,51 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/unsigned_long_long_listHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 2008 14:12:28 CEST +*/ + +public final class unsigned_long_long_listHolder implements org.omg.CORBA.portable.Streamable { + public long value[] = null; + + public unsigned_long_long_listHolder() { + } + + public unsigned_long_long_listHolder(long[] initialValue) { + value = initialValue; + } + + public void _read(org.omg.CORBA.portable.InputStream i) { + value = org.apache.tuscany.sca.binding.corba.testing.generated.unsigned_long_long_listHelper.read(i); + } + + public void _write(org.omg.CORBA.portable.OutputStream o) { + org.apache.tuscany.sca.binding.corba.testing.generated.unsigned_long_long_listHelper.write(o, value); + } + + public org.omg.CORBA.TypeCode _type() { + return org.apache.tuscany.sca.binding.corba.testing.generated.unsigned_long_long_listHelper.type(); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/unsigned_short_listHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/unsigned_short_listHelper.java new file mode 100644 index 0000000000..ec4526cebf --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/unsigned_short_listHelper.java @@ -0,0 +1,76 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/unsigned_short_listHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 2008 14:12:28 CEST +*/ + +abstract public class unsigned_short_listHelper { + private static String _id = "IDL:org/apache/tuscany/sca/binding/corba/testing/generated/unsigned_short_list:1.0"; + + public static void insert(org.omg.CORBA.Any a, short[] that) { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream(); + a.type(type()); + write(out, that); + a.read_value(out.create_input_stream(), type()); + } + + public static short[] extract(org.omg.CORBA.Any a) { + return read(a.create_input_stream()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + + synchronized public static org.omg.CORBA.TypeCode type() { + if (__typeCode == null) { + __typeCode = org.omg.CORBA.ORB.init().get_primitive_tc(org.omg.CORBA.TCKind.tk_ushort); + __typeCode = org.omg.CORBA.ORB.init().create_sequence_tc(0, __typeCode); + __typeCode = + org.omg.CORBA.ORB.init() + .create_alias_tc(org.apache.tuscany.sca.binding.corba.testing.generated.unsigned_short_listHelper + .id(), + "unsigned_short_list", + __typeCode); + } + return __typeCode; + } + + public static String id() { + return _id; + } + + public static short[] read(org.omg.CORBA.portable.InputStream istream) { + short value[] = null; + int _len0 = istream.read_long(); + value = new short[_len0]; + istream.read_ushort_array(value, 0, _len0); + return value; + } + + public static void write(org.omg.CORBA.portable.OutputStream ostream, short[] value) { + ostream.write_long(value.length); + ostream.write_ushort_array(value, 0, value.length); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/unsigned_short_listHolder.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/unsigned_short_listHolder.java new file mode 100644 index 0000000000..56ab28f0be --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/unsigned_short_listHolder.java @@ -0,0 +1,51 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/unsigned_short_listHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 2008 14:12:28 CEST +*/ + +public final class unsigned_short_listHolder implements org.omg.CORBA.portable.Streamable { + public short value[] = null; + + public unsigned_short_listHolder() { + } + + public unsigned_short_listHolder(short[] initialValue) { + value = initialValue; + } + + public void _read(org.omg.CORBA.portable.InputStream i) { + value = org.apache.tuscany.sca.binding.corba.testing.generated.unsigned_short_listHelper.read(i); + } + + public void _write(org.omg.CORBA.portable.OutputStream o) { + org.apache.tuscany.sca.binding.corba.testing.generated.unsigned_short_listHelper.write(o, value); + } + + public org.omg.CORBA.TypeCode _type() { + return org.apache.tuscany.sca.binding.corba.testing.generated.unsigned_short_listHelper.type(); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/wchar_listHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/wchar_listHelper.java new file mode 100644 index 0000000000..73a10d3b7f --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/wchar_listHelper.java @@ -0,0 +1,75 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/wchar_listHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 2008 14:12:28 CEST +*/ + +abstract public class wchar_listHelper { + private static String _id = "IDL:org/apache/tuscany/sca/binding/corba/testing/generated/wchar_list:1.0"; + + public static void insert(org.omg.CORBA.Any a, char[] that) { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream(); + a.type(type()); + write(out, that); + a.read_value(out.create_input_stream(), type()); + } + + public static char[] extract(org.omg.CORBA.Any a) { + return read(a.create_input_stream()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + + synchronized public static org.omg.CORBA.TypeCode type() { + if (__typeCode == null) { + __typeCode = org.omg.CORBA.ORB.init().get_primitive_tc(org.omg.CORBA.TCKind.tk_wchar); + __typeCode = org.omg.CORBA.ORB.init().create_sequence_tc(0, __typeCode); + __typeCode = + org.omg.CORBA.ORB.init() + .create_alias_tc(org.apache.tuscany.sca.binding.corba.testing.generated.wchar_listHelper.id(), + "wchar_list", + __typeCode); + } + return __typeCode; + } + + public static String id() { + return _id; + } + + public static char[] read(org.omg.CORBA.portable.InputStream istream) { + char value[] = null; + int _len0 = istream.read_long(); + value = new char[_len0]; + istream.read_wchar_array(value, 0, _len0); + return value; + } + + public static void write(org.omg.CORBA.portable.OutputStream ostream, char[] value) { + ostream.write_long(value.length); + ostream.write_wchar_array(value, 0, value.length); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/wchar_listHolder.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/wchar_listHolder.java new file mode 100644 index 0000000000..c5c1e87756 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/wchar_listHolder.java @@ -0,0 +1,51 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/wchar_listHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 2008 14:12:28 CEST +*/ + +public final class wchar_listHolder implements org.omg.CORBA.portable.Streamable { + public char value[] = null; + + public wchar_listHolder() { + } + + public wchar_listHolder(char[] initialValue) { + value = initialValue; + } + + public void _read(org.omg.CORBA.portable.InputStream i) { + value = org.apache.tuscany.sca.binding.corba.testing.generated.wchar_listHelper.read(i); + } + + public void _write(org.omg.CORBA.portable.OutputStream o) { + org.apache.tuscany.sca.binding.corba.testing.generated.wchar_listHelper.write(o, value); + } + + public org.omg.CORBA.TypeCode _type() { + return org.apache.tuscany.sca.binding.corba.testing.generated.wchar_listHelper.type(); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/wstring_listHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/wstring_listHelper.java new file mode 100644 index 0000000000..3e45568f01 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/wstring_listHelper.java @@ -0,0 +1,77 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/wstring_listHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 2008 14:12:28 CEST +*/ + +abstract public class wstring_listHelper { + private static String _id = "IDL:org/apache/tuscany/sca/binding/corba/testing/generated/wstring_list:1.0"; + + public static void insert(org.omg.CORBA.Any a, String[] that) { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream(); + a.type(type()); + write(out, that); + a.read_value(out.create_input_stream(), type()); + } + + public static String[] extract(org.omg.CORBA.Any a) { + return read(a.create_input_stream()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + + synchronized public static org.omg.CORBA.TypeCode type() { + if (__typeCode == null) { + __typeCode = org.omg.CORBA.ORB.init().create_wstring_tc(0); + __typeCode = org.omg.CORBA.ORB.init().create_sequence_tc(0, __typeCode); + __typeCode = + org.omg.CORBA.ORB.init() + .create_alias_tc(org.apache.tuscany.sca.binding.corba.testing.generated.wstring_listHelper.id(), + "wstring_list", + __typeCode); + } + return __typeCode; + } + + public static String id() { + return _id; + } + + public static String[] read(org.omg.CORBA.portable.InputStream istream) { + String value[] = null; + int _len0 = istream.read_long(); + value = new String[_len0]; + for (int _o1 = 0; _o1 < value.length; ++_o1) + value[_o1] = istream.read_wstring(); + return value; + } + + public static void write(org.omg.CORBA.portable.OutputStream ostream, String[] value) { + ostream.write_long(value.length); + for (int _i0 = 0; _i0 < value.length; ++_i0) + ostream.write_wstring(value[_i0]); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/wstring_listHolder.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/wstring_listHolder.java new file mode 100644 index 0000000000..bdbf9d995b --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/generated/wstring_listHolder.java @@ -0,0 +1,51 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.generated; + +/** +* org/apache/tuscany/sca/binding/corba/testing/generated/wstring_listHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* monday, 23 june 2008 2008 14:12:28 CEST +*/ + +public final class wstring_listHolder implements org.omg.CORBA.portable.Streamable { + public String value[] = null; + + public wstring_listHolder() { + } + + public wstring_listHolder(String[] initialValue) { + value = initialValue; + } + + public void _read(org.omg.CORBA.portable.InputStream i) { + value = org.apache.tuscany.sca.binding.corba.testing.generated.wstring_listHelper.read(i); + } + + public void _write(org.omg.CORBA.portable.OutputStream o) { + org.apache.tuscany.sca.binding.corba.testing.generated.wstring_listHelper.write(o, value); + } + + public org.omg.CORBA.TypeCode _type() { + return org.apache.tuscany.sca.binding.corba.testing.generated.wstring_listHelper.type(); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/ArraysTestStruct.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/ArraysTestStruct.java new file mode 100644 index 0000000000..ba1a5c0a51 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/ArraysTestStruct.java @@ -0,0 +1,45 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.hierarchy; + +import org.apache.tuscany.sca.binding.corba.provider.meta.CorbaArray; + +public final class ArraysTestStruct { + + public ArraysTestStruct() { + + } + + public ArraysTestStruct(String[] field1, int[][] field2, float[][][] field3) { + this.field1 = field1; + this.field2 = field2; + this.field3 = field3; + } + + @CorbaArray( {2}) + public String[] field1; + + @CorbaArray( {2, 4}) + public int[][] field2; + + @CorbaArray( {2, 4, 2}) + public float[][][] field3; + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/Calc.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/Calc.java new file mode 100644 index 0000000000..7c33b1d449 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/Calc.java @@ -0,0 +1,30 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.hierarchy; + +import org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.DivByZero; + +public interface Calc { + + public double div(double arg1, double arg2) throws DivByZero; + + public double divForSmallArgs(double arg1, double arg2); + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/DummyObject.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/DummyObject.java new file mode 100644 index 0000000000..d0ebff5fec --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/DummyObject.java @@ -0,0 +1,28 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.hierarchy; + +public interface DummyObject { + + int getLong(); + + DummyObject cloneObject(); + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InnerUnion.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InnerUnion.java new file mode 100644 index 0000000000..6e4204b9b7 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InnerUnion.java @@ -0,0 +1,55 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.hierarchy; + +import org.apache.tuscany.sca.binding.corba.provider.meta.CorbaUnionElement; +import org.apache.tuscany.sca.binding.corba.provider.meta.CorbaUnionElementType; + +public final class InnerUnion { + + @CorbaUnionElement(type = CorbaUnionElementType.option, optionNumber = 1) + private int x; + + @CorbaUnionElement(type = CorbaUnionElementType.option, optionNumber = 2) + private float y; + + @CorbaUnionElement(type = CorbaUnionElementType.discriminator) + @SuppressWarnings("unused") + private int discriminator; + + public int getX() { + return x; + } + + public void setX(int x) { + discriminator = 1; + this.x = x; + } + + public float getY() { + return y; + } + + public void setY(float y) { + discriminator = 2; + this.y = y; + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidCorbaArray.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidCorbaArray.java new file mode 100644 index 0000000000..cb3b6842c3 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidCorbaArray.java @@ -0,0 +1,38 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.hierarchy; + +import org.apache.tuscany.sca.binding.corba.provider.meta.CorbaArray; + +public final class InvalidCorbaArray { + + // annotation argument array is not equal to declared arrays dimension + @CorbaArray( {1}) + public String[][] array; + + public InvalidCorbaArray() { + + } + + public InvalidCorbaArray(String[][] arg) { + + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidEnum1.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidEnum1.java new file mode 100644 index 0000000000..0c9de5bb31 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidEnum1.java @@ -0,0 +1,36 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.hierarchy; + +public class InvalidEnum1 { + + public static final InvalidEnum1 red = new InvalidEnum1(0); + + public int value() { + return 0; + } + + public static InvalidEnum1 from_int(int value) { + return null; + } + + protected InvalidEnum1(int value) { + } +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidEnum2.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidEnum2.java new file mode 100644 index 0000000000..8746eb7f9b --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidEnum2.java @@ -0,0 +1,33 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.hierarchy; + +public class InvalidEnum2 { + + public static final int _red = 0; + public static final InvalidEnum2 red = new InvalidEnum2(_red); + + public static InvalidEnum2 from_int(int value) { + return null; + } + + protected InvalidEnum2(int value) { + } +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidEnum3.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidEnum3.java new file mode 100644 index 0000000000..6d124b0485 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidEnum3.java @@ -0,0 +1,33 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.hierarchy; + +public class InvalidEnum3 { + + public static final int _red = 0; + public static final InvalidEnum2 red = new InvalidEnum2(_red); + + public int value() { + return 0; + } + + protected InvalidEnum3(int value) { + } +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidStruct1.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidStruct1.java new file mode 100644 index 0000000000..8cf66e2fac --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidStruct1.java @@ -0,0 +1,28 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.hierarchy; + +public final class InvalidStruct1 { + + public InvalidStruct1() { + + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidStruct2.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidStruct2.java new file mode 100644 index 0000000000..5f361512f0 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidStruct2.java @@ -0,0 +1,31 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.hierarchy; + +public final class InvalidStruct2 { + + public int f1; + public String f2; + + public InvalidStruct2(int f1, String f2) { + + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidStruct3.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidStruct3.java new file mode 100644 index 0000000000..adc81ea5a2 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidStruct3.java @@ -0,0 +1,36 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.hierarchy; + +public final class InvalidStruct3 { + + public int f1; + public String f2; + public static byte f3; + + public InvalidStruct3() { + + } + + public InvalidStruct3(int f1, String f2, byte f3) { + + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidUnion1.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidUnion1.java new file mode 100644 index 0000000000..4f6d0085af --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidUnion1.java @@ -0,0 +1,37 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.hierarchy; + +import org.apache.tuscany.sca.binding.corba.provider.meta.CorbaUnionElement; +import org.apache.tuscany.sca.binding.corba.provider.meta.CorbaUnionElementType; + +/** + * More than one discriminators + */ +public final class InvalidUnion1 { + + @CorbaUnionElement(type = CorbaUnionElementType.discriminator) + @SuppressWarnings("unused") + private int a; + @CorbaUnionElement(type = CorbaUnionElementType.discriminator) + @SuppressWarnings("unused") + private int b; + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidUnion2.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidUnion2.java new file mode 100644 index 0000000000..98462bbabe --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidUnion2.java @@ -0,0 +1,34 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.hierarchy; + +import org.apache.tuscany.sca.binding.corba.provider.meta.CorbaUnionElement; +import org.apache.tuscany.sca.binding.corba.provider.meta.CorbaUnionElementType; + +/** + * Discriminator is missing + */ +public final class InvalidUnion2 { + + @CorbaUnionElement(type=CorbaUnionElementType.defaultOption) + @SuppressWarnings("unused") + private int a; + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidUnion3.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidUnion3.java new file mode 100644 index 0000000000..994ed6aea3 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidUnion3.java @@ -0,0 +1,35 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.hierarchy; + +import org.apache.tuscany.sca.binding.corba.provider.meta.CorbaUnionElement; +import org.apache.tuscany.sca.binding.corba.provider.meta.CorbaUnionElementType; + +/** + * No option, only discriminator + */ +public final class InvalidUnion3{ + + @CorbaUnionElement(type = CorbaUnionElementType.discriminator) + @SuppressWarnings("unused") + private int a; + +} + diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidUnion4.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidUnion4.java new file mode 100644 index 0000000000..d68d903375 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidUnion4.java @@ -0,0 +1,39 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.hierarchy; + +import org.apache.tuscany.sca.binding.corba.provider.meta.CorbaUnionElement; +import org.apache.tuscany.sca.binding.corba.provider.meta.CorbaUnionElementType; + +/** + * Invalid field modifiers + */ +public final class InvalidUnion4{ + + @CorbaUnionElement(type = CorbaUnionElementType.discriminator) + @SuppressWarnings("unused") + private static int a; + + @CorbaUnionElement(type = CorbaUnionElementType.defaultOption) + @SuppressWarnings("unused") + private static int b; + +} + diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidUnion5.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidUnion5.java new file mode 100644 index 0000000000..d4f8b0e6fa --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/InvalidUnion5.java @@ -0,0 +1,42 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.hierarchy; + +import org.apache.tuscany.sca.binding.corba.provider.meta.CorbaUnionElement; +import org.apache.tuscany.sca.binding.corba.provider.meta.CorbaUnionElementType; + +/** + * Reused option id + */ +public final class InvalidUnion5 { + + @CorbaUnionElement(type = CorbaUnionElementType.discriminator) + @SuppressWarnings("unused") + private int a; + + @CorbaUnionElement(type = CorbaUnionElementType.option, optionNumber = 1) + @SuppressWarnings("unused") + private int b; + + @CorbaUnionElement(type = CorbaUnionElementType.option, optionNumber = 1) + @SuppressWarnings("unused") + private int c; + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/NonCorbaException.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/NonCorbaException.java new file mode 100644 index 0000000000..a514b5e222 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/NonCorbaException.java @@ -0,0 +1,28 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.hierarchy; + +public class NonCorbaException extends Exception { + + private static final long serialVersionUID = 1L; + + public String someField; + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/RichUnion.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/RichUnion.java new file mode 100644 index 0000000000..452dee8d95 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/RichUnion.java @@ -0,0 +1,91 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.hierarchy; + +import org.apache.tuscany.sca.binding.corba.provider.meta.CorbaUnionElement; +import org.apache.tuscany.sca.binding.corba.provider.meta.CorbaUnionElementType; + +public final class RichUnion { + + @CorbaUnionElement(type = CorbaUnionElementType.option, optionNumber = 1) + private int x; + + @CorbaUnionElement(type = CorbaUnionElementType.option, optionNumber = 2) + private float y; + + @CorbaUnionElement(type = CorbaUnionElementType.option, optionNumber = 3) + private String z; + + @CorbaUnionElement(type = CorbaUnionElementType.option, optionNumber = 4) + private InnerUnion iu; + + @CorbaUnionElement(type = CorbaUnionElementType.defaultOption) + private boolean def; + + @CorbaUnionElement(type = CorbaUnionElementType.discriminator) + @SuppressWarnings("unused") + private int discriminator = -1; + + public int getX() { + return x; + } + + public void setX(int x) { + this.discriminator = 1; + this.x = x; + } + + public float getY() { + return y; + } + + public void setY(float y) { + this.discriminator = 2; + this.y = y; + } + + public String getZ() { + return z; + } + + public void setZ(String z) { + this.discriminator = 3; + this.z = z; + } + + public boolean isDef() { + return def; + } + + public void setDef(boolean def) { + this.discriminator = -1; + this.def = def; + } + + public InnerUnion getIu() { + return iu; + } + + public void setIu(InnerUnion iu) { + this.discriminator = 4; + this.iu = iu; + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/SimpleStruct.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/SimpleStruct.java new file mode 100644 index 0000000000..85ca3798f4 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/SimpleStruct.java @@ -0,0 +1,30 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.hierarchy; + +/** + * @version $Rev$ $Date$ + */ +public class SimpleStruct { + + public String field1; + public int field2; + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/SomeStruct.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/SomeStruct.java new file mode 100644 index 0000000000..d8cdf1835a --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/hierarchy/SomeStruct.java @@ -0,0 +1,33 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.hierarchy; + +/** + * @version $Rev$ $Date$ + */ +public class SomeStruct { + + public SimpleStruct innerStruct; + public String str; + public String[] str_list; + public int[][] twoDimSeq; + public int[][][] threeDimSeq; + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/DummyObject.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/DummyObject.java new file mode 100644 index 0000000000..bb72fdbbf3 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/DummyObject.java @@ -0,0 +1,30 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.references; + +/** +* org/apache/tuscany/sca/binding/corba/testing/references/DummyObject.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from remote_objects.idl +* niedziela, 8 czerwiec 2008 16:43:12 CEST +*/ + +public interface DummyObject extends DummyObjectOperations, org.omg.CORBA.Object, org.omg.CORBA.portable.IDLEntity { +} // interface DummyObject diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/DummyObjectHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/DummyObjectHelper.java new file mode 100644 index 0000000000..606d333bb3 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/DummyObjectHelper.java @@ -0,0 +1,100 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.references; + +/** +* org/apache/tuscany/sca/binding/corba/testing/references/DummyObjectHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from remote_objects.idl +* niedziela, 8 czerwiec 2008 16:43:12 CEST +*/ + +abstract public class DummyObjectHelper { + private static String _id = "IDL:org/apache/tuscany/sca/binding/corba/testing/references/DummyObject:1.0"; + + public static void insert(org.omg.CORBA.Any a, + org.apache.tuscany.sca.binding.corba.testing.references.DummyObject that) { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream(); + a.type(type()); + write(out, that); + a.read_value(out.create_input_stream(), type()); + } + + public static org.apache.tuscany.sca.binding.corba.testing.references.DummyObject extract(org.omg.CORBA.Any a) { + return read(a.create_input_stream()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + + synchronized public static org.omg.CORBA.TypeCode type() { + if (__typeCode == null) { + __typeCode = + org.omg.CORBA.ORB + .init() + .create_interface_tc(org.apache.tuscany.sca.binding.corba.testing.references.DummyObjectHelper.id(), + "DummyObject"); + } + return __typeCode; + } + + public static String id() { + return _id; + } + + public static org.apache.tuscany.sca.binding.corba.testing.references.DummyObject read(org.omg.CORBA.portable.InputStream istream) { + return narrow(istream.read_Object(_DummyObjectStub.class)); + } + + public static void write(org.omg.CORBA.portable.OutputStream ostream, + org.apache.tuscany.sca.binding.corba.testing.references.DummyObject value) { + ostream.write_Object((org.omg.CORBA.Object)value); + } + + public static org.apache.tuscany.sca.binding.corba.testing.references.DummyObject narrow(org.omg.CORBA.Object obj) { + if (obj == null) + return null; + else if (obj instanceof org.apache.tuscany.sca.binding.corba.testing.references.DummyObject) + return (org.apache.tuscany.sca.binding.corba.testing.references.DummyObject)obj; + else if (!obj._is_a(id())) + throw new org.omg.CORBA.BAD_PARAM(); + else { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate(); + org.apache.tuscany.sca.binding.corba.testing.references._DummyObjectStub stub = + new org.apache.tuscany.sca.binding.corba.testing.references._DummyObjectStub(); + stub._set_delegate(delegate); + return stub; + } + } + + public static org.apache.tuscany.sca.binding.corba.testing.references.DummyObject unchecked_narrow(org.omg.CORBA.Object obj) { + if (obj == null) + return null; + else if (obj instanceof org.apache.tuscany.sca.binding.corba.testing.references.DummyObject) + return (org.apache.tuscany.sca.binding.corba.testing.references.DummyObject)obj; + else { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate(); + org.apache.tuscany.sca.binding.corba.testing.references._DummyObjectStub stub = + new org.apache.tuscany.sca.binding.corba.testing.references._DummyObjectStub(); + stub._set_delegate(delegate); + return stub; + } + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/DummyObjectHolder.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/DummyObjectHolder.java new file mode 100644 index 0000000000..0ff9540502 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/DummyObjectHolder.java @@ -0,0 +1,51 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.references; + +/** +* org/apache/tuscany/sca/binding/corba/testing/references/DummyObjectHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from remote_objects.idl +* niedziela, 8 czerwiec 2008 16:43:12 CEST +*/ + +public final class DummyObjectHolder implements org.omg.CORBA.portable.Streamable { + public org.apache.tuscany.sca.binding.corba.testing.references.DummyObject value = null; + + public DummyObjectHolder() { + } + + public DummyObjectHolder(org.apache.tuscany.sca.binding.corba.testing.references.DummyObject initialValue) { + value = initialValue; + } + + public void _read(org.omg.CORBA.portable.InputStream i) { + value = org.apache.tuscany.sca.binding.corba.testing.references.DummyObjectHelper.read(i); + } + + public void _write(org.omg.CORBA.portable.OutputStream o) { + org.apache.tuscany.sca.binding.corba.testing.references.DummyObjectHelper.write(o, value); + } + + public org.omg.CORBA.TypeCode _type() { + return org.apache.tuscany.sca.binding.corba.testing.references.DummyObjectHelper.type(); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/DummyObjectOperations.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/DummyObjectOperations.java new file mode 100644 index 0000000000..912bd16f9b --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/DummyObjectOperations.java @@ -0,0 +1,33 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.references; + +/** +* org/apache/tuscany/sca/binding/corba/testing/references/DummyObjectOperations.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from remote_objects.idl +* niedziela, 8 czerwiec 2008 16:43:12 CEST +*/ + +public interface DummyObjectOperations { + int getLong(); + + org.apache.tuscany.sca.binding.corba.testing.references.DummyObject cloneObject(); +} // interface DummyObjectOperations diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/ObjectManager.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/ObjectManager.java new file mode 100644 index 0000000000..79f7959c72 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/ObjectManager.java @@ -0,0 +1,30 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.references; + +/** +* org/apache/tuscany/sca/binding/corba/testing/references/ObjectManager.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from remote_objects.idl +* niedziela, 8 czerwiec 2008 16:43:12 CEST +*/ + +public interface ObjectManager extends ObjectManagerOperations, org.omg.CORBA.Object, org.omg.CORBA.portable.IDLEntity { +} // interface ObjectManager diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/ObjectManagerHelper.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/ObjectManagerHelper.java new file mode 100644 index 0000000000..495a614d84 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/ObjectManagerHelper.java @@ -0,0 +1,100 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.references; + +/** +* org/apache/tuscany/sca/binding/corba/testing/references/ObjectManagerHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from remote_objects.idl +* niedziela, 8 czerwiec 2008 16:43:12 CEST +*/ + +abstract public class ObjectManagerHelper { + private static String _id = "IDL:org/apache/tuscany/sca/binding/corba/testing/references/ObjectManager:1.0"; + + public static void insert(org.omg.CORBA.Any a, + org.apache.tuscany.sca.binding.corba.testing.references.ObjectManager that) { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream(); + a.type(type()); + write(out, that); + a.read_value(out.create_input_stream(), type()); + } + + public static org.apache.tuscany.sca.binding.corba.testing.references.ObjectManager extract(org.omg.CORBA.Any a) { + return read(a.create_input_stream()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + + synchronized public static org.omg.CORBA.TypeCode type() { + if (__typeCode == null) { + __typeCode = + org.omg.CORBA.ORB.init() + .create_interface_tc(org.apache.tuscany.sca.binding.corba.testing.references.ObjectManagerHelper + .id(), + "ObjectManager"); + } + return __typeCode; + } + + public static String id() { + return _id; + } + + public static org.apache.tuscany.sca.binding.corba.testing.references.ObjectManager read(org.omg.CORBA.portable.InputStream istream) { + return narrow(istream.read_Object(_ObjectManagerStub.class)); + } + + public static void write(org.omg.CORBA.portable.OutputStream ostream, + org.apache.tuscany.sca.binding.corba.testing.references.ObjectManager value) { + ostream.write_Object((org.omg.CORBA.Object)value); + } + + public static org.apache.tuscany.sca.binding.corba.testing.references.ObjectManager narrow(org.omg.CORBA.Object obj) { + if (obj == null) + return null; + else if (obj instanceof org.apache.tuscany.sca.binding.corba.testing.references.ObjectManager) + return (org.apache.tuscany.sca.binding.corba.testing.references.ObjectManager)obj; + else if (!obj._is_a(id())) + throw new org.omg.CORBA.BAD_PARAM(); + else { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate(); + org.apache.tuscany.sca.binding.corba.testing.references._ObjectManagerStub stub = + new org.apache.tuscany.sca.binding.corba.testing.references._ObjectManagerStub(); + stub._set_delegate(delegate); + return stub; + } + } + + public static org.apache.tuscany.sca.binding.corba.testing.references.ObjectManager unchecked_narrow(org.omg.CORBA.Object obj) { + if (obj == null) + return null; + else if (obj instanceof org.apache.tuscany.sca.binding.corba.testing.references.ObjectManager) + return (org.apache.tuscany.sca.binding.corba.testing.references.ObjectManager)obj; + else { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate(); + org.apache.tuscany.sca.binding.corba.testing.references._ObjectManagerStub stub = + new org.apache.tuscany.sca.binding.corba.testing.references._ObjectManagerStub(); + stub._set_delegate(delegate); + return stub; + } + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/ObjectManagerHolder.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/ObjectManagerHolder.java new file mode 100644 index 0000000000..11cfc82ac2 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/ObjectManagerHolder.java @@ -0,0 +1,51 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.references; + +/** +* org/apache/tuscany/sca/binding/corba/testing/references/ObjectManagerHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from remote_objects.idl +* niedziela, 8 czerwiec 2008 16:43:12 CEST +*/ + +public final class ObjectManagerHolder implements org.omg.CORBA.portable.Streamable { + public org.apache.tuscany.sca.binding.corba.testing.references.ObjectManager value = null; + + public ObjectManagerHolder() { + } + + public ObjectManagerHolder(org.apache.tuscany.sca.binding.corba.testing.references.ObjectManager initialValue) { + value = initialValue; + } + + public void _read(org.omg.CORBA.portable.InputStream i) { + value = org.apache.tuscany.sca.binding.corba.testing.references.ObjectManagerHelper.read(i); + } + + public void _write(org.omg.CORBA.portable.OutputStream o) { + org.apache.tuscany.sca.binding.corba.testing.references.ObjectManagerHelper.write(o, value); + } + + public org.omg.CORBA.TypeCode _type() { + return org.apache.tuscany.sca.binding.corba.testing.references.ObjectManagerHelper.type(); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/ObjectManagerOperations.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/ObjectManagerOperations.java new file mode 100644 index 0000000000..e0e56d1017 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/ObjectManagerOperations.java @@ -0,0 +1,33 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.references; + +/** +* org/apache/tuscany/sca/binding/corba/testing/references/ObjectManagerOperations.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from remote_objects.idl +* niedziela, 8 czerwiec 2008 16:43:12 CEST +*/ + +public interface ObjectManagerOperations { + org.apache.tuscany.sca.binding.corba.testing.references.DummyObject getDummyObject(); + + org.apache.tuscany.sca.binding.corba.testing.references.DummyObject getObjectByArgument(org.apache.tuscany.sca.binding.corba.testing.references.DummyObject dummy); +} // interface ObjectManagerOperations diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/_DummyObjectImplBase.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/_DummyObjectImplBase.java new file mode 100644 index 0000000000..c706661eaa --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/_DummyObjectImplBase.java @@ -0,0 +1,84 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.references; + +/** +* org/apache/tuscany/sca/binding/corba/testing/references/_DummyObjectImplBase.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from remote_objects.idl +* niedziela, 8 czerwiec 2008 16:43:12 CEST +*/ + +public abstract class _DummyObjectImplBase extends org.omg.CORBA.portable.ObjectImpl implements + org.apache.tuscany.sca.binding.corba.testing.references.DummyObject, org.omg.CORBA.portable.InvokeHandler { + + // Constructors + public _DummyObjectImplBase() { + } + + private static java.util.Hashtable _methods = new java.util.Hashtable(); + static { + _methods.put("getLong", new java.lang.Integer(0)); + _methods.put("cloneObject", new java.lang.Integer(1)); + } + + public org.omg.CORBA.portable.OutputStream _invoke(String $method, + org.omg.CORBA.portable.InputStream in, + org.omg.CORBA.portable.ResponseHandler $rh) { + org.omg.CORBA.portable.OutputStream out = null; + java.lang.Integer __method = (java.lang.Integer)_methods.get($method); + if (__method == null) + throw new org.omg.CORBA.BAD_OPERATION(0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE); + + switch (__method.intValue()) { + case 0: // org/apache/tuscany/sca/binding/corba/testing/references/DummyObject/getLong + { + int $result = (int)0; + $result = this.getLong(); + out = $rh.createReply(); + out.write_long($result); + break; + } + + case 1: // org/apache/tuscany/sca/binding/corba/testing/references/DummyObject/cloneObject + { + org.apache.tuscany.sca.binding.corba.testing.references.DummyObject $result = null; + $result = this.cloneObject(); + out = $rh.createReply(); + org.apache.tuscany.sca.binding.corba.testing.references.DummyObjectHelper.write(out, $result); + break; + } + + default: + throw new org.omg.CORBA.BAD_OPERATION(0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE); + } + + return out; + } // _invoke + + // Type-specific CORBA::Object operations + private static String[] __ids = {"IDL:org/apache/tuscany/sca/binding/corba/testing/references/DummyObject:1.0"}; + + @Override + public String[] _ids() { + return (String[])__ids.clone(); + } + +} // class _DummyObjectImplBase diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/_DummyObjectStub.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/_DummyObjectStub.java new file mode 100644 index 0000000000..c9a31deb27 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/_DummyObjectStub.java @@ -0,0 +1,92 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.references; + +/** +* org/apache/tuscany/sca/binding/corba/testing/references/_DummyObjectStub.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from remote_objects.idl +* niedziela, 8 czerwiec 2008 16:43:12 CEST +*/ + +public class _DummyObjectStub extends org.omg.CORBA.portable.ObjectImpl implements + org.apache.tuscany.sca.binding.corba.testing.references.DummyObject { + + public int getLong() { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("getLong", true); + $in = _invoke($out); + int $result = $in.read_long(); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return getLong(); + } finally { + _releaseReply($in); + } + } // getLong + + public org.apache.tuscany.sca.binding.corba.testing.references.DummyObject cloneObject() { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("cloneObject", true); + $in = _invoke($out); + org.apache.tuscany.sca.binding.corba.testing.references.DummyObject $result = + org.apache.tuscany.sca.binding.corba.testing.references.DummyObjectHelper.read($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return cloneObject(); + } finally { + _releaseReply($in); + } + } // cloneObject + + // Type-specific CORBA::Object operations + private static String[] __ids = {"IDL:org/apache/tuscany/sca/binding/corba/testing/references/DummyObject:1.0"}; + + @Override + public String[] _ids() { + return (String[])__ids.clone(); + } + + private void readObject(java.io.ObjectInputStream s) throws java.io.IOException { + String str = s.readUTF(); + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.Object obj = org.omg.CORBA.ORB.init(args, props).string_to_object(str); + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate(); + _set_delegate(delegate); + } + + private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { + String[] args = null; + java.util.Properties props = null; + String str = org.omg.CORBA.ORB.init(args, props).object_to_string(this); + s.writeUTF(str); + } +} // class _DummyObjectStub diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/_ObjectManagerImplBase.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/_ObjectManagerImplBase.java new file mode 100644 index 0000000000..a6b55b8bae --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/_ObjectManagerImplBase.java @@ -0,0 +1,86 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.references; + +/** +* org/apache/tuscany/sca/binding/corba/testing/references/_ObjectManagerImplBase.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from remote_objects.idl +* niedziela, 8 czerwiec 2008 16:43:12 CEST +*/ + +public abstract class _ObjectManagerImplBase extends org.omg.CORBA.portable.ObjectImpl implements + org.apache.tuscany.sca.binding.corba.testing.references.ObjectManager, org.omg.CORBA.portable.InvokeHandler { + + // Constructors + public _ObjectManagerImplBase() { + } + + private static java.util.Hashtable _methods = new java.util.Hashtable(); + static { + _methods.put("getDummyObject", new java.lang.Integer(0)); + _methods.put("getObjectByArgument", new java.lang.Integer(1)); + } + + public org.omg.CORBA.portable.OutputStream _invoke(String $method, + org.omg.CORBA.portable.InputStream in, + org.omg.CORBA.portable.ResponseHandler $rh) { + org.omg.CORBA.portable.OutputStream out = null; + java.lang.Integer __method = (java.lang.Integer)_methods.get($method); + if (__method == null) + throw new org.omg.CORBA.BAD_OPERATION(0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE); + + switch (__method.intValue()) { + case 0: // org/apache/tuscany/sca/binding/corba/testing/references/ObjectManager/getDummyObject + { + org.apache.tuscany.sca.binding.corba.testing.references.DummyObject $result = null; + $result = this.getDummyObject(); + out = $rh.createReply(); + org.apache.tuscany.sca.binding.corba.testing.references.DummyObjectHelper.write(out, $result); + break; + } + + case 1: // org/apache/tuscany/sca/binding/corba/testing/references/ObjectManager/getObjectByArgument + { + org.apache.tuscany.sca.binding.corba.testing.references.DummyObject dummy = + org.apache.tuscany.sca.binding.corba.testing.references.DummyObjectHelper.read(in); + org.apache.tuscany.sca.binding.corba.testing.references.DummyObject $result = null; + $result = this.getObjectByArgument(dummy); + out = $rh.createReply(); + org.apache.tuscany.sca.binding.corba.testing.references.DummyObjectHelper.write(out, $result); + break; + } + + default: + throw new org.omg.CORBA.BAD_OPERATION(0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE); + } + + return out; + } // _invoke + + // Type-specific CORBA::Object operations + private static String[] __ids = {"IDL:org/apache/tuscany/sca/binding/corba/testing/references/ObjectManager:1.0"}; + + @Override + public String[] _ids() { + return (String[])__ids.clone(); + } + +} // class _ObjectManagerImplBase diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/_ObjectManagerStub.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/_ObjectManagerStub.java new file mode 100644 index 0000000000..e06a078a93 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/references/_ObjectManagerStub.java @@ -0,0 +1,94 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.references; + +/** +* org/apache/tuscany/sca/binding/corba/testing/references/_ObjectManagerStub.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from remote_objects.idl +* niedziela, 8 czerwiec 2008 16:43:12 CEST +*/ + +public class _ObjectManagerStub extends org.omg.CORBA.portable.ObjectImpl implements + org.apache.tuscany.sca.binding.corba.testing.references.ObjectManager { + + public org.apache.tuscany.sca.binding.corba.testing.references.DummyObject getDummyObject() { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("getDummyObject", true); + $in = _invoke($out); + org.apache.tuscany.sca.binding.corba.testing.references.DummyObject $result = + org.apache.tuscany.sca.binding.corba.testing.references.DummyObjectHelper.read($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return getDummyObject(); + } finally { + _releaseReply($in); + } + } // getDummyObject + + public org.apache.tuscany.sca.binding.corba.testing.references.DummyObject getObjectByArgument(org.apache.tuscany.sca.binding.corba.testing.references.DummyObject dummy) { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("getObjectByArgument", true); + org.apache.tuscany.sca.binding.corba.testing.references.DummyObjectHelper.write($out, dummy); + $in = _invoke($out); + org.apache.tuscany.sca.binding.corba.testing.references.DummyObject $result = + org.apache.tuscany.sca.binding.corba.testing.references.DummyObjectHelper.read($in); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return getObjectByArgument(dummy); + } finally { + _releaseReply($in); + } + } // getObjectByArgument + + // Type-specific CORBA::Object operations + private static String[] __ids = {"IDL:org/apache/tuscany/sca/binding/corba/testing/references/ObjectManager:1.0"}; + + @Override + public String[] _ids() { + return (String[])__ids.clone(); + } + + private void readObject(java.io.ObjectInputStream s) throws java.io.IOException { + String str = s.readUTF(); + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.Object obj = org.omg.CORBA.ORB.init(args, props).string_to_object(str); + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate(); + _set_delegate(delegate); + } + + private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { + String[] args = null; + java.util.Properties props = null; + String str = org.omg.CORBA.ORB.init(args, props).object_to_string(this); + s.writeUTF(str); + } +} // class _ObjectManagerStub diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/ArraysSetterServant.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/ArraysSetterServant.java new file mode 100644 index 0000000000..0aec4d278d --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/ArraysSetterServant.java @@ -0,0 +1,89 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.servants; + +import org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObject; +import org.apache.tuscany.sca.binding.corba.testing.generated._ArraysSetterImplBase; + +public class ArraysSetterServant extends _ArraysSetterImplBase { + + private static final long serialVersionUID = 1L; + + public boolean[] setBoolean(boolean[] arg) { + return arg; + } + + public char[] setChar(char[] arg) { + return arg; + } + + public double[] setDouble(double[] arg) { + return arg; + } + + public float[] setFloat(float[] arg) { + return arg; + } + + public int[] setLong(int[] arg) { + return arg; + } + + public long[] setLongLong(long[] arg) { + return arg; + } + + public byte[] setOctet(byte[] arg) { + return arg; + } + + public RemoteObject[] setRemoteObject(RemoteObject[] obj) { + return obj; + } + + public short[] setShort(short[] arg) { + return arg; + } + + public String[] setString(String[] arg) { + return arg; + } + + public int[] setUnsignedLong(int[] arg) { + return arg; + } + + public long[] setUnsignedLongLong(long[] arg) { + return arg; + } + + public short[] setUnsignedShort(short[] arg) { + return arg; + } + + public char[] setWchar(char[] arg) { + return arg; + } + + public String[] setWstring(String[] arg) { + return arg; + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/ArraysUnionsServant.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/ArraysUnionsServant.java new file mode 100644 index 0000000000..d9bde48a5a --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/ArraysUnionsServant.java @@ -0,0 +1,42 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.servants; + +import org.apache.tuscany.sca.binding.corba.testing.arrays_unions.RichUnion; +import org.apache.tuscany.sca.binding.corba.testing.arrays_unions.TestStruct; +import org.apache.tuscany.sca.binding.corba.testing.arrays_unions._ArraysUnionsTestsImplBase; + +public class ArraysUnionsServant extends _ArraysUnionsTestsImplBase { + + private static final long serialVersionUID = 1L; + + public TestStruct passTestStruct(TestStruct arg) { + return arg; + } + + public String[][] passStringArray(String[][] arg) { + return arg; + } + + public RichUnion passRichUnion(RichUnion arg) { + return arg; + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/ArraysUnionsTuscanyServant.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/ArraysUnionsTuscanyServant.java new file mode 100644 index 0000000000..9ff94f8313 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/ArraysUnionsTuscanyServant.java @@ -0,0 +1,43 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.servants; + +import org.apache.tuscany.sca.binding.corba.provider.meta.CorbaArray; +import org.apache.tuscany.sca.binding.corba.testing.hierarchy.ArraysTestStruct; +import org.apache.tuscany.sca.binding.corba.testing.hierarchy.RichUnion; + +public class ArraysUnionsTuscanyServant { + + private static final long serialVersionUID = 1L; + + public ArraysTestStruct passTestStruct(ArraysTestStruct arg) { + return arg; + } + + @CorbaArray( {2, 2}) + public String[][] passStringArray(@CorbaArray( {2, 2})String[][] arg) { + return arg; + } + + public RichUnion passRichUnion(RichUnion arg) { + return arg; + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/CalcServant.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/CalcServant.java new file mode 100644 index 0000000000..fd789e19cb --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/CalcServant.java @@ -0,0 +1,52 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.servants; + +import org.apache.tuscany.sca.binding.corba.testing.exceptions._CalcImplBase; +import org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.Arguments; +import org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.DivByZero; +import org.apache.tuscany.sca.binding.corba.testing.exceptions.CalcPackage.NotSupported; + +public class CalcServant extends _CalcImplBase { + + private static final long serialVersionUID = 1L; + + public double div(double arg1, double arg2) throws DivByZero { + if (arg2 == 0) { + DivByZero exception = new DivByZero(); + exception.arguments = new Arguments(arg1, arg2); + exception.info = "Error occured during div: div by zero"; + throw exception; + } else { + return arg1 / arg2; + } + } + + public double divForSmallArgs(double arg1, double arg2) throws DivByZero, NotSupported { + if (arg1 > 100 || arg2 > 100) { + NotSupported exception = new NotSupported(); + exception.info = "arg1: " + arg1 + ", arg2: " + arg2; + throw exception; + } else { + return div(arg1, arg2); + } + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/DummyObjectServant.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/DummyObjectServant.java new file mode 100644 index 0000000000..2e205f1d0f --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/DummyObjectServant.java @@ -0,0 +1,42 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.servants; + +import org.apache.tuscany.sca.binding.corba.testing.references.DummyObject; +import org.apache.tuscany.sca.binding.corba.testing.references._DummyObjectImplBase; + +public class DummyObjectServant extends _DummyObjectImplBase { + + private static final long serialVersionUID = 1L; + private int retVal; + + public DummyObjectServant() { + retVal = (int)System.currentTimeMillis(); + } + + public int getLong() { + return retVal; + } + + public DummyObject cloneObject() { + return new DummyObjectServant(); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/EnumManagerServant.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/EnumManagerServant.java new file mode 100644 index 0000000000..52386aeef7 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/EnumManagerServant.java @@ -0,0 +1,33 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.servants; + +import org.apache.tuscany.sca.binding.corba.testing.enums.Color; +import org.apache.tuscany.sca.binding.corba.testing.enums._EnumManagerImplBase; + +public class EnumManagerServant extends _EnumManagerImplBase { + + private static final long serialVersionUID = 1L; + + public Color getColor(Color color) { + return color; + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/InvalidTestObjectServant.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/InvalidTestObjectServant.java new file mode 100644 index 0000000000..b7fbb69627 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/InvalidTestObjectServant.java @@ -0,0 +1,24 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.servants; + +public class InvalidTestObjectServant { + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/InvalidTypesServant.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/InvalidTypesServant.java new file mode 100644 index 0000000000..dda8203f79 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/InvalidTypesServant.java @@ -0,0 +1,34 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.servants; + +import org.apache.tuscany.sca.binding.corba.testing.hierarchy.InvalidStruct1; + +public class InvalidTypesServant { + + public InvalidStruct1 firstMethodWithInvalidArg() { + return null; + } + + public void secondMethodWithInvalidArg(InvalidStruct1 arg) { + + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/NonCorbaServant.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/NonCorbaServant.java new file mode 100644 index 0000000000..20700a0392 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/NonCorbaServant.java @@ -0,0 +1,36 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.servants; + +import org.apache.tuscany.sca.binding.corba.testing.hierarchy.NonCorbaException; + +public class NonCorbaServant { + + public String setString(String arg) { + return arg; + } + + public void throwException() throws NonCorbaException { + NonCorbaException e = new NonCorbaException(); + e.someField = "test"; + throw e; + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/ObjectManagerServant.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/ObjectManagerServant.java new file mode 100644 index 0000000000..213c7fbd7c --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/ObjectManagerServant.java @@ -0,0 +1,37 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.servants; + +import org.apache.tuscany.sca.binding.corba.testing.references.DummyObject; +import org.apache.tuscany.sca.binding.corba.testing.references._ObjectManagerImplBase; + +public class ObjectManagerServant extends _ObjectManagerImplBase { + + private static final long serialVersionUID = 1L; + + public DummyObject getObjectByArgument(DummyObject arg) { + return arg; + } + + public DummyObject getDummyObject() { + return new DummyObjectServant(); + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/PrimitivesSetterServant.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/PrimitivesSetterServant.java new file mode 100644 index 0000000000..92e18741ae --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/PrimitivesSetterServant.java @@ -0,0 +1,89 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.servants; + +import org.apache.tuscany.sca.binding.corba.testing.generated.RemoteObject; +import org.apache.tuscany.sca.binding.corba.testing.generated._PrimitivesSetterImplBase; + +public class PrimitivesSetterServant extends _PrimitivesSetterImplBase { + + private static final long serialVersionUID = 1L; + + public boolean setBoolean(boolean arg) { + return arg; + } + + public char setChar(char arg) { + return arg; + } + + public double setDouble(double arg) { + return arg; + } + + public float setFloat(float arg) { + return arg; + } + + public int setLong(int arg) { + return arg; + } + + public long setLongLong(long arg) { + return arg; + } + + public byte setOctet(byte arg) { + return arg; + } + + public RemoteObject setRemoteObject(RemoteObject obj) { + return obj; + } + + public short setShort(short arg) { + return arg; + } + + public String setString(String arg) { + return arg; + } + + public int setUnsignedLong(int arg) { + return arg; + } + + public long setUnsignedLongLong(long arg) { + return arg; + } + + public short setUnsignedShort(short arg) { + return arg; + } + + public char setWchar(char arg) { + return arg; + } + + public String setWstring(String arg) { + return arg; + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/TestObjectServant.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/TestObjectServant.java new file mode 100644 index 0000000000..153268983f --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/servants/TestObjectServant.java @@ -0,0 +1,71 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.servants; + +import org.apache.tuscany.sca.binding.corba.testing.generated.SimpleStruct; +import org.apache.tuscany.sca.binding.corba.testing.generated.SimpleStructHolder; +import org.apache.tuscany.sca.binding.corba.testing.generated.SomeStruct; +import org.apache.tuscany.sca.binding.corba.testing.generated._TestObjectImplBase; +import org.apache.tuscany.sca.binding.corba.testing.generated.long_seq1Holder; +import org.apache.tuscany.sca.binding.corba.testing.generated.long_seq2Holder; +import org.apache.tuscany.sca.binding.corba.testing.generated.long_seq3Holder; + +/** + * @version $Rev$ $Date$ + */ +public class TestObjectServant extends _TestObjectImplBase { + + private static final long serialVersionUID = 1L; + + public int[] setLongSeq1(long_seq1Holder arg) { + return arg.value; + } + + public int[][] setLongSeq2(long_seq2Holder arg) { + + return arg.value; + } + + public int[][][] setLongSeq3(long_seq3Holder arg) { + return arg.value; + } + + public SimpleStruct setSimpleStruct(SimpleStructHolder arg) { + return arg.value; + } + + public SomeStruct setStruct(SomeStruct arg) { + return arg; + } + + public SomeStruct pickStructFromArgs(SomeStruct arg1, SomeStruct arg2, SomeStruct arg3, int structNumber) { + switch (structNumber) { + case 1: + return arg1; + case 2: + return arg2; + case 3: + return arg3; + default: + return arg1; + } + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/service/mocks/TestDataType.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/service/mocks/TestDataType.java new file mode 100644 index 0000000000..7ebc3fce85 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/service/mocks/TestDataType.java @@ -0,0 +1,88 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.service.mocks; + +import java.lang.reflect.Type; + +import org.apache.tuscany.sca.interfacedef.DataType; + +/** + * Mock DataType implementation. Only few methods needs to be implemented. + */ +public class TestDataType implements DataType { + + public Class typeClass; + public L logical; + + public TestDataType(Class typeClass) { + this.typeClass = typeClass; + } + + public TestDataType(Class typeClass, L logical) { + this.typeClass = typeClass; + this.logical = logical; + } + + public String getDataBinding() { + return null; + } + + public Type getGenericType() { + return null; + } + + public L getLogical() { + return logical; + } + + public T getMetaData(Class arg0) { + return null; + } + + public Class getPhysical() { + return typeClass; + } + + public void setDataBinding(String arg0) { + + } + + public void setGenericType(Type arg0) { + + } + + public void setLogical(L arg0) { + + } + + public void setMetaData(Class arg0, T arg1) { + + } + + public void setPhysical(Class arg0) { + + } + + @Override + public Object clone() { + return null; + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/service/mocks/TestInterface.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/service/mocks/TestInterface.java new file mode 100644 index 0000000000..2c5a0d8159 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/service/mocks/TestInterface.java @@ -0,0 +1,139 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.service.mocks; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.interfacedef.java.JavaInterface; +import org.apache.tuscany.sca.policy.Intent; +import org.apache.tuscany.sca.policy.IntentAttachPointType; +import org.apache.tuscany.sca.policy.PolicySet; + +/** + * Mock TestInterface implementation. Only few methods needs to be implemented. + */ +public class TestInterface implements JavaInterface { + + private List operations; + private Class javaClass; + + public TestInterface(List opearations, Class javaClass) { + this.operations = opearations; + this.javaClass = javaClass; + } + + public List getOperations() { + return operations; + } + + public boolean isConversational() { + return false; + } + + public boolean isDynamic() { + return false; + } + + public boolean isRemotable() { + return false; + } + + public void resetDataBinding(String dataBinding) { + + } + + public void setConversational(boolean conversational) { + + } + + public void setDefaultDataBinding(String dataBinding) { + + } + + public void setRemotable(boolean remotable) { + + } + + public List getApplicablePolicySets() { + return null; + } + + public List getPolicySets() { + return null; + } + + public List getRequiredIntents() { + return null; + } + + public IntentAttachPointType getType() { + return null; + } + + public void setType(IntentAttachPointType type) { + + } + + @Override + public Object clone() { + return null; + } + + public Class getCallbackClass() { + return null; + } + + public Class getJavaClass() { + return javaClass; + } + + public String getName() { + return null; + } + + public QName getQName() { + return null; + } + + public void setCallbackClass(Class arg0) { + } + + public void setJavaClass(Class javaClass) { + this.javaClass = javaClass; + } + + public void setName(String arg0) { + } + + public void setQName(QName arg0) { + + } + + public boolean isUnresolved() { + return false; + } + + public void setUnresolved(boolean arg0) { + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/service/mocks/TestInterfaceContract.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/service/mocks/TestInterfaceContract.java new file mode 100644 index 0000000000..d691705955 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/service/mocks/TestInterfaceContract.java @@ -0,0 +1,58 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.service.mocks; + +import org.apache.tuscany.sca.interfacedef.Interface; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; + +/** + * Mock InterfaceContract implementation. Only few methods needs to be + * implemented. + */ +public class TestInterfaceContract implements InterfaceContract { + + private Interface iface; + + public Interface getCallbackInterface() { + return null; + } + + public Interface getInterface() { + return iface; + } + + public InterfaceContract makeUnidirectional(boolean isCallback) { + return null; + } + + public void setCallbackInterface(Interface callbackInterface) { + + } + + public void setInterface(Interface callInterface) { + this.iface = callInterface; + } + + @Override + public Object clone() { + return null; + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/service/mocks/TestOperation.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/service/mocks/TestOperation.java new file mode 100644 index 0000000000..90551ec25d --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/service/mocks/TestOperation.java @@ -0,0 +1,174 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.service.mocks; + +import java.util.List; +import java.util.Map; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.interfacedef.ConversationSequence; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.Interface; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.interfacedef.util.WrapperInfo; +import org.apache.tuscany.sca.interfacedef.util.XMLType; +import org.apache.tuscany.sca.policy.Intent; +import org.apache.tuscany.sca.policy.IntentAttachPointType; +import org.apache.tuscany.sca.policy.PolicySet; + +/** + * Mock Operation implementation. Only few methods needs to be implemented. + */ +public class TestOperation implements Operation { + + private DataType> inputType; + private DataType outputType; + private String name; + + public ConversationSequence getConversationSequence() { + return null; + } + + public String getDataBinding() { + return null; + } + + public Map>> getFaultBeans() { + return null; + } + + public List getFaultTypes() { + return null; + } + + public DataType> getInputType() { + return inputType; + } + + public Interface getInterface() { + return null; + } + + public String getName() { + return name; + } + + public DataType getOutputType() { + return outputType; + } + + public WrapperInfo getWrapper() { + return null; + } + + public boolean isDynamic() { + return false; + } + + public boolean isNonBlocking() { + return false; + } + + public boolean isUnresolved() { + return false; + } + + public boolean isWrapperStyle() { + return false; + } + + public void setConversationSequence(ConversationSequence sequence) { + + } + + public void setDataBinding(String dataBinding) { + + } + + public void setDynamic(boolean b) { + + } + + public void setFaultBeans(Map>> faultBeans) { + + } + + public void setFaultTypes(List faultTypes) { + + } + + public void setInputType(DataType> inputType) { + this.inputType = inputType; + } + + public void setInterface(Interface interfaze) { + + } + + public void setName(String name) { + this.name = name; + } + + public void setNonBlocking(boolean nonBlocking) { + + } + + public void setOutputType(DataType outputType) { + this.outputType = outputType; + } + + public void setUnresolved(boolean unresolved) { + + } + + public void setWrapper(WrapperInfo wrapperInfo) { + + } + + public void setWrapperStyle(boolean wrapperStyle) { + + } + + public List getApplicablePolicySets() { + return null; + } + + public List getPolicySets() { + return null; + } + + @Override + public Object clone() { + return null; + } + + public List getRequiredIntents() { + return null; + } + + public IntentAttachPointType getType() { + return null; + } + + public void setType(IntentAttachPointType type) { + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/service/mocks/TestRuntimeComponentService.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/service/mocks/TestRuntimeComponentService.java new file mode 100644 index 0000000000..6fc5f9398e --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/service/mocks/TestRuntimeComponentService.java @@ -0,0 +1,234 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.service.mocks; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.List; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.assembly.Callback; +import org.apache.tuscany.sca.assembly.ComponentReference; +import org.apache.tuscany.sca.assembly.ConfiguredOperation; +import org.apache.tuscany.sca.assembly.Service; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.InvocationChain; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.policy.Intent; +import org.apache.tuscany.sca.policy.IntentAttachPointType; +import org.apache.tuscany.sca.policy.PolicySet; +import org.apache.tuscany.sca.provider.PolicyProvider; +import org.apache.tuscany.sca.provider.ServiceBindingProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; +import org.apache.tuscany.sca.runtime.RuntimeWire; + +/** + * Mock RuntimeComponentService implementation. Only few methods needs to be + * implemented. + */ +public class TestRuntimeComponentService implements RuntimeComponentService { + + private InterfaceContract interfaceContract; + private RuntimeWire runtimeWire; + + public TestRuntimeComponentService(Object invocationTarget) { + runtimeWire = new TestRuntimeWire(invocationTarget); + List operations = new ArrayList(); + Method[] methods = invocationTarget.getClass().getMethods(); + for (int i = 0; i < methods.length; i++) { + int mod = methods[i].getModifiers(); + if (methods[i].getDeclaringClass().equals(invocationTarget.getClass()) && Modifier.isPublic(mod) + && !methods[i].getName().startsWith("_")) { + Operation operation = new TestOperation(); + DataType returnType = new TestDataType(methods[i].getReturnType()); + operation.setOutputType(returnType); + Class[] argTypes = methods[i].getParameterTypes(); + List argDataTypes = new ArrayList(); + for (int j = 0; j < argTypes.length; j++) { + argDataTypes.add(new TestDataType(argTypes[j])); + } + TestDataType> inputDataType = new TestDataType>(null, argDataTypes); + operation.setInputType(inputDataType); + operations.add(operation); + operation.setName(methods[i].getName()); + } + } + TestInterface iface = new TestInterface(operations, invocationTarget.getClass()); + interfaceContract = new TestInterfaceContract(); + interfaceContract.setInterface(iface); + } + + public void addPolicyProvider(Binding binding, PolicyProvider policyProvider) { + + } + + public ServiceBindingProvider getBindingProvider(Binding binding) { + return null; + } + + public List getCallbackWires() { + return null; + } + + public InvocationChain getInvocationChain(Binding binding, Operation operation) { + return null; + } + + public InvocationChain getInvocationChain(Binding binding, InterfaceContract interfaceContract, Operation operation) { + return null; + } + + public Invoker getInvoker(Binding binding, Operation operation) { + return null; + } + + public Invoker getInvoker(Binding binding, InterfaceContract interfaceContract, Operation operation) { + return null; + } + + public List getPolicyProviders(Binding binding) { + return null; + } + + public RuntimeWire getRuntimeWire(Binding binding) { + return runtimeWire; + } + + public RuntimeWire getRuntimeWire(Binding binding, InterfaceContract interfaceContract) { + return null; + } + + public List getRuntimeWires() { + return null; + } + + public void setBindingProvider(Binding binding, ServiceBindingProvider bindingProvider) { + + } + + public ComponentReference getCallbackReference() { + return null; + } + + public Service getService() { + return null; + } + + public void setCallbackReference(ComponentReference callbackReference) { + + } + + public void setService(Service service) { + + } + + public InterfaceContract getInterfaceContract() { + return interfaceContract; + } + + public InterfaceContract getInterfaceContract(Binding binding) { + return getInterfaceContract(); + } + + public String getName() { + return null; + } + + public boolean isCallback() { + return false; + } + + public void setInterfaceContract(InterfaceContract interfaceContract) { + this.interfaceContract = interfaceContract; + } + + public void setIsCallback(boolean isCallback) { + + } + + public void setName(String name) { + + } + + public boolean isUnresolved() { + return false; + } + + public void setUnresolved(boolean unresolved) { + + } + + public List getExtensions() { + return null; + } + + public List getRequiredIntents() { + return null; + } + + public IntentAttachPointType getType() { + return null; + } + + public void setType(IntentAttachPointType type) { + + } + + public List getConfiguredOperations() { + return null; + } + + public B getBinding(Class bindingClass) { + return null; + } + + public List getBindings() { + return null; + } + + public Callback getCallback() { + return null; + } + + public B getCallbackBinding(Class bindingClass) { + return null; + } + + public void setCallback(Callback callback) { + + } + + public List getApplicablePolicySets() { + return null; + } + + public List getPolicySets() { + return null; + } + + @Override + public Object clone() { + return null; + } + +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/service/mocks/TestRuntimeWire.java b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/service/mocks/TestRuntimeWire.java new file mode 100644 index 0000000000..5b7caf1010 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/java/org/apache/tuscany/sca/binding/corba/testing/service/mocks/TestRuntimeWire.java @@ -0,0 +1,107 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.testing.service.mocks; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.List; + +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.InvocationChain; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.runtime.EndpointReference; +import org.apache.tuscany.sca.runtime.RuntimeWire; + +/** + * Mock RuntimeWire implementation. Only few methods needs to be implemented. + */ +public class TestRuntimeWire implements RuntimeWire { + private Object invocationTarget; + + public TestRuntimeWire(Object invocationTarget) { + this.invocationTarget = invocationTarget; + } + + public InvocationChain getInvocationChain(Operation arg0) { + return null; + } + + public List getInvocationChains() { + return null; + } + + public EndpointReference getSource() { + return null; + } + + public EndpointReference getTarget() { + return null; + } + + public Object invoke(Operation operation, Object[] args) throws InvocationTargetException { + Class[] types = new Class[args.length]; + for (int i = 0; i < args.length; i++) { + types[i] = args[i].getClass(); + } + Object result = null; + try { + Method[] methods = invocationTarget.getClass().getMethods(); + for (int i = 0; i < methods.length; i++) { + if (methods[i].getName().equals(operation.getName())) { + result = methods[i].invoke(invocationTarget, args); + break; + } + } + } catch (InvocationTargetException e) { + throw e; + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + + return result; + } + + public Object invoke(Operation operation, Message arg1) throws InvocationTargetException { + + return null; + } + + public Object invoke(Message arg1) throws InvocationTargetException { + + return null; + } + + public void rebuild() { + + } + + public void setTarget(EndpointReference arg0) { + + } + + @Override + public Object clone() { + return null; + } + + public InvocationChain getBindingInvocationChain() { + return null; + } +} diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/resources/arrays_unions.idl b/java/sca/contrib/modules/binding-corba-runtime/src/test/resources/arrays_unions.idl new file mode 100644 index 0000000000..0f4ed03b4e --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/resources/arrays_unions.idl @@ -0,0 +1,69 @@ +/* + * 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. + */ + +/* + * compile by + * idlj -fall -oldImplBase arrays_unions.idl + */ + +module org { + module apache { + module tuscany { + module sca { + module binding { + module corba { + module testing { + module arrays_unions { + + struct TestStruct { + string oneDimArray[2]; + long twoDimArray[2][4]; + float threeDimArray[2][4][2]; + }; + + typedef string StringArray[2][2]; + + union InnerUnion switch (long) { + case 1: long x; + case 2: float y; + }; + + union RichUnion switch (long) { + case 1: long x; + case 2: float y; + case 3: string z; + case 4: InnerUnion iu; + default: boolean a; + }; + + interface ArraysUnionsTests { + TestStruct passTestStruct(in TestStruct arg); + StringArray passStringArray(in StringArray arg); + RichUnion passRichUnion(in RichUnion arg); + }; + + }; + }; + }; + }; + }; + }; + }; +}; + diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/resources/enums.idl b/java/sca/contrib/modules/binding-corba-runtime/src/test/resources/enums.idl new file mode 100644 index 0000000000..2e4e829b0f --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/resources/enums.idl @@ -0,0 +1,44 @@ +/* + * 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. + */ + +/* + * compile by + * idlj -fall -oldImplBase enums.idl + */ + +module org { + module apache { + module tuscany { + module sca { + module binding { + module corba { + module testing { + module enums { + enum Color {red, yellow, green}; + interface EnumManager { + Color getColor(in Color color); + }; + }; + }; + }; + }; + }; + }; + }; +}; diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/resources/exceptions.idl b/java/sca/contrib/modules/binding-corba-runtime/src/test/resources/exceptions.idl new file mode 100644 index 0000000000..b34ec46458 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/resources/exceptions.idl @@ -0,0 +1,58 @@ +/* + * 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. + */ + +/* + * compile by + * idlj -fall -oldImplBase exceptions.idl + */ + +module org { + module apache { + module tuscany { + module sca { + module binding { + module corba { + module testing { + module exceptions { + interface Calc { + struct Arguments { + double arg1; + double arg2; + }; + + exception DivByZero{ + Arguments arguments; + string info; + }; + + exception NotSupported { + string info; + }; + + double div(in double arg1, in double arg2) raises(DivByZero); + double divForSmallArgs(in double arg1, in double arg2) raises(DivByZero, NotSupported); + }; + }; + }; + }; + }; + }; + }; + }; +}; diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/resources/general_tests.idl b/java/sca/contrib/modules/binding-corba-runtime/src/test/resources/general_tests.idl new file mode 100644 index 0000000000..db253338c3 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/resources/general_tests.idl @@ -0,0 +1,124 @@ +/* + * 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. + */ + +/* + * compile by + * idlj -fall -oldImplBase general_tests.idl + */ + +module org { + module apache { + module tuscany { + module sca { + module binding { + module corba { + module testing { + module generated { + + interface RemoteObject { + + }; + + typedef sequence remote_object_list; + typedef sequence boolean_list; + typedef sequence char_list; + typedef sequence wchar_list; + typedef sequence octet_list; + typedef sequence short_list; + typedef sequence unsigned_short_list; + typedef sequence long_list; + typedef sequence unsigned_long_list; + typedef sequence long_long_list; + typedef sequence unsigned_long_long_list; + typedef sequence float_list; + typedef sequence double_list; + typedef sequence string_list; + typedef sequence wstring_list; + + interface PrimitivesSetter { + boolean setBoolean(in boolean arg); + char setChar(in char arg); + wchar setWchar(in wchar arg); + octet setOctet(in octet arg); + short setShort(in short arg); + unsigned short setUnsignedShort(in unsigned short arg); + long setLong(in long arg); + unsigned long setUnsignedLong(in unsigned long arg); + long long setLongLong(in long long arg); + unsigned long long setUnsignedLongLong(in unsigned long long arg); + float setFloat(in float arg); + double setDouble(in double arg); + string setString(in string arg); + wstring setWstring(in wstring arg); + RemoteObject setRemoteObject(in RemoteObject obj); + }; + + interface ArraysSetter { + boolean_list setBoolean(in boolean_list arg); + char_list setChar(in char_list arg); + wchar_list setWchar(in wchar_list arg); + octet_list setOctet(in octet_list arg); + short_list setShort(in short_list arg); + unsigned_short_list setUnsignedShort(in unsigned_short_list arg); + long_list setLong(in long_list arg); + unsigned_long_list setUnsignedLong(in unsigned_long_list arg); + long_long_list setLongLong(in long_long_list arg); + unsigned_long_long_list setUnsignedLongLong(in unsigned_long_long_list arg); + float_list setFloat(in float_list arg); + double_list setDouble(in double_list arg); + string_list setString(in string_list arg); + wstring_list setWstring(in wstring_list arg); + remote_object_list setRemoteObject(in remote_object_list obj); + }; + + typedef sequence long_seq1; + typedef sequence long_seq2; + typedef sequence long_seq3; + + struct SimpleStruct { + string field1; + long field2; + }; + + + struct SomeStruct { + SimpleStruct innerStruct; + string str; + string_list str_list; + long_seq2 twoDimSeq; + long_seq3 threeDimSeq; + }; + + interface TestObject { + SomeStruct pickStructFromArgs(in SomeStruct arg1, in SomeStruct arg2, in SomeStruct arg3, in long structNumber); + SomeStruct setStruct(in SomeStruct arg); + SimpleStruct setSimpleStruct(inout SimpleStruct arg); + long_seq1 setLongSeq1(inout long_seq1 arg); + long_seq2 setLongSeq2(inout long_seq2 arg); + long_seq3 setLongSeq3(inout long_seq3 arg); + }; + + }; + }; + }; + }; + }; + }; + }; +}; diff --git a/java/sca/contrib/modules/binding-corba-runtime/src/test/resources/references.idl b/java/sca/contrib/modules/binding-corba-runtime/src/test/resources/references.idl new file mode 100644 index 0000000000..72b58806e6 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba-runtime/src/test/resources/references.idl @@ -0,0 +1,50 @@ +/* + * 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. + */ + +/* + * compile by + * idlj -fall -oldImplBase remote_objects.idl + */ + +module org { + module apache { + module tuscany { + module sca { + module binding { + module corba { + module testing { + module references { + + interface DummyObject { + long getLong(); + DummyObject cloneObject(); + }; + + interface ObjectManager { + DummyObject getDummyObject(); + DummyObject getObjectByArgument(in DummyObject dummy); + }; + }; + }; + }; + }; + }; + }; + }; +}; diff --git a/java/sca/contrib/modules/binding-corba/LICENSE b/java/sca/contrib/modules/binding-corba/LICENSE new file mode 100644 index 0000000000..6e529a25c4 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba/LICENSE @@ -0,0 +1,205 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + + diff --git a/java/sca/contrib/modules/binding-corba/META-INF/MANIFEST.MF b/java/sca/contrib/modules/binding-corba/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..d41630838c --- /dev/null +++ b/java/sca/contrib/modules/binding-corba/META-INF/MANIFEST.MF @@ -0,0 +1,28 @@ +Manifest-Version: 1.0 +Export-Package: org.apache.tuscany.sca.binding.corba;uses:="org.apache + .tuscany.sca.assembly,javax.xml.namespace";version="2.0.0" +Private-Package: org.apache.tuscany.sca.binding.corba.impl;version="1. + 4" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA CORBA Binding Extension +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397128062 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA CORBA Binding Extension +Import-Package: javax.xml.namespace, + javax.xml.stream, + org.apache.tuscany.sca.assembly;version="2.0.0", + org.apache.tuscany.sca.assembly.xml;version="2.0.0", + org.apache.tuscany.sca.binding.corba;version="2.0.0", + org.apache.tuscany.sca.contribution.processor;version="2.0.0", + org.apache.tuscany.sca.contribution.resolver;version="2.0.0", + org.apache.tuscany.sca.core;version="2.0.0", + org.apache.tuscany.sca.host.corba;version="2.0.0", + org.apache.tuscany.sca.interfacedef;version="2.0.0", + org.apache.tuscany.sca.policy;version="2.0.0" +Bundle-SymbolicName: org.apache.tuscany.sca.binding.corba +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/binding-corba/NOTICE b/java/sca/contrib/modules/binding-corba/NOTICE new file mode 100644 index 0000000000..51042eab05 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/binding-corba/pom.xml b/java/sca/contrib/modules/binding-corba/pom.xml new file mode 100644 index 0000000000..fd6a3d12ff --- /dev/null +++ b/java/sca/contrib/modules/binding-corba/pom.xml @@ -0,0 +1,53 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + tuscany-binding-corba + Apache Tuscany SCA CORBA Binding Extension + + + + + org.apache.tuscany.sca + tuscany-core-spi + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-assembly-xml + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-host-corba + 2.0-SNAPSHOT + + + + + diff --git a/java/sca/contrib/modules/binding-corba/src/main/java/org/apache/tuscany/sca/binding/corba/CorbaBinding.java b/java/sca/contrib/modules/binding-corba/src/main/java/org/apache/tuscany/sca/binding/corba/CorbaBinding.java new file mode 100644 index 0000000000..8ccce730cf --- /dev/null +++ b/java/sca/contrib/modules/binding-corba/src/main/java/org/apache/tuscany/sca/binding/corba/CorbaBinding.java @@ -0,0 +1,47 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.assembly.Binding; + +/** + * @version $Rev$ $Date$ + */ +public interface CorbaBinding extends Binding { + String SCA10_TUSCANY_NS = "http://tuscany.apache.org/xmlns/sca/1.0"; + String BINDING_CORBA = "binding.corba"; + QName BINDING_CORBA_QNAME = new QName(SCA10_TUSCANY_NS, BINDING_CORBA); + + String getHost(); + + void setHost(String host); + + int getPort(); + + void setPort(int port); + + String getId(); + + void setId(String id); + + String getCorbaname(); +} diff --git a/java/sca/contrib/modules/binding-corba/src/main/java/org/apache/tuscany/sca/binding/corba/CorbaBindingFactory.java b/java/sca/contrib/modules/binding-corba/src/main/java/org/apache/tuscany/sca/binding/corba/CorbaBindingFactory.java new file mode 100644 index 0000000000..67e3bdcf74 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba/src/main/java/org/apache/tuscany/sca/binding/corba/CorbaBindingFactory.java @@ -0,0 +1,31 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba; + +/** + * @version $Rev$ $Date$ + */ +public interface CorbaBindingFactory { + /** + * Create a CorbaBinding model + * @return The CorbaBinding model + */ + CorbaBinding createCorbaBinding(); +} diff --git a/java/sca/contrib/modules/binding-corba/src/main/java/org/apache/tuscany/sca/binding/corba/impl/CorbaBindingFactoryImpl.java b/java/sca/contrib/modules/binding-corba/src/main/java/org/apache/tuscany/sca/binding/corba/impl/CorbaBindingFactoryImpl.java new file mode 100644 index 0000000000..cecb4fb567 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba/src/main/java/org/apache/tuscany/sca/binding/corba/impl/CorbaBindingFactoryImpl.java @@ -0,0 +1,37 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.impl; + +import org.apache.tuscany.sca.binding.corba.CorbaBinding; +import org.apache.tuscany.sca.binding.corba.CorbaBindingFactory; + +/** + * @version $Rev$ $Date$ + */ +public class CorbaBindingFactoryImpl implements CorbaBindingFactory { + + /** + * @see org.apache.tuscany.sca.binding.corba.CorbaBindingFactory#createCorbaBinding() + */ + public CorbaBinding createCorbaBinding() { + return new CorbaBindingImpl(); + } + +} diff --git a/java/sca/contrib/modules/binding-corba/src/main/java/org/apache/tuscany/sca/binding/corba/impl/CorbaBindingImpl.java b/java/sca/contrib/modules/binding-corba/src/main/java/org/apache/tuscany/sca/binding/corba/impl/CorbaBindingImpl.java new file mode 100644 index 0000000000..54e98d4117 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba/src/main/java/org/apache/tuscany/sca/binding/corba/impl/CorbaBindingImpl.java @@ -0,0 +1,132 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.impl; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.tuscany.sca.binding.corba.CorbaBinding; +import org.apache.tuscany.sca.host.corba.CorbaHostUtils; +import org.apache.tuscany.sca.policy.Intent; +import org.apache.tuscany.sca.policy.IntentAttachPointType; +import org.apache.tuscany.sca.policy.PolicySet; +import org.apache.tuscany.sca.policy.PolicySetAttachPoint; + +/** + * @version $Rev$ $Date$ + */ +public class CorbaBindingImpl implements CorbaBinding, PolicySetAttachPoint { + private String name; + private String uri; + private String host; + private int port; + private String id; + + private List requiredIntents = new ArrayList(); + private List policySets = new ArrayList(); + private IntentAttachPointType intentAttachPointType; + private List applicablePolicySets = new ArrayList(); + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public int getPort() { + return port; + } + + public void setPort(int port) { + this.port = port; + } + + public String getName() { + return name; + } + + public String getURI() { + return uri; + } + + public void setName(String name) { + this.name = name; + + } + + public void setURI(String uri) { + this.uri = uri; + } + + public boolean isUnresolved() { + return false; + } + + public void setUnresolved(boolean unresolved) { + } + + public List getPolicySets() { + return policySets; + } + + public List getRequiredIntents() { + return requiredIntents; + } + + public IntentAttachPointType getType() { + return intentAttachPointType; + } + + public void setType(IntentAttachPointType intentAttachPointType) { + this.intentAttachPointType = intentAttachPointType; + } + + public void setPolicySets(List policySets) { + this.policySets = policySets; + } + + public void setRequiredIntents(List intents) { + this.requiredIntents = intents; + } + + public List getApplicablePolicySets() { + return applicablePolicySets; + } + + @Override + public Object clone() throws CloneNotSupportedException { + return super.clone(); + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getCorbaname() { + return CorbaHostUtils.isValidCorbanameURI(getURI()) ? getURI(): CorbaHostUtils.createCorbanameURI(getHost(), getPort(), getName()); + } + +} diff --git a/java/sca/contrib/modules/binding-corba/src/main/java/org/apache/tuscany/sca/binding/corba/impl/CorbaBindingProcessor.java b/java/sca/contrib/modules/binding-corba/src/main/java/org/apache/tuscany/sca/binding/corba/impl/CorbaBindingProcessor.java new file mode 100644 index 0000000000..930a8d39d9 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba/src/main/java/org/apache/tuscany/sca/binding/corba/impl/CorbaBindingProcessor.java @@ -0,0 +1,133 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.corba.impl; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; + +import org.apache.tuscany.sca.assembly.xml.PolicyAttachPointProcessor; +import org.apache.tuscany.sca.binding.corba.CorbaBinding; +import org.apache.tuscany.sca.contribution.processor.ContributionReadException; +import org.apache.tuscany.sca.contribution.processor.ContributionResolveException; +import org.apache.tuscany.sca.contribution.processor.ContributionWriteException; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.core.FactoryExtensionPoint; +import org.apache.tuscany.sca.policy.PolicyFactory; + +/** + * @version $Rev$ $Date$ + */ +public class CorbaBindingProcessor implements StAXArtifactProcessor { + private PolicyFactory policyFactory; + private PolicyAttachPointProcessor policyProcessor; + + public CorbaBindingProcessor(FactoryExtensionPoint modelFactories) { + this.policyFactory = modelFactories.getFactory(PolicyFactory.class); + this.policyProcessor = new PolicyAttachPointProcessor(policyFactory); + } + + /** + * @see org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor#getArtifactType() + */ + public QName getArtifactType() { + return CorbaBinding.BINDING_CORBA_QNAME; + } + + /** + * @see org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor#read(javax.xml.stream.XMLStreamReader) + */ + public CorbaBinding read(XMLStreamReader reader) throws ContributionReadException, XMLStreamException { + CorbaBinding binding = new CorbaBindingImpl(); + + // Read the policies + policyProcessor.readPolicies(binding, reader); + + binding.setHost(reader.getAttributeValue(null, "host")); + String port = reader.getAttributeValue(null, "port"); + if (port != null) { + binding.setPort(Integer.parseInt(port)); + } + + // Read the name + String name = reader.getAttributeValue(null, "name"); + if (name != null) { + binding.setName(name); + } + + // Read binding URI + String uri = reader.getAttributeValue(null, "uri"); + if (uri != null) { + binding.setURI(uri); + } + + // Read CORBA id + String id = reader.getAttributeValue(null, "id"); + if (id != null) { + binding.setId(id); + } + return binding; + } + + /** + * @see org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor#write(java.lang.Object, javax.xml.stream.XMLStreamWriter) + */ + public void write(CorbaBinding model, XMLStreamWriter writer) throws ContributionWriteException, XMLStreamException { + // Write a + writer.writeStartElement(CorbaBinding.SCA10_TUSCANY_NS, CorbaBinding.BINDING_CORBA); + + if (model.getName() != null) { + writer.writeAttribute("name", model.getName()); + } + + if (model.getURI() != null) { + writer.writeAttribute("uri", model.getURI()); + } + + if (model.getHost() != null) { + writer.writeAttribute("host", model.getHost()); + } + + if (model.getPort() != -1) { + writer.writeAttribute("port", String.valueOf(model.getPort())); + } + + if (model.getId() != null) { + writer.writeAttribute("id", model.getId()); + } + writer.writeEndElement(); + } + + /** + * @see org.apache.tuscany.sca.contribution.processor.ArtifactProcessor#getModelType() + */ + public Class getModelType() { + return CorbaBinding.class; + } + + /** + * @see org.apache.tuscany.sca.contribution.processor.ArtifactProcessor#resolve(java.lang.Object, org.apache.tuscany.sca.contribution.resolver.ModelResolver) + */ + public void resolve(CorbaBinding model, ModelResolver resolver) throws ContributionResolveException { + } + +} diff --git a/java/sca/contrib/modules/binding-corba/src/main/resources/META-INF/services/org.apache.tuscany.sca.binding.corba.CorbaBindingFactory b/java/sca/contrib/modules/binding-corba/src/main/resources/META-INF/services/org.apache.tuscany.sca.binding.corba.CorbaBindingFactory new file mode 100644 index 0000000000..57959840d4 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba/src/main/resources/META-INF/services/org.apache.tuscany.sca.binding.corba.CorbaBindingFactory @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for the model factory +org.apache.tuscany.sca.binding.corba.impl.CorbaBindingFactoryImpl \ No newline at end of file diff --git a/java/sca/contrib/modules/binding-corba/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor b/java/sca/contrib/modules/binding-corba/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor new file mode 100644 index 0000000000..71d14bc077 --- /dev/null +++ b/java/sca/contrib/modules/binding-corba/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for the artifact processor extension +org.apache.tuscany.sca.binding.corba.impl.CorbaBindingProcessor;qname=http://tuscany.apache.org/xmlns/sca/1.0#binding.corba,model=org.apache.tuscany.sca.binding.corba.CorbaBinding,factory=org.apache.tuscany.sca.binding.corba.CorbaBindingFactory diff --git a/java/sca/contrib/modules/binding-ejb-runtime/LICENSE b/java/sca/contrib/modules/binding-ejb-runtime/LICENSE new file mode 100644 index 0000000000..8aa906c321 --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb-runtime/LICENSE @@ -0,0 +1,205 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + + diff --git a/java/sca/contrib/modules/binding-ejb-runtime/META-INF/MANIFEST.MF b/java/sca/contrib/modules/binding-ejb-runtime/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..6adfd6cb93 --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb-runtime/META-INF/MANIFEST.MF @@ -0,0 +1,42 @@ +Manifest-Version: 1.0 +Private-Package: org.apache.tuscany.sca.binding.ejb.corba;version="1.4 + ",org.apache.tuscany.sca.binding.ejb.provider;version="2.0.0",org.apach + e.tuscany.sca.binding.ejb.util;version="2.0.0" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA EJB Binding Runtime +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397250828 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA EJB Binding Runtime +Import-Package: javax.ejb, + javax.ejb.spi, + javax.naming, + javax.rmi, + javax.rmi.CORBA, + + net.sf.cglib.core, + net.sf.cglib.proxy, + org.apache.tuscany.sca.assembly;version="2.0.0", + org.apache.tuscany.sca.binding.ejb;version="2.0.0", + org.apache.tuscany.sca.core;version="2.0.0", + org.apache.tuscany.sca.interfacedef;version="2.0.0", + org.apache.tuscany.sca.interfacedef.java;version="2.0.0", + org.apache.tuscany.sca.invocation;version="2.0.0", + org.apache.tuscany.sca.policy;version="2.0.0", + org.apache.tuscany.sca.provider;version="2.0.0", + org.apache.tuscany.sca.runtime;version="2.0.0", + org.omg.CORBA, + org.omg.CORBA.portable, + org.omg.CORBA_2_3.portable, + org.omg.CosNaming, + org.omg.IOP, + org.omg.PortableInterceptor, + org.omg.stub.java.rmi, + org.oasisopen.sca;version="2.0.0", + org.oasisopen.sca.annotation;version="2.0.0";resolution:=optional +Bundle-SymbolicName: org.apache.tuscany.sca.binding.ejb.runtime +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/binding-ejb-runtime/NOTICE b/java/sca/contrib/modules/binding-ejb-runtime/NOTICE new file mode 100644 index 0000000000..25bb89c9b2 --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb-runtime/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/binding-ejb-runtime/pom.xml b/java/sca/contrib/modules/binding-ejb-runtime/pom.xml new file mode 100644 index 0000000000..357ecf9206 --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb-runtime/pom.xml @@ -0,0 +1,170 @@ + + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + + tuscany-binding-ejb-runtime + Apache Tuscany SCA EJB Binding Runtime + + + + org.apache.tuscany.sca + tuscany-binding-ejb + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-core-spi + 2.0-SNAPSHOT + + + + cglib + cglib-nodep + 2.2 + compile + + + + org.apache.geronimo.specs + geronimo-ejb_3.0_spec + 1.0 + compile + + + + junit + junit + 4.5 + test + + + + org.apache.tuscany.sca + tuscany-implementation-java-runtime + 2.0-SNAPSHOT + test + + + + org.apache.tuscany.sca + tuscany-node-impl + 2.0-SNAPSHOT + test + + + + org.apache.geronimo.modules + geronimo-openejb + 2.0.2 + test + + + org.apache.geronimo.modules + geronimo-connector + + + org.apache.geronimo.modules + geronimo-persistence-jpa10 + + + org.apache.openejb + openejb-ejbd + + + org.apache.openejb + openejb-server + + + org.apache.openejb + openejb-loader + + + org.apache.openejb + openejb-jee + + + org.apache.openejb + openejb-ejbd + + + org.apache.openejb + openejb-javaagent + + + com.sun.xml.bind + jaxb-impl + + + asm + asm + + + asm + asm-commons + + + + + + asm + asm-all + 3.1 + test + + + + org.apache.geronimo.specs + geronimo-jms_1.1_spec + 1.1 + + + org.apache.geronimo.specs + geronimo-jms_1.1_spec + + + + + + + + + geronimo-repository + Geronimo Repository + http://svn.apache.org/repos/asf/geronimo/server/tags/2.0.2/repository + default + + false + + + true + + + + + diff --git a/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/corba/ClassLoadingUtil.java b/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/corba/ClassLoadingUtil.java new file mode 100644 index 0000000000..c65868c23b --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/corba/ClassLoadingUtil.java @@ -0,0 +1,365 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.ejb.corba; + +import java.lang.reflect.Array; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; + +/** + * Utility class for loading classes by a variety of name variations. + *

+ * Supported names types are: + *

+ * 1) Fully qualified class name (e.g., "java.lang.String", "org.apache.geronimo.kernel.ClassLoading" + * 2) Method signature encoding ("Ljava.lang.String;", "J", "I", etc.) + * 3) Primitive type names ("int", "boolean", etc.) + * 4) Method array signature strings ("[I", "[Ljava.lang.String") + * 5) Arrays using Java code format ("int[]", "java.lang.String[][]") + *

+ * The classes are loaded using the provided class loader. For the basic types, the primitive + * reflection types are returned. + * + * @version $Rev$ $Date$ + */ +public class ClassLoadingUtil { + + /** + * Table for mapping primitive class names/signatures to the implementing + * class object + */ + private static final HashMap PRIMITIVE_CLASS_MAP = new HashMap(); + + /** + * Table for mapping primitive classes back to their name signature type, which + * allows a reverse mapping to be performed from a class object into a resolvable + * signature. + */ + private static final HashMap CLASS_TO_SIGNATURE_MAP = new HashMap(); + + + /** + * Setup the primitives map. We make any entry for each primitive class using both the + * human readable name and the method signature shorthand type. + */ + static { + PRIMITIVE_CLASS_MAP.put("boolean", boolean.class); + PRIMITIVE_CLASS_MAP.put("Z", boolean.class); + PRIMITIVE_CLASS_MAP.put("byte", byte.class); + PRIMITIVE_CLASS_MAP.put("B", byte.class); + PRIMITIVE_CLASS_MAP.put("char", char.class); + PRIMITIVE_CLASS_MAP.put("C", char.class); + PRIMITIVE_CLASS_MAP.put("short", short.class); + PRIMITIVE_CLASS_MAP.put("S", short.class); + PRIMITIVE_CLASS_MAP.put("int", int.class); + PRIMITIVE_CLASS_MAP.put("I", int.class); + PRIMITIVE_CLASS_MAP.put("long", long.class); + PRIMITIVE_CLASS_MAP.put("J", long.class); + PRIMITIVE_CLASS_MAP.put("float", float.class); + PRIMITIVE_CLASS_MAP.put("F", float.class); + PRIMITIVE_CLASS_MAP.put("double", double.class); + PRIMITIVE_CLASS_MAP.put("D", double.class); + PRIMITIVE_CLASS_MAP.put("void", void.class); + PRIMITIVE_CLASS_MAP.put("V", void.class); + + // Now build a reverse mapping table. The table above has a many-to-one mapping for + // class names. To do the reverse, we need to pick just one. As long as the + // returned name supports "round tripping" of the requests, this will work fine. + + CLASS_TO_SIGNATURE_MAP.put(boolean.class, "Z"); + CLASS_TO_SIGNATURE_MAP.put(byte.class, "B"); + CLASS_TO_SIGNATURE_MAP.put(char.class, "C"); + CLASS_TO_SIGNATURE_MAP.put(short.class, "S"); + CLASS_TO_SIGNATURE_MAP.put(int.class, "I"); + CLASS_TO_SIGNATURE_MAP.put(long.class, "J"); + CLASS_TO_SIGNATURE_MAP.put(float.class, "F"); + CLASS_TO_SIGNATURE_MAP.put(double.class, "D"); + CLASS_TO_SIGNATURE_MAP.put(void.class, "V"); + } + + + /** + * Load a class that matches the requested name, using the provided class loader context. + *

+ * The class name may be a standard class name, the name of a primitive type Java + * reflection class (e.g., "boolean" or "int"), or a type in method type signature + * encoding. Array classes in either encoding form are also processed. + * + * @param className The name of the required class. + * @param classLoader The class loader used to resolve the class object. + * @return The Class object resolved from "className". + * @throws ClassNotFoundException When unable to resolve the class object. + * @throws IllegalArgumentException If either argument is null. + */ + public static Class loadClass(String className, ClassLoader classLoader) throws ClassNotFoundException { + + // the tests require IllegalArgumentExceptions for null values on either of these. + if (className == null) { + throw new IllegalArgumentException("className is null"); + } + + if (classLoader == null) { + throw new IllegalArgumentException("classLoader is null"); + } + // The easiest case is a proper class name. We just have the class loader resolve this. + // If the class loader throws a ClassNotFoundException, then we need to check each of the + // special name encodings we support. + try { + return classLoader.loadClass(className); + } catch (ClassNotFoundException ignore) { + // if not found, continue on to the other name forms. + } + + + // The second easiest version to resolve is a direct map to a primitive type name + // or method signature. Check our name-to-class map for one of those. + Class resolvedClass = (Class) PRIMITIVE_CLASS_MAP.get(className); + if (resolvedClass != null) { + return resolvedClass; + } + + // Class names in method signature have the format "Lfully.resolved.name;", + // so if it ends in a semicolon and begins with an "L", this must be in + // this format. Have the class loader try to load this. There are no other + // options if this fails, so just allow the class loader to throw the + // ClassNotFoundException. + if (className.endsWith(";") && className.startsWith("L")) { + // pick out the name portion + String typeName = className.substring(1, className.length() - 1); + // and delegate the loading to the class loader. + return classLoader.loadClass(typeName); + } + + // All we have left now are the array types. Method signature array types + // have a series of leading "[" characters to specify the number of dimensions. + // The other array type we handle uses trailing "[]" for the dimensions, just + // like the Java language syntax. + + // first check for the signature form ([[[[type). + if (className.charAt(0) == '[') { + // we have at least one array marker, now count how many leading '['s we have + // to get the dimension count. + int count = 0; + int nameLen = className.length(); + + while (count < nameLen && className.charAt(count) == '[') { + count++; + } + + // pull of the name subtype, which is everything after the last '[' + String arrayTypeName = className.substring(count, className.length()); + // resolve the type using a recursive call, which will load any of the primitive signature + // types as well as class names. + Class arrayType = loadClass(arrayTypeName, classLoader); + + // Resolving array types require a little more work. The array classes are + // created dynamically when the first instance of a given dimension and type is + // created. We need to create one using reflection to do this. + return getArrayClass(arrayType, count); + } + + + // ok, last chance. Now check for an array specification in Java language + // syntax. This will be a type name followed by pairs of "[]" to indicate + // the number of dimensions. + if (className.endsWith("[]")) { + // get the base component class name and the arrayDimensions + int count = 0; + int position = className.length(); + + while (position > 1 && className.substring(position - 2, position).equals("[]")) { + // count this dimension + count++; + // and step back the probe position. + position -= 2; + } + + // position now points at the location of the last successful test. This makes it + // easy to pick off the class name. + + String typeName = className.substring(0, position); + + // load the base type, again, doing this recursively + Class arrayType = loadClass(typeName, classLoader); + // and turn this into the class object + return getArrayClass(arrayType, count); + } + + throw new ClassNotFoundException("Could not load class " + className + " from unknown classloader; " + classLoader); + } + + + /** + * Map a class object back to a class name. The returned class object + * must be "round trippable", which means + *

+ * type == ClassLoading.loadClass(ClassLoading.getClassName(type), classLoader) + *

+ * must be true. To ensure this, the class name is always returned in + * method signature format. + * + * @param type The class object we convert into name form. + * @return A string representation of the class name, in method signature + * format. + */ + public static String getClassName(Class type) { + StringBuffer name = new StringBuffer(); + + // we test these in reverse order from the resolution steps, + // first handling arrays, then primitive types, and finally + // "normal" class objects. + + // First handle arrays. If a class is an array, the type is + // element stored at that level. So, for a 2-dimensional array + // of ints, the top-level type will be "[I". We need to loop + // down the hierarchy until we hit a non-array type. + while (type.isArray()) { + // add another array indicator at the front of the name, + // and continue with the next type. + name.append('['); + type = type.getComponentType(); + } + + // we're down to the base type. If this is a primitive, then + // we poke in the single-character type specifier. + if (type.isPrimitive()) { + name.append((String) CLASS_TO_SIGNATURE_MAP.get(type)); + } + // a "normal" class. This gets expressing using the "Lmy.class.name;" syntax. + else { + name.append('L'); + name.append(type.getName()); + name.append(';'); + } + return name.toString(); + } + + private static Class getArrayClass(Class type, int dimension) { + // Array.newInstance() requires an array of the requested number of dimensions + // that gives the size for each dimension. We just request 0 in each of the + // dimensions, which is not unlike a black hole singularity. + int[] dimensions = new int[dimension]; + // create an instance and return the associated class object. + return Array.newInstance(type, dimensions).getClass(); + } + + public static Set getAllTypes(Class type) { + Set allTypes = new LinkedHashSet(); + allTypes.add(type); + allTypes.addAll(getAllSuperClasses(type)); + allTypes.addAll(getAllInterfaces(type)); + return allTypes; + } + + private static Set getAllSuperClasses(Class clazz) { + Set allSuperClasses = new LinkedHashSet(); + for (Class superClass = clazz.getSuperclass(); superClass != null; superClass = superClass.getSuperclass()) { + allSuperClasses.add(superClass); + } + return allSuperClasses; + } + + private static Set getAllInterfaces(Class clazz) { + Set allInterfaces = new LinkedHashSet(); + LinkedList stack = new LinkedList(); + stack.addAll(Arrays.asList(clazz.getInterfaces())); + while (!stack.isEmpty()) { + Class intf = (Class) stack.removeFirst(); + if (!allInterfaces.contains(intf)) { + allInterfaces.add(intf); + stack.addAll(Arrays.asList(intf.getInterfaces())); + } + } + return allInterfaces; + } + + public static Set reduceInterfaces(Set source) { + Class[] classes = (Class[]) source.toArray(new Class[source.size()]); + classes = reduceInterfaces(classes); + return new LinkedHashSet(Arrays.asList(classes)); + } + + /** + * If there are multiple interfaces, and some of them extend each other, + * eliminate the superclass in favor of the subclasses that extend them. + * + * If one of the entries is a class (not an interface), make sure it's + * the first one in the array. If more than one of the entries is a + * class, throws an IllegalArgumentException + * + * @param source the original list of interfaces + * @return the equal or smaller list of interfaces + */ + public static Class[] reduceInterfaces(Class[] source) { + // use a copy of the source array + source = (Class[]) source.clone(); + + for (int leftIndex = 0; leftIndex < source.length-1; leftIndex++) { + Class left = source[leftIndex]; + if(left == null) { + continue; + } + + for (int rightIndex = leftIndex +1; rightIndex < source.length; rightIndex++) { + Class right = source[rightIndex]; + if(right == null) { + continue; + } + + if(left == right || right.isAssignableFrom(left)) { + // right is the same as class or a sub class of left + source[rightIndex] = null; + } else if(left.isAssignableFrom(right)) { + // left is the same as class or a sub class of right + source[leftIndex] = null; + + // the left has been eliminated; move on to the next left + break; + } + } + } + + Class clazz = null; + for (int i = 0; i < source.length; i++) { + if (source[i] != null && !source[i].isInterface()) { + if (clazz != null) { + throw new IllegalArgumentException("Source contains two classes which are not subclasses of each other: " + clazz.getName() + ", " + source[i].getName()); + } + clazz = source[i]; + source[i] = null; + } + } + + List list = new ArrayList(source.length); + if (clazz != null) list.add(clazz); + for (int i = 0; i < source.length; i++) { + if(source[i] != null) { + list.add(source[i]); + } + } + return (Class[]) list.toArray(new Class[list.size()]); + } +} + diff --git a/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/corba/DynamicStubClassLoader.java b/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/corba/DynamicStubClassLoader.java new file mode 100644 index 0000000000..82554a1c8f --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/corba/DynamicStubClassLoader.java @@ -0,0 +1,150 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.ejb.corba; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + +import javax.rmi.CORBA.Stub; + +import net.sf.cglib.core.NamingPolicy; +import net.sf.cglib.core.Predicate; +import net.sf.cglib.proxy.Callback; +import net.sf.cglib.proxy.CallbackFilter; +import net.sf.cglib.proxy.Enhancer; +import net.sf.cglib.proxy.FixedValue; +import net.sf.cglib.proxy.MethodInterceptor; +import net.sf.cglib.proxy.NoOp; + +/** + * @version $Revision$ $Date$ + */ +public class DynamicStubClassLoader extends ClassLoader { + private static final String PACKAGE_PREFIX = "org.omg.stub."; + + @Override + public synchronized Class loadClass(final String name) throws ClassNotFoundException { + ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); + + // check if the stub already exists first + try { + return classLoader.loadClass(name); + } catch (ClassNotFoundException e) { + } + + // if this is not a class from the org.omg.stub name space don't attempt to generate + if (!name.startsWith(PACKAGE_PREFIX)) { + throw new ClassNotFoundException("Could not load class: " + name); + } + + // load the interfaces class we are attempting to create a stub for + Class iface = loadStubInterfaceClass(name, classLoader); + + // create the stub builder + try { + Enhancer enhancer = new Enhancer(); + enhancer.setSuperclass(Stub.class); + enhancer.setInterfaces(new Class[] {iface}); + enhancer.setCallbackFilter(FILTER); + enhancer.setCallbackTypes(new Class[] {NoOp.class, MethodInterceptor.class, FixedValue.class}); + enhancer.setUseFactory(false); + enhancer.setClassLoader(classLoader); + enhancer.setNamingPolicy(new NamingPolicy() { + public String getClassName(String s, String s1, Object o, Predicate predicate) { + return name; + } + }); + + // generate the class + Class result = enhancer.createClass(); + assert result != null; + + StubMethodInterceptor interceptor = new StubMethodInterceptor(iface); + Ids ids = new Ids(iface); + Enhancer.registerStaticCallbacks(result, new Callback[] {NoOp.INSTANCE, interceptor, ids}); + + return result; + } catch (RuntimeException e) { + throw e; + } catch (Error e) { + throw e; + } + } + + private Class loadStubInterfaceClass(String name, ClassLoader classLoader) throws ClassNotFoundException { + try { + int begin = name.lastIndexOf('.') + 1; + String iPackage = name.substring(13, begin); + String iName = iPackage + name.substring(begin + 1, name.length() - 5); + + return classLoader.loadClass(iName); + } catch (ClassNotFoundException e) { + // don't log exceptions from CosNaming because it attempts to load every + // class bound into the name server + + //FIXME this variable is never read, can we remove the + // whole block of code?? + //boolean shouldLog = true; + StackTraceElement[] stackTrace = e.getStackTrace(); + for (int i = 0; i < stackTrace.length; i++) { + StackTraceElement stackTraceElement = stackTrace[i]; + if (stackTraceElement.getClassName().equals("org.omg.CosNaming.NamingContextExtPOA") && stackTraceElement + .getMethodName().equals("_invoke")) { + //shouldLog = false; + break; + } + } + + throw new ClassNotFoundException("Unable to generate stub", e); + } + } + + private static final CallbackFilter FILTER = new CallbackFilter() { + public int accept(Method method) { + // we don't intercept non-public methods like finalize + if (!Modifier.isPublic(method.getModifiers())) { + return 0; + } + + if (method.getReturnType().equals(String[].class) && method.getParameterTypes().length == 0 + && method.getName().equals("_ids")) { + return 2; + } + + if (Modifier.isAbstract(method.getModifiers())) { + return 1; + } + + return 0; + } + }; + + private static final class Ids implements FixedValue { + private final String[] typeIds; + + public Ids(Class type) { + typeIds = Java2IDLUtil.createCorbaIds(type); + } + + public Object loadObject() throws Exception { + return typeIds; + } + } + +} diff --git a/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/corba/Java2IDLUtil.java b/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/corba/Java2IDLUtil.java new file mode 100644 index 0000000000..de8090c45b --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/corba/Java2IDLUtil.java @@ -0,0 +1,811 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.ejb.corba; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.io.UnsupportedEncodingException; +import java.lang.reflect.Method; +import java.rmi.Remote; +import java.rmi.RemoteException; +import java.rmi.UnexpectedException; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.ejb.spi.HandleDelegate; +import javax.naming.InitialContext; +import javax.naming.NamingException; +import javax.rmi.PortableRemoteObject; + +import org.omg.CORBA.ORB; +import org.omg.CORBA.UserException; +import org.omg.CORBA.portable.IDLEntity; +import org.omg.CORBA.portable.ResponseHandler; +import org.omg.CORBA.portable.UnknownException; +import org.omg.CORBA_2_3.portable.InputStream; +import org.omg.CORBA_2_3.portable.OutputStream; +import org.omg.IOP.Codec; +import org.omg.IOP.CodecFactory; +import org.omg.IOP.ENCODING_CDR_ENCAPS; +import org.omg.IOP.Encoding; + +/** + * Various utility functions. + *

+ * Note: #getORB() and #getCodec() rely on UtilInitializer to initialize the ORB and codec. + * + * @version $Rev$ $Date$ + * @see UtilInitializer + */ +public final class Java2IDLUtil { + private static ORB orb; + private static Codec codec; + private static HandleDelegate handleDelegate; + + public static ORB getORB() { + assert orb != null; + return orb; + } + + + + public static void setORB(ORB orb) throws UserException { + if (Java2IDLUtil.orb == null) { + Java2IDLUtil.orb = orb; + CodecFactory factory = (CodecFactory) Java2IDLUtil.orb.resolve_initial_references("CodecFactory"); + codec = factory.create_codec(new Encoding(ENCODING_CDR_ENCAPS.value, (byte) 1, (byte) 2)); + } + } + + public static Codec getCodec() { + assert codec != null; + return codec; + } + + public static HandleDelegate getHandleDelegate() throws NamingException { + if (handleDelegate == null) { + InitialContext ic = new InitialContext(); + handleDelegate = (HandleDelegate) ic.lookup("java:comp/HandleDelegate"); + } + return handleDelegate; + } + + private static final Pattern SCOPED_NAME_EXTRACTION_PATTERN = Pattern.compile("(\\\\\\\\)|(\\\\@)|(@)|(\\z)"); + + /** + * See csiv2 Specification 16.2.5 par. 63-64. We extract the username if any and un-escape any + * escaped \ and @ characters. + * + * @param scopedNameBytes + * @return + * @throws UnsupportedEncodingException + */ + public static String extractUserNameFromScopedName(byte[] scopedNameBytes) throws UnsupportedEncodingException { + String scopedUserName = new String(scopedNameBytes, "UTF8"); + return extractUserNameFromScopedName(scopedUserName); + } + + public static String extractUserNameFromScopedName(String scopedUserName) { + Matcher m = SCOPED_NAME_EXTRACTION_PATTERN.matcher(scopedUserName); + StringBuffer buf = new StringBuffer(); + while (m.find()) { + m.appendReplacement(buf, ""); + if (m.group(1) != null) { + buf.append('\\'); + } else if (m.group(2) != null) { + buf.append("@"); + } else if (m.group(3) != null) { + break; + } + } + return buf.toString(); + } + + private static final Pattern SCOPED_NAME_ESCAPE_PATTERN = Pattern.compile("(\\\\)|(@)"); + + public static String buildScopedUserName(String user, String domain) { + StringBuffer buf = new StringBuffer(); + if (user != null) { + escape(user, buf); + } + if (domain != null) { + buf.append('@'); + escape(domain, buf); + } + return buf.toString(); + } + + private static void escape(String s, StringBuffer buf) { + Matcher m = SCOPED_NAME_ESCAPE_PATTERN.matcher(s); + while (m.find()) { + m.appendReplacement(buf, ""); + if (m.group(1) != null) { + buf.append("\\\\"); + } else if (m.group(2) != null) { + buf.append("\\@"); + } + } + m.appendTail(buf); + } + + + public static String byteToString(byte[] data) { + StringBuffer buffer = new StringBuffer(); + for (int i = 0; i < data.length; i++) { + buffer.append(HEXCHAR[(data[i] >>> 4) & 0x0F]); + buffer.append(HEXCHAR[(data[i]) & 0x0F]); + } + return buffer.toString(); + + } + + private static final char[] HEXCHAR = { + '0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' + }; + + public static void writeObject(Class type, Object object, OutputStream out) { + if (type == Void.TYPE) { + // do nothing for a void + } else if (type == Boolean.TYPE) { + out.write_boolean(((Boolean) object).booleanValue()); + } else if (type == Byte.TYPE) { + out.write_octet(((Byte) object).byteValue()); + } else if (type == Character.TYPE) { + out.write_wchar(((Character) object).charValue()); + } else if (type == Double.TYPE) { + out.write_double(((Double) object).doubleValue()); + } else if (type == Float.TYPE) { + out.write_float(((Float) object).floatValue()); + } else if (type == Integer.TYPE) { + out.write_long(((Integer) object).intValue()); + } else if (type == Long.TYPE) { + out.write_longlong(((Long) object).longValue()); + } else if (type == Short.TYPE) { + out.write_short(((Short) object).shortValue()); + } else { + // object types must be written in the context of the CORBA application server + // which properly write replaces our objects for CORBA + // ApplicationServer oldApplicationServer = ServerFederation.getApplicationServer(); + try { + // ServerFederation.setApplicationServer(corbaApplicationServer); + + // todo check if + // copy the result to force replacement + // CORBA does not call writeReplace on remote proxies + // + // HOWEVER, if this is an array, then we don't want to do the replacement + // because we can end up with a replacement element that's not compatible with the + // original array type, which results in an ArrayStoreException. Fortunately, + // the Yoko RMI support appears to be able to sort this out for us correctly. + if (object instanceof Serializable && !object.getClass().isArray()) { + try { + object = copyObj(Thread.currentThread().getContextClassLoader(), object); + } catch (Exception e) { + throw new UnknownException(e); + } + } + + if (type == Object.class || type == Serializable.class) { + javax.rmi.CORBA.Util.writeAny(out, object); + } else if (org.omg.CORBA.Object.class.isAssignableFrom(type)) { + out.write_Object((org.omg.CORBA.Object) object); + } else if (Remote.class.isAssignableFrom(type)) { + javax.rmi.CORBA.Util.writeRemoteObject(out, object); + } else if (type.isInterface() && Serializable.class.isAssignableFrom(type)) { + javax.rmi.CORBA.Util.writeAbstractObject(out, object); + } else { + out.write_value((Serializable) object, type); + } + } finally { + // ServerFederation.setApplicationServer(oldApplicationServer); + } + } + } + + private static Object copyObj(ClassLoader classLoader, Object object) throws IOException, ClassNotFoundException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(baos); + oos.writeObject(object); + oos.flush(); + oos.close(); + ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); + ObjectInputStreamExt ois = new ObjectInputStreamExt(bais, classLoader); + return ois.readObject(); + } + + public static Object readObject(Class type, InputStream in) { + if (type == Void.TYPE) { + return null; + } else if (type == Boolean.TYPE) { + return new Boolean(in.read_boolean()); + } else if (type == Byte.TYPE) { + return new Byte(in.read_octet()); + } else if (type == Character.TYPE) { + return new Character(in.read_wchar()); + } else if (type == Double.TYPE) { + return new Double(in.read_double()); + } else if (type == Float.TYPE) { + return new Float(in.read_float()); + } else if (type == Integer.TYPE) { + return new Integer(in.read_long()); + } else if (type == Long.TYPE) { + return new Long(in.read_longlong()); + } else if (type == Short.TYPE) { + return new Short(in.read_short()); + } else if (type == Object.class || type == Serializable.class) { + return javax.rmi.CORBA.Util.readAny(in); + } else if (org.omg.CORBA.Object.class.isAssignableFrom(type)) { + return in.read_Object(type); + } else if (Remote.class.isAssignableFrom(type)) { + return PortableRemoteObject.narrow(in.read_Object(), type); + } else if (type.isInterface() && Serializable.class.isAssignableFrom(type)) { + return in.read_abstract_interface(); + } else { + return in.read_value(type); + } + } + + public static void throwException(Method method, InputStream in) throws Throwable { + // read the exception id + final String id = in.read_string(); + + // get the class name from the id + if (!id.startsWith("IDL:")) { + return; + } + + Class[] exceptionTypes = method.getExceptionTypes(); + for (int i = 0; i < exceptionTypes.length; i++) { + Class exceptionType = exceptionTypes[i]; + + String exceptionId = getExceptionId(exceptionType); + if (id.equals(exceptionId)) { + throw (Throwable) in.read_value(exceptionType); + } + } + throw new UnexpectedException(id); + } + + public static OutputStream writeUserException(Method method, ResponseHandler reply, Exception exception) throws Exception { + if (exception instanceof RuntimeException || exception instanceof RemoteException) { + throw exception; + } + + Class[] exceptionTypes = method.getExceptionTypes(); + for (int i = 0; i < exceptionTypes.length; i++) { + Class exceptionType = exceptionTypes[i]; + if (!exceptionType.isInstance(exception)) { + continue; + } + + OutputStream out = (OutputStream) reply.createExceptionReply(); + String exceptionId = getExceptionId(exceptionType); + out.write_string(exceptionId); + out.write_value(exception); + return out; + } + throw exception; + } + + public static String getExceptionId(Class exceptionType) { + String exceptionName = exceptionType.getName().replace('.', '/'); + if (exceptionName.endsWith("Exception")) { + exceptionName = exceptionName.substring(0, exceptionName.length() - "Exception".length()); + } + exceptionName += "Ex"; + String exceptionId = "IDL:" + exceptionName + ":1.0"; + return exceptionId; + } + + public static String[] createCorbaIds(Class type) { + List ids = new LinkedList(); + for (Iterator iterator = getAllInterfaces(type).iterator(); iterator.hasNext();) { + Class superInterface = (Class) iterator.next(); + if (Remote.class.isAssignableFrom(superInterface) && superInterface != Remote.class) { + ids.add("RMI:" + superInterface.getName() + ":0000000000000000"); + } + } + return (String[]) ids.toArray(new String[ids.size()]); + } + + private static Set getAllInterfaces(Class intfClass) { + Set allInterfaces = new LinkedHashSet(); + + LinkedList stack = new LinkedList(); + stack.addFirst(intfClass); + + while (!stack.isEmpty()) { + Class intf = (Class) stack.removeFirst(); + allInterfaces.add(intf); + stack.addAll(0, Arrays.asList(intf.getInterfaces())); + } + + return allInterfaces; + } + + public static Map mapMethodToOperation(Class intfClass) { + return iiopMap(intfClass, false); + } + + public static Map mapOperationToMethod(Class intfClass) { + return iiopMap(intfClass, true); + } + + private static Map iiopMap(Class intfClass, boolean operationToMethod) { + Method[] methods = getAllMethods(intfClass); + + // find every valid getter + HashMap getterByMethod = new HashMap(methods.length); + HashMap getterByName = new HashMap(methods.length); + for (int i = 0; i < methods.length; i++) { + Method method = methods[i]; + String methodName = method.getName(); + + // no arguments allowed + if (method.getParameterTypes().length != 0) { + continue; + } + + // must start with get or is + String verb; + if (methodName.startsWith("get") && methodName.length() > 3 && method.getReturnType() != void.class) { + verb = "get"; + } else if (methodName.startsWith("is") && methodName.length() > 2 && method.getReturnType() == boolean.class) { + verb = "is"; + } else { + continue; + } + + // must only throw Remote or Runtime Exceptions + boolean exceptionsValid = true; + Class[] exceptionTypes = method.getExceptionTypes(); + for (int j = 0; j < exceptionTypes.length; j++) { + Class exceptionType = exceptionTypes[j]; + if (!RemoteException.class.isAssignableFrom(exceptionType) && + !RuntimeException.class.isAssignableFrom(exceptionType) && + !Error.class.isAssignableFrom(exceptionType)) { + exceptionsValid = false; + break; + } + } + if (!exceptionsValid) { + continue; + } + + String propertyName; + if (methodName.length() > verb.length() + 1 && Character.isUpperCase(methodName.charAt(verb.length() + 1))) { + propertyName = methodName.substring(verb.length()); + } else { + propertyName = Character.toLowerCase(methodName.charAt(verb.length())) + methodName.substring(verb.length() + 1); + } + getterByMethod.put(method, propertyName); + getterByName.put(propertyName, method); + } + + HashMap setterByMethod = new HashMap(methods.length); + for (int i = 0; i < methods.length; i++) { + Method method = methods[i]; + String methodName = method.getName(); + + // must have exactally one arg + if (method.getParameterTypes().length != 1) { + continue; + } + + // must return non void + if (method.getReturnType() != void.class) { + continue; + } + + // must start with set + if (!methodName.startsWith("set") || methodName.length() <= 3) { + continue; + } + + // must only throw Remote or Runtime Exceptions + boolean exceptionsValid = true; + Class[] exceptionTypes = method.getExceptionTypes(); + for (int j = 0; j < exceptionTypes.length; j++) { + Class exceptionType = exceptionTypes[j]; + if (!RemoteException.class.isAssignableFrom(exceptionType) && + !RuntimeException.class.isAssignableFrom(exceptionType) && + !Error.class.isAssignableFrom(exceptionType)) { + exceptionsValid = false; + break; + } + } + if (!exceptionsValid) { + continue; + } + + String propertyName; + if (methodName.length() > 4 && Character.isUpperCase(methodName.charAt(4))) { + propertyName = methodName.substring(3); + } else { + propertyName = Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4); + } + + // must have a matching getter + Method getter = (Method) getterByName.get(propertyName); + if (getter == null) { + continue; + } + + // setter property must match getter return value + if (!method.getParameterTypes()[0].equals(getter.getReturnType())) { + continue; + } + setterByMethod.put(method, propertyName); + } + + // index the methods by name... used to determine which methods are overloaded + HashMap overloadedMethods = new HashMap(methods.length); + for (int i = 0; i < methods.length; i++) { + Method method = methods[i]; + if (getterByMethod.containsKey(method) || setterByMethod.containsKey(method)) { + continue; + } + String methodName = method.getName(); + List methodList = (List) overloadedMethods.get(methodName); + if (methodList == null) { + methodList = new LinkedList(); + overloadedMethods.put(methodName, methodList); + } + methodList.add(method); + } + + // index the methods by lower case name... used to determine which methods differ only by case + HashMap caseCollisionMethods = new HashMap(methods.length); + for (int i = 0; i < methods.length; i++) { + Method method = methods[i]; + if (getterByMethod.containsKey(method) || setterByMethod.containsKey(method)) { + continue; + } + String lowerCaseMethodName = method.getName().toLowerCase(); + Set methodSet = (Set) caseCollisionMethods.get(lowerCaseMethodName); + if (methodSet == null) { + methodSet = new HashSet(); + caseCollisionMethods.put(lowerCaseMethodName, methodSet); + } + methodSet.add(method.getName()); + } + + String className = getClassName(intfClass); + Map iiopMap = new HashMap(methods.length); + for (int i = 0; i < methods.length; i++) { + Method method = methods[i]; + + String iiopName = (String) getterByMethod.get(method); + if (iiopName != null) { + // if we have a leading underscore prepend with J + if (iiopName.charAt(0) == '_') { + iiopName = "J_get_" + iiopName.substring(1); + } else { + iiopName = "_get_" + iiopName; + } + } else { + iiopName = (String) setterByMethod.get(method); + if (iiopName != null) { + // if we have a leading underscore prepend with J + if (iiopName.charAt(0) == '_') { + iiopName = "J_set_" + iiopName.substring(1); + } else { + iiopName = "_set_" + iiopName; + } + } else { + iiopName = method.getName(); + + // if we have a leading underscore prepend with J + if (iiopName.charAt(0) == '_') { + iiopName = "J" + iiopName; + } + } + } + + // if this name only differs by case add the case index to the end + Set caseCollisions = (Set) caseCollisionMethods.get(method.getName().toLowerCase()); + if (caseCollisions != null && caseCollisions.size() > 1) { + iiopName += upperCaseIndexString(iiopName); + } + + // if this is an overloaded method append the parameter string + List overloads = (List) overloadedMethods.get(method.getName()); + if (overloads != null && overloads.size() > 1) { + iiopName += buildOverloadParameterString(method.getParameterTypes()); + } + + // if we have a leading underscore prepend with J + iiopName = replace(iiopName, '$', "U0024"); + + // if we have matched a keyword prepend with an underscore + if (keywords.contains(iiopName.toLowerCase())) { + iiopName = "_" + iiopName; + } + + // if the name is the same as the class name, append an underscore + if (iiopName.equalsIgnoreCase(className)) { + iiopName += "_"; + } + + if (operationToMethod) { + iiopMap.put(iiopName, method); + } else { + iiopMap.put(method, iiopName); + } + } + + return iiopMap; + } + + private static Method[] getAllMethods(Class intfClass) { + LinkedList methods = new LinkedList(); + for (Iterator iterator = getAllInterfaces(intfClass).iterator(); iterator.hasNext();) { + Class intf = (Class) iterator.next(); + methods.addAll(Arrays.asList(intf.getDeclaredMethods())); + } + + return (Method[]) methods.toArray(new Method[methods.size()]); + } + + /** + * Return the a string containing an underscore '_' index of each uppercase character in the IIOP name. + * + * This is used for distinction of names that only differ by case, since CORBA does not support case sensitive names. + */ + private static String upperCaseIndexString(String iiopName) { + StringBuffer stringBuffer = new StringBuffer(); + for (int i = 0; i < iiopName.length(); i++) { + char c = iiopName.charAt(i); + if (Character.isUpperCase(c)) { + stringBuffer.append('_').append(i); + } + } + return stringBuffer.toString(); + } + + /** + * Replaces any occurances of the specified "oldChar" with the new string. + * + * This is used to replace occurances if '$' in CORBA names since '$' is a special character + */ + private static String replace(String source, char oldChar, String newString) { + StringBuffer stringBuffer = new StringBuffer(source.length()); + for (int i = 0; i < source.length(); i++) { + char c = source.charAt(i); + if (c == oldChar) { + stringBuffer.append(newString); + } else { + stringBuffer.append(c); + } + } + return stringBuffer.toString(); + } + + /** + * Return the a string containing a double underscore '__' list of parameter types encoded using the Java to IDL rules. + * + * This is used for distinction of methods that only differ by parameter lists. + */ + private static String buildOverloadParameterString(Class[] parameterTypes) { + String name = ""; + if (parameterTypes.length ==0) { + name += "__"; + } else { + for (int i = 0; i < parameterTypes.length; i++) { + Class parameterType = parameterTypes[i]; + name += buildOverloadParameterString(parameterType); + } + } + return name.replace('.', '_'); + } + + /** + * Returns a single parameter type encoded using the Java to IDL rules. + */ + private static String buildOverloadParameterString(Class parameterType) { + String name = "_"; + + int arrayDimensions = 0; + while (parameterType.isArray()) { + arrayDimensions++; + parameterType = parameterType.getComponentType(); + } + + // arrays start with org_omg_boxedRMI_ + if (arrayDimensions > 0) { + name += "_org_omg_boxedRMI"; + } + + // IDLEntity types must be prefixed with org_omg_boxedIDL_ + if (IDLEntity.class.isAssignableFrom(parameterType)) { + name += "_org_omg_boxedIDL"; + } + + // add package... some types have special mappings in corba + String packageName = (String) specialTypePackages.get(parameterType.getName()); + if (packageName == null) { + packageName = getPackageName(parameterType.getName()); + } + if (packageName.length() > 0) { + name += "_" + packageName; + } + + // arrays now contain a dimension indicator + if (arrayDimensions > 0) { + name += "_" + "seq" + arrayDimensions; + } + + // add the class name + String className = (String) specialTypeNames.get(parameterType.getName()); + if (className == null) { + className = buildClassName(parameterType); + } + name += "_" + className; + + return name; + } + + /** + * Returns a string containing an encoded class name. + */ + private static String buildClassName(Class type) { + if (type.isArray()) { + throw new IllegalArgumentException("type is an array: " + type); + } + + // get the classname + String typeName = type.getName(); + int endIndex = typeName.lastIndexOf('.'); + if (endIndex < 0) { + return typeName; + } + StringBuffer className = new StringBuffer(typeName.substring(endIndex + 1)); + + // for innerclasses replace the $ separator with two underscores + // we can't just blindly replace all $ characters since class names can contain the $ character + if (type.getDeclaringClass() != null) { + String declaringClassName = getClassName(type.getDeclaringClass()); + assert className.toString().startsWith(declaringClassName + "$"); + className.replace(declaringClassName.length(), declaringClassName.length() + 1, "__"); + } + + // if we have a leading underscore prepend with J + if (className.charAt(0) == '_') { + className.insert(0, "J"); + } + return className.toString(); + } + + private static String getClassName(Class type) { + if (type.isArray()) { + throw new IllegalArgumentException("type is an array: " + type); + } + + // get the classname + String typeName = type.getName(); + int endIndex = typeName.lastIndexOf('.'); + if (endIndex < 0) { + return typeName; + } + return typeName.substring(endIndex + 1); + } + + private static String getPackageName(String interfaceName) { + int endIndex = interfaceName.lastIndexOf('.'); + if (endIndex < 0) { + return ""; + } + return interfaceName.substring(0, endIndex); + } + + private static final Map specialTypeNames; + private static final Map specialTypePackages; + private static final Set keywords; + + static { + specialTypeNames = new HashMap(); + specialTypeNames.put("boolean", "boolean"); + specialTypeNames.put("char", "wchar"); + specialTypeNames.put("byte", "octet"); + specialTypeNames.put("short", "short"); + specialTypeNames.put("int", "long"); + specialTypeNames.put("long", "long_long"); + specialTypeNames.put("float", "float"); + specialTypeNames.put("double", "double"); + specialTypeNames.put("java.lang.Class", "ClassDesc"); + specialTypeNames.put("java.lang.String", "WStringValue"); + specialTypeNames.put("org.omg.CORBA.Object", "Object"); + + specialTypePackages = new HashMap(); + specialTypePackages.put("boolean", ""); + specialTypePackages.put("char", ""); + specialTypePackages.put("byte", ""); + specialTypePackages.put("short", ""); + specialTypePackages.put("int", ""); + specialTypePackages.put("long", ""); + specialTypePackages.put("float", ""); + specialTypePackages.put("double", ""); + specialTypePackages.put("java.lang.Class", "javax.rmi.CORBA"); + specialTypePackages.put("java.lang.String", "CORBA"); + specialTypePackages.put("org.omg.CORBA.Object", ""); + + keywords = new HashSet(); + keywords.add("abstract"); + keywords.add("any"); + keywords.add("attribute"); + keywords.add("boolean"); + keywords.add("case"); + keywords.add("char"); + keywords.add("const"); + keywords.add("context"); + keywords.add("custom"); + keywords.add("default"); + keywords.add("double"); + keywords.add("enum"); + keywords.add("exception"); + keywords.add("factory"); + keywords.add("false"); + keywords.add("fixed"); + keywords.add("float"); + keywords.add("in"); + keywords.add("inout"); + keywords.add("interface"); + keywords.add("long"); + keywords.add("module"); + keywords.add("native"); + keywords.add("object"); + keywords.add("octet"); + keywords.add("oneway"); + keywords.add("out"); + keywords.add("private"); + keywords.add("public"); + keywords.add("raises"); + keywords.add("readonly"); + keywords.add("sequence"); + keywords.add("short"); + keywords.add("string"); + keywords.add("struct"); + keywords.add("supports"); + keywords.add("switch"); + keywords.add("true"); + keywords.add("truncatable"); + keywords.add("typedef"); + keywords.add("union"); + keywords.add("unsigned"); + keywords.add("valuebase"); + keywords.add("valuetype"); + keywords.add("void"); + keywords.add("wchar"); + keywords.add("wstring"); + } + +} diff --git a/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/corba/ObjectInputStreamExt.java b/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/corba/ObjectInputStreamExt.java new file mode 100644 index 0000000000..1be4a98a48 --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/corba/ObjectInputStreamExt.java @@ -0,0 +1,61 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.ejb.corba; + +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectInputStream; +import java.io.ObjectStreamClass; +import java.lang.reflect.Proxy; + +/** + * @version $Rev$ $Date$ + */ +public class ObjectInputStreamExt extends ObjectInputStream { + + private ClassLoader classloader; + + public ObjectInputStreamExt(InputStream in, ClassLoader loader) throws IOException { + super(in); + this.classloader = loader; + } + + @Override + protected Class resolveClass(ObjectStreamClass classDesc) throws IOException, ClassNotFoundException { + return ClassLoadingUtil.loadClass(classDesc.getName(), classloader); + } + + @Override + protected Class resolveProxyClass(String[] interfaces) throws IOException, ClassNotFoundException { + Class[] cinterfaces = new Class[interfaces.length]; + for (int i = 0; i < interfaces.length; i++) + cinterfaces[i] = classloader.loadClass(interfaces[i]); + + try { + return Proxy.getProxyClass(classloader, cinterfaces); + } catch (IllegalArgumentException e) { + throw new ClassNotFoundException(null, e); + } + } + + ClassLoader getClassloader() { + return classloader; + } + +} diff --git a/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/corba/StubMethodInterceptor.java b/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/corba/StubMethodInterceptor.java new file mode 100644 index 0000000000..3ff0ed552a --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/corba/StubMethodInterceptor.java @@ -0,0 +1,154 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.ejb.corba; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Collections; +import java.util.Map; + +import javax.ejb.EJBObject; +import javax.rmi.CORBA.Stub; +import javax.rmi.CORBA.Util; + +import net.sf.cglib.proxy.MethodInterceptor; +import net.sf.cglib.proxy.MethodProxy; + +import org.omg.CORBA.SystemException; +import org.omg.CORBA.portable.ApplicationException; +import org.omg.CORBA.portable.RemarshalException; +import org.omg.CORBA.portable.ServantObject; +import org.omg.CORBA_2_3.portable.InputStream; +import org.omg.CORBA_2_3.portable.OutputStream; + +/** + * @version $Revision$ $Date$ + */ +public class StubMethodInterceptor implements MethodInterceptor { + private static final Method ISIDENTICAL; + + static { + try { + ISIDENTICAL = EJBObject.class.getMethod("isIdentical", new Class[]{EJBObject.class}); + } catch (NoSuchMethodException e) { + throw new ExceptionInInitializerError(e); + } + } + + private final Class type; + private final Map operations; + + public StubMethodInterceptor(Class type) { + this.type = type; + this.operations = Collections.unmodifiableMap(org.apache.tuscany.sca.binding.ejb.corba.Java2IDLUtil.mapMethodToOperation(type)); + } + + public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { + Stub stub = (Stub) proxy; + + // handle is identical in stub to avoid unnecessary round trip + if (method.equals(ISIDENTICAL)) { + org.omg.CORBA.Object otherObject = (org.omg.CORBA.Object) args[0]; + return new Boolean(stub._is_equivalent(otherObject)); + } + + // get the operation name object + String operationName = (String) operations.get(method); + if (operationName == null) { + throw new IllegalStateException("Unknown method: " + method); + } + + while (true) { + // if this is a stub to a remote object we invoke over the wire + if (!Util.isLocal(stub)) { + + InputStream in = null; + try { + // create the request output stream + OutputStream out = (OutputStream) stub._request(operationName, true); + + // write the arguments + Class[] parameterTypes = method.getParameterTypes(); + for (int i = 0; i < parameterTypes.length; i++) { + Class parameterType = parameterTypes[i]; + org.apache.tuscany.sca.binding.ejb.corba.Java2IDLUtil.writeObject(parameterType, args[i], out); + } + + // send the invocation + in = (InputStream) stub._invoke(out); + + // read the result + Object result = org.apache.tuscany.sca.binding.ejb.corba.Java2IDLUtil.readObject(method.getReturnType(), in); + return result; + } catch (RemarshalException exception) { + continue; + } catch (ApplicationException exception) { + org.apache.tuscany.sca.binding.ejb.corba.Java2IDLUtil.throwException(method, (InputStream) exception.getInputStream()); + } catch (SystemException e) { + throw Util.mapSystemException(e); + } finally { + stub._releaseReply(in); + } + } else { + // get the servant + ServantObject servantObject = stub._servant_preinvoke(operationName, type); + if (servantObject == null) { + continue; + } + + try { + // copy the arguments + Object[] argsCopy = Util.copyObjects(args, stub._orb()); + + // invoke the servant + Object result = null; + try { + result = method.invoke(servantObject.servant, argsCopy); + } catch (InvocationTargetException e) { + if (e.getCause() != null) { + throw e.getCause(); + } + throw e; + } + + // copy the result + result = Util.copyObject(result, stub._orb()); + + return result; + } catch (Throwable throwable) { + // copy the exception + Throwable throwableCopy = (Throwable) Util.copyObject(throwable, stub._orb()); + + // if it is one of my exception rethrow it + Class[] exceptionTypes = method.getExceptionTypes(); + for (int i = 0; i < exceptionTypes.length; i++) { + Class exceptionType = exceptionTypes[i]; + if (exceptionType.isInstance(throwableCopy)) { + throw throwableCopy; + } + } + + throw Util.wrapException(throwableCopy); + } finally { + stub._servant_postinvoke(servantObject); + } + } + } + } +} diff --git a/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/corba/UtilInitializer.java b/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/corba/UtilInitializer.java new file mode 100644 index 0000000000..f9aa9ffa22 --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/corba/UtilInitializer.java @@ -0,0 +1,69 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.ejb.corba; + +import org.omg.CORBA.LocalObject; +import org.omg.PortableInterceptor.ORBInitInfo; +import org.omg.PortableInterceptor.ORBInitializer; + +/** + * The sole purpose of this initializer is to register a non-singleton ORB + * with the class Util. + * + * @version $Revision$ $Date$ + * @see Java2IDLUtil + */ +public class UtilInitializer extends LocalObject implements ORBInitializer { + + private static final long serialVersionUID = 4901857563505370955L; + + /** + * Called during ORB initialization. If it is expected that initial + * services registered by an interceptor will be used by other + * interceptors, then those initial services shall be registered at + * this point via calls to + * ORBInitInfo.register_initial_reference. + * + * @param info provides initialization attributes and operations by + * which Interceptors can be registered. + */ + public void pre_init(ORBInitInfo info) { + } + + /** + * Called during ORB initialization. If a service must resolve initial + * references as part of its initialization, it can assume that all + * initial references will be available at this point. + *

+ * Calling the post_init operations is not the final + * task of ORB initialization. The final task, following the + * post_init calls, is attaching the lists of registered + * interceptors to the ORB. Therefore, the ORB does not contain the + * interceptors during calls to post_init. If an + * ORB-mediated call is made from within post_init, no + * request interceptors will be invoked on that call. + * Likewise, if an operation is performed which causes an IOR to be + * created, no IOR interceptors will be invoked. + * + * @param info provides initialization attributes and + * operations by which Interceptors can be registered. + */ + public void post_init(ORBInitInfo info) { + } +} diff --git a/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/provider/EJBBindingInvoker.java b/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/provider/EJBBindingInvoker.java new file mode 100644 index 0000000000..9247c1d3db --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/provider/EJBBindingInvoker.java @@ -0,0 +1,92 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.ejb.provider; + +import org.apache.tuscany.sca.binding.ejb.EJBBinding; +import org.apache.tuscany.sca.binding.ejb.util.EJBHandler; +import org.apache.tuscany.sca.binding.ejb.util.NamingEndpoint; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.invocation.DataExchangeSemantics; + +/** + * EJBTargetInvoker + * + * @version $Rev$ $Date$ + */ +public class EJBBindingInvoker implements Invoker, DataExchangeSemantics { + + private Operation operation; + private String location; + private Class serviceInterface; + + public EJBBindingInvoker(EJBBinding ejbBinding, Class serviceInterface, Operation operation) { + this.serviceInterface = serviceInterface; + this.location = ejbBinding.getURI(); + this.operation = operation; + } + + public Message invoke(Message msg) { + ClassLoader tccl = Thread.currentThread().getContextClassLoader(); + try { + Thread.currentThread().setContextClassLoader(serviceInterface.getClassLoader()); + Object resp = doInvoke(msg.getBody()); + msg.setBody(resp); + } catch (Throwable e) { + e.printStackTrace(); + msg.setFaultBody(e); + } finally { + Thread.currentThread().setContextClassLoader(tccl); + } + return msg; + } + + /** + * Invoke a EJB operation + * + * @param payload + * @return + */ + public Object doInvoke(final Object payload) { + + // construct NamingendPoint + NamingEndpoint endpoint = getNamingEndpoint(); + + // lookup home and ejb stub + EJBHandler ejbHandler = new EJBHandler(endpoint, serviceInterface); + + String methodName = operation.getName(); + + // invoke business method on ejb + Object response = ejbHandler.invoke(methodName, (Object[])payload); + + return response; + } + + protected NamingEndpoint getNamingEndpoint() { + return new NamingEndpoint(location); + } + + public boolean allowsPassByReference() { + // EJB RMI/IIOP always pass by value + return true; + } + +} diff --git a/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/provider/EJBBindingProviderFactory.java b/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/provider/EJBBindingProviderFactory.java new file mode 100644 index 0000000000..a6ea583d0b --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/provider/EJBBindingProviderFactory.java @@ -0,0 +1,56 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.ejb.provider; + +import org.apache.tuscany.sca.binding.ejb.EJBBinding; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.provider.BindingProviderFactory; +import org.apache.tuscany.sca.provider.ReferenceBindingProvider; +import org.apache.tuscany.sca.provider.ServiceBindingProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; + +/** + * A factory from creating the EJB binding provider. + * + * @version $Rev$ $Date$ + */ +public class EJBBindingProviderFactory implements BindingProviderFactory { + + public EJBBindingProviderFactory(ExtensionPointRegistry extensionPoints) { + } + + public ReferenceBindingProvider createReferenceBindingProvider(RuntimeComponent component, + RuntimeComponentReference reference, + EJBBinding binding) { + return new EJBBindingReferenceBindingProvider(component, reference, binding); + } + + public ServiceBindingProvider createServiceBindingProvider(RuntimeComponent component, + RuntimeComponentService service, + EJBBinding binding) { + return null; + //throw new EJBBindingException("Service Binding not supported for EJB Binding"); + } + + public Class getModelType() { + return EJBBinding.class; + } +} diff --git a/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/provider/EJBBindingReferenceBindingProvider.java b/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/provider/EJBBindingReferenceBindingProvider.java new file mode 100644 index 0000000000..2a02bf0d08 --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/provider/EJBBindingReferenceBindingProvider.java @@ -0,0 +1,86 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.ejb.provider; + +import org.apache.tuscany.sca.binding.ejb.EJBBinding; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.interfacedef.java.JavaInterface; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.provider.ReferenceBindingProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; + +/** + * Implementation of the ReferenceBindingProvider for the EJBBinding. + * + * @version $Rev$ $Date$ + */ +public class EJBBindingReferenceBindingProvider implements ReferenceBindingProvider { + private EJBBinding ejbBinding; + private RuntimeComponentReference reference; + + /** + * Constructor + * + * @param component + * @param reference + * @param binding + */ + public EJBBindingReferenceBindingProvider(RuntimeComponent component, + RuntimeComponentReference reference, + EJBBinding binding) { + this.reference = reference; + this.ejbBinding = binding; + } + + /** + * {@inheritDoc} + */ + public Invoker createInvoker(Operation operation) { + return new EJBBindingInvoker(ejbBinding, ((JavaInterface)reference.getInterfaceContract().getInterface()) + .getJavaClass(), operation); + } + + /** + * {@inheritDoc} + */ + public InterfaceContract getBindingInterfaceContract() { + return reference.getInterfaceContract(); + } + + /** + * {@inheritDoc} + */ + public void start() { + } + + /** + * {@inheritDoc} + */ + public void stop() { + } + + /** + * {@inheritDoc} + */ + public boolean supportsOneWayInvocation() { + return true; + } +} diff --git a/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/util/EJBHandler.java b/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/util/EJBHandler.java new file mode 100644 index 0000000000..c7c0f90710 --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/util/EJBHandler.java @@ -0,0 +1,338 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.ejb.util; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.rmi.RemoteException; +import java.util.HashMap; +import java.util.Map; + +import javax.ejb.EJBObject; +import javax.rmi.CORBA.Util; + +import org.apache.tuscany.sca.binding.ejb.corba.ClassLoadingUtil; +import org.omg.CORBA.ORB; +import org.omg.CORBA.SystemException; +import org.omg.CORBA.portable.ApplicationException; +import org.omg.CORBA.portable.ObjectImpl; +import org.omg.CORBA.portable.RemarshalException; +import org.omg.CORBA.portable.ServantObject; +import org.omg.CORBA_2_3.portable.InputStream; +import org.omg.CORBA_2_3.portable.OutputStream; +import org.oasisopen.sca.ServiceRuntimeException; + +/** + * EJBMessageHandler + * + * @version $Rev$ $Date$ + */ +public class EJBHandler { + private static final Map PRIMITIVE_TYPES = new HashMap(); + static { + PRIMITIVE_TYPES.put("boolean", boolean.class); + PRIMITIVE_TYPES.put("byte", byte.class); + PRIMITIVE_TYPES.put("char", char.class); + PRIMITIVE_TYPES.put("short", short.class); + PRIMITIVE_TYPES.put("int", int.class); + PRIMITIVE_TYPES.put("long", long.class); + PRIMITIVE_TYPES.put("float", float.class); + PRIMITIVE_TYPES.put("double", double.class); + PRIMITIVE_TYPES.put("void", void.class); + } + + private Object ejbStub; + + private InterfaceInfo interfaceInfo; + private Class ejbInterface; + + public EJBHandler(NamingEndpoint namingEndpoint, Class ejbInterface) { + this(namingEndpoint, InterfaceInfo.getInstance(ejbInterface)); + this.ejbInterface = ejbInterface; + } + + // locates the stub + private EJBHandler(NamingEndpoint namingEndpoint, InterfaceInfo ejbInterface) { + try { + this.ejbStub = EJBStubHelper.lookup(namingEndpoint, ejbInterface); + this.interfaceInfo = ejbInterface; + } catch (Exception e) { + throw new ServiceRuntimeException(e); + } + } + + private static Class loadClass(final String name) { + try { + return ClassLoadingUtil.loadClass(name, Thread.currentThread().getContextClassLoader()); + } catch (ClassNotFoundException e) { + throw new ServiceRuntimeException(e); + } + } + + // invokes EJB method + public Object invoke(String methodName, Object[] args) { + Object response = null; + try { + if (ejbStub instanceof ObjectImpl) { + ObjectImpl objectImpl = (ObjectImpl)ejbStub; + // TODO: If the Java 2 security is turned on, then + // the ORB will try to create proxy + // from the interfaces defined on the stub + if (System.getSecurityManager() == null && objectImpl._is_local()) { + /* + * CORBA.Stub is what the object from JNDI will be for a + * remote EJB in the same JVM as the client, but with no + * stub classes available on the client + */ + response = invokeLocalCORBACall(objectImpl, methodName, args); + } else { + /* + * _EJBObject_Stub is what the object from JNDI will be for + * a remote EJB with no stub classes available on the client + */ + response = invokeRemoteCORBACall(objectImpl, methodName, args); + } + } else { + /* + * A generated ejb stub or it must be an EJB in the same ear as + * the client or an AppServer with a single ClassLoader, so + * reflection can be used directly on the JNDI + */ + JavaReflectionAdapter reflectionAdapter = + JavaReflectionAdapter.createJavaReflectionAdapter(ejbStub.getClass()); + try { + Method method = reflectionAdapter.getMethod(methodName); + response = method.invoke(ejbStub, args); + } catch (InvocationTargetException e) { + Throwable t = e.getTargetException(); + // FIXME need to throw really a business exception. + // ServiceBusinessException? + // Tuscany core doesn't have ServiceBusinessException + throw new ServiceRuntimeException(t); + } + } + + return response; + } catch (Exception e) { + // FIXME this be business exception? Tuscany core doesn't have + // ServiceBusinessException + throw new ServiceRuntimeException(e); + + } catch (Throwable e) { + throw new ServiceRuntimeException(e); + } + } + + /** + * Get the IDL operation name for a java method + * + * @param methodName java method name + * @return The IDL operation name + */ + private String getOperation(String methodName) { + if (interfaceInfo == null) { + return methodName; + } + MethodInfo methodInfo = interfaceInfo.getMethod(methodName); + if (methodInfo != null) { + return methodInfo.getIDLName(); + } else { + return null; + } + } + + /* + * Derive the EJB interface name from the Stub When loading a stub class + * corresponding to an interface or class ., the + * class .__Stub shall be used if it exists; + * otherwise, the class org.omg.stub..__Stub shall + * be used. + */ + private static String getInterface(String stubName) { + int index = stubName.lastIndexOf('.'); + String packageName = null; + String typeName = stubName; + if (index != -1) { + packageName = stubName.substring(0, index); + if (packageName.startsWith("org.omg.stub.")) { + packageName = packageName.substring("org.omg.stub.".length()); + } + typeName = stubName.substring(index + 1); + } + if (typeName.startsWith("_") && typeName.endsWith("_Stub")) { + typeName = typeName.substring(1, typeName.length() - "_Stub".length()); + } + if (packageName != null) + return packageName + "." + typeName; + else + return typeName; + } + + /** + * Invoke a method on the local CORBA object + * + * @param stub + * @param methodName + * @param args + * @return + * @throws RemoteException + * @throws ServiceBusinessException + */ + private Object invokeLocalCORBACall(final ObjectImpl stub, String methodName, Object[] args) + throws RemoteException { + + final String operation = getOperation(methodName); + + Class type = loadClass(getInterface(stub.getClass().getName())); + if (type == null) + type = (ejbInterface != null) ? ejbInterface : EJBObject.class; + + ServantObject so = stub._servant_preinvoke(operation, type); + if (so == null) { + // The Servant is not local any more + return invokeRemoteCORBACall(stub, methodName, args); + } + Object[] newArgs = null; + ORB orb = stub._orb(); + try { + if (args != null) + newArgs = Util.copyObjects(args, orb); + JavaReflectionAdapter reflectionAdapter = + JavaReflectionAdapter.createJavaReflectionAdapter(so.servant.getClass()); + Method method = reflectionAdapter.getMethod(methodName); + Object obj = reflectionAdapter.invoke(method, so.servant, newArgs); + Object result = Util.copyObject(obj, orb); + return result; + + } catch (InvocationTargetException e) { + Throwable exCopy = (Throwable)Util.copyObject(e.getTargetException(), orb); + MethodInfo methodInfo = interfaceInfo.getMethod(methodName); + String[] exceptionTypes = methodInfo.getExceptionTypes(); + for (int i = 0; i < exceptionTypes.length; i++) { + Class exceptionType = + methodInfo.getMethod() != null ? methodInfo.getMethod().getExceptionTypes()[i] + : loadClass(exceptionTypes[i]); + if (exceptionType.isAssignableFrom(exCopy.getClass())) + throw new ServiceRuntimeException(exCopy); // FIXME should + // be business + // exception? + } + throw Util.wrapException(exCopy); + } catch (Throwable e) { + // Other exceptions thrown from "invoke" + throw new ServiceRuntimeException(e); + } finally { + stub._servant_postinvoke(so); + } + } + + /** + * Invoke a method on a remote CORBA object + * + * @param stub The remote stub + * @param methodName The name of the method + * @param args Argument list + * @return + * @throws RemoteException + * @throws ServiceBusinessException + */ + private Object invokeRemoteCORBACall(ObjectImpl stub, String methodName, Object[] args) throws RemoteException { + + try { + String operation = getOperation(methodName); + + MethodInfo methodInfo = interfaceInfo.getMethod(methodName); + if (methodInfo == null) { + throw new ServiceRuntimeException("Invalid Method " + methodName); + } + Class[] parameterTypes = null; + Class returnType = null; + if (methodInfo.getMethod() != null) { + parameterTypes = methodInfo.getMethod().getParameterTypes(); + returnType = methodInfo.getMethod().getReturnType(); + } else { + String[] types = methodInfo.getParameterTypes(); + if (args != null) { + if (types.length != args.length) + throw new ServiceRuntimeException( + "The argument list doesn't match the method signature of " + methodName); + } + + parameterTypes = new Class[types.length]; + for (int i = 0; i < types.length; i++) { + parameterTypes[i] = loadClass(types[i]); + } + returnType = loadClass(methodInfo.getReturnType()); + } + + InputStream in = null; + try { + OutputStream out = (OutputStream)stub._request(operation, true); + + for (int i = 0; i < parameterTypes.length; i++) { + // Object arg = (args.length < i) ? null : args[i]; + writeValue(out, args[i], parameterTypes[i]); + } + if (returnType == void.class) { + // void return + stub._invoke(out); + return null; + } else { + // read the return value + in = (InputStream)stub._invoke(out); + Object response = readValue(in, returnType); + return response; + } + + } catch (ApplicationException ex) { + in = (InputStream)ex.getInputStream(); + try { + org.apache.tuscany.sca.binding.ejb.corba.Java2IDLUtil.throwException(methodInfo.getMethod(), in); + return null; + } catch (Throwable e) { + throw new RemoteException(e.getMessage(), e); + } + } catch (RemarshalException ex) { + return invokeRemoteCORBACall(stub, methodName, args); + } finally { + stub._releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } + + /** + * @param out + * @param value + * @param type + */ + private void writeValue(OutputStream out, Object value, Class type) { + org.apache.tuscany.sca.binding.ejb.corba.Java2IDLUtil.writeObject(type, value, out); + } + + /** + * @param in + * @param type + * @return + */ + private Object readValue(InputStream in, Class type) { + return org.apache.tuscany.sca.binding.ejb.corba.Java2IDLUtil.readObject(type, in); + } +} diff --git a/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/util/EJBLocator.java b/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/util/EJBLocator.java new file mode 100644 index 0000000000..0b97f42746 --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/util/EJBLocator.java @@ -0,0 +1,483 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.ejb.util; + +import java.net.URL; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Properties; +import java.util.Set; + +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; + +import org.omg.CORBA.ORB; +import org.omg.CosNaming.NamingContextExt; + +/** + * CosNaming utility + * + * @version $Rev$ $Date$ + */ +class EJBLocator { + + /* + * Root Context Initial Reference Key ------------ + * ----------------------------------- Server Root NameServiceServerRoot + * Cell Persistent Root NameServiceCellPersistentRoot Cell Root + * NameServiceCellRoot, NameService Node Root NameServiceNodeRoot + */ + public static final String SERVER_ROOT = "NameServiceServerRoot"; + public static final String CELL_PERSISTENT_ROOT = "NameServiceCellPersistentRoot"; + public static final String CELL_ROOT = "NameServiceCellRoot"; + public static final String NODE_ROOT = "NameServiceNodeRoot"; + public static final String DEFAULT_ROOT = "NameService"; // Same as + // CELL_ROOT + + public static final String DEFAULT_HOST = "127.0.0.1"; // Default host name + // or IP address for + // WebSphere + public static final int DEFAULT_NAMING_PORT = 2809; // Default port + public static final String NAMING_SERVICE = "NameService"; // The name of + // the naming + // service + private static final Set ROOTS = + new HashSet(Arrays.asList(new String[] {SERVER_ROOT, CELL_PERSISTENT_ROOT, CELL_ROOT, DEFAULT_ROOT, + NODE_ROOT})); + + // private static final String CHARS_TO_ESCAPE = "\\/."; + private static final String RFC2396 = + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789;/:?@&=+$,-_.!~*'()"; + private static final String HEX = "0123456789ABCDEF"; + + private String hostName = DEFAULT_HOST; + private int port = DEFAULT_NAMING_PORT; + private String root = SERVER_ROOT; + + private ORB orb = null; + private ObjectLocator locator = null; + private boolean managed = true; + + EJBLocator(boolean managed) { + this.managed = managed; + if (!managed) { + String url = AccessController.doPrivileged(new PrivilegedAction() { + public String run() { + return System.getProperty(Context.PROVIDER_URL); + } + }); + processCorbaURL(url); + } + } + + EJBLocator(String hostName, int port) { + this.hostName = (hostName == null) ? DEFAULT_HOST : hostName; + this.port = port > 0 ? port : DEFAULT_NAMING_PORT; + this.root = SERVER_ROOT; + } + + EJBLocator(String hostName, int port, String root) { + this(hostName, port); + if (ROOTS.contains(root)) { + this.root = root; + } else { + throw new IllegalArgumentException(root + " is not a legal root"); + } + } + + EJBLocator(String corbaName, boolean managed) { + this.managed = managed; + if (corbaName.startsWith("corbaname:iiop:")) { + processCorbaURL(corbaName); + } else { + throw new IllegalArgumentException(corbaName + " is not a legal corbaname"); + } + } + + private void processCorbaURL(String url) { + if (url != null && (url.startsWith("corbaname:iiop:") || url.startsWith("corbaloc:iiop:"))) { + /** + * corbaname:iiop::/#name corbaloc:iiop::/ + * For example, + * "corbaname:iiop:localhost:2809/NameServiceServerRoot#ejb/MyEJBHome"; + * or "corbaloc:iiop:myhost:2809/NameServiceServerRoot" + */ + String[] parts = url.split("(:|/|#)"); + if (parts.length > 2 && parts[2].length() > 0) { + hostName = parts[2]; // The host name + int index = hostName.lastIndexOf('@'); // version@hostname + if (index != -1) { + hostName = hostName.substring(index + 1); + } + } + if (parts.length > 3 && parts[3].length() > 0) { + port = Integer.parseInt(parts[3]); // The port number + } + if (parts.length > 4 && parts[4].length() > 0) { + root = parts[4]; // The root of naming + } + } + } + + /** + * The corbaloc and corbaname formats enable you to provide a URL to access + * CORBA objects. Use the corbaloc format for resolving to a particular + * CORBAservice without going through a naming service. Use the corbaname + * format to resolve a stringified name from a specific naming context. + */ + + /** + * corbaname Syntax The full corbaname BNF is: <corbaname> = + * "corbaname:"<corbaloc_obj>["#"<string_name>] + * <corbaloc_obj> = <obj_addr_list> ["/"<key_string>] + * <obj_addr_list> = as defined in a corbaloc URL <key_string> = + * as defined in a corbaloc URL <string_name>= stringified Name + * empty_string Where: + *

    + *
  • corbaloc_obj: portion of a corbaname URL that identifies the naming + * context. The syntax is identical to its use in a corbaloc URL. + *
  • obj_addr_list: as defined in a corbaloc URL + *
  • key_string: as defined in a corbaloc URL. + *
  • string_name: a stringified Name with URL escapes as defined below. + *
+ * + * @param hostName The host name or IP address of the naming server + * @param port The port number of the naming service + * @param root The root of the namespace + * @param name The JNDI name + */ + private static String getCorbaname(String hostName, int port, String root, String name) { + if (name == null) { + return "corbaname:iiop:" + hostName + ":" + port + "/" + root; + } else { + return "corbaname:iiop:" + hostName + ":" + port + "/" + root + "#" + toCorbaname(name); + } + } + + String getCorbaname(String name) { + return getCorbaname(hostName, port, root, name); + } + + /** + * Connect to the ORB. + */ + + // FIXME. May need to change the IBM classes if this binding is contributed + // to Tuscany + public ORB connect() { + if (orb == null) { + Properties props = new Properties(); + /* + * This code is for IBM JVM props.put("org.omg.CORBA.ORBClass", + * "com.ibm.CORBA.iiop.ORB"); + * props.put("com.ibm.CORBA.ORBInitRef.NameService", + * getCorbaloc(NAMING_SERVICE)); + * props.put("com.ibm.CORBA.ORBInitRef.NameServiceServerRoot", + * getCorbaloc("NameServiceServerRoot")); + */ + orb = ORB.init((String[])null, props); + } + return orb; + } + + /** + * Replace substrings + * + * @param source The source string. + * @param match The string to search for within the source string. + * @param replace The replacement for any matching components. + * @return + */ + private static String replace(String source, String match, String replace) { + int index = source.indexOf(match, 0); + if (index >= 0) { + + // We have at least one match, so got to do the + // work... + + StringBuffer result = new StringBuffer(source.length() + 16); + int matchLength = match.length(); + int startIndex = 0; + + while (index >= 0) { + result.append(source.substring(startIndex, index)); + result.append(replace); + startIndex = index + matchLength; + index = source.indexOf(match, startIndex); + } + + // Grab the last piece, if any... + if (startIndex < source.length()) { + result.append(source.substring(startIndex)); + } + + return result.toString(); + + } else { + // No matches, just return the source... + return source; + } + } + + /** + * Resolved the JNDI name from the initial CosNaming context + * + * @param jndiName + * @return resolved CORBA object + * @throws NamingException + */ + private static org.omg.CORBA.Object resovleString(NamingContextExt initCtx, String jndiName) throws NamingException { + try { + String name = stringify(jndiName); + return initCtx.resolve_str(name); + } catch (Exception e) { + NamingException ne = new NamingException(e.getMessage()); + ne.setRootCause(e); + throw ne; + } + } + + /** + * Look up a CORBA object by its JNDI name + * + * @param jndiName + * @return + * @throws NamingException + */ + org.omg.CORBA.Object stringToObject(String jndiName) throws NamingException { + /* + * Using an existing ORB and invoking string_to_object with a CORBA + * object URL with multiple name server addresses to get an initial + * context CORBA object URLs can contain more than one bootstrap server + * address. Use this feature when attempting to obtain an initial + * context from a server cluster. You can specify the bootstrap server + * addresses for all servers in the cluster in the URL. The operation + * will succeed if at least one of the servers is running, eliminating a + * single point of failure. There is no guarantee of any particular + * order in which the address list will be processed. For example, the + * second bootstrap server address may be used to obtain the initial + * context even though the first bootstrap server in the list is + * available. An example of a corbaloc URL with multiple addresses + * follows. obj = + * orb.string_to_object("corbaloc::myhost1:9810,:myhost1:9811,:myhost2:9810/NameService"); + */ + String corbaName = null; + if (jndiName.startsWith("corbaloc:") || jndiName.startsWith("corbaname:")) { + // Keep the qualified URL + corbaName = jndiName; + } else { + // Create a corbaname URL + corbaName = getCorbaname(jndiName); + } + + connect(); + org.omg.CORBA.Object obj = orb.string_to_object(corbaName); + return obj; + } + + private boolean isJndiConfigured() { + if (managed) + return true; + Boolean provided = AccessController.doPrivileged(new PrivilegedAction() { + public Boolean run() { + String initCtxFactory = System.getProperty(Context.INITIAL_CONTEXT_FACTORY); + if (initCtxFactory == null) { + URL file = Thread.currentThread().getContextClassLoader().getResource("jndi.properties"); + if (file != null) { + return Boolean.TRUE; + } else { + return Boolean.FALSE; + } + } else { + return Boolean.TRUE; + } + } + }); + return provided.booleanValue(); + } + + /** + * The character escape rules for the stringified name portion of an + * corbaname are: US-ASCII alphanumeric characters are not escaped. + * Characters outside this range are escaped, except for the following: ; / : ? @ & = + $ , - _ . ! ~ * ' ( ) + * corbaname Escape Mechanism The percent '%' character is used as an + * escape. If a character that requires escaping is present in a name + * component it is encoded as two hexadecimal digits following a "%" + * character to represent the octet. (The first hexadecimal character + * represent the highorder nibble of the octet, the second hexadecimal + * character represents the low-order nibble.) If a '%' is not followed by + * two hex digits, the stringified name is syntactically invalid. + * @param s + * @return RFC2396-encoded stringified name + */ + static String encode2396(String s) { + if (s == null) { + return null; + } + StringBuffer encoded = new StringBuffer(s); + for (int i = 0; i < encoded.length(); i++) { + char c = encoded.charAt(i); + if (RFC2396.indexOf(c) == -1) { + encoded.setCharAt(i, '%'); + char[] ac = Integer.toHexString(c).toCharArray(); + if (ac.length == 2) { + encoded.insert(i + 1, ac); + } else if (ac.length == 1) { + encoded.insert(i + 1, '0'); + encoded.insert(i + 2, ac[0]); + } else { + throw new IllegalArgumentException("Invalid character '" + c + "' in \"" + s + "\""); + } + i += 2; // NOPMD + } + } + return encoded.toString(); + } + + /** + * Decode an RFC2396-encoded string + * + * @param s + * @return Plain string + */ + static String decode2396(String s) { + if (s == null) { + return null; + } + StringBuffer decoded = new StringBuffer(s); + for (int i = 0; i < decoded.length(); i++) { + char c = decoded.charAt(i); + if (c == '%') { + if (i + 2 >= decoded.length()) { + throw new IllegalArgumentException("Incomplete key_string escape sequence"); + } + int j; + j = HEX.indexOf(decoded.charAt(i + 1)) * 16 + HEX.indexOf(decoded.charAt(i + 2)); + decoded.setCharAt(i, (char)j); + decoded.delete(i + 1, i + 3); + } else if (RFC2396.indexOf(c) == -1) { + throw new IllegalArgumentException("Invalid key_string character '" + c + "'"); + } + } + return decoded.toString(); + } + + /** + * The backslash '\' character escapes the reserved meaning of '/', '.', and + * '\' in a stringified name. + * + * @param jndiName + * @return Escaped stringified name for CosNaming + */ + private static String stringify(String jndiName) { + // Escape . into \. since it's an INS naming delimiter + return replace(encode2396(jndiName), ".", "\\."); + } + + /** + * Escape the "." into "%5C%2E" + * + * @param jndiName + * @return corbaname treating "." as a literal + */ + private static String toCorbaname(String jndiName) { + // Escape . into %5C%2E (\.) since it's an INS naming delimiter + // For example, sca.sample.StockQuote ---> + // sca%5C%2Esample%5C%2EStockQuote/StockQuote + return replace(encode2396(jndiName), ".", "%5C%2E"); + } + + private ObjectLocator getObjectLocator() throws NamingException { + if (locator != null) { + return locator; + } + /* + * For managed env, JNDI is assumed to be configured by default For + * unmanaged environment, JNDI could have configured through + * jndi.properties file + */ + if (isJndiConfigured()) { + locator = new JndiLocator(); + } else { // this is definitely JSE env without JNDI configured. Use + // CORBA. + locator = new CosNamingLocator(); + } + return locator; + } + + public Object locate(String jndiName) throws NamingException { + + Object result = getObjectLocator().locate(jndiName); + return result; + } + + private static interface ObjectLocator { + Object locate(String name) throws NamingException; + } + + private final class JndiLocator implements ObjectLocator { + private Context context; + + private JndiLocator() throws NamingException { + /* + final Properties props = AccessController.doPrivileged(new PrivilegedAction() { + public Properties run() { + return System.getProperties(); + } + }); + Properties properties = new Properties(); + for (Map.Entry e : props.entrySet()) { + String name = (String)e.getKey(); + if (name.startsWith("java.naming.")) { + properties.setProperty(name, (String)e.getValue()); + } + } + // System.out.println(properties); + this.context = new InitialContext(properties); + */ + this.context = new InitialContext(); + } + + public Object locate(String name) throws NamingException { + return context.lookup(name); + } + } + + private final class CosNamingLocator implements ObjectLocator { + private NamingContextExt context; + + private CosNamingLocator() { + } + + public Object locate(String name) throws NamingException { + if (context != null) { + return resovleString(context, name); + } else { + return stringToObject(name); + } + } + } + + public void setHostEnv(boolean managed) { + this.managed = managed; + } +} diff --git a/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/util/EJBObjectFactory.java b/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/util/EJBObjectFactory.java new file mode 100644 index 0000000000..119282adb9 --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/util/EJBObjectFactory.java @@ -0,0 +1,209 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.ejb.util; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.rmi.RemoteException; +import java.rmi.UnexpectedException; + +import javax.ejb.CreateException; +import javax.ejb.EJBLocalHome; +import javax.naming.NamingException; +import javax.rmi.CORBA.Util; + +import org.omg.CORBA.SystemException; +import org.omg.CORBA.portable.ApplicationException; +import org.omg.CORBA.portable.ObjectImpl; +import org.omg.CORBA.portable.RemarshalException; +import org.omg.stub.java.rmi._Remote_Stub; +import org.oasisopen.sca.ServiceRuntimeException; + +/** + * Factor class that is used to create EJB Proxies. + * + * @version $Rev$ $Date$ + */ +final class EJBObjectFactory { + + private EJBObjectFactory() { + } + + /** + * Get either a generated of dynamic EJB stub using the specified JNDI + * properties. + *

+ * The returned stub will implement the specified stubInterface Interface. + * If the underlying EJB stub is not assignable from the specified + * stubInterface then a proxy is used to convert between the two. + *

+ * The returned EJB stub may be either the pregenerated EJB stub or a + * dynamic stub. This allows a client to invoke an EJB without requiring any + * of the pregenerated EJB stub classes be available in the classpath. + *

+ */ + static Object createStub(NamingEndpoint namingEndpoint, InterfaceInfo ejbInterface) throws NamingException, + RemoteException, CreateException { + + EJBLocator locator = namingEndpoint.getLocator(); + Object homeObject = locator.locate(namingEndpoint.getJndiName()); + /* + * The type of the object returned from the lookup is as follows: If the + * generated stub exists on the classpath, it's an instance of that + * type, otherwise, "org.omg.stub.java.rmi._Remote_Stub" or + * "org.omg.stub.javax.ejb._EJBHome_Stub" + */ + Object stub = getEJBStub(homeObject, ejbInterface); + // Cache dynamic stub only + return stub; + } + + /** + * @param homeObject + * @param ejbHomeClass + * @return + * @throws RemoteException + */ + private static Object getEJBStub(Object homeObject, InterfaceInfo ejbInterface) throws RemoteException, + CreateException { + + Object stub = null; + + // Get the business interface of the EJB + Class ejbInterfaceClass = null; + try { + ejbInterfaceClass = Thread.currentThread().getContextClassLoader().loadClass(ejbInterface.getName()); + } catch (ClassNotFoundException e) { + // ignore + } + + if (ejbInterfaceClass != null && ejbInterfaceClass.isInstance(homeObject)) { + // EJB 3 + stub = homeObject; + } else if (homeObject instanceof EJBLocalHome) { + // Local EJB + stub = createEJBLocalObject(homeObject); + } else { + // Handle dynamic stub + if (homeObject instanceof ObjectImpl) { + ObjectImpl objectImpl = (ObjectImpl)homeObject; + stub = createEJBObject(objectImpl); + }/** + * Above checks will be satisfied if Bean is running on servers like WebSphere. With this + * logic, client (SCA composite with EJB ref binding) doesn't need to include home class or + * client stubs. + * + * Below check is needed SCA composite with EJB ref binding is accessing openEJB implementation. + * For e.g if the bean is running on Geronimo. + */ + else if ((javax.rmi.PortableRemoteObject.narrow(homeObject, javax.ejb.EJBHome.class)) instanceof javax.ejb.EJBHome) { + stub = createEJBObjectFromHome(homeObject); + } else + throw new ServiceRuntimeException("Invalid stub type: " + homeObject.getClass()); + } + return stub; + } + + /** + * Create a pre-generated EJB stub + * + * @param homeObject + * @return + * @throws RemoteException + */ + static private Object createEJBLocalObject(Object homeObject) throws RemoteException { + + Object stub = null; + try { + // Find the "create()" method + Method createMethod = homeObject.getClass().getMethod("create", null); + // Create an EJB object + stub = createMethod.invoke(homeObject, null); + } catch (NoSuchMethodException e) { + // "create()" method not found, it's still a dynamic stub + stub = null; + } catch (InvocationTargetException e) { + throw new RemoteException(e.getTargetException().toString()); + } catch (Exception e) { + throw new RemoteException(e.toString()); + } + return stub; + } + + /** + * Here homeObject is instance of EJBHome + * + * @param homeObject + * @return + * @throws RemoteException + */ + private static Object createEJBObjectFromHome(Object homeObject) throws RemoteException { + + Object stub = null; + try { + // Find the "create()" method + Method createMethod = homeObject.getClass().getMethod("create", null); + // Create an EJB object + stub = createMethod.invoke(homeObject, null); + } catch (NoSuchMethodException e) { + // "create()" method not found, it's still a dynamic stub + stub = null; + } catch (InvocationTargetException e) { + throw new RemoteException(e.getTargetException().toString()); + } catch (Exception e) { + throw new RemoteException(e.toString()); + } + return stub; + } + + /** + * Create an EJBObject using RMI/IIOP APIs + * + * @param ejbHomeObject + * @return The EJBObject remote stub + * @throws CreateException + * @throws RemoteException + */ + private static Object createEJBObject(ObjectImpl ejbHomeObject) throws CreateException, RemoteException { + + try { + org.omg.CORBA_2_3.portable.InputStream in = null; + try { + org.omg.CORBA.portable.OutputStream out = ejbHomeObject._request("create", true); + in = (org.omg.CORBA_2_3.portable.InputStream)ejbHomeObject._invoke(out); + // The Remote stub should be available in JDK + // TODO: [rfeng] Work around an issue in Apache Yoko which doesn't understand the org.omg.stub.* + return in.read_Object(_Remote_Stub.class); + } catch (ApplicationException ex) { + in = (org.omg.CORBA_2_3.portable.InputStream)ex.getInputStream(); + String id = in.read_string(); + if (id.equals("IDL:javax/ejb/CreateEx:1.0")) { + throw (CreateException)in.read_value(CreateException.class); + } + throw new UnexpectedException(id); + } catch (RemarshalException ex) { + return createEJBObject(ejbHomeObject); + } finally { + ejbHomeObject._releaseReply(in); + } + } catch (SystemException ex) { + throw Util.mapSystemException(ex); + } + } +} diff --git a/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/util/EJBStubHelper.java b/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/util/EJBStubHelper.java new file mode 100644 index 0000000000..72f7dc9e43 --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/util/EJBStubHelper.java @@ -0,0 +1,69 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.ejb.util; + +import java.rmi.RemoteException; + +import javax.ejb.CreateException; +import javax.naming.NamingException; + +import org.oasisopen.sca.ServiceRuntimeException; +import org.oasisopen.sca.ServiceUnavailableException; + +final class EJBStubHelper { + + private static Object stub; + private static ServiceRuntimeException exception; + + private EJBStubHelper() { + } + + /** + * @param owner + * @param jndiName + * @return + */ + + static Object lookup(NamingEndpoint endpoint, InterfaceInfo ejbInterface) { + return getStub(endpoint, ejbInterface); + } + + private static Object getStub(NamingEndpoint namingEndpoint, InterfaceInfo ejbInterface) { + try { + stub = EJBObjectFactory.createStub(namingEndpoint, ejbInterface); + } catch (NamingException e) { + exception = new ServiceUnavailableException(e); + e.printStackTrace(); + throw (ServiceUnavailableException)exception; + } catch (CreateException e) { + exception = new ServiceUnavailableException(e); + throw (ServiceUnavailableException)exception; + } catch (RemoteException e) { + exception = new ServiceRuntimeException(e); + throw (ServiceRuntimeException)exception; + } + + if (exception == null) { + return stub; // Normal result + } else { + throw exception; // Throw the exception + } + } + +} diff --git a/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/util/InterfaceInfo.java b/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/util/InterfaceInfo.java new file mode 100644 index 0000000000..e60e526e01 --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/util/InterfaceInfo.java @@ -0,0 +1,117 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.ejb.util; + +import java.io.Serializable; +import java.lang.reflect.Method; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.WeakHashMap; + +import org.apache.tuscany.sca.binding.ejb.corba.Java2IDLUtil; + +/** + * The signature for a java interface + * + * @version $Rev$ $Date$ + */ +class InterfaceInfo implements Serializable { + + private static final Map INTERFACES = + Collections.synchronizedMap(new WeakHashMap()); + + private static final long serialVersionUID = 2314533906465094860L; + private String name; + + private Map methods = new HashMap(); + + InterfaceInfo(final Class iface) { + super(); + if (iface == null) { + throw new IllegalArgumentException("The interface cannot be null"); + } + this.name = iface.getName(); + // SECURITY + /* + * Permission: accessDeclaredMembers : Access denied + * (java.lang.RuntimePermission accessDeclaredMembers) + */ + Map idlNames = AccessController.doPrivileged(new PrivilegedAction() { + public Map run() { + return Java2IDLUtil.mapMethodToOperation(iface); + } + }); + Iterator i = idlNames.entrySet().iterator(); + while (i.hasNext()) { + Map.Entry entry = (Map.Entry)i.next(); + Method method = (Method)entry.getKey(); + MethodInfo methodInfo = new MethodInfo(method); + methodInfo.setIDLName((String) entry.getValue()); + methods.put(method.getName(), methodInfo); + methods.put(methodInfo.getIDLName(), methodInfo); + } + } + + static final synchronized InterfaceInfo getInstance(final Class iface) { + InterfaceInfo info = (InterfaceInfo)INTERFACES.get(iface); + if (info == null) { + info = new InterfaceInfo(iface); + INTERFACES.put(iface, info); + } + return info; + } + + /** + * @return + */ + Map getMethods() { + return methods; + } + + /** + * @return + */ + MethodInfo getMethod(String name) { + return (MethodInfo)methods.get(name); + } + + /** + * @return + */ + String getName() { + return name; + } + + @Override + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append("interface ").append(name).append("{ \n"); + Iterator i = methods.values().iterator(); + while (i.hasNext()) { + MethodInfo methodInfo = (MethodInfo)i.next(); + sb.append("\t").append(methodInfo).append("\n"); + } + sb.append("};\n"); + return sb.toString(); + } +} diff --git a/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/util/JavaReflectionAdapter.java b/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/util/JavaReflectionAdapter.java new file mode 100644 index 0000000000..651c967aad --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/util/JavaReflectionAdapter.java @@ -0,0 +1,157 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.ejb.util; + +import java.beans.PropertyDescriptor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.WeakHashMap; + +import org.oasisopen.sca.ServiceRuntimeException; + +/** + * An adapter for java classes, indexes the methods by name and provides an + * invoke method that takes a method name. + * + * @version $Rev$ $Date$ + */ +final class JavaReflectionAdapter { + + private static Map adapters = + Collections.synchronizedMap(new WeakHashMap()); + + private static final Map DEFAULT_VALUES = new HashMap(); + static { + DEFAULT_VALUES.put(boolean.class, Boolean.FALSE); + DEFAULT_VALUES.put(byte.class, new Byte((byte)0)); + DEFAULT_VALUES.put(char.class, new Character((char)0)); + DEFAULT_VALUES.put(short.class, new Short((short)0)); + DEFAULT_VALUES.put(int.class, Integer.valueOf(0)); + DEFAULT_VALUES.put(long.class, new Long(0)); + DEFAULT_VALUES.put(float.class, new Float(0.0)); + DEFAULT_VALUES.put(double.class, new Double(0.0)); + } + + private Map methodMap = new HashMap(); + + /** + * Constructor + * + * @param clazz + */ + private JavaReflectionAdapter(final Class clazz) { + // Index the methods on the implementation class + // FIXME J2 Security - promote this to callers of this method + Method[] methods = AccessController.doPrivileged(new PrivilegedAction() { + public Method[] run() { + return clazz.getMethods(); + } + }); + for (int i = 0; i < methods.length; i++) { + methodMap.put(methods[i].getName(), methods[i]); + } + } + + /** + * Create a java reflection adapter + * + * @param clazz + */ + static synchronized JavaReflectionAdapter createJavaReflectionAdapter(Class clazz) { + JavaReflectionAdapter adapter = (JavaReflectionAdapter)adapters.get(clazz); + if (adapter == null) { + adapter = new JavaReflectionAdapter(clazz); + adapters.put(clazz, adapter); + } + return adapter; + } + + /** + * Return the specified method + * + * @param methodName + * @return + * @throws NoSuchMethodException + */ + Method getMethod(String methodName) throws NoSuchMethodException { + + Method method = (Method)methodMap.get(methodName); + if (method == null) { + throw new NoSuchMethodException(methodName); + } + return method; + } + + /** + * Returns a map containing the methods on the class, keyed by name + * + * @return + */ + Map getMethods() { + return methodMap; + } + + /** + * Invoke a method using Java reflection. + * + * @param method + * @param object + * @param args + * @return + * @throws InvocationTargetException + * @throws IllegalAccessException + */ + Object invoke(Method method, Object object, Object[] args) throws InvocationTargetException, + IllegalAccessException { + Class[] parameterTypes = method.getParameterTypes(); + for (int i = 0; i < parameterTypes.length; i++) { + Class parameterType = parameterTypes[i]; + if (args[i] == null && parameterType.isPrimitive()) { + args[i] = DEFAULT_VALUES.get(parameterType); + } + } + return method.invoke(object, args); + } + + /** + * Set the java bean property + * + * @param bean + * @param propertyName + * @param value + * @return + */ + boolean setProperty(Object bean, String propertyName, Object value) { + try { + PropertyDescriptor propertyDescriptor = new PropertyDescriptor(propertyName, bean.getClass()); + Method writeMethod = propertyDescriptor.getWriteMethod(); + writeMethod.invoke(bean, new Object[] {value}); + return true; + } catch (InvocationTargetException e) { + throw new ServiceRuntimeException(e.getTargetException()); + } catch (Exception e) { + return false; + } + } +} diff --git a/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/util/MethodInfo.java b/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/util/MethodInfo.java new file mode 100644 index 0000000000..e7ea7c9077 --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/util/MethodInfo.java @@ -0,0 +1,189 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.ejb.util; + +import java.io.Serializable; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; + +/** + * MetaData for a java method + * + * @version $Rev$ $Date$ + */ +class MethodInfo implements Serializable { + + /** Automatically generated javadoc for: serialVersionUID */ + private static final long serialVersionUID = -5557260979514687514L; + private String name; + private String returnType; + private String[] parameterTypes; + private String[] exceptionTypes; + + private String IDLName; + + private transient Method method; + + /** + * Type Signature Java Type -------------- --------- Z boolean B byte C char + * S short I int J long F float D double L fully-qualified-class ; + * fully-qualified-class [ type type[] ( arg-types ) ret-type method type + */ + private static final Map signatures = new HashMap(); + static { + signatures.put("Z", boolean.class); + signatures.put("B", byte.class); + signatures.put("C", char.class); + signatures.put("S", short.class); + signatures.put("I", int.class); + signatures.put("J", long.class); + signatures.put("F", float.class); + signatures.put("D", double.class); + signatures.put("V", void.class); + } + + MethodInfo(Method method) { + this.method = method; + this.name = method.getName(); + // this.declaringClass = method.getDeclaringClass().getName(); + this.returnType = method.getReturnType().getName(); + Class[] types = method.getParameterTypes(); + this.parameterTypes = new String[types.length]; + for (int i = 0; i < types.length; i++) { + this.parameterTypes[i] = types[i].getName(); + } + types = method.getExceptionTypes(); + this.exceptionTypes = new String[types.length]; + for (int i = 0; i < types.length; i++) { + this.exceptionTypes[i] = types[i].getName(); + } + IDLName = this.name; + } + + MethodInfo(String name, String returnType, String[] parameterTypes, String[] exceptionTypes) { + this.name = name; + this.returnType = returnType; + this.parameterTypes = parameterTypes; + this.exceptionTypes = exceptionTypes; + this.IDLName = name; + } + + /** + * Parse the class name from the internal signature Sample signatures: int + * ---> I; int[] ---> [I Object ---> java/lang/Object Object[] ---> + * [Ljava/lang/Object; + * + * @param value + * @return + */ + private static String getName(String signature) { + String name = signature; + // Remove leading ARRAY ([) signatures + int index = name.lastIndexOf('['); + if (index != -1) + name = name.substring(index + 1); + + // Remove L<...>; + if (name.charAt(0) == 'L' && name.charAt(name.length() - 1) == ';') + name = name.substring(1, name.length() - 1); + + // Primitive types + Class primitiveClass = (Class)signatures.get(name); + if (primitiveClass != null) { + name = primitiveClass.getName(); + } + + for (int i = 0; i < index + 1; i++) { + name = name + "[]"; + } + return name; + } + + /** + * @return + */ + String getName() { + return name; + } + + /** + * @return + */ + String[] getParameterTypes() { + return parameterTypes; + } + + /** + * @return + */ + String getReturnType() { + return returnType; + } + + /** + * @return + */ + String[] getExceptionTypes() { + return exceptionTypes; + } + + @Override + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append(getName(returnType)).append(" ").append(name).append("("); + for (int j = 0; j < parameterTypes.length; j++) { + sb.append(getName(parameterTypes[j])).append(" ").append("arg" + j); + if (j < (parameterTypes.length - 1)) + sb.append(", "); + } + sb.append(")"); + if (exceptionTypes.length > 0) { + sb.append(" throws "); + for (int k = 0; k < exceptionTypes.length; k++) { + sb.append(exceptionTypes[k]); + if (k < (exceptionTypes.length - 1)) + sb.append(", "); + } + } + sb.append(";"); + return sb.toString(); + } + + /** + * @return Returns the iDLName. + */ + String getIDLName() { + return IDLName; + } + + /** + * @param name The iDLName to set. + */ + void setIDLName(String name) { + IDLName = name; + } + + /** + * @return the method + */ + Method getMethod() { + return method; + } +} diff --git a/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/util/NamingEndpoint.java b/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/util/NamingEndpoint.java new file mode 100644 index 0000000000..346b7c5cf6 --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb-runtime/src/main/java/org/apache/tuscany/sca/binding/ejb/util/NamingEndpoint.java @@ -0,0 +1,124 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.ejb.util; + +import java.security.AccessController; +import java.security.PrivilegedAction; + +public class NamingEndpoint { + private String jndiName; + private EJBLocator locator; + private boolean managed = true; + + public NamingEndpoint(String hostName, int port, String jndiName) { + this.jndiName = jndiName; + this.locator = new EJBLocator(hostName, port); + } + + public NamingEndpoint(String name) { + + /** + * by default it's a managed environment means SCA composite with ref + * binding is running on an AppServer. If running on J2SE, pass + * -Dmanaged=false for the VM + */ + final String managedEnv = AccessController.doPrivileged(new PrivilegedAction() { + public String run() { + return System.getProperty("managed"); + } + }); + + if (managedEnv != null) { + managed = Boolean.valueOf(managedEnv); + } + + if ((!managed) && name.startsWith("corbaname:iiop:")) { + /** + * if (name.startsWith("corbaname:iiop:")) { corbaname:iiop::/#name + * For example, + * "corbaname:iiop:localhost:2809/NameServiceServerRoot#ejb/MyEJBHome"; + */ + + String[] parts = split(name, '#'); + if (parts.length != 2) { + throw new IllegalArgumentException("Invalid corbaname: " + name); + } + + this.jndiName = name; // The logical JNDI name + this.locator = new EJBLocator(parts[0], managed); + + } else { + this.jndiName = name; + this.locator = new EJBLocator(managed); + } + + } + + private static String[] split(String str, char ch) { + int index = str.lastIndexOf(ch); + if (index == -1) { + return new String[] {str, ""}; + } else { + return new String[] {str.substring(0, index), str.substring(index + 1)}; + } + } + + /** + * @return Returns the jndiName. + */ + public String getJndiName() { + return jndiName; + } + + public EJBLocator getLocator() { + return locator; + } + + public String getCorbaname() { + return locator.getCorbaname(jndiName); + } + + /** + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (obj instanceof NamingEndpoint) { + NamingEndpoint endpoint = (NamingEndpoint)obj; + return jndiName.equals(endpoint.jndiName); + } + return false; + } + + /** + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + return jndiName.hashCode(); + } + + /** + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return jndiName; + } +} diff --git a/java/sca/contrib/modules/binding-ejb-runtime/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.BindingProviderFactory b/java/sca/contrib/modules/binding-ejb-runtime/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.BindingProviderFactory new file mode 100644 index 0000000000..a89f711da9 --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb-runtime/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.BindingProviderFactory @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for the binding extension +org.apache.tuscany.sca.binding.ejb.provider.EJBBindingProviderFactory;model=org.apache.tuscany.sca.binding.ejb.EJBBinding diff --git a/java/sca/contrib/modules/binding-ejb-runtime/src/main/resources/binding-ejb-validation-messages.properties b/java/sca/contrib/modules/binding-ejb-runtime/src/main/resources/binding-ejb-validation-messages.properties new file mode 100644 index 0000000000..28477dd3ac --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb-runtime/src/main/resources/binding-ejb-validation-messages.properties @@ -0,0 +1,23 @@ +# +# +# 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. +# +# +UnknownEJBSessionType = Unknown EJB Session Type of {0} for {1} +UnknownEJBVersion = Unknown EJB Version of {0} for {1} + diff --git a/java/sca/contrib/modules/binding-ejb-runtime/src/test/java/account/BankManagerFacade.java b/java/sca/contrib/modules/binding-ejb-runtime/src/test/java/account/BankManagerFacade.java new file mode 100644 index 0000000000..337bb004b5 --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb-runtime/src/test/java/account/BankManagerFacade.java @@ -0,0 +1,33 @@ +/* + * 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. + */ +package account; + +import org.oasisopen.sca.annotation.Remotable; + +/** + * + * Compatible EJB interface + * + * @version $Rev$ $Date$ + */ +@Remotable +public interface BankManagerFacade { + Double getAccountBalance( String accountNo ); + void changeAccountBalance( String accountNo, Double balance ); +} diff --git a/java/sca/contrib/modules/binding-ejb-runtime/src/test/java/account/Customer.java b/java/sca/contrib/modules/binding-ejb-runtime/src/test/java/account/Customer.java new file mode 100644 index 0000000000..8585301868 --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb-runtime/src/test/java/account/Customer.java @@ -0,0 +1,36 @@ +/* + * 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. + */ +package account; + +import org.oasisopen.sca.annotation.Remotable; + +@Remotable +public interface Customer { + + /** + * This method deposits the amount. method accesses external EJB to get the + * current balance and add the amount to existing balance. + * + * @param accountNo The number of the account into which to deposit the money + * @param amount The amount to be deposited + * @return total amount in customer account after deposit + */ + Double depositAmount(java.lang.String accountNo, Double amount); + +} diff --git a/java/sca/contrib/modules/binding-ejb-runtime/src/test/java/account/CustomerImpl.java b/java/sca/contrib/modules/binding-ejb-runtime/src/test/java/account/CustomerImpl.java new file mode 100644 index 0000000000..7406b9bd37 --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb-runtime/src/test/java/account/CustomerImpl.java @@ -0,0 +1,57 @@ +/* + * 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. + */ +package account; + +import org.oasisopen.sca.ServiceRuntimeException; +import org.oasisopen.sca.annotation.Reference; +import org.oasisopen.sca.annotation.Service; + +import calculator.AddService; + +@Service(Customer.class) +public class CustomerImpl implements Customer { + + private AddService extEJBService = null; + + public AddService getExtEJBService() { + return extEJBService; + } + + @Reference + public void setExtEJBService(AddService extEJBService) { + this.extEJBService = extEJBService; + } + + // this method invokes external EJB through EJB reference binding + public Double depositAmount(java.lang.String accountNo, Double amount) { + + Double total = null; + + System.out.println("In component implementation. Invoking external EJB through EJB reference binding "); + + try { + Double balance = extEJBService.add(amount.doubleValue(), 1000); //invoke external ejb through ejb reference binding + total = balance + amount; + } catch (Exception e) { + throw new ServiceRuntimeException(e); + } + return total; + } + +} diff --git a/java/sca/contrib/modules/binding-ejb-runtime/src/test/java/calculator/AddService.java b/java/sca/contrib/modules/binding-ejb-runtime/src/test/java/calculator/AddService.java new file mode 100644 index 0000000000..7cefba530a --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb-runtime/src/test/java/calculator/AddService.java @@ -0,0 +1,27 @@ +/* + * 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. + */ + +package calculator; + +/** + * @version $Rev$ $Date$ + */ +public interface AddService { + double add(double n1, double n2); +} diff --git a/java/sca/contrib/modules/binding-ejb-runtime/src/test/java/calculator/AddServiceHome.java b/java/sca/contrib/modules/binding-ejb-runtime/src/test/java/calculator/AddServiceHome.java new file mode 100644 index 0000000000..799bcaa672 --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb-runtime/src/test/java/calculator/AddServiceHome.java @@ -0,0 +1,31 @@ +/* + * 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. + */ + +package calculator; + +import java.rmi.RemoteException; + +import javax.ejb.CreateException; +import javax.ejb.EJBHome; + +public interface AddServiceHome extends EJBHome { + + AddService create() throws CreateException, RemoteException; + +} diff --git a/java/sca/contrib/modules/binding-ejb-runtime/src/test/java/org/apache/geronimo/samples/bank/ejb/BankManagerFacade.java b/java/sca/contrib/modules/binding-ejb-runtime/src/test/java/org/apache/geronimo/samples/bank/ejb/BankManagerFacade.java new file mode 100644 index 0000000000..e480e648d9 --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb-runtime/src/test/java/org/apache/geronimo/samples/bank/ejb/BankManagerFacade.java @@ -0,0 +1,44 @@ +/* + * 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. + */ + +/* + * Generated by XDoclet - Do not edit! + */ +package org.apache.geronimo.samples.bank.ejb; + +// copied from the Geronimo Bank sample: http://cwiki.apache.org/GMOxDOC11/ejb-sample-application.html#EJBsampleapplication-overview + +/** + * Remote interface for BankManagerFacadeBean. + * @xdoclet-generated at ${TODAY} + * @copyright The XDoclet Team + * + * @version $Rev$ $Date$ + */ +public interface BankManagerFacade + extends javax.ejb.EJBObject +{ + + void changeAccountBalance( java.lang.String accountNo,java.lang.Double balance ) + throws java.rmi.RemoteException; + + java.lang.Double getAccountBalance( java.lang.String accountNo ) + throws java.rmi.RemoteException; + +} diff --git a/java/sca/contrib/modules/binding-ejb-runtime/src/test/java/org/apache/geronimo/samples/bank/ejb/BankManagerFacadeHome.java b/java/sca/contrib/modules/binding-ejb-runtime/src/test/java/org/apache/geronimo/samples/bank/ejb/BankManagerFacadeHome.java new file mode 100644 index 0000000000..0d02be3b95 --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb-runtime/src/test/java/org/apache/geronimo/samples/bank/ejb/BankManagerFacadeHome.java @@ -0,0 +1,44 @@ +/* + * 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. + */ + +/* + * Generated by XDoclet - Do not edit! + */ + +// copied from the Geronimo Bank sample: http://cwiki.apache.org/GMOxDOC11/ejb-sample-application.html#EJBsampleapplication-overview + +package org.apache.geronimo.samples.bank.ejb; + +/** + * Home interface for BankManagerFacadeBean. + * @xdoclet-generated at ${TODAY} + * @copyright The XDoclet Team + * + * @version $Rev$ $Date$ + */ +public interface BankManagerFacadeHome + extends javax.ejb.EJBHome +{ + String COMP_NAME="java:comp/env/ejb/BankManagerFacadeBean"; + String JNDI_NAME="org.apache.geronimo.samples.bank.ejb.BankManagerFacadeBean"; + + org.apache.geronimo.samples.bank.ejb.BankManagerFacade create() + throws javax.ejb.CreateException,java.rmi.RemoteException; + +} diff --git a/java/sca/contrib/modules/binding-ejb-runtime/src/test/java/org/apache/tuscany/sca/binding/ejb/tests/EJBReferenceTestCase.java b/java/sca/contrib/modules/binding-ejb-runtime/src/test/java/org/apache/tuscany/sca/binding/ejb/tests/EJBReferenceTestCase.java new file mode 100644 index 0000000000..87616330dc --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb-runtime/src/test/java/org/apache/tuscany/sca/binding/ejb/tests/EJBReferenceTestCase.java @@ -0,0 +1,73 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.ejb.tests; + +import junit.framework.TestCase; + +import org.apache.tuscany.sca.node.Contribution; +import org.apache.tuscany.sca.node.ContributionLocationHelper; +import org.apache.tuscany.sca.node.Node; +import org.apache.tuscany.sca.node.NodeFactory; + +import account.Customer; + +/** + * Invokes the component which calls the reference using the EJB binding + * + * @version $Rev$ $Date$ + */ +public class EJBReferenceTestCase extends TestCase { + private static final int MOCK_PORT = 8085; + private Node node; + + @Override + protected void setUp() throws Exception { + System.setProperty("java.naming.factory.initial", "org.apache.openejb.client.RemoteInitialContextFactory"); + System.setProperty("java.naming.provider.url", "ejbd://localhost:" + MOCK_PORT); + System.setProperty("managed", "false"); + + String contribution = ContributionLocationHelper.getContributionLocation(EJBReferenceTestCase.class); + node = NodeFactory.newInstance().createNode("account/account.composite", new Contribution("account", contribution)); + node.start(); + + // To capture the network traffic for the MockServer, uncomment the next line + // new Thread(new SocketTracer(MOCK_PORT, OPENEJB_PORT)).start(); + + // Start the mock server to simulate the remote EJB + new Thread(new MockServer(MOCK_PORT)).start(); + + // Wait enough for the server to be started + Thread.sleep(500); + } + + @Override + protected void tearDown() throws Exception { + node.stop(); + node.destroy(); + } + + public void testCalculator() throws Exception { + Customer customer = node.getService(Customer.class, "CustomerComponent"); + // This is one of the customer numbers in bank application running on Geronimo + String accountNo = "1234567890"; + Double balance = customer.depositAmount(accountNo, new Double(100)); + // System.out.println("Balance amount for account " + accountNo + " is $" + balance); + assertEquals(1200.0, balance); + } +} diff --git a/java/sca/contrib/modules/binding-ejb-runtime/src/test/java/org/apache/tuscany/sca/binding/ejb/tests/MockServer.java b/java/sca/contrib/modules/binding-ejb-runtime/src/test/java/org/apache/tuscany/sca/binding/ejb/tests/MockServer.java new file mode 100644 index 0000000000..48e87fb6d1 --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb-runtime/src/test/java/org/apache/tuscany/sca/binding/ejb/tests/MockServer.java @@ -0,0 +1,151 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.ejb.tests; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.ServerSocket; +import java.net.Socket; + +public class MockServer implements Runnable { + + private int listen; + byte[][] seq = + { + {79, 69, 74, 80, 47, 51, 46, 48, 1, -84, -19, 0, 5, 119, 58, 1, 27, 0, 54, 47, 104, 101, 108, 108, 111, 45, + 97, 100, 100, 115, 101, 114, 118, 105, 99, 101, 47, 65, 100, 100, 83, 101, 114, 118, 105, 99, 101, 66, 101, + 97, 110, 47, 99, 97, 108, 99, 117, 108, 97, 116, 111, 114, 46, 65, 100, 100, 83, 101, 114, 118, 105, 99, 101, + 112}, + + {79, 69, 74, 80, 47, 50, 46, 48, -84, -19, 0, 5, 119, 3, 1, 13, 1, 118, 114, 0, 25, 99, 97, 108, 99, 117, 108, + 97, 116, 111, 114, 46, 65, 100, 100, 83, 101, 114, 118, 105, 99, 101, 72, 111, 109, 101, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 120, 112, 118, 114, 0, 21, 99, 97, 108, 99, 117, 108, 97, 116, 111, 114, 46, 65, 100, 100, 83, + 101, 114, 118, 105, 99, 101, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 120, 112, 112, 112, 119, 38, 7, 0, 31, 104, + 101, 108, 108, 111, 45, 97, 100, 100, 115, 101, 114, 118, 105, 99, 101, 47, 65, 100, 100, 83, 101, 114, 118, + 105, 99, 101, 66, 101, 97, 110, -1, -1, 0, 0}, + + {79, 69, 74, 80, 47, 51, 46, 48, 0, -84, -19, 0, 5, 119, 1, 10, 116, 0, 31, 104, 101, 108, 108, 111, 45, 97, + 100, 100, 115, 101, 114, 118, 105, 99, 101, 47, 65, 100, 100, 83, 101, 114, 118, 105, 99, 101, 66, 101, 97, + 110, 119, 2, -1, -1, 112, 119, 1, 1, 112, 118, 114, 0, 25, 99, 97, 108, 99, 117, 108, 97, 116, 111, 114, 46, + 65, 100, 100, 83, 101, 114, 118, 105, 99, 101, 72, 111, 109, 101, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 120, 112, + 119, 9, 0, 6, 99, 114, 101, 97, 116, 101, 0}, + {79, 69, 74, 80, 47, 50, 46, 48, -84, -19, 0, 5, 119, 2, 1, 4, 112}, + + {79, 69, 74, 80, 47, 51, 46, 48, 0, -84, -19, 0, 5, 119, 1, 23, 116, 0, 31, 104, 101, 108, 108, 111, 45, 97, + 100, 100, 115, 101, 114, 118, 105, 99, 101, 47, 65, 100, 100, 83, 101, 114, 118, 105, 99, 101, 66, 101, 97, + 110, 119, 2, -1, -1, 112, 119, 1, 1, 112, 118, 114, 0, 21, 99, 97, 108, 99, 117, 108, 97, 116, 111, 114, 46, + 65, 100, 100, 83, 101, 114, 118, 105, 99, 101, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 120, 112, 119, 24, 0, 3, 97, + 100, 100, 2, 4, 64, 89, 0, 0, 0, 0, 0, 0, 4, 64, -113, 64, 0, 0, 0, 0, 0}, + {79, 69, 74, 80, 47, 50, 46, 48, -84, -19, 0, 5, 119, 2, 1, 4, 115, 114, 0, 16, 106, 97, 118, 97, 46, 108, 97, + 110, 103, 46, 68, 111, 117, 98, 108, 101, -128, -77, -62, 74, 41, 107, -5, 4, 2, 0, 1, 68, 0, 5, 118, 97, + 108, 117, 101, 120, 114, 0, 16, 106, 97, 118, 97, 46, 108, 97, 110, 103, 46, 78, 117, 109, 98, 101, 114, + -122, -84, -107, 29, 11, -108, -32, -117, 2, 0, 0, 120, 112, 64, -111, 48, 0, 0, 0, 0, 0} + + }; + + public MockServer(int listen) { + this.listen = listen; + } + + public void run() { + try { + ServerSocket ss = new ServerSocket(listen); + for (int i = 0; i < seq.length; i += 2) { + // System.out.println("Processing request[" + i/2 + "]"); + doExchange(ss.accept(), seq[i], seq[i + 1]); + } + + } catch (Exception e) { + e.printStackTrace(); + } + } + + private void doExchange(Socket socket, byte[] read, byte[] write) throws IOException, InterruptedException { + Thread t2 = readBytes(socket, read.length); + Thread t1 = writeBytes(socket, write); + t1.join(); + t2.join(); + socket.close(); + } + + private Thread readBytes(Socket socket, int x) throws IOException, InterruptedException { + byte[] buf = new byte[x]; + Thread t = new Reader(socket, buf); + t.start(); + return t; + } + + private Thread writeBytes(Socket socket, byte[] bs) throws IOException, InterruptedException { + Thread t = new Writer(socket, bs); + t.start(); + return t; + } + + private static class Reader extends Thread { + + private InputStream is; + private byte[] buf; + + Reader(Socket socket, byte[] buf) throws IOException { + this.is = socket.getInputStream(); + this.buf = buf; + } + + @Override + public void run() { + try { + int totalSize = buf.length; + int readSize = 0; + int offset = 0; + while (totalSize > 0 && (readSize = is.read(buf, offset, totalSize)) != -1) { + offset += readSize; + totalSize -= readSize; + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + } + + private static class Writer extends Thread { + + private OutputStream os; + private byte[] buf; + + Writer(Socket socket, byte[] buf) throws IOException { + this.os = socket.getOutputStream(); + this.buf = buf; + } + + @Override + public void run() { + try { + os.write(buf); + os.flush(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + } + +} diff --git a/java/sca/contrib/modules/binding-ejb-runtime/src/test/java/org/apache/tuscany/sca/binding/ejb/tests/SocketTracer.java b/java/sca/contrib/modules/binding-ejb-runtime/src/test/java/org/apache/tuscany/sca/binding/ejb/tests/SocketTracer.java new file mode 100644 index 0000000000..66b3feb458 --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb-runtime/src/test/java/org/apache/tuscany/sca/binding/ejb/tests/SocketTracer.java @@ -0,0 +1,138 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.ejb.tests; + +import java.io.InputStream; +import java.io.OutputStream; +import java.net.ServerSocket; +import java.net.Socket; + +/** + * Displays the bytes flowing across a Socket connection. + * Used to get the read count and reply data for the MockServer + * + * @version $Rev$ $Date$ + */ +public class SocketTracer implements Runnable { + + private int listen; + private int send; + + SocketTracer(int listen, int send) { + this.listen = listen; + this.send = send; + } + + public void run() { + try { + ServerSocket ss = new ServerSocket(listen); + while (true) { + Socket sin = ss.accept(); + + Socket sout = new Socket("localhost", send); + + Thread st = new Thread(new Send(sin, sout)); + st.start(); + } + + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * @param buf + * @param count + */ + static synchronized void dump(String str, byte[] buf, int count) { + // System.out.println(Thread.currentThread()); + System.out.print(str+"{"); + for (int j = 0; j < count; j++) { + if (j == count - 1) { + System.out.println(buf[j] + "}, "); + } else { + System.out.print(buf[j] + ", "); + } + } + } +} + + +class Send implements Runnable { + + Socket sin; + Socket sout; + + Send(Socket sin, Socket sout) { + this.sin = sin; + this.sout = sout; + } + + public void run() { + try { + + Reply rr = new Reply(sout.getInputStream(), sin.getOutputStream()); + Thread rt = new Thread(rr); + rt.start(); + + OutputStream outout = sout.getOutputStream(); + InputStream is = sin.getInputStream(); + byte[] buf = new byte[4096]; + int i = 0; + int count = 0; + while ((i = is.read()) != -1) { + buf[count++] = (byte)i; + outout.write(i); + } + SocketTracer.dump("Req: ", buf, count); + + } catch (Exception e) { + e.printStackTrace(); + } + } + +} + +class Reply implements Runnable { + + InputStream is; + OutputStream outout; + + Reply(InputStream is, OutputStream outout) { + this.is = is; + this.outout = outout; + } + + public void run() { + try { + byte[] buf = new byte[4096]; + int i = 0; + int count = 0; + while ((i = is.read()) != -1) { + buf[count++] = (byte)i; + outout.write(i); + } + SocketTracer.dump("Res: ", buf, count); + } catch (Exception e) { + e.printStackTrace(); + } + } + +} diff --git a/java/sca/contrib/modules/binding-ejb-runtime/src/test/resources/account/account.composite b/java/sca/contrib/modules/binding-ejb-runtime/src/test/resources/account/account.composite new file mode 100644 index 0000000000..14f77eed08 --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb-runtime/src/test/resources/account/account.composite @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + diff --git a/java/sca/contrib/modules/binding-ejb/LICENSE b/java/sca/contrib/modules/binding-ejb/LICENSE new file mode 100644 index 0000000000..8aa906c321 --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb/LICENSE @@ -0,0 +1,205 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + + diff --git a/java/sca/contrib/modules/binding-ejb/META-INF/MANIFEST.MF b/java/sca/contrib/modules/binding-ejb/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..5aa1b50c93 --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb/META-INF/MANIFEST.MF @@ -0,0 +1,27 @@ +Manifest-Version: 1.0 +Export-Package: org.apache.tuscany.sca.binding.ejb;uses:="org.apache.t + uscany.sca.assembly,javax.xml.namespace";version="2.0.0" +Private-Package: org.apache.tuscany.sca.binding.ejb.impl;version="2.0.0" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA EJB Binding Model +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397146656 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA EJB Binding Model +Import-Package: javax.xml.namespace, + javax.xml.stream, + org.apache.tuscany.sca.assembly;version="2.0.0", + org.apache.tuscany.sca.assembly.xml;version="2.0.0", + org.apache.tuscany.sca.binding.ejb;version="2.0.0", + org.apache.tuscany.sca.contribution.processor;version="2.0.0", + org.apache.tuscany.sca.contribution.resolver;version="2.0.0", + org.apache.tuscany.sca.core;version="2.0.0", + org.apache.tuscany.sca.interfacedef;version="2.0.0", + org.apache.tuscany.sca.monitor;version="2.0.0", + org.apache.tuscany.sca.policy;version="2.0.0" +Bundle-SymbolicName: org.apache.tuscany.sca.binding.ejb +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/binding-ejb/NOTICE b/java/sca/contrib/modules/binding-ejb/NOTICE new file mode 100644 index 0000000000..25bb89c9b2 --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/binding-ejb/pom.xml b/java/sca/contrib/modules/binding-ejb/pom.xml new file mode 100644 index 0000000000..7fa7b2d6c3 --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb/pom.xml @@ -0,0 +1,66 @@ + + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + + tuscany-binding-ejb + Apache Tuscany SCA EJB Binding Model + + + + org.apache.tuscany.sca + tuscany-assembly + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-assembly-xml + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-interface-java + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-policy + 2.0-SNAPSHOT + + + + junit + junit + 4.5 + test + + + + diff --git a/java/sca/contrib/modules/binding-ejb/src/main/java/org/apache/tuscany/sca/binding/ejb/EJBBinding.java b/java/sca/contrib/modules/binding-ejb/src/main/java/org/apache/tuscany/sca/binding/ejb/EJBBinding.java new file mode 100644 index 0000000000..271a113429 --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb/src/main/java/org/apache/tuscany/sca/binding/ejb/EJBBinding.java @@ -0,0 +1,94 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.ejb; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.assembly.Base; +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.assembly.xml.Constants; + +/** + * An implementation of EJBBinding. + * + * @version $Rev$ $Date$ + */ +public interface EJBBinding extends Binding, Base { + // Constants used when describing the EJB binding + // model and for setting up defaults + String BINDING_EJB = "binding.ejb"; + QName BINDING_EJB_QNAME = new QName(Constants.SCA10_NS, BINDING_EJB); + + // Constants for the XML describing the EJB Binding + String HOME_INTERFACE = "homeInterface"; + String EJB_LINK_NAME = "ejb-link-name"; + String SESSION_TYPE = "session-type"; + String EJB_VERSION = "ejb-version"; + String NAME = "name"; + String POLICY_SETS = "policySets"; + String REQUIRES = "requires"; + String URI = "uri"; + + // Enums for the EJB Binding + enum EJBVersion { + EJB2, EJB3 + }; + + enum SessionType { + STATEFUL, STATELESS + }; + + /** + * Gets the homeInterface. + * + * @return home interface of the service binding + */ + String getHomeInterface(); + + /** + * Set homeInterface + * + * @param homeInterface + */ + void setHomeInterface(String homeInterface); + + /** + * get ejb-link-name + * + * @return ejb-link-name + */ + String getEjbLinkName(); + + /** + * Set ejb-link-name + * + * @param ejb-link-name + */ + void setEjbLinkName(String ejbLinkName); + + SessionType getSessionType(); + void setSessionType(SessionType sessionType); + + EJBVersion getEjbVersion(); + void setEjbVersion(EJBVersion ejbVersion); + + // FIXME: Should use Intent instead of String + String getRequires(); + void setRequires(String requires); +} diff --git a/java/sca/contrib/modules/binding-ejb/src/main/java/org/apache/tuscany/sca/binding/ejb/EJBBindingException.java b/java/sca/contrib/modules/binding-ejb/src/main/java/org/apache/tuscany/sca/binding/ejb/EJBBindingException.java new file mode 100644 index 0000000000..6e2c8d358f --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb/src/main/java/org/apache/tuscany/sca/binding/ejb/EJBBindingException.java @@ -0,0 +1,56 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.ejb; + +/** + * Exception for the EJB Binding + * + * @version $Rev$ $Date$ + */ +public class EJBBindingException extends RuntimeException { + private static final long serialVersionUID = 1L; + + /** + * {@inheritDoc} + */ + public EJBBindingException() { + super(); + } + + /** + * {@inheritDoc} + */ + public EJBBindingException(String message, Throwable cause) { + super(message, cause); + } + + /** + * {@inheritDoc} + */ + public EJBBindingException(String message) { + super(message); + } + + /** + * {@inheritDoc} + */ + public EJBBindingException(Throwable cause) { + super(cause); + } +} diff --git a/java/sca/contrib/modules/binding-ejb/src/main/java/org/apache/tuscany/sca/binding/ejb/EJBBindingFactory.java b/java/sca/contrib/modules/binding-ejb/src/main/java/org/apache/tuscany/sca/binding/ejb/EJBBindingFactory.java new file mode 100644 index 0000000000..13b069a6bb --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb/src/main/java/org/apache/tuscany/sca/binding/ejb/EJBBindingFactory.java @@ -0,0 +1,35 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.ejb; + +/** + * Factory for the EJB binding + * + * @version $Rev$ $Date$ + */ +public interface EJBBindingFactory { + + /** + * Creates a new EJB binding. + * @return the new EJB binding + */ + EJBBinding createEJBBinding(); + +} diff --git a/java/sca/contrib/modules/binding-ejb/src/main/java/org/apache/tuscany/sca/binding/ejb/impl/EJBBindingFactoryImpl.java b/java/sca/contrib/modules/binding-ejb/src/main/java/org/apache/tuscany/sca/binding/ejb/impl/EJBBindingFactoryImpl.java new file mode 100644 index 0000000000..e84de86eca --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb/src/main/java/org/apache/tuscany/sca/binding/ejb/impl/EJBBindingFactoryImpl.java @@ -0,0 +1,36 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.ejb.impl; + +import org.apache.tuscany.sca.binding.ejb.EJBBinding; +import org.apache.tuscany.sca.binding.ejb.EJBBindingFactory; + +/** + * Factory class for building EJBBindings. + * + * @version $Rev$ $Date$ + * + */ +public class EJBBindingFactoryImpl implements EJBBindingFactory { + + public EJBBinding createEJBBinding() { + return new EJBBindingImpl(); + } + +} diff --git a/java/sca/contrib/modules/binding-ejb/src/main/java/org/apache/tuscany/sca/binding/ejb/impl/EJBBindingImpl.java b/java/sca/contrib/modules/binding-ejb/src/main/java/org/apache/tuscany/sca/binding/ejb/impl/EJBBindingImpl.java new file mode 100644 index 0000000000..4abed80aa3 --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb/src/main/java/org/apache/tuscany/sca/binding/ejb/impl/EJBBindingImpl.java @@ -0,0 +1,183 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.ejb.impl; + +import org.apache.tuscany.sca.binding.ejb.EJBBinding; + +/** + * An implementation of EJBBinding. + * + * @version $Rev$ $Date$ + */ +public class EJBBindingImpl implements EJBBinding { + + /** + * CORBA location For example, + * "corbaname:iiop:localhost:2809/NameServiceServerRoot#ejb/MyEJBHome" + */ + private String uri; + + /** + * homeInterface. remote or local + */ + private String homeInterface; + + /** + * The ejb-link-name attribute allows a SCA client to bind to an EJB that is + * packaged in the same JEE EAR file as the SCA client. This is functionally + * equivalent to using the subelement of the element + * in s EJB deployment descriptor. Used only for Service binding + */ + private String ejbLinkName; + + /** + * The name of this binding + */ + private String name; + + /** + * Whether the binding is unresolved + */ + private boolean unresolved; + + /** + * Clone the binding + */ + @Override + public Object clone() throws CloneNotSupportedException { + return super.clone(); + } + + /** + * The type of session for this EJB Binding + */ + private SessionType sessionType; + + /** + * The EJB version for this EJB Binding + */ + private EJBVersion ejbVersion; + + private String requires; + + /** + * Constructor + */ + public EJBBindingImpl() { + super(); + unresolved = true; + } + + /** + * Gets the homeInterface. + * + * @return home interface of the service binding + */ + public String getHomeInterface() { + return homeInterface; + } + + /** + * Set homeInterface + * + * @param homeInterface + */ + public void setHomeInterface(String homeInterface) { + this.homeInterface = homeInterface; + } + + /** + * get ejb-link-name + * + * @return ejb-link-name + */ + public String getEjbLinkName() { + return ejbLinkName; + } + + /** + * Set ejb-link-name + * + * @param ejb-link-name + */ + public void setEjbLinkName(String ejbLinkName) { + this.ejbLinkName = ejbLinkName; + } + + /** + * {@inheritDoc} + */ + public String getName() { + return this.name; + } + + /** + * {@inheritDoc} + */ + public String getURI() { + return uri; + } + + /** + * {@inheritDoc} + */ + public void setName(String name) { + this.name = name; + } + + /** + * {@inheritDoc} + */ + public void setURI(String uri) { + this.uri = uri; + } + + public boolean isUnresolved() { + return this.unresolved; + } + + public void setUnresolved(boolean unresolved) { + this.unresolved = unresolved; + } + + public void setSessionType(SessionType ejb_version_enum) { + this.sessionType = ejb_version_enum; + } + + public void setEjbVersion(EJBVersion ejb_version_enum) { + this.ejbVersion = ejb_version_enum; + } + + public void setRequires(String requires) { + this.requires = requires; + + } + + public SessionType getSessionType() { + return sessionType; + } + + public EJBVersion getEjbVersion() { + return ejbVersion; + } + + public String getRequires() { + return requires; + } +} diff --git a/java/sca/contrib/modules/binding-ejb/src/main/java/org/apache/tuscany/sca/binding/ejb/impl/EJBBindingProcessor.java b/java/sca/contrib/modules/binding-ejb/src/main/java/org/apache/tuscany/sca/binding/ejb/impl/EJBBindingProcessor.java new file mode 100644 index 0000000000..0320142dde --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb/src/main/java/org/apache/tuscany/sca/binding/ejb/impl/EJBBindingProcessor.java @@ -0,0 +1,184 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.ejb.impl; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; + +import org.apache.tuscany.sca.assembly.xml.Constants; +import org.apache.tuscany.sca.assembly.xml.PolicyAttachPointProcessor; +import org.apache.tuscany.sca.binding.ejb.EJBBinding; +import org.apache.tuscany.sca.binding.ejb.EJBBindingFactory; +import org.apache.tuscany.sca.contribution.processor.ContributionReadException; +import org.apache.tuscany.sca.contribution.processor.ContributionResolveException; +import org.apache.tuscany.sca.contribution.processor.ContributionWriteException; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.core.FactoryExtensionPoint; +import org.apache.tuscany.sca.monitor.Monitor; +import org.apache.tuscany.sca.monitor.Problem; +import org.apache.tuscany.sca.monitor.Problem.Severity; +import org.apache.tuscany.sca.policy.PolicyFactory; + +/** + * A processor to read the XML that describes the EJB binding... + * + * + * + * + * + * + * + * @version $Rev$ $Date$ + */ +public class EJBBindingProcessor implements StAXArtifactProcessor { + private PolicyFactory policyFactory; + private PolicyAttachPointProcessor policyProcessor; + private Monitor monitor; + private EJBBindingFactory ejbBindingFactory; + + public EJBBindingProcessor(FactoryExtensionPoint modelFactories, Monitor monitor) { + this.policyFactory = modelFactories.getFactory(PolicyFactory.class); + this.ejbBindingFactory = modelFactories.getFactory(EJBBindingFactory.class); + this.policyProcessor = new PolicyAttachPointProcessor(policyFactory); + this.monitor = monitor; + } + + /** + * Report a error. + * + * @param problems + * @param message + * @param model + */ + private void error(String message, Object model, Object... messageParameters) { + if (monitor != null) { + Problem problem = monitor.createProblem(this.getClass().getName(), "binding-ejb-validation-messages", Severity.ERROR, model, message, (Object[])messageParameters); + monitor.problem(problem); + } + } + + /** + * {@inheritDoc} + */ + public QName getArtifactType() { + return EJBBinding.BINDING_EJB_QNAME; + } + + /** + * {@inheritDoc} + */ + public EJBBinding read(XMLStreamReader reader) throws ContributionReadException, XMLStreamException { + EJBBinding ejbBinding = ejbBindingFactory.createEJBBinding(); + + // Read the policies + policyProcessor.readPolicies(ejbBinding, reader); + + // Read the name + String name = reader.getAttributeValue(null, EJBBinding.NAME); + if (name != null) { + ejbBinding.setName(name); + } + + // Read binding URI + String uri = reader.getAttributeValue(null, EJBBinding.URI); + if (uri != null) { + ejbBinding.setURI(uri); + } + + String homeInterface = reader.getAttributeValue(null, EJBBinding.HOME_INTERFACE); + if (homeInterface != null) { + ejbBinding.setHomeInterface(homeInterface); + } + + String ejbLinkName = reader.getAttributeValue(null, EJBBinding.EJB_LINK_NAME); + if (ejbLinkName != null) { + ejbBinding.setEjbLinkName(ejbLinkName); + } + + String sessionType = reader.getAttributeValue(null, EJBBinding.SESSION_TYPE); + if (sessionType != null) { + if (sessionType.equals("stateless")) { + ejbBinding.setSessionType(EJBBinding.SessionType.STATELESS); + } else if (sessionType.equals("stateful")) { + ejbBinding.setSessionType(EJBBinding.SessionType.STATEFUL); + } else { + error("UnknownEJBSessionType", reader, sessionType, name); + //throw new ContributionReadException("Unknown EJB Session Type of " + sessionType + " for " + name); + } + } + + String ejbVersion = reader.getAttributeValue(null, EJBBinding.EJB_VERSION); + if (ejbVersion != null) { + if (ejbVersion.equals("EJB2")) { + ejbBinding.setEjbVersion(EJBBinding.EJBVersion.EJB2); + } else if (ejbVersion.equals("EJB3")) { + ejbBinding.setEjbVersion(EJBBinding.EJBVersion.EJB3); + } else { + error("UnknownEJBVersion", reader, ejbVersion, name); + //throw new ContributionReadException("Unknown EJB Version of " + ejbVersion + " for " + name); + } + } + + // TODO: Read requires + String requires = reader.getAttributeValue(null, EJBBinding.REQUIRES); + if (requires != null) { + ejbBinding.setRequires(requires); + } + + return ejbBinding; + } + + public void write(EJBBinding ejbBinding, XMLStreamWriter writer) throws ContributionWriteException, + XMLStreamException { + // Write a + writer.writeStartElement(Constants.SCA10_NS, EJBBinding.BINDING_EJB); + + if (ejbBinding.getName() != null){ + writer.writeAttribute(EJBBinding.NAME, ejbBinding.getName()); + } + + if (ejbBinding.getURI() != null){ + writer.writeAttribute(EJBBinding.URI, ejbBinding.getURI()); + } + + + // FIXME Implement the rest + + writer.writeEndElement(); + } + + public Class getModelType() { + return EJBBinding.class; + } + + public void resolve(EJBBinding ejbBinding, ModelResolver modelResolver) throws ContributionResolveException { + } +} diff --git a/java/sca/contrib/modules/binding-ejb/src/main/resources/META-INF/services/org.apache.tuscany.sca.binding.ejb.EJBBindingFactory b/java/sca/contrib/modules/binding-ejb/src/main/resources/META-INF/services/org.apache.tuscany.sca.binding.ejb.EJBBindingFactory new file mode 100644 index 0000000000..c445a82ecb --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb/src/main/resources/META-INF/services/org.apache.tuscany.sca.binding.ejb.EJBBindingFactory @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for model factory +org.apache.tuscany.sca.binding.ejb.impl.EJBBindingFactoryImpl diff --git a/java/sca/contrib/modules/binding-ejb/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor b/java/sca/contrib/modules/binding-ejb/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor new file mode 100644 index 0000000000..82e85ef067 --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for the artifact processor extension +org.apache.tuscany.sca.binding.ejb.impl.EJBBindingProcessor;qname=http://www.osoa.org/xmlns/sca/1.0#binding.ejb,model=org.apache.tuscany.sca.binding.ejb.EJBBinding diff --git a/java/sca/contrib/modules/binding-ejb/src/main/resources/binding-ejb-validation-messages.properties b/java/sca/contrib/modules/binding-ejb/src/main/resources/binding-ejb-validation-messages.properties new file mode 100644 index 0000000000..28477dd3ac --- /dev/null +++ b/java/sca/contrib/modules/binding-ejb/src/main/resources/binding-ejb-validation-messages.properties @@ -0,0 +1,23 @@ +# +# +# 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. +# +# +UnknownEJBSessionType = Unknown EJB Session Type of {0} for {1} +UnknownEJBVersion = Unknown EJB Version of {0} for {1} + diff --git a/java/sca/contrib/modules/binding-gdata-runtime/LICENSE b/java/sca/contrib/modules/binding-gdata-runtime/LICENSE new file mode 100644 index 0000000000..8aa906c321 --- /dev/null +++ b/java/sca/contrib/modules/binding-gdata-runtime/LICENSE @@ -0,0 +1,205 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + + diff --git a/java/sca/contrib/modules/binding-gdata-runtime/META-INF/MANIFEST.MF b/java/sca/contrib/modules/binding-gdata-runtime/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..41d0fbf451 --- /dev/null +++ b/java/sca/contrib/modules/binding-gdata-runtime/META-INF/MANIFEST.MF @@ -0,0 +1,48 @@ +Manifest-Version: 1.0 +Export-Package: org.apache.tuscany.sca.binding.gdata.collection;uses:= + "org.oasisopen.sca.annotation,com.google.gdata.client,com.google.gdata.da + ta";version="2.0.0" +Private-Package: org.apache.tuscany.sca.binding.gdata.provider;version + ="1.4" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA Gdata Binding Extension Runtime GSOC +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397270375 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA Gdata Binding Extension Runtime + GSOC +Import-Package: com.google.gdata.client, + com.google.gdata.data, + com.google.gdata.util, + com.google.gdata.util.common.xml, + javax.servlet, + javax.servlet.http, + javax.xml.namespace, + org.apache.commons.codec.binary, + org.apache.commons.httpclient, + org.apache.commons.httpclient.auth, + org.apache.commons.httpclient.methods, + org.apache.commons.httpclient.params, + org.apache.tuscany.sca.assembly;version="2.0.0", + org.apache.tuscany.sca.binding.gdata;version="2.0.0", + org.apache.tuscany.sca.binding.gdata.collection;version="2.0.0", + org.apache.tuscany.sca.core;version="2.0.0", + org.apache.tuscany.sca.data.collection;version="2.0.0", + org.apache.tuscany.sca.databinding;version="2.0.0", + org.apache.tuscany.sca.databinding.impl;version="2.0.0", + org.apache.tuscany.sca.host.http;version="2.0.0", + org.apache.tuscany.sca.interfacedef;version="2.0.0", + org.apache.tuscany.sca.interfacedef.impl;version="2.0.0", + org.apache.tuscany.sca.interfacedef.util;version="2.0.0", + org.apache.tuscany.sca.invocation;version="2.0.0", + org.apache.tuscany.sca.policy;version="2.0.0", + org.apache.tuscany.sca.provider;version="2.0.0", + org.apache.tuscany.sca.runtime;version="2.0.0", + org.oasisopen.sca;version="2.0.0", + org.oasisopen.sca.annotation;version="2.0.0" +Bundle-SymbolicName: org.apache.tuscany.sca.binding.gdata.runtime +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/binding-gdata-runtime/NOTICE b/java/sca/contrib/modules/binding-gdata-runtime/NOTICE new file mode 100644 index 0000000000..25bb89c9b2 --- /dev/null +++ b/java/sca/contrib/modules/binding-gdata-runtime/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/binding-gdata-runtime/pom.xml b/java/sca/contrib/modules/binding-gdata-runtime/pom.xml new file mode 100644 index 0000000000..2670493cfe --- /dev/null +++ b/java/sca/contrib/modules/binding-gdata-runtime/pom.xml @@ -0,0 +1,169 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + + tuscany-binding-gdata-runtime + Apache Tuscany SCA Gdata Binding Extension Runtime GSOC + + + + com.google.gdata + http://people.apache.org/~lresende/google-gdata/maven/ + + + + + + + org.apache.tuscany.sca + tuscany-binding-gdata + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-assembly + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-interface-java + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-data-api + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-core-spi + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-databinding + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-host-http + 2.0-SNAPSHOT + + + + commons-httpclient + commons-httpclient + 3.1 + + + + com.google.gdata + gdata-client + 1.0 + + + + com.google.gdata + gdata-client-meta + 1.0 + + + + com.google.gdata + gdata-core + 1.0 + + + + com.google.gdata + gdata-media + 1.0 + + + + javax.servlet + servlet-api + 2.5 + + + + org.apache.tuscany.sca + tuscany-host-jetty + 2.0-SNAPSHOT + test + + + + org.apache.tuscany.sca + tuscany-implementation-java-runtime + 2.0-SNAPSHOT + test + + + + org.apache.tuscany.sca + tuscany-node-impl + 2.0-SNAPSHOT + test + + + + junit + junit + 4.5 + test + + + + commons-codec + commons-codec + 1.3 + + + commons-codec + commons-codec + + + + + + commons-logging + commons-logging + 1.1.1 + + + javax.servlet + servlet-api + + + avalon-framework + avalon-framework + + + + + + + diff --git a/java/sca/contrib/modules/binding-gdata-runtime/src/main/java/org/apache/tuscany/sca/binding/gdata/collection/Collection.java b/java/sca/contrib/modules/binding-gdata-runtime/src/main/java/org/apache/tuscany/sca/binding/gdata/collection/Collection.java new file mode 100644 index 0000000000..b3d672b9d4 --- /dev/null +++ b/java/sca/contrib/modules/binding-gdata-runtime/src/main/java/org/apache/tuscany/sca/binding/gdata/collection/Collection.java @@ -0,0 +1,79 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.gdata.collection; + +import com.google.gdata.client.Query; +import com.google.gdata.data.Entry; +import com.google.gdata.data.Feed; +import org.oasisopen.sca.annotation.Remotable; + +/** + * Provides access to a collection of resources using Gdata. + */ +@Remotable +public interface Collection { + + /** + * Get a GData feed for a collection of resources. + * + * @return the GData feed + */ + Feed getFeed(); + + /** + * Get a GData feed for a collection of resources resulting from a query. + * + * @param queryString a query string + * @return the GData feed + */ + Feed query(Query query); + + /** + * Creates a new entry. + * + * @param entry + * @return + */ + Entry post(Entry entry); + + /** + * Retrieves an entry. + * + * @param id + * @return + */ + Entry get(String id) throws NotFoundException; + + /** + * Update an entry. + * + * @param id + * @param entry + * @return + */ + void put(String id, Entry entry) throws NotFoundException; + + /** + * Delete an entry. + * + * @param id + */ + void delete(String id) throws NotFoundException; + +} diff --git a/java/sca/contrib/modules/binding-gdata-runtime/src/main/java/org/apache/tuscany/sca/binding/gdata/collection/MediaCollection.java b/java/sca/contrib/modules/binding-gdata-runtime/src/main/java/org/apache/tuscany/sca/binding/gdata/collection/MediaCollection.java new file mode 100644 index 0000000000..174efef1bc --- /dev/null +++ b/java/sca/contrib/modules/binding-gdata-runtime/src/main/java/org/apache/tuscany/sca/binding/gdata/collection/MediaCollection.java @@ -0,0 +1,55 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.gdata.collection; + +import java.io.InputStream; + +import org.oasisopen.sca.annotation.Remotable; + +import com.google.gdata.data.Entry; + +/** + * Provides access to a collection of resources using Atom. + * + * @version $Rev$ $Date$ + */ +@Remotable +public interface MediaCollection extends Collection { + + /** + * Creates a new media entry + * + * @param title + * @param slug + * @param contentType + * @param media + */ + Entry postMedia(String title, String slug, String contentType, InputStream media); + + /** + * Update a media entry. + * + * @param id + * @param contentType + * @param media + * @return + */ + void putMedia(String id, String contentType, InputStream media) throws NotFoundException; + +} diff --git a/java/sca/contrib/modules/binding-gdata-runtime/src/main/java/org/apache/tuscany/sca/binding/gdata/collection/NotFoundException.java b/java/sca/contrib/modules/binding-gdata-runtime/src/main/java/org/apache/tuscany/sca/binding/gdata/collection/NotFoundException.java new file mode 100644 index 0000000000..91e3616ad9 --- /dev/null +++ b/java/sca/contrib/modules/binding-gdata-runtime/src/main/java/org/apache/tuscany/sca/binding/gdata/collection/NotFoundException.java @@ -0,0 +1,45 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.gdata.collection; + +/** + * Indicates that a resource could not be found. + * + * @version $Rev$ $Date$ + */ + +public class NotFoundException extends Exception { + private static final long serialVersionUID = -5046027674128627383L; + + public NotFoundException() { + } + + public NotFoundException(String message) { + super(message); + } + + public NotFoundException(Throwable cause) { + super(cause); + } + + public NotFoundException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/java/sca/contrib/modules/binding-gdata-runtime/src/main/java/org/apache/tuscany/sca/binding/gdata/provider/GdataBindingInvoker.java b/java/sca/contrib/modules/binding-gdata-runtime/src/main/java/org/apache/tuscany/sca/binding/gdata/provider/GdataBindingInvoker.java new file mode 100644 index 0000000000..312c1fe641 --- /dev/null +++ b/java/sca/contrib/modules/binding-gdata-runtime/src/main/java/org/apache/tuscany/sca/binding/gdata/provider/GdataBindingInvoker.java @@ -0,0 +1,425 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.gdata.provider; + +import static org.apache.tuscany.sca.binding.gdata.provider.GdataBindingUtil.entry; +import static org.apache.tuscany.sca.binding.gdata.provider.GdataBindingUtil.feedEntry; + +import java.io.IOException; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.methods.DeleteMethod; +import org.apache.commons.httpclient.methods.GetMethod; +import org.apache.commons.httpclient.methods.PutMethod; +import org.apache.tuscany.sca.binding.gdata.collection.NotFoundException; +import org.apache.tuscany.sca.data.collection.Entry; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.DataExchangeSemantics; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; +import org.oasisopen.sca.ServiceRuntimeException; + +import com.google.gdata.client.GoogleService; +import com.google.gdata.client.Query; +import com.google.gdata.data.Feed; +import com.google.gdata.util.ResourceNotFoundException; +import com.google.gdata.util.ServiceException; + +/** + * Invoker for the GData binding. + * + * @version $Rev$ $Date$ + */ +class GdataBindingInvoker implements Invoker, DataExchangeSemantics { + + Operation operation; + String uri; + HttpClient httpClient; + String authorizationHeader; + GdataReferenceBindingProvider provider; + GoogleService googleService; + + GdataBindingInvoker(Operation operation, + String uri, + GoogleService googleService, + HttpClient httpClient, + String authorizationHeader, + GdataReferenceBindingProvider bindingProvider) { + this.operation = operation; + this.uri = uri; + this.googleService = googleService; + this.httpClient = httpClient; + this.authorizationHeader = authorizationHeader; + this.provider = bindingProvider; + + } + + + public boolean allowsPassByReference() { + return true; + } + + public Message invoke(Message msg) { + // Shouldn't get here, as the only supported methods are + // defined in the ResourceCollection interface, and implemented + // by specific invoker subclasses + throw new UnsupportedOperationException(operation.getName()); + } + + + /** + * Get operation invoker + */ + public static class GetInvoker extends GdataBindingInvoker { + + public GetInvoker(Operation operation, + String uri, + GoogleService googleService, + HttpClient httpClient, + String authorizationHeader, + GdataReferenceBindingProvider bindingProvider) { + super(operation, uri, googleService, httpClient, authorizationHeader, bindingProvider); + } + + @SuppressWarnings("finally") + @Override + public Message invoke(Message msg) { + + // Get the entry id from the message body + String id = (String)((Object[])msg.getBody())[0]; + + // Send an HTTP GET + GetMethod getMethod = new GetMethod(uri + "/" + id); + getMethod.setRequestHeader("Authorization", authorizationHeader); + + try { + URL entryURL = new URL(uri + "/" + id); + com.google.gdata.data.Entry feedEntry = googleService.getEntry(entryURL, com.google.gdata.data.Entry.class); + msg.setBody(feedEntry); + } catch (IOException ex) { + msg.setFaultBody(new ServiceRuntimeException(ex)); + } catch (ServiceException ex) { + msg.setFaultBody(new ServiceRuntimeException(ex)); + } finally { + return msg; + } + + } + } + + /** + * Post operation invoker + */ + public static class PostInvoker extends GdataBindingInvoker { + + public PostInvoker(Operation operation, + String uri, + GoogleService googleService, + HttpClient httpClient, + String authorizationHeader, + GdataReferenceBindingProvider bindingProvider) { + super(operation, uri, googleService, httpClient, authorizationHeader, bindingProvider); + } + + @SuppressWarnings("finally") + @Override + public Message invoke(Message msg) { + + System.out.println("[Debug Info]GdataBindingInvoker.PostInvoker --- invoke method reached"); + // Post an entry + Object[] args = (Object[])msg.getBody(); + com.google.gdata.data.Entry feedEntry = null; + + if (provider.supportsFeedEntries()) { + + // Expect an GData entry + + System.out.println("[Debug Info]GdataBindingInvoker.PostInvoker --- supportsFeedEntries: " + provider.supportsFeedEntries()); + feedEntry = (com.google.gdata.data.Entry)args[0]; + + System.out.println("[Debug Info]GdataBindingInvoker.PostInvoker --- feedEntry title: " + feedEntry.getTitle().getPlainText()); + + } else { + // Expect a key and data item + Entry entry = new Entry(args[0], args[1]); + + // FIXME: this needs to be examinated more.... + feedEntry = feedEntry(entry, provider.getItemClassType(), provider.getItemXMLType(), provider.getMediator()); + } + + try { + + com.google.gdata.data.Entry createdEntry = googleService.insert(new URL(uri), feedEntry); + + msg.setBody(createdEntry); + + } catch (IOException ex) { + msg.setFaultBody(new ServiceRuntimeException(ex)); + } catch (ServiceException ex) { + msg.setFaultBody(new ServiceRuntimeException(ex)); + } finally { + return msg; + } + } + } + + + + /** + * Put operation invoker + */ + public static class PutInvoker extends GdataBindingInvoker { + + public PutInvoker(Operation operation, + String uri, + GoogleService googleService, + HttpClient httpClient, + String authorizationHeader, + GdataReferenceBindingProvider bindingProvider) { + super(operation, uri, googleService, httpClient, authorizationHeader, bindingProvider); + } + + @SuppressWarnings("finally") + @Override + public Message invoke(Message msg) { + + // Put an entry + Object[] args = (Object[])msg.getBody(); + String id; + com.google.gdata.data.Entry feedEntry = null; + if (provider.supportsFeedEntries()) { + // Expect a key and GData entry + id = (String)args[0]; + feedEntry = (com.google.gdata.data.Entry)args[1]; + } else { + + // Expect a key and data item + id = (String)args[0]; + Entry entry = new Entry(id, args[1]); + + } + + // Send an HTTP PUT + PutMethod putMethod = new PutMethod(uri + "/" + id); + putMethod.setRequestHeader("Authorization", authorizationHeader); + try { + URL entryURL = new URL(uri + "/" + id); + + com.google.gdata.data.Entry toUpdateEntry = googleService.getEntry(entryURL, com.google.gdata.data.Entry.class); + + System.out.println("EditHtml:" + toUpdateEntry.getEditLink().getHref()); + + URL editURL = new URL(toUpdateEntry.getEditLink().getHref()); + + com.google.gdata.data.Entry updatedEntry = googleService.update(editURL, feedEntry); + + msg.setBody(updatedEntry); + + } catch (IOException ex) { + msg.setFaultBody(new ServiceRuntimeException(ex)); + } catch (ServiceException ex) { + msg.setFaultBody(new ServiceRuntimeException(ex)); + } finally { + return msg; + } } + } + + /** + * Delete operation invoker + */ + public static class DeleteInvoker extends GdataBindingInvoker { + + public DeleteInvoker(Operation operation, + String uri, + GoogleService googleService, + HttpClient httpClient, + String authorizationHeader, + GdataReferenceBindingProvider bindingProvider) { + super(operation, uri, googleService, httpClient, authorizationHeader, bindingProvider); + } + + @SuppressWarnings("finally") + @Override + public Message invoke(Message msg) { + + // Delete an entry + String id = (String)((Object[])msg.getBody())[0]; + + // Send an HTTP DELETE(Localhost) + DeleteMethod deleteMethod = new DeleteMethod(uri + "/" + id); + deleteMethod.setRequestHeader("Authorization", authorizationHeader); + + try { + URL entryURL = new URL(uri + "/" + id); + + com.google.gdata.data.Entry toUpdateEntry = googleService.getEntry(entryURL, com.google.gdata.data.Entry.class); + + System.out.println("EditHtml:" + toUpdateEntry.getEditLink().getHref()); + + URL editURL = new URL(toUpdateEntry.getEditLink().getHref()); + + googleService.delete(editURL); + + } catch (IOException ex) { + msg.setFaultBody(new ServiceRuntimeException(ex)); + } catch (ServiceException ex) { + msg.setFaultBody(new ServiceRuntimeException(ex)); + } finally { + return msg; + } + } + + } + + + /** + * GetAll operation invoker + */ + public static class GetAllInvoker extends GdataBindingInvoker { + + public GetAllInvoker(Operation operation, + String uri, + GoogleService googleService, + HttpClient httpClient, + String authorizationHeader, + GdataReferenceBindingProvider bindingProvider) { + super(operation, uri, googleService, httpClient, authorizationHeader, bindingProvider); + } + + @SuppressWarnings("finally") + @Override + public Message invoke(Message msg) { + + // Send an HTTP GET + GetMethod getMethod = new GetMethod(uri); + getMethod.setRequestHeader("Authorization", authorizationHeader); + + System.out.println("[Debug Info] GdataBindingInvoker.GetAllInvoker.invoke---feedURL: " + uri); + + try { + + Feed feed = googleService.getFeed(new URL(uri), Feed.class); + msg.setBody(feed); + + } catch (ResourceNotFoundException ex) { + msg.setFaultBody(new ResourceNotFoundException("Invalid Resource at " + uri)); + } catch (ServiceException ex) { + msg.setFaultBody(new ServiceRuntimeException(ex)); + } catch (Exception ex) { + msg.setFaultBody(new ServiceRuntimeException(ex)); + } finally { + return msg; + } + + } + } + + /** + * Query operation invoker + */ + public static class QueryInvoker extends GdataBindingInvoker { + + public QueryInvoker(Operation operation, + String uri, + GoogleService googleService, + HttpClient httpClient, + String authorizationHeader, + GdataReferenceBindingProvider bindingProvider) { + super(operation, uri, googleService, httpClient, authorizationHeader, bindingProvider); + } + + @SuppressWarnings("finally") + @Override + public Message invoke(Message msg) { + + // Send an HTTP GET + GetMethod getMethod = new GetMethod(uri); + getMethod.setRequestHeader("Authorization", authorizationHeader); + + Object[] args = (Object[])msg.getBody(); + Query myQuery = (Query)args[0]; + + System.out.println("[Debug Info] GdataBindingInvoker.QueryInvoker.invoke---feedURL: " + uri); + + try { + + Feed resultFeed = googleService.query(myQuery, Feed.class); + msg.setBody(resultFeed); + + } catch (ResourceNotFoundException ex) { + msg.setFaultBody(new ResourceNotFoundException("Invalid Resource at " + uri)); + } catch (ServiceException ex) { + msg.setFaultBody(new ServiceRuntimeException(ex)); + } catch (Exception ex) { + msg.setFaultBody(new ServiceRuntimeException(ex)); + } finally { + return msg; + } + + + } + } + + + + /** + * PostMedia operation invoker + */ + public static class PostMediaInvoker extends GdataBindingInvoker { + + public PostMediaInvoker(Operation operation, + String uri, + GoogleService googleService, + HttpClient httpClient, + String authorizationHeader, + GdataReferenceBindingProvider bindingProvider) { + super(operation, uri, googleService, httpClient, authorizationHeader, bindingProvider); + } + + @Override + public Message invoke(Message msg) { + // TODO implement + return super.invoke(msg); + } + } + + /** + * PutMedia operation invoker + */ + public static class PutMediaInvoker extends GdataBindingInvoker { + + public PutMediaInvoker(Operation operation, + String uri, + GoogleService googleService, + HttpClient httpClient, + String authorizationHeader, + GdataReferenceBindingProvider bindingProvider) { + super(operation, uri, googleService, httpClient, authorizationHeader, bindingProvider); + } + + @Override + public Message invoke(Message msg) { + // TODO implement + return super.invoke(msg); + } + } +} \ No newline at end of file diff --git a/java/sca/contrib/modules/binding-gdata-runtime/src/main/java/org/apache/tuscany/sca/binding/gdata/provider/GdataBindingListenerServlet.java b/java/sca/contrib/modules/binding-gdata-runtime/src/main/java/org/apache/tuscany/sca/binding/gdata/provider/GdataBindingListenerServlet.java new file mode 100644 index 0000000000..4fa89fc634 --- /dev/null +++ b/java/sca/contrib/modules/binding-gdata-runtime/src/main/java/org/apache/tuscany/sca/binding/gdata/provider/GdataBindingListenerServlet.java @@ -0,0 +1,736 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.gdata.provider; + +import static org.apache.tuscany.sca.binding.gdata.provider.GdataBindingUtil.entry; +import static org.apache.tuscany.sca.binding.gdata.provider.GdataBindingUtil.feedEntry; + +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.io.UnsupportedEncodingException; +import java.io.Writer; +import java.net.URLDecoder; +import java.util.ArrayList; +import java.util.StringTokenizer; +import java.util.logging.Logger; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.xml.namespace.QName; + +import org.apache.commons.codec.binary.Base64; +import org.apache.tuscany.sca.data.collection.Entry; +import org.apache.tuscany.sca.databinding.Mediator; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.interfacedef.impl.DataTypeImpl; +import org.apache.tuscany.sca.interfacedef.util.XMLType; +import org.apache.tuscany.sca.invocation.InvocationChain; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.invocation.MessageFactory; +import org.apache.tuscany.sca.runtime.RuntimeWire; + +import com.google.gdata.data.ExtensionProfile; +import com.google.gdata.data.ParseSource; +import com.google.gdata.data.PlainTextConstruct; +import com.google.gdata.util.ParseException; +import com.google.gdata.util.ServiceException; + + +/** + * A resource collection binding listener, implemented as a Servlet and + * registered in a Servlet host provided by the SCA hosting runtime. + * + * @version $Rev$ $Date$ + */ +class GdataBindingListenerServlet extends HttpServlet { + private static final Logger logger = Logger.getLogger(GdataBindingListenerServlet.class.getName()); + private static final long serialVersionUID = 1L; + + private RuntimeWire wire; + private Invoker getFeedInvoker; + private Invoker getAllInvoker; + private Invoker queryInvoker; + private Invoker getInvoker; + private Invoker postInvoker; + private Invoker postMediaInvoker; + private Invoker putInvoker; + private Invoker putMediaInvoker; + private Invoker deleteInvoker; + private MessageFactory messageFactory; + private String title; + private Mediator mediator; + private DataType itemClassType; + private DataType itemXMLType; + private boolean supportsFeedEntries; + + /** + * Constructs a new binding listener. + * + * @param wire + * @param messageFactory + * @param feedType + */ + GdataBindingListenerServlet(RuntimeWire wire, MessageFactory messageFactory, Mediator mediator, String title) { + this.wire = wire; + this.messageFactory = messageFactory; + this.mediator = mediator; + this.title = title; + + // Get the invokers for the supported operations + Operation getOperation = null; + for (InvocationChain invocationChain : this.wire.getInvocationChains()) { + invocationChain.setAllowsPassByReference(true); + Operation operation = invocationChain.getTargetOperation(); + String operationName = operation.getName(); + + if (operationName.equals("getFeed")) { + + //System.out.println("[Debug Info]GdataBindingListenerServlet constructor --- operation: getFeed"); + getFeedInvoker = invocationChain.getHeadInvoker(); + + } else if (operationName.equals("getAll")) { + + getAllInvoker = invocationChain.getHeadInvoker(); + + } else if (operationName.equals("query")) { + + queryInvoker = invocationChain.getHeadInvoker(); + + } else if (operationName.equals("get")) { + + //System.out.println("[Debug Info]GdataBindingListenerServlet Constructor --- opeartion: get"); + getInvoker = invocationChain.getHeadInvoker(); + getOperation = operation; + + } else if (operationName.equals("put")) { + + putInvoker = invocationChain.getHeadInvoker(); + + } else if (operationName.equals("putMedia")) { + + putMediaInvoker = invocationChain.getHeadInvoker(); + + } else if (operationName.equals("post")) { + + //System.out.println("[Debug Info]GdataBindingListenerServlet Constructor --- opeartion: post"); + postInvoker = invocationChain.getHeadInvoker(); + + } else if (operationName.equals("postMedia")) { + postMediaInvoker = invocationChain.getHeadInvoker(); + } else if (operationName.equals("delete")) { + deleteInvoker = invocationChain.getHeadInvoker(); + } + } + + //System.out.println("[Debug Info]GdataBindingListenerServlet constructor --- I am good here 00"); + + // Determine the collection item type + itemXMLType = new DataTypeImpl>(String.class.getName(), String.class, String.class); + Class itemClass = getOperation.getOutputType().getPhysical(); + + if (itemClass == com.google.gdata.data.Entry.class) { + supportsFeedEntries = true; + } + DataType outputType = getOperation.getOutputType(); + QName qname = outputType.getLogical().getElementName(); + qname = new QName(qname.getNamespaceURI(), itemClass.getSimpleName()); + itemClassType = new DataTypeImpl("java:complexType", itemClass, new XMLType(qname, null)); + + System.out.println("[Debug Info]GdataBindingListenerServlet --- initilized!"); + } + + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + // No authentication required for a get request + System.out.println("[Debug Info]GdataBindingListenerServlet doGet() --- I am good here 00"); + + // Get the request path + String path = URLDecoder.decode(request.getRequestURI().substring(request.getServletPath().length()), "UTF-8"); + + System.out.println("[Debug Info]GdataBindingListenerServlet doGet() --- request.getRequestURI(): " + request + .getRequestURI()); + System.out.println("[Debug Info]GdataBindingListenerServlet doGet()--- path: " + path); + + // FIXME: Log this get http request, commented out for testing + logger.fine("get " + request.getRequestURI()); + + // Handle an Atom request + if (path != null && path.equals("/atomsvc")) { + + //FIXME: This needs to be fixed, for /atomsvc + + /* + System.out.println("GdataBindingListenerServlet doGet(): I am good here brach 01"); + // Return the Atom service document + response.setContentType("application/atomsvc+xml; charset=utf-8"); + Service service = abderaFactory.newService(); + // service.setText("service"); + + Workspace workspace = abderaFactory.newWorkspace(); + workspace.setTitle("resource"); + + String href = request.getRequestURL().toString(); + href = href.substring(0, href.length() - "/atomsvc".length()); + + Collection collection = workspace.addCollection("collection", "atom/feed"); + collection.setTitle("entries"); + collection.setAttributeValue("href", href); + collection.setAccept("entry"); + collection.addCategories().setFixed(false); + + workspace.addCollection(collection); + + service.addWorkspace(workspace); + + // FIXME add prettyPrint support + try { + service.getDocument().writeTo(response.getOutputStream()); + } catch (IOException ioe) { + throw new ServletException(ioe); + } + */ + + } else if (path == null || path.length() == 0 || path.equals("/")) { + + // get HTTP request asking for a feed + + System.out.println("[Debug Info]GdataBindingListenerServlet doGet() --- I am good here brach 02"); + + // Return a feed containing the entries in the collection + com.google.gdata.data.Feed feed = null; + + if (supportsFeedEntries) { + + System.out.println("[Debug Info]GdataBindingListenerServlet doGet() --- supportsFeedEntries: " + supportsFeedEntries); + + // The service implementation supports feed entries, invoke its + // getFeed operation + Message requestMessage = messageFactory.createMessage(); + Message responseMessage; + if (request.getQueryString() != null) { + System.out.println("getQueryString != null"); + requestMessage.setBody(new Object[] {request.getQueryString()}); + responseMessage = queryInvoker.invoke(requestMessage); + } else { + System.out.println("getQueryString == null"); + responseMessage = getFeedInvoker.invoke(requestMessage); + } + if (responseMessage.isFault()) { + throw new ServletException((Throwable)responseMessage.getBody()); + } + + //System.out.println("response msg class:" + responseMessage.getBody().getClass()); + + feed = (com.google.gdata.data.Feed)responseMessage.getBody(); + + System.out.println("feed title: " + feed.getTitle().getPlainText()); + + } else { + + System.out.println("GdataBindingListenerServlet doGet(): do not supportsFeedEntries"); + + // The service implementation does not support feed entries, + // invoke its getAll operation to get the data item collection, + // then create + // feed entries from the items + Message requestMessage = messageFactory.createMessage(); + Message responseMessage; + if (request.getQueryString() != null) { + requestMessage.setBody(new Object[] {request.getQueryString()}); + responseMessage = queryInvoker.invoke(requestMessage); + } else { + responseMessage = getAllInvoker.invoke(requestMessage); + + //System.out + // .println("GdataBindingListner.doGet(): get msg from getAllInvoker.invoke()" + responseMessage + // .getBody().toString()); + + } + if (responseMessage.isFault()) { + throw new ServletException((Throwable)responseMessage.getBody()); + } + Entry[] collection = (Entry[])responseMessage.getBody(); + if (collection != null) { + + // Create the feed + feed = new com.google.gdata.data.Feed(); + + // Set the feed title + if (title != null) { + feed.setTitle(new PlainTextConstruct(title)); + } else { + feed.setTitle(new PlainTextConstruct("Feed title")); + } + + // Add entries to the feed + ArrayList entries = new ArrayList(); + for (Entry entry : collection) { + com.google.gdata.data.Entry feedEntry = feedEntry(entry, itemClassType, itemXMLType, mediator); + entries.add(feedEntry); + } + feed.setEntries(entries); + + } + } + if (feed != null) { + + // //System.out.println("feed(from the http response)is not + // null"); + + // Write a GData feed using Atom representation + response.setContentType("application/atom+xml; charset=utf-8"); + + // Generate the corresponding Atom representation of the feed + StringWriter stringWriter = new StringWriter(); + com.google.gdata.util.common.xml.XmlWriter w = + new com.google.gdata.util.common.xml.XmlWriter(stringWriter); + feed.generateAtom(w, new ExtensionProfile()); + w.flush(); + + // Write the Atom representation(XML) into Http response content + OutputStreamWriter osw = new OutputStreamWriter(response.getOutputStream()); + PrintWriter out = new PrintWriter(response.getOutputStream()); + out.println(stringWriter.toString()); + out.close(); + + System.out.println("Feed content in plain text:" + stringWriter.toString()); + } else { + response.sendError(HttpServletResponse.SC_NOT_FOUND); + } + + } else if (path.startsWith("/")) { + + // get HTTP request asking for an entry + + // Return a specific entry in the collection + com.google.gdata.data.Entry feedEntry = null; + + // Invoke the get operation on the service implementation + Message requestMessage = messageFactory.createMessage(); + String id = path.substring(1); + requestMessage.setBody(new Object[] {id}); + Message responseMessage = getInvoker.invoke(requestMessage); + if (responseMessage.isFault()) { + throw new ServletException((Throwable)responseMessage.getBody()); + } + + if (supportsFeedEntries) { + // The service implementation returns a feed entry + feedEntry = (com.google.gdata.data.Entry)responseMessage.getBody(); + + System.out.println("entry title: " + feedEntry.getTitle().getPlainText()); + + } else { + // The service implementation only returns a data item, create + // an entry + // from it + Entry entry = new Entry(id, responseMessage.getBody()); + // FIXME The line below needs to be fixed + // feedEntry = feedEntry(entry, itemClassType, itemXMLType, + // mediator, abderaFactory); + } + + // Write the Gdata entry + if (feedEntry != null) { + + // Write a GData entry using Atom representation + response.setContentType("application/atom+xml; charset=utf-8"); + + // Generate the corresponding Atom representation of the feed + StringWriter stringWriter = new StringWriter(); + com.google.gdata.util.common.xml.XmlWriter w = + new com.google.gdata.util.common.xml.XmlWriter(stringWriter); + feedEntry.generateAtom(w, new ExtensionProfile()); + w.flush(); + + // Write the Atom representation(XML) into Http response content + OutputStreamWriter osw = new OutputStreamWriter(response.getOutputStream()); + PrintWriter out = new PrintWriter(response.getOutputStream()); + out.println(stringWriter.toString()); + out.close(); + + } else { + response.sendError(HttpServletResponse.SC_NOT_FOUND); + } + } else { + // Path doesn't match any known pattern + response.sendError(HttpServletResponse.SC_NOT_FOUND); + } + + } + + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, + IOException { + + System.out.println("[Debug Info]GdataBindingListenerServlet doPost() --- reached"); + + // Authenticate the user + String user = processAuthorizationHeader(request); + if (user == null) { + unauthorized(response); + return; + } + + // Get the request path + String path = URLDecoder.decode(request.getRequestURI().substring(request.getServletPath().length()), "UTF-8"); + + System.out.println("[Debug Info]GdataBindingListenerServlet path --- " + path); + + if (path == null || path.length() == 0 || path.equals("/")) { + // Create a new Gdata entry + com.google.gdata.data.Entry createdFeedEntry = null; + String contentType = request.getContentType(); + + if (contentType != null && contentType.startsWith("application/atom+xml")) { + + // Read the entry from the request + com.google.gdata.data.Entry feedEntry = null; + try { + ParseSource source = new ParseSource(request.getReader()); + feedEntry = com.google.gdata.data.Entry.readEntry(source, com.google.gdata.data.Entry.class, null); + } catch (com.google.gdata.util.ParseException pe) { + throw new ServletException(pe); + } catch (ServiceException e) { + throw new ServletException(e); + } + + // Let the component implementation create it + if (supportsFeedEntries) { + + // The service implementation supports feed entries, pass + // the entry to it + Message requestMessage = messageFactory.createMessage(); + + requestMessage.setBody(new Object[] {feedEntry}); + + Message responseMessage = postInvoker.invoke(requestMessage); + if (responseMessage.isFault()) { + throw new ServletException((Throwable)responseMessage.getBody()); + } + createdFeedEntry = responseMessage.getBody(); + } else { + + // The service implementation does not support feed entries, + // pass the data item to it + Message requestMessage = messageFactory.createMessage(); + Entry entry = entry(feedEntry, itemClassType, itemXMLType, mediator); + requestMessage.setBody(new Object[] {entry.getKey(), entry.getData()}); + Message responseMessage = postInvoker.invoke(requestMessage); + if (responseMessage.isFault()) { + throw new ServletException((Throwable)responseMessage.getBody()); + } + entry.setKey(responseMessage.getBody()); + + createdFeedEntry = feedEntry(entry, itemClassType, itemXMLType, mediator); + } + + } else if (contentType != null) { + + // Create a new media entry + + // Get incoming headers + String title = request.getHeader("Title"); + String slug = request.getHeader("Slug"); + + // Let the component implementation create the media entry + Message requestMessage = messageFactory.createMessage(); + requestMessage.setBody(new Object[] {title, slug, contentType, request.getInputStream()}); + Message responseMessage = postMediaInvoker.invoke(requestMessage); + if (responseMessage.isFault()) { + throw new ServletException((Throwable)responseMessage.getBody()); + } + createdFeedEntry = responseMessage.getBody(); + } else { + response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE); + } + + // A new entry was created successfully + if (createdFeedEntry != null) { + + // Set location of the created entry in the Location header + // Link link = createdFeedEntry.getSelfLink(); + // if (link != null) { + // response.addHeader("Location", link.getHref().toString()); + // } + + // Write the created Atom entry + response.setStatus(HttpServletResponse.SC_CREATED); + response.setContentType("application/atom+xml; charset=utf-8"); + + // Generate the corresponding Atom representation of the + // feed + StringWriter stringWriter = new StringWriter(); + com.google.gdata.util.common.xml.XmlWriter w = + new com.google.gdata.util.common.xml.XmlWriter(stringWriter); + createdFeedEntry.generateAtom(w, new ExtensionProfile()); + w.flush(); + + // Write the Atom representation(XML) into Http response + // content + OutputStreamWriter osw = new OutputStreamWriter(response.getOutputStream()); + PrintWriter out = new PrintWriter(response.getOutputStream()); + out.println(stringWriter.toString()); + out.close(); + + } else { + response.sendError(HttpServletResponse.SC_NOT_FOUND); + } + + } else { + response.sendError(HttpServletResponse.SC_NOT_FOUND); + } + } + + private Writer getWriter(HttpServletResponse response) throws UnsupportedEncodingException, IOException { + Writer writer = new OutputStreamWriter(response.getOutputStream(), "UTF-8"); + return writer; + } + + + @Override + protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + // Authenticate the user + String user = processAuthorizationHeader(request); + if (user == null) { + unauthorized(response); + return; + } + + // Get the request path + String path = request.getRequestURI().substring(request.getServletPath().length()); + + System.out.println("[Debug Info] localServlet doPut --- path: " + path); + + if (path != null && path.startsWith("/")) { + String id = path.substring(1); + + // Update an Atom entry + String contentType = request.getContentType(); + if (contentType != null && contentType.startsWith("application/atom+xml")) { + + // Read the entry from the request + com.google.gdata.data.Entry feedEntry = null; + try { + ParseSource source = new ParseSource(request.getReader()); + feedEntry = com.google.gdata.data.Entry.readEntry(source, com.google.gdata.data.Entry.class, null); + + System.out.println("[Debug Info] localServlet doPut --- feedEntry title: " + feedEntry.getTitle().getPlainText()); + } catch (com.google.gdata.util.ParseException pe) { + throw new ServletException(pe); + } catch (ServiceException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + + + // Let the component implementation create it + if (supportsFeedEntries) { + + System.out.println("[Debug Info] localServlet doPut --- supportsFeedEntries: " + supportsFeedEntries); + + // The service implementation supports feed entries, pass + // the entry to it + Message requestMessage = messageFactory.createMessage(); + requestMessage.setBody(new Object[] {id, feedEntry}); + Message responseMessage = putInvoker.invoke(requestMessage); + if (responseMessage.isFault()) { + Object body = responseMessage.getBody(); + if (body.getClass().getName().endsWith(".NotFoundException")) { + response.sendError(HttpServletResponse.SC_NOT_FOUND); + } else { + throw new ServletException((Throwable)responseMessage.getBody()); + } + } + } else { + + // The service implementation does not support feed entries, + // pass the data item to it + Message requestMessage = messageFactory.createMessage(); + Entry entry = entry(feedEntry, itemClassType, itemXMLType, mediator); + requestMessage.setBody(new Object[] {entry.getKey(), entry.getData()}); + Message responseMessage = putInvoker.invoke(requestMessage); + if (responseMessage.isFault()) { + Object body = responseMessage.getBody(); + if (body.getClass().getName().endsWith(".NotFoundException")) { + response.sendError(HttpServletResponse.SC_NOT_FOUND); + } else { + throw new ServletException((Throwable)responseMessage.getBody()); + } + } + } + + // Write the Gdata entry + if (feedEntry != null) { + + // Write a GData entry using Atom representation + response.setContentType("application/atom+xml; charset=utf-8"); + + // Generate the corresponding Atom representation of the feed + StringWriter stringWriter = new StringWriter(); + com.google.gdata.util.common.xml.XmlWriter w = + new com.google.gdata.util.common.xml.XmlWriter(stringWriter); + feedEntry.generateAtom(w, new ExtensionProfile()); + w.flush(); + + // Write the Atom representation(XML) into Http response content + OutputStreamWriter osw = new OutputStreamWriter(response.getOutputStream()); + PrintWriter out = new PrintWriter(response.getOutputStream()); + out.println(stringWriter.toString()); + out.close(); + + } + + } else if (contentType != null) { + + // Updated a media entry + + // Let the component implementation create the media entry + Message requestMessage = messageFactory.createMessage(); + requestMessage.setBody(new Object[] {id, contentType, request.getInputStream()}); + Message responseMessage = putMediaInvoker.invoke(requestMessage); + Object body = responseMessage.getBody(); + if (responseMessage.isFault()) { + if (body.getClass().getName().endsWith(".NotFoundException")) { + response.sendError(HttpServletResponse.SC_NOT_FOUND); + } else { + throw new ServletException((Throwable)responseMessage.getBody()); + } + } + } else { + response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE); + } + } else { + response.sendError(HttpServletResponse.SC_NOT_FOUND); + } + } + + + + + @Override + protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, + IOException { + + // Authenticate the user + String user = processAuthorizationHeader(request); + if (user == null) { + unauthorized(response); + return; + } + + // Get the request path + String path = URLDecoder.decode(request.getRequestURI().substring(request.getServletPath().length()), "UTF-8"); + + String id; + if (path != null && path.startsWith("/")) { + id = path.substring(1); + } else { + id = ""; + } + + // Delete a specific entry from the collection + Message requestMessage = messageFactory.createMessage(); + requestMessage.setBody(new Object[] {id}); + Message responseMessage = deleteInvoker.invoke(requestMessage); + if (responseMessage.isFault()) { + Object body = responseMessage.getBody(); + if (body.getClass().getName().endsWith(".NotFoundException")) { + response.sendError(HttpServletResponse.SC_NOT_FOUND); + } else { + throw new ServletException((Throwable)responseMessage.getBody()); + } + } + } + + + + /** + * Process the authorization header + * + * @param request + * @return + * @throws ServletException + */ + private String processAuthorizationHeader(HttpServletRequest request) throws ServletException { + + // FIXME temporarily disabling this as it doesn't work with all browsers + if (true) + return "admin"; + + try { + String authorization = request.getHeader("Authorization"); + if (authorization != null) { + StringTokenizer tokens = new StringTokenizer(authorization); + if (tokens.hasMoreTokens()) { + String basic = tokens.nextToken(); + if (basic.equalsIgnoreCase("Basic")) { + String credentials = tokens.nextToken(); + String userAndPassword = new String(Base64.decodeBase64(credentials.getBytes())); + int colon = userAndPassword.indexOf(":"); + if (colon != -1) { + String user = userAndPassword.substring(0, colon); + String password = userAndPassword.substring(colon + 1); + + // Authenticate the User. + if (authenticate(user, password)) { + return user; + } + } + } + } + } + } catch (Exception e) { + throw new ServletException(e); + } + return null; + } + + /** + * Authenticate a user. + * + * @param user + * @param password + * @return + */ + private boolean authenticate(String user, String password) { + // TODO Handle this using SCA security policies + return ("admin".equals(user) && "admin".equals(password)); + } + + /** + * Reject an unauthorized request. + * + * @param response + */ + private void unauthorized(HttpServletResponse response) throws IOException { + response.setHeader("WWW-Authenticate", "BASIC realm=\"Tuscany\""); + response.sendError(HttpServletResponse.SC_UNAUTHORIZED); + } +} diff --git a/java/sca/contrib/modules/binding-gdata-runtime/src/main/java/org/apache/tuscany/sca/binding/gdata/provider/GdataBindingProviderFactory.java b/java/sca/contrib/modules/binding-gdata-runtime/src/main/java/org/apache/tuscany/sca/binding/gdata/provider/GdataBindingProviderFactory.java new file mode 100644 index 0000000000..9de4772a70 --- /dev/null +++ b/java/sca/contrib/modules/binding-gdata-runtime/src/main/java/org/apache/tuscany/sca/binding/gdata/provider/GdataBindingProviderFactory.java @@ -0,0 +1,83 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.gdata.provider; + +import org.apache.tuscany.sca.binding.gdata.GdataBinding; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.core.FactoryExtensionPoint; +import org.apache.tuscany.sca.databinding.DataBindingExtensionPoint; +import org.apache.tuscany.sca.databinding.Mediator; +import org.apache.tuscany.sca.databinding.TransformerExtensionPoint; +import org.apache.tuscany.sca.databinding.impl.MediatorImpl; +import org.apache.tuscany.sca.host.http.ServletHost; +import org.apache.tuscany.sca.host.http.ServletHostExtensionPoint; +import org.apache.tuscany.sca.invocation.MessageFactory; +import org.apache.tuscany.sca.provider.BindingProviderFactory; +import org.apache.tuscany.sca.provider.ReferenceBindingProvider; +import org.apache.tuscany.sca.provider.ServiceBindingProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; + +import com.google.gdata.util.AuthenticationException; + +/** + * Implementation of a Binding provider factory for the Atom binding. + * + * @version $Rev$ $Date$ + */ +public class GdataBindingProviderFactory implements BindingProviderFactory { + + private MessageFactory messageFactory; + private Mediator mediator; + private ServletHost servletHost; + + public GdataBindingProviderFactory(ExtensionPointRegistry extensionPoints) { + ServletHostExtensionPoint servletHosts = extensionPoints.getExtensionPoint(ServletHostExtensionPoint.class); + this.servletHost = servletHosts.getServletHosts().get(0); + FactoryExtensionPoint modelFactories = extensionPoints.getExtensionPoint(FactoryExtensionPoint.class); + this.messageFactory = modelFactories.getFactory(MessageFactory.class); + this.mediator = + new MediatorImpl(extensionPoints.getExtensionPoint(DataBindingExtensionPoint.class), extensionPoints + .getExtensionPoint(TransformerExtensionPoint.class)); + } + + public ReferenceBindingProvider createReferenceBindingProvider(RuntimeComponent component, + RuntimeComponentReference reference, + GdataBinding binding) { + try { + return new GdataReferenceBindingProvider(component, reference, binding, mediator); + } catch (AuthenticationException e) { + e.printStackTrace(); + return null; //Google authentication error! : This exception needs to be handled into a better way + } + + } + + public ServiceBindingProvider createServiceBindingProvider(RuntimeComponent component, + RuntimeComponentService service, + GdataBinding binding) { + return new GdataServiceBindingProvider(component, service, binding, servletHost, messageFactory, mediator); + } + + public Class getModelType() { + return GdataBinding.class; + } +} diff --git a/java/sca/contrib/modules/binding-gdata-runtime/src/main/java/org/apache/tuscany/sca/binding/gdata/provider/GdataBindingUtil.java b/java/sca/contrib/modules/binding-gdata-runtime/src/main/java/org/apache/tuscany/sca/binding/gdata/provider/GdataBindingUtil.java new file mode 100644 index 0000000000..3d476df764 --- /dev/null +++ b/java/sca/contrib/modules/binding-gdata-runtime/src/main/java/org/apache/tuscany/sca/binding/gdata/provider/GdataBindingUtil.java @@ -0,0 +1,171 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.gdata.provider; + +import java.util.Date; + +import org.apache.tuscany.sca.data.collection.Entry; +import org.apache.tuscany.sca.data.collection.Item; +import org.apache.tuscany.sca.databinding.Mediator; +import org.apache.tuscany.sca.interfacedef.DataType; + +import com.google.gdata.data.DateTime; +import com.google.gdata.data.PlainTextConstruct; +import com.google.gdata.data.TextContent; + +/** + * Utility methods used in this package. + * + * @version $Rev$ $Date$ + */ +class GdataBindingUtil { + + /** + * Create a data item from an GData entry. + * + * @param feedEntry + * @param itemClassType + * @param itemXMLType + * @param mediator + * @return + */ + static Entry entry(com.google.gdata.data.Entry feedEntry, + DataType itemClassType, + DataType itemXMLType, + Mediator mediator) { + if (feedEntry != null) { + if (itemClassType.getPhysical() == Item.class) { + String key = feedEntry.getId().toString(); + + Item item = new Item(); + item.setTitle(feedEntry.getTitle().toString()); + TextContent content = (TextContent)feedEntry.getContent(); + item.setContents(content.getContent().getPlainText()); + + for (com.google.gdata.data.Link link : feedEntry.getLinks()) { + if (link.getRel() == null || "self".equals(link.getRel())) { + if (item.getLink() == null) { + item.setLink(link.getHref().toString()); + } + } else if ("related".equals(link.getRel())) { + item.setRelated(link.getHref().toString()); + } else if ("alternate".equals(link.getRel())) { + item.setAlternate(link.getHref().toString()); + } + } + + Date date = new Date(feedEntry.getUpdated().getValue()); + item.setDate(date); + return new Entry(key, item); + + } else { + String key = null; + if (feedEntry.getId() != null) { + key = feedEntry.getId(); + } + + // Create the item from XML + if (feedEntry.getContent() == null) { + return null; + } + + TextContent content = (TextContent)feedEntry.getContent(); + String value = content.getContent().getPlainText(); + Object data = mediator.mediate(value, itemXMLType, itemClassType, null); + return new Entry(key, data); + } + } else { + return null; + } + } + + /** + * Create an Gdata entry for a key and item from a collection. + * + * @param entry + * @param itemClassType + * @param itemXMLType + * @param mediator + * @param factory + * @return + */ + static com.google.gdata.data.Entry feedEntry(Entry entry, + DataType itemClassType, + DataType itemXMLType, + Mediator mediator) { + + Object key = entry.getKey(); + Object data = entry.getData(); + if (data instanceof Item) { + Item item = (Item)data; + + com.google.gdata.data.Entry feedEntry = new com.google.gdata.data.Entry(); + if (key != null) { + feedEntry.setId(key.toString()); + } + feedEntry.setTitle(new PlainTextConstruct(item.getTitle())); + feedEntry.setContent(new PlainTextConstruct(item.getContents())); + + String href = item.getLink(); + if (href == null && key != null) { + href = key.toString(); + } + + if (href != null) { + feedEntry.addHtmlLink(href, "", ""); + } + String related = item.getRelated(); + if (related != null) { + feedEntry.addHtmlLink(related, "", "related"); + } + String alternate = item.getAlternate(); + if (alternate != null) { + feedEntry.addHtmlLink(alternate, "", "alternate"); + } + + Date date = item.getDate(); + if (date != null) { + DateTime datetime = new DateTime(date); + feedEntry.setUpdated(datetime); + } + return feedEntry; + + } else if (data != null) { + + com.google.gdata.data.Entry feedEntry = new com.google.gdata.data.Entry(); + feedEntry.setId(key.toString()); + feedEntry.setTitle(new PlainTextConstruct("item")); + + // Convert the item to XML + String value = mediator.mediate(data, itemClassType, itemXMLType, null).toString(); + + // Might be wrong because the example uses XML datatype, I am using + // plainText here + feedEntry.setContent(new PlainTextConstruct(value)); + + feedEntry.addHtmlLink(key.toString(), "", ""); + return feedEntry; + + } else { + return null; + } + } + +} diff --git a/java/sca/contrib/modules/binding-gdata-runtime/src/main/java/org/apache/tuscany/sca/binding/gdata/provider/GdataReferenceBindingProvider.java b/java/sca/contrib/modules/binding-gdata-runtime/src/main/java/org/apache/tuscany/sca/binding/gdata/provider/GdataReferenceBindingProvider.java new file mode 100644 index 0000000000..c20e44f7da --- /dev/null +++ b/java/sca/contrib/modules/binding-gdata-runtime/src/main/java/org/apache/tuscany/sca/binding/gdata/provider/GdataReferenceBindingProvider.java @@ -0,0 +1,229 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.gdata.provider; + +import java.net.URI; + +import javax.xml.namespace.QName; + +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.httpclient.Credentials; +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.HttpConnectionManager; +import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; +import org.apache.commons.httpclient.UsernamePasswordCredentials; +import org.apache.commons.httpclient.auth.AuthScope; +import org.apache.tuscany.sca.binding.gdata.GdataBinding; +import org.apache.tuscany.sca.databinding.Mediator; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.interfacedef.impl.DataTypeImpl; +import org.apache.tuscany.sca.interfacedef.util.XMLType; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.provider.ReferenceBindingProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; + +import com.google.gdata.client.GoogleService; +import com.google.gdata.util.AuthenticationException; + +/** + * Implementation of the Atom binding provider. + * + * @version $Rev$ $Date$ + */ +class GdataReferenceBindingProvider implements ReferenceBindingProvider { + + private RuntimeComponentReference reference; + private GdataBinding binding; + private String authorizationHeader; + private GoogleService googleService; + private HttpClient httpClient; + private Mediator mediator; + private DataType itemClassType; + private DataType itemXMLType; + private boolean supportsFeedEntries; + + /** + * Constructs a new AtomReferenceBindingProvider + * + * @param component + * @param reference + * @param binding + * @param mediator + * @throws AuthenticationException + */ + GdataReferenceBindingProvider(RuntimeComponent component, + RuntimeComponentReference reference, + GdataBinding binding, + Mediator mediator) throws AuthenticationException { + this.reference = reference; + this.binding = binding; + this.mediator = mediator; + + // Prepare authorization header + String authorization = "admin" + ":" + "admin"; + authorizationHeader = "Basic " + new String(Base64.encodeBase64(authorization.getBytes())); + + // Prepare gdata header + String serviceType = binding.getServiceType(); + String usernane = binding.getUsername(); + String password = binding.getPassword(); + + System.out.println("[Debug Info] binding.getServiceType()" + serviceType); + System.out.println("[Debug Info] binding.getName()" +usernane); + System.out.println("[Debug Info] binding.getPassword()" + password); + + googleService = new GoogleService(serviceType, ""); + if(binding.getUsername().equals("admin") == false && binding.getPassword().equals("admin")==false){ + googleService.setUserCredentials(binding.getUsername(),binding.getPassword()); + } + + // Create an HTTP client + HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); + connectionManager.getParams().setDefaultMaxConnectionsPerHost(10); + connectionManager.getParams().setConnectionTimeout(60000); + httpClient = new HttpClient(connectionManager); + } + + public Invoker createInvoker(Operation operation) { + + String operationName = operation.getName(); + + if (operationName.equals("get")) { + + // Determine the collection item type + itemXMLType = new DataTypeImpl>(String.class.getName(), String.class, String.class); + Class itemClass = operation.getOutputType().getPhysical(); + DataType outputType = operation.getOutputType(); + QName qname = outputType.getLogical().getElementName(); + qname = new QName(qname.getNamespaceURI(), itemClass.getSimpleName()); + itemClassType = new DataTypeImpl("java:complexType", itemClass, new XMLType(qname, null)); + + if (itemClassType.getPhysical() == com.google.gdata.data.Entry.class) { + supportsFeedEntries = true; + } + + String entryURI = this.binding.getURI(); + if(entryURI.contains("picasaweb.google.com/data/feed/api/")){ + entryURI = entryURI.replace("picasaweb.google.com/data/feed/api/", "picasaweb.google.com/data/entry/api/"); + } + + return new GdataBindingInvoker.GetInvoker(operation, entryURI, googleService, httpClient, authorizationHeader, this); + + } else if (operationName.equals("post")) { + + return new GdataBindingInvoker.PostInvoker(operation, binding.getURI(), googleService, httpClient, authorizationHeader, this); + + } else if (operationName.equals("put")) { + + String entryURI = this.binding.getURI(); + if(entryURI.contains("picasaweb.google.com/data/feed/api/")){ + entryURI = entryURI.replace("picasaweb.google.com/data/feed/api/", "picasaweb.google.com/data/entry/api/"); + } + + return new GdataBindingInvoker.PutInvoker(operation, entryURI, googleService, httpClient, authorizationHeader, this); + + } else if (operationName.equals("delete")) { + + String entryURI = this.binding.getURI(); + if(entryURI.contains("picasaweb.google.com/data/feed/api/")){ + entryURI = entryURI.replace("picasaweb.google.com/data/feed/api/", "picasaweb.google.com/data/entry/api/"); + } + return new GdataBindingInvoker.DeleteInvoker(operation, entryURI, googleService, httpClient, authorizationHeader, this); + + } else if (operationName.equals("getFeed") || operationName.equals("getAll")) { + + return new GdataBindingInvoker.GetAllInvoker(operation, binding.getURI(), googleService, httpClient, authorizationHeader, this); + + } else if (operationName.equals("postMedia")) { + + return new GdataBindingInvoker.PostMediaInvoker(operation, binding.getURI(), googleService, httpClient, authorizationHeader, this); + + } else if (operationName.equals("putMedia")) { + + return new GdataBindingInvoker.PutMediaInvoker(operation, binding.getURI(), googleService, httpClient, authorizationHeader, this); + + } else if (operationName.equals("query")) { + + return new GdataBindingInvoker.QueryInvoker(operation, binding.getURI(), googleService, httpClient, authorizationHeader, this); + } + + return new GdataBindingInvoker(operation, binding.getURI(), googleService, httpClient, authorizationHeader, this); + } + + public InterfaceContract getBindingInterfaceContract() { + return reference.getInterfaceContract(); + } + + public void start() { + // Configure the HTTP client credentials + Credentials credentials = new UsernamePasswordCredentials("admin", "admin"); + httpClient.getParams().setAuthenticationPreemptive(true); + URI uri = URI.create(binding.getURI()); + httpClient.getState().setCredentials(new AuthScope(uri.getHost(), uri.getPort()), credentials); + } + + public void stop() { + + } + + public boolean supportsOneWayInvocation() { + return false; + } + + /** + * Returns the mediator. + * + * @return + */ + Mediator getMediator() { + return mediator; + } + + /** + * Returns the item class type. + * + * @return + */ + DataType getItemClassType() { + return itemClassType; + } + + /** + * Returns the item XML type. + * + * @return + */ + DataType getItemXMLType() { + return itemXMLType; + } + + /** + * Returns true if the invoker should work with Atom feed entries. + * + * @return + */ + boolean supportsFeedEntries() { + return supportsFeedEntries; + } + +} diff --git a/java/sca/contrib/modules/binding-gdata-runtime/src/main/java/org/apache/tuscany/sca/binding/gdata/provider/GdataServiceBindingProvider.java b/java/sca/contrib/modules/binding-gdata-runtime/src/main/java/org/apache/tuscany/sca/binding/gdata/provider/GdataServiceBindingProvider.java new file mode 100644 index 0000000000..10faf74371 --- /dev/null +++ b/java/sca/contrib/modules/binding-gdata-runtime/src/main/java/org/apache/tuscany/sca/binding/gdata/provider/GdataServiceBindingProvider.java @@ -0,0 +1,90 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.gdata.provider; + +import org.apache.tuscany.sca.binding.gdata.GdataBinding; +import org.apache.tuscany.sca.databinding.Mediator; +import org.apache.tuscany.sca.host.http.ServletHost; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.invocation.MessageFactory; +import org.apache.tuscany.sca.provider.ServiceBindingProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; +import org.apache.tuscany.sca.runtime.RuntimeWire; + +/** + * Implementation of the Atom binding provider. + * + * @version $Rev$ $Date$ + */ +class GdataServiceBindingProvider implements ServiceBindingProvider { + + private RuntimeComponentService service; + private GdataBinding binding; + private ServletHost servletHost; + private MessageFactory messageFactory; + private String servletMapping; + private Mediator mediator; + + GdataServiceBindingProvider(RuntimeComponent component, + RuntimeComponentService service, + GdataBinding binding, + ServletHost servletHost, + MessageFactory messageFactory, + Mediator mediator) { + this.service = service; + this.binding = binding; + this.servletHost = servletHost; + this.messageFactory = messageFactory; + this.mediator = mediator; + } + + public InterfaceContract getBindingInterfaceContract() { + return service.getInterfaceContract(); + } + + public boolean supportsOneWayInvocation() { + return false; + } + + public void start() { + RuntimeComponentService componentService = (RuntimeComponentService)service; + RuntimeWire wire = componentService.getRuntimeWire(binding); + + GdataBindingListenerServlet servlet = + new GdataBindingListenerServlet(wire, messageFactory, mediator, binding.getTitle()); + + servletMapping = binding.getURI(); + if (!servletMapping.endsWith("/")) { + servletMapping += "/"; + } + if (!servletMapping.endsWith("*")) { + servletMapping += "*"; + } + servletHost.addServletMapping(servletMapping, servlet); + + // Save the actual binding URI in the binding + binding.setURI(servletHost.getURLMapping(binding.getURI()).toString()); + } + + public void stop() { + servletHost.removeServletMapping(servletMapping); + } +} diff --git a/java/sca/contrib/modules/binding-gdata-runtime/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.BindingProviderFactory b/java/sca/contrib/modules/binding-gdata-runtime/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.BindingProviderFactory new file mode 100644 index 0000000000..5e380eb4e0 --- /dev/null +++ b/java/sca/contrib/modules/binding-gdata-runtime/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.BindingProviderFactory @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for the binding extension +org.apache.tuscany.sca.binding.gdata.provider.GdataBindingProviderFactory;model=org.apache.tuscany.sca.binding.gdata.GdataBinding diff --git a/java/sca/contrib/modules/binding-gdata-runtime/src/main/resources/tuscany-binding-gdata.xsd b/java/sca/contrib/modules/binding-gdata-runtime/src/main/resources/tuscany-binding-gdata.xsd new file mode 100644 index 0000000000..5148e2ef2d --- /dev/null +++ b/java/sca/contrib/modules/binding-gdata-runtime/src/main/resources/tuscany-binding-gdata.xsd @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + diff --git a/java/sca/contrib/modules/binding-gdata-runtime/src/test/java/org/apache/tuscany/sca/binding/gdata/Consumer.java b/java/sca/contrib/modules/binding-gdata-runtime/src/test/java/org/apache/tuscany/sca/binding/gdata/Consumer.java new file mode 100644 index 0000000000..50a3ec3886 --- /dev/null +++ b/java/sca/contrib/modules/binding-gdata-runtime/src/test/java/org/apache/tuscany/sca/binding/gdata/Consumer.java @@ -0,0 +1,66 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.gdata; + +import org.apache.tuscany.sca.node.Contribution; +import org.apache.tuscany.sca.node.ContributionLocationHelper; +import org.apache.tuscany.sca.node.Node; +import org.apache.tuscany.sca.node.NodeFactory; + +import com.google.gdata.data.Entry; +import com.google.gdata.data.Feed; +import com.google.gdata.data.PlainTextConstruct; + +public class Consumer { + + public static void main(String[] args) throws Exception { + + //Initialize the GData client service (Reference Binding test) + String contribution = ContributionLocationHelper.getContributionLocation(Consumer.class); + Node node = NodeFactory.newInstance().createNode( + "org/apache/tuscany/sca/binding/gdata/ConsumerGoogleBlogger.composite", new Contribution("consumer", contribution)); + node.start(); + CustomerClient testService = node.getService(CustomerClient.class, "CustomerClient"); + + + Feed feed = testService.clientGetFeed(); + + System.out.println("#Entries(Before post): "+ testService.clientGetFeed().getEntries().size()); + + /* + String entryID = "tag:blogger.com,1999:blog-4520949313432095990.post-973462497533349425"; + Entry entry = testService.clientGetEntry(entryID); + System.out.println("Entry id: " + entry.getId()); + */ + + Entry myEntry = new Entry(); + myEntry.setTitle(new PlainTextConstruct("titleByConsumer2")); + myEntry.setContent(new PlainTextConstruct("contentByConsmer2")); + testService.clientPost(myEntry); + + System.out.println("#Entries(After post): "+ testService.clientGetFeed().getEntries().size()); + + String entryID = "tag:blogger.com,1999:blog-4520949313432095990.post-973462497533349425"; + Entry entry = testService.clientGetEntry(entryID); + System.out.println("Entry id: " + entry.getId()); + + + } +} diff --git a/java/sca/contrib/modules/binding-gdata-runtime/src/test/java/org/apache/tuscany/sca/binding/gdata/ConsumerProviderTestCase.java b/java/sca/contrib/modules/binding-gdata-runtime/src/test/java/org/apache/tuscany/sca/binding/gdata/ConsumerProviderTestCase.java new file mode 100644 index 0000000000..e4d502357d --- /dev/null +++ b/java/sca/contrib/modules/binding-gdata-runtime/src/test/java/org/apache/tuscany/sca/binding/gdata/ConsumerProviderTestCase.java @@ -0,0 +1,153 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.gdata; + +import junit.framework.TestCase; + +import org.apache.tuscany.sca.node.Contribution; +import org.apache.tuscany.sca.node.ContributionLocationHelper; +import org.apache.tuscany.sca.node.Node; +import org.apache.tuscany.sca.node.NodeFactory; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.google.gdata.data.Entry; +import com.google.gdata.data.Feed; +import com.google.gdata.data.PlainTextConstruct; + +public class ConsumerProviderTestCase extends TestCase { + + private Node providerNode = null; + private Node consumerNode = null; + private CustomerClient testService = null; + + @Before + @Override + public void setUp() throws Exception { + System.out.println("Method Test Start-----------------------------------------------------------------------"); + + // Setup the local GData servlet (Service Binding test) + String contribution = ContributionLocationHelper.getContributionLocation(ConsumerProviderTestCase.class); + providerNode = NodeFactory.newInstance().createNode( + "org/apache/tuscany/sca/binding/gdata/Provider.composite", new Contribution("provider", contribution)); + providerNode.start(); + System.out.println("[Debug Info] Provider.composite ready..."); + + // Initialize the GData client service (Reference Binding test) + consumerNode = NodeFactory.newInstance().createNode( + "org/apache/tuscany/sca/binding/gdata/Consumer.composite", new Contribution("consumer", contribution)); + consumerNode.start(); + testService = consumerNode.getService(CustomerClient.class, "CustomerClient"); + } + + @After + @Override + public void tearDown() { + providerNode.stop(); + providerNode.destroy(); + consumerNode.stop(); + consumerNode.destroy(); + System.out.println("Method Test End------------------------------------------------------------------------"); + System.out.println("\n\n"); + } + + + @Test + public void testClientGetFeed() throws Exception { + Feed feed = testService.clientGetFeed(); + System.out.println(feed.getTitle().getPlainText()); + assertNotNull(feed); + // Given we are testing on the localhost providing feed, we know the + // feed title is "Feedtitle(LocalHostServlet)" + assertEquals("Feedtitle(LocalHostServlet)", feed.getTitle().getPlainText()); + } + + @Test + public void testClientGetEntry() throws Exception { + String entryID = "urn:uuid:customer-0"; + Entry entry = testService.clientGetEntry(entryID); + System.out.println("entryID in testcase: " + entry.getId()); + assertEquals(entryID, entry.getId()); + } + + @Test + public void testClientPost() throws Exception { + Entry newEntry = new Entry(); + newEntry.setTitle(new PlainTextConstruct("NewEntry title by Post")); + newEntry.setContent(new PlainTextConstruct("NewEntry Content by Post")); + Entry postedEntry = testService.clientPost(newEntry); + assertEquals("NewEntry title by Post", postedEntry.getTitle().getPlainText()); + } + + + + @Test + public void testClientPut() throws Exception { + String newTitleValue = "newTitleValueByPut"; + String entryID = "urn:uuid:customer-0"; + System.out.println("Before clientPut"); + testService.clientPut(entryID, newTitleValue); + System.out.println("After clientPut"); + Entry updatedEntry = testService.clientGetEntry(entryID); + System.out.println("title: "+ updatedEntry.getTitle().getPlainText()); + assertEquals(newTitleValue, updatedEntry.getTitle().getPlainText()); + } + + + + @Test + public void testClientDelete() throws Exception { + + // We first create a new entry, then delete it + + // Post a new entry + Entry newEntry = new Entry(); + newEntry.setTitle(new PlainTextConstruct("NewEntry title to be deleted")); + newEntry.setContent(new PlainTextConstruct("NewEntry Content to be delted")); + Entry confirmedNewEntry = testService.clientPost(newEntry); + + Thread.sleep(300); + + Feed feed00 = testService.clientGetFeed(); + int entryNum00 = feed00.getEntries().size(); // The number of entries + // before deleting + System.out.println("entryNum00:" + entryNum00); + + // Delete this newly created entry + String entryID = confirmedNewEntry.getId(); + Thread.sleep(300); + + System.out.println("confirmed entry ID: " + confirmedNewEntry.getId()); + System.out.println("confirmed entry title: " + confirmedNewEntry.getTitle().getPlainText()); + + System.out.println("Before test clientDelete"); + testService.clientDelete(entryID); + System.out.println("After test clientDelete"); + + Feed feed01 = testService.clientGetFeed(); + int entryNum01 = feed01.getEntries().size(); + System.out.println("entryNum01:" + entryNum01); // The number of entries after deleting + + //assertEquals(1, entryNum00 - entryNum01); + } + + +} diff --git a/java/sca/contrib/modules/binding-gdata-runtime/src/test/java/org/apache/tuscany/sca/binding/gdata/CustomerClient.java b/java/sca/contrib/modules/binding-gdata-runtime/src/test/java/org/apache/tuscany/sca/binding/gdata/CustomerClient.java new file mode 100644 index 0000000000..7aa0a8961c --- /dev/null +++ b/java/sca/contrib/modules/binding-gdata-runtime/src/test/java/org/apache/tuscany/sca/binding/gdata/CustomerClient.java @@ -0,0 +1,40 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.gdata; + +import com.google.gdata.client.Query; +import com.google.gdata.data.Entry; +import com.google.gdata.data.Feed; + +public interface CustomerClient { + + Feed clientGetFeed() throws Exception; + + Entry clientGetEntry(String entryID) throws Exception; + + Entry clientPost(Entry entry) throws Exception; + + void clientDelete(String entryID) throws Exception; + + void clientPut(String entryID, String newTitle) throws Exception; + + Feed clientQuery(Query query) throws Exception; + +} diff --git a/java/sca/contrib/modules/binding-gdata-runtime/src/test/java/org/apache/tuscany/sca/binding/gdata/CustomerClientImpl.java b/java/sca/contrib/modules/binding-gdata-runtime/src/test/java/org/apache/tuscany/sca/binding/gdata/CustomerClientImpl.java new file mode 100644 index 0000000000..488bfa0f71 --- /dev/null +++ b/java/sca/contrib/modules/binding-gdata-runtime/src/test/java/org/apache/tuscany/sca/binding/gdata/CustomerClientImpl.java @@ -0,0 +1,123 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.gdata; + +import com.google.gdata.client.Query; +import com.google.gdata.data.Feed; +import com.google.gdata.data.Entry; +import com.google.gdata.data.PlainTextConstruct; + +import org.apache.tuscany.sca.binding.gdata.collection.Collection; +import org.apache.tuscany.sca.binding.gdata.collection.NotFoundException; +import org.oasisopen.sca.annotation.Reference; + +public class CustomerClientImpl implements CustomerClient { + + @Reference + public Collection resourceCollection; + + // Call Collection.getFeed() + public Feed clientGetFeed() throws Exception { + // Get all the entries from the provider, return in a single feed + System.out.println(">>> get the feed from the provider service"); + Feed feed = resourceCollection.getFeed(); + System.out.println("\n\n!!! Fetched feed title: " + feed.getTitle().getPlainText()); + int i = 0; + for (Object o : feed.getEntries()) { + com.google.gdata.data.Entry e = (com.google.gdata.data.Entry)o; + System.out.print("Entry" + i + "\t"); + System.out.println(" id = " + e.getId() + "\t title = " + e.getTitle().getPlainText()); + i++; + } + return feed; + } + + + // Call Collection.get(entryID) + public Entry clientGetEntry(String entryID) throws Exception { + // Get an existing entry based on its id + System.out.println(">>> get an existing entry from the provider service"); + Entry entry = resourceCollection.get(entryID); + System.out.println("\n\n!!! Entry retrieved with id=" + entry.getId() + + " title=" + + entry.getTitle().getPlainText()); + return entry; + } + + + // Call Collection.post(newEntry) + public Entry clientPost(Entry newEntry) throws Exception { + // Put a new entry to the provider + System.out.println(">>> post a new entry to the provider service"); + Entry confirmedNewEntry = resourceCollection.post(newEntry); + System.out.println("!!! New entry posted with id=" + confirmedNewEntry.getId() + + " title=" + + confirmedNewEntry.getTitle().getPlainText()); + System.out.println("\n"); + return confirmedNewEntry; + } + + + // Call Collection.delete(newEntry) + public void clientDelete(String entryID) throws Exception { + // Put a new entry to the provider + System.out.println(">>> delete an existing entry from the provider service"); + System.out.println(">>> delete id=" + "urn:uuid:customer-1"); + resourceCollection.delete(entryID); + System.out.println("!!! entry with id" + entryID); + System.out.println("\n"); + } + + + + // Call Collection.put(entry, updatedTitle) + public void clientPut(String entryID, String newTitle) throws Exception { + + System.out.println("clientPut"); + // Put a new entry to the provider + System.out.println(">>> put id=" + entryID + " title=" + newTitle); + Entry entry = resourceCollection.get(entryID); + + //change the title of this entry + entry.setTitle(new PlainTextConstruct(newTitle)); + resourceCollection.put(entryID, entry); + System.out.println("!!! Updated entry with id=" + entry.getId() + " title=" + entry.getTitle()); + System.out.println("\n"); + } + + + + // Call Collection.getFeed() + public Feed clientQuery(Query query) throws Exception { + // Get all the entries from the provider, return in a single feed + System.out.println(">>> query the service"); + Feed feed = resourceCollection.query(query); + System.out.println("\n\n!!! Query result feed title: " + feed.getTitle().getPlainText()); + int i = 0; + for (Object o : feed.getEntries()) { + com.google.gdata.data.Entry e = (com.google.gdata.data.Entry)o; + System.out.print("Entry" + i + "\t"); + System.out.println(" id = " + e.getId() + "\t title = " + e.getTitle().getPlainText()); + i++; + } + return feed; + } + +} diff --git a/java/sca/contrib/modules/binding-gdata-runtime/src/test/java/org/apache/tuscany/sca/binding/gdata/CustomerCollectionImpl.java b/java/sca/contrib/modules/binding-gdata-runtime/src/test/java/org/apache/tuscany/sca/binding/gdata/CustomerCollectionImpl.java new file mode 100644 index 0000000000..e283b6e023 --- /dev/null +++ b/java/sca/contrib/modules/binding-gdata-runtime/src/test/java/org/apache/tuscany/sca/binding/gdata/CustomerCollectionImpl.java @@ -0,0 +1,143 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.gdata; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import com.google.gdata.client.Query; +import com.google.gdata.data.DateTime; +import com.google.gdata.data.Entry; +import com.google.gdata.data.Feed; +import com.google.gdata.data.Link; +import com.google.gdata.data.PlainTextConstruct; + +import org.apache.tuscany.sca.binding.gdata.collection.Collection; +import org.oasisopen.sca.annotation.Scope; + +@Scope("COMPOSITE") +public class CustomerCollectionImpl implements Collection { + + + private Map entries = new HashMap(); + + /** + * Default constructor that initializes collection with couple customer + * entries + */ + public CustomerCollectionImpl() { + + for (int i = 0; i < 4; i++) { + // id is supposed to be generated in a random way, but for the + // purpose of testing, we just make them as static ids + + // String id = "urn:uuid:customer-" + UUID.randomUUID().toString(); + + String id = "urn:uuid:customer-" + String.valueOf(i); + Entry entry = new Entry(); + entry.setId(id); + entry.setTitle(new PlainTextConstruct("EntryTitle_" + i)); + entry.setContent(new PlainTextConstruct("content_" + i)); + entry.setUpdated(DateTime.now()); + // FIXME: The following three lines of code need to be fixed to add + // HTML links. + Link link = new Link(); + link.setType(Link.Type.ATOM); + link.setRel(Link.Rel.ENTRY_EDIT); + link.setHref("http://localhost:8084/customer" + "/" + id); + entry.getLinks().add(link); + + // entry.addHtmlLink(""+id, "", "edit"); + // entry.addHtmlLink(""+id, "", "alternate"); + entries.put(id, entry); + System.out.println(">>> id=" + id); + } + } + + public Entry post(Entry entry) { + System.out.println(">>> ResourceCollectionImpl.post entry=" + entry.getTitle()); + + String id = "urn:uuid:customer-" + UUID.randomUUID().toString(); + entry.setId(id); + + Link link = new Link(); + link.setType(Link.Type.ATOM); + link.setRel(Link.Rel.ENTRY_EDIT); + link.setHref("http://localhost:8084/customer" + "/" + id); + entry.getLinks().add(link); + + //entry.addLink("" + id, "edit"); entry.addLink("" + id, "alternate"); + entry.setUpdated(DateTime.now()); + + // entry.addHtmlLink("http://www.google.com", "languageType", "edit"); + // entry.addHtmlLink("http://www.google.com", "languageType", + // "alternate"); + + entries.put(id, entry); + System.out.println(">>> ResourceCollectionImpl.post return id=" + id); + return entry; + } + + public Entry get(String id) { + System.out.println(">>> ResourceCollectionImpl.get id= " + id); + return entries.get(id); + } + + public void put(String id, Entry entry) { + System.out.println(">>> ResourceCollectionImpl.put id=" + id + " entry=" + entry.getTitle().getPlainText()); + entry.setUpdated(DateTime.now()); + entries.put(id, entry); + } + + + public void delete(String id) { + System.out.println(">>> ResourceCollectionImpl.delete id=" + id); + entries.remove(id); + } + + + public Feed getFeed() { + System.out.println(">>> ResourceCollectionImpl.get collection"); + + Feed feed = new Feed(); + feed.setTitle(new PlainTextConstruct("Feedtitle(LocalHostServlet)")); + feed.setSubtitle(new PlainTextConstruct("Subtitle: This is a sample feed")); + feed.setUpdated(DateTime.now()); + // FIXME: The following two lines of code need to be fixed + // feed.addHtmlLink("", "", ""); + // feed.addHtmlLink("", "languageType", "self"); + ArrayList entryList = new ArrayList(); + for (Entry entry : entries.values()) { + entryList.add(entry); + } + feed.setEntries(entryList); + + return feed; + } + + //FIXME: need to be modified + public Feed query(Query query) { + System.out.println(">>> ResourceCollectionImpl.query collection "); + return getFeed(); + } + +} diff --git a/java/sca/contrib/modules/binding-gdata-runtime/src/test/java/org/apache/tuscany/sca/binding/gdata/GoogleBloggerServiceTestCase.java b/java/sca/contrib/modules/binding-gdata-runtime/src/test/java/org/apache/tuscany/sca/binding/gdata/GoogleBloggerServiceTestCase.java new file mode 100644 index 0000000000..902d251200 --- /dev/null +++ b/java/sca/contrib/modules/binding-gdata-runtime/src/test/java/org/apache/tuscany/sca/binding/gdata/GoogleBloggerServiceTestCase.java @@ -0,0 +1,156 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.gdata; + +import java.net.URL; + +import junit.framework.TestCase; + +import org.apache.tuscany.sca.node.Contribution; +import org.apache.tuscany.sca.node.ContributionLocationHelper; +import org.apache.tuscany.sca.node.Node; +import org.apache.tuscany.sca.node.NodeFactory; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.google.gdata.client.Query; +import com.google.gdata.data.DateTime; +import com.google.gdata.data.Entry; +import com.google.gdata.data.Feed; +import com.google.gdata.data.PlainTextConstruct; + +public class GoogleBloggerServiceTestCase extends TestCase{ + + private Node consumerNode = null; + private CustomerClient testService = null; + + public GoogleBloggerServiceTestCase(){ + } + + @Before + @Override + public void setUp() throws Exception { + System.out.println("Method Test Start-----------------------------------------------------------------------"); + + //Initialize the GData client service (Reference Binding test) + String contribution = ContributionLocationHelper.getContributionLocation(GoogleBloggerServiceTestCase.class); + consumerNode = NodeFactory.newInstance().createNode( + "org/apache/tuscany/sca/binding/gdata/ConsumerGoogleBlogger.composite", new Contribution("consumer", contribution)); + consumerNode.start(); + testService = consumerNode.getService(CustomerClient.class, "CustomerClient"); + } + + @After + @Override + public void tearDown(){ + System.out.println("Method Test End------------------------------------------------------------------------"); + System.out.println("\n\n"); + consumerNode.stop(); + consumerNode.destroy(); + } + + @Test + public void testClientGetFeed() throws Exception { + Feed feed = testService.clientGetFeed(); + System.out.println("feed title: " + feed.getTitle().getPlainText()); + assertEquals("gdata binding tuscany test", feed.getTitle().getPlainText()); + } + + + @Test + public void testClientGetEntry() throws Exception { + String entryID = "8308734583601887890"; + Entry blogEntry = testService.clientGetEntry(entryID); + System.out.println("Entry ID: " + blogEntry.getId()); + assertTrue(blogEntry.getId().endsWith(entryID)); + System.out.println("------------------------------------------------------------\n\n"); + } + + + @Test + public void testClientPut() throws Exception { + String entryID = "2889832689497686762"; + String newBlogEntryTitle = "updatedTitleByTestCase2"; + testService.clientPut(entryID, newBlogEntryTitle); //update the title + Thread.sleep(300); + Entry updatedEntry = testService.clientGetEntry(entryID); + assertEquals(newBlogEntryTitle, updatedEntry.getTitle().getPlainText()); + } + + + + @Test + public void testClientPost() throws Exception { + String blogEntryTitle = "titleByBloogerTestcase000"; + Entry newEntry = new Entry(); + newEntry.setTitle(new PlainTextConstruct(blogEntryTitle)); + newEntry.setContent(new PlainTextConstruct("contentByBloggerTestCase000")); + Entry postedEntry = testService.clientPost(newEntry); + assertEquals(blogEntryTitle, postedEntry.getTitle().getPlainText()); + } + + + @Test + public void testClientDelete() throws Exception { + + //This test case might fail + //because Google blogger service has limitation on new posts allowed everyday/every hour? + + System.out.println("testClientDelete"); + //We create a new post, and then delete it + Entry newEntry = new Entry(); + newEntry.setTitle(new PlainTextConstruct("blogEntryShouldNotApear")); + newEntry.setContent(new PlainTextConstruct("contentByBloggerShouldNotAppear")); + Entry postedEntry = testService.clientPost(newEntry); + Thread.sleep(300); + int idStartPosition = postedEntry.getId().lastIndexOf("-"); + String postedEntryID = postedEntry.getId().substring(idStartPosition+1); + System.out.println("postedEntryID: " + postedEntryID ); + + //Before deletion + Entry entry00 = testService.clientGetEntry(postedEntryID); + System.out.println("Before Deleteion: " + entry00.getId()); + + //Delete this entry + testService.clientDelete(postedEntryID); + + //Worked: this newly posted entry did not appear in the blogspot website, + //But we need a Junit assertion here + //Link: http://haibotuscany.blogspot.com/feeds/posts/default/ + //FIXME: Need an assertion here + //Assert(....); + } + + + @Test + public void testClientQuery() throws Exception { + Query myQuery = new Query(new URL("http://haibotuscany.blogspot.com/feeds/posts/default")); + myQuery.setMaxResults(100); + //myQuery.setUpdatedMin(startTime); + myQuery.setUpdatedMax(DateTime.now()); + Feed resultFeed = testService.clientQuery(myQuery); + System.out.println("Query result feed title: " + resultFeed.getTitle().getPlainText()); + System.out.println("Query result entry number: "+ resultFeed.getEntries().size()); + //assertEquals("gdata binding tuscany test", resultFeed.getTitle().getPlainText()); + } + + +} diff --git a/java/sca/contrib/modules/binding-gdata-runtime/src/test/java/org/apache/tuscany/sca/binding/gdata/GoogleCalendarServiceTestCase.java b/java/sca/contrib/modules/binding-gdata-runtime/src/test/java/org/apache/tuscany/sca/binding/gdata/GoogleCalendarServiceTestCase.java new file mode 100644 index 0000000000..749dd41710 --- /dev/null +++ b/java/sca/contrib/modules/binding-gdata-runtime/src/test/java/org/apache/tuscany/sca/binding/gdata/GoogleCalendarServiceTestCase.java @@ -0,0 +1,164 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.gdata; + +import java.net.URL; + +import junit.framework.TestCase; + +import org.apache.tuscany.sca.node.Contribution; +import org.apache.tuscany.sca.node.ContributionLocationHelper; +import org.apache.tuscany.sca.node.Node; +import org.apache.tuscany.sca.node.NodeFactory; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.google.gdata.client.Query; +import com.google.gdata.data.DateTime; +import com.google.gdata.data.Entry; +import com.google.gdata.data.Feed; +import com.google.gdata.data.PlainTextConstruct; + +public class GoogleCalendarServiceTestCase extends TestCase{ + + private Node consumerNode = null; + private CustomerClient testService = null; + + public GoogleCalendarServiceTestCase(){ + } + + @Before + @Override + public void setUp() throws Exception { + System.out.println("Method Test Start-----------------------------------------------------------------------"); + + //Initialize the GData client service (Reference Binding test) + String contribution = ContributionLocationHelper.getContributionLocation(GoogleCalendarServiceTestCase.class); + consumerNode = NodeFactory.newInstance().createNode( + "org/apache/tuscany/sca/binding/gdata/ConsumerGoogleCalendar.composite", new Contribution("consumer", contribution)); + consumerNode.start(); + testService = consumerNode.getService(CustomerClient.class, "CustomerClient"); + } + + @After + @Override + public void tearDown(){ + System.out.println("Method Test End------------------------------------------------------------------------"); + System.out.println("\n\n"); + consumerNode.stop(); + consumerNode.destroy(); + } + + @Test + public void testClientGetFeed() throws Exception { + Feed feed = testService.clientGetFeed(); + System.out.println("feed title: " + feed.getTitle().getPlainText()); + assertEquals("gsoc gosc", feed.getTitle().getPlainText()); + } + + + @Test + public void testClientGetEntry() throws Exception { + String entryID = "1c76lcl70jg9r0fm18rcbneea8"; + Entry blogEntry = testService.clientGetEntry(entryID); + System.out.println("Entry ID: " + blogEntry.getId()); + assertTrue(blogEntry.getId().endsWith(entryID)); + System.out.println("------------------------------------------------------------\n\n"); + } + + + @Test + public void testClientPut() throws Exception { + String entryID = "1c76lcl70jg9r0fm18rcbneea8"; + String newBlogEntryTitle = "updatedTitleByGoogleContactsConsumerTestCase"; + testService.clientPut(entryID, newBlogEntryTitle); //update the title + Thread.sleep(300); + Entry updatedEntry = testService.clientGetEntry(entryID); + assertEquals(newBlogEntryTitle, updatedEntry.getTitle().getPlainText()); + } + + + + @Test + public void testClientPost() throws Exception { + String blogEntryTitle = "titleByGoogleCalendarTestcase"; + Entry newEntry = new Entry(); + newEntry.setTitle(new PlainTextConstruct(blogEntryTitle)); + newEntry.setContent(new PlainTextConstruct("contentByGoogleCalendarTestCase")); + Entry postedEntry = testService.clientPost(newEntry); + assertEquals(blogEntryTitle, postedEntry.getTitle().getPlainText()); + } + + + @Test + public void testClientDelete() throws Exception { + + //This test case might fail + //because Google blogger service has limitation on new posts allowed everyday/every hour? + + System.out.println("testClientDelete"); + //We create a new post, and then delete it + Entry newEntry = new Entry(); + newEntry.setTitle(new PlainTextConstruct("calendarEntryShouldNotApear")); + newEntry.setContent(new PlainTextConstruct("calendarByBloggerShouldNotAppear")); + Entry postedEntry = testService.clientPost(newEntry); + Thread.sleep(300); + + System.out.println("ID: " + postedEntry.getId()); + + int idStartPosition = postedEntry.getId().lastIndexOf("/"); + String postedEntryID = postedEntry.getId().substring(idStartPosition+1); + System.out.println("postedEntryID: " + postedEntryID ); + + //Before deletion + Entry entry00 = testService.clientGetEntry(postedEntryID); + System.out.println("Before Deleteion: " + entry00.getId()); + + //Delete this entry + testService.clientDelete(postedEntryID); + + //Worked: this newly posted entry did not appear in the contact list + //But we need a Junit assertion here + //Link: http://haibotuscany.blogspot.com/feeds/posts/default/ + //FIXME: Need an assertion here + //Assert(....); + } + + + @Test + public void testClientQuery() throws Exception { + Query myQuery = new Query(new URL("http://www.google.com/calendar/feeds/haibotuscany@gmail.com/private/full")); + myQuery.setMaxResults(100); + //myQuery.setUpdatedMin(startTime); + myQuery.setUpdatedMax(DateTime.now()); + + //Google Calendar service supports full-text search + String queryString = "event0"; + myQuery.setFullTextQuery(queryString); + + Feed resultFeed = testService.clientQuery(myQuery); + System.out.println("Query result feed title: " + resultFeed.getTitle().getPlainText()); + System.out.println("Query result entry number: "+ resultFeed.getEntries().size()); + //assertEquals("gdata binding tuscany test", resultFeed.getTitle().getPlainText()); + } + + +} diff --git a/java/sca/contrib/modules/binding-gdata-runtime/src/test/java/org/apache/tuscany/sca/binding/gdata/GoogleContactsServiceTestCase.java b/java/sca/contrib/modules/binding-gdata-runtime/src/test/java/org/apache/tuscany/sca/binding/gdata/GoogleContactsServiceTestCase.java new file mode 100644 index 0000000000..cab7196a69 --- /dev/null +++ b/java/sca/contrib/modules/binding-gdata-runtime/src/test/java/org/apache/tuscany/sca/binding/gdata/GoogleContactsServiceTestCase.java @@ -0,0 +1,160 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.gdata; + +import java.net.URL; + +import junit.framework.TestCase; + +import org.apache.tuscany.sca.node.Contribution; +import org.apache.tuscany.sca.node.ContributionLocationHelper; +import org.apache.tuscany.sca.node.Node; +import org.apache.tuscany.sca.node.NodeFactory; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.google.gdata.client.Query; +import com.google.gdata.data.DateTime; +import com.google.gdata.data.Entry; +import com.google.gdata.data.Feed; +import com.google.gdata.data.PlainTextConstruct; + +public class GoogleContactsServiceTestCase extends TestCase{ + + private Node consumerNode = null; + private CustomerClient testService = null; + + public GoogleContactsServiceTestCase(){ + + } + + @Before + @Override + public void setUp() throws Exception { + System.out.println("Method Test Start-----------------------------------------------------------------------"); + + //Initialize the GData client service (Reference Binding test) + String contribution = ContributionLocationHelper.getContributionLocation(GoogleContactsServiceTestCase.class); + consumerNode = NodeFactory.newInstance().createNode( + "org/apache/tuscany/sca/binding/gdata/ConsumerGoogleContacts.composite", new Contribution("consumer", contribution)); + consumerNode.start(); + testService = consumerNode.getService(CustomerClient.class, "CustomerClient"); + } + + @After + @Override + public void tearDown(){ + System.out.println("Method Test End------------------------------------------------------------------------"); + System.out.println("\n\n"); + consumerNode.stop(); + consumerNode.destroy(); + } + + @Test + public void testClientGetFeed() throws Exception { + Feed feed = testService.clientGetFeed(); + System.out.println("feed title: " + feed.getTitle().getPlainText()); + assertEquals("Haibo Zhao's Contacts", feed.getTitle().getPlainText()); + } + + + @Test + public void testClientGetEntry() throws Exception { + String entryID = "12feeeb38ab87365"; + Entry contactEntry = testService.clientGetEntry(entryID); + System.out.println("Entry ID: " + contactEntry.getId()); + assertTrue(contactEntry.getId().endsWith(entryID)); + System.out.println("------------------------------------------------------------\n\n"); + } + + + @Test + public void testClientPut() throws Exception { + String entryID = "12feeeb38ab87365"; + String newBlogEntryTitle = "updatedTitleByGoogleContactsConsumerTestCase"; + testService.clientPut(entryID, newBlogEntryTitle); //update the title + Thread.sleep(300); + Entry updatedEntry = testService.clientGetEntry(entryID); + assertEquals(newBlogEntryTitle, updatedEntry.getTitle().getPlainText()); + } + + + + @Test + public void testClientPost() throws Exception { + String blogEntryTitle = "titleByGoogleContactsTestcase"; + Entry newEntry = new Entry(); + newEntry.setTitle(new PlainTextConstruct(blogEntryTitle)); + newEntry.setContent(new PlainTextConstruct("contentByGoogleContactsTestCase")); + Entry postedEntry = testService.clientPost(newEntry); + assertEquals(blogEntryTitle, postedEntry.getTitle().getPlainText()); + } + + + @Test + public void testClientDelete() throws Exception { + + //This test case might fail + //because Google blogger service has limitation on new posts allowed everyday/every hour? + + System.out.println("testClientDelete"); + //We create a new post, and then delete it + Entry newEntry = new Entry(); + newEntry.setTitle(new PlainTextConstruct("contactEntryShouldNotApear")); + newEntry.setContent(new PlainTextConstruct("contactByBloggerShouldNotAppear")); + Entry postedEntry = testService.clientPost(newEntry); + Thread.sleep(300); + + System.out.println("ID: " + postedEntry.getId()); + + int idStartPosition = postedEntry.getId().lastIndexOf("/"); + String postedEntryID = postedEntry.getId().substring(idStartPosition+1); + System.out.println("postedEntryID: " + postedEntryID ); + + //Before deletion + Entry entry00 = testService.clientGetEntry(postedEntryID); + System.out.println("Before Deleteion: " + entry00.getId()); + + //Delete this entry + testService.clientDelete(postedEntryID); + + //Worked: this newly posted entry did not appear in the contact list + //But we need a Junit assertion here + //Link: http://haibotuscany.blogspot.com/feeds/posts/default/ + //FIXME: Need an assertion here + //Assert(....); + } + + + @Test + public void testClientQuery() throws Exception { + Query myQuery = new Query(new URL("http://www.google.com/m8/feeds/contacts/default/base")); + myQuery.setMaxResults(100); + //myQuery.setUpdatedMin(startTime); + myQuery.setUpdatedMax(DateTime.now()); + Feed resultFeed = testService.clientQuery(myQuery); + System.out.println("Query result feed title: " + resultFeed.getTitle().getPlainText()); + System.out.println("Query result entry number: "+ resultFeed.getEntries().size()); + //assertEquals("gdata binding tuscany test", resultFeed.getTitle().getPlainText()); + } + + +} diff --git a/java/sca/contrib/modules/binding-gdata-runtime/src/test/java/org/apache/tuscany/sca/binding/gdata/Provider.java b/java/sca/contrib/modules/binding-gdata-runtime/src/test/java/org/apache/tuscany/sca/binding/gdata/Provider.java new file mode 100644 index 0000000000..a9b12c3d32 --- /dev/null +++ b/java/sca/contrib/modules/binding-gdata-runtime/src/test/java/org/apache/tuscany/sca/binding/gdata/Provider.java @@ -0,0 +1,48 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.gdata; + +import java.io.IOException; + +import org.apache.tuscany.sca.node.Contribution; +import org.apache.tuscany.sca.node.ContributionLocationHelper; +import org.apache.tuscany.sca.node.Node; +import org.apache.tuscany.sca.node.NodeFactory; + +public class Provider { + + public static void main(String[] args) { + + String contribution = ContributionLocationHelper.getContributionLocation(Provider.class); + Node node = NodeFactory.newInstance().createNode( + "org/apache/tuscany/sca/binding/gdata/Provider.composite", new Contribution("provider", contribution)); + node.start(); + System.out.println("Provider.composite ready..."); + + try { + System.in.read(); + } catch (IOException e) { + e.printStackTrace(); + } + + node.stop(); + node.destroy(); + } +} diff --git a/java/sca/contrib/modules/binding-gdata-runtime/src/test/java/org/apache/tuscany/sca/binding/gdata/StartLocalhostServlet.java b/java/sca/contrib/modules/binding-gdata-runtime/src/test/java/org/apache/tuscany/sca/binding/gdata/StartLocalhostServlet.java new file mode 100644 index 0000000000..141f641575 --- /dev/null +++ b/java/sca/contrib/modules/binding-gdata-runtime/src/test/java/org/apache/tuscany/sca/binding/gdata/StartLocalhostServlet.java @@ -0,0 +1,48 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.gdata; + +import java.io.IOException; + +import org.apache.tuscany.sca.node.Contribution; +import org.apache.tuscany.sca.node.ContributionLocationHelper; +import org.apache.tuscany.sca.node.Node; +import org.apache.tuscany.sca.node.NodeFactory; + +public class StartLocalhostServlet { + + public static void main(String[] args) { + + String contribution = ContributionLocationHelper.getContributionLocation(Provider.class); + Node node = NodeFactory.newInstance().createNode( + "org/apache/tuscany/sca/binding/gdata/Provider.composite", new Contribution("provider", contribution)); + node.start(); + System.out.println("Provider.composite ready..."); + + try { + System.in.read(); + } catch (IOException e) { + e.printStackTrace(); + } + + node.stop(); + node.destroy(); + } +} diff --git a/java/sca/contrib/modules/binding-gdata-runtime/src/test/resources/log4j.properties b/java/sca/contrib/modules/binding-gdata-runtime/src/test/resources/log4j.properties new file mode 100644 index 0000000000..33eaf11c1f --- /dev/null +++ b/java/sca/contrib/modules/binding-gdata-runtime/src/test/resources/log4j.properties @@ -0,0 +1,25 @@ +# +# 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. +# + +# Set root logger level to WARN and its only appender to CONSOLE +log4j.rootLogger=INFO, CONSOLE + + +# Console appender +log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender +log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout +log4j.appender.CONSOLE.layout.ConversionPattern=%d{ABSOLUTE} %-5p %x - %m\n diff --git a/java/sca/contrib/modules/binding-gdata-runtime/src/test/resources/org/apache/tuscany/sca/binding/gdata/Consumer.composite b/java/sca/contrib/modules/binding-gdata-runtime/src/test/resources/org/apache/tuscany/sca/binding/gdata/Consumer.composite new file mode 100644 index 0000000000..a7941a2056 --- /dev/null +++ b/java/sca/contrib/modules/binding-gdata-runtime/src/test/resources/org/apache/tuscany/sca/binding/gdata/Consumer.composite @@ -0,0 +1,32 @@ + + + + + + + + + + + + diff --git a/java/sca/contrib/modules/binding-gdata-runtime/src/test/resources/org/apache/tuscany/sca/binding/gdata/ConsumerGoogleBlogger.composite b/java/sca/contrib/modules/binding-gdata-runtime/src/test/resources/org/apache/tuscany/sca/binding/gdata/ConsumerGoogleBlogger.composite new file mode 100644 index 0000000000..078873c44f --- /dev/null +++ b/java/sca/contrib/modules/binding-gdata-runtime/src/test/resources/org/apache/tuscany/sca/binding/gdata/ConsumerGoogleBlogger.composite @@ -0,0 +1,32 @@ + + + + + + + + + + + + diff --git a/java/sca/contrib/modules/binding-gdata-runtime/src/test/resources/org/apache/tuscany/sca/binding/gdata/ConsumerGoogleCalendar.composite b/java/sca/contrib/modules/binding-gdata-runtime/src/test/resources/org/apache/tuscany/sca/binding/gdata/ConsumerGoogleCalendar.composite new file mode 100644 index 0000000000..7e0c925482 --- /dev/null +++ b/java/sca/contrib/modules/binding-gdata-runtime/src/test/resources/org/apache/tuscany/sca/binding/gdata/ConsumerGoogleCalendar.composite @@ -0,0 +1,32 @@ + + + + + + + + + + + + diff --git a/java/sca/contrib/modules/binding-gdata-runtime/src/test/resources/org/apache/tuscany/sca/binding/gdata/ConsumerGoogleContacts.composite b/java/sca/contrib/modules/binding-gdata-runtime/src/test/resources/org/apache/tuscany/sca/binding/gdata/ConsumerGoogleContacts.composite new file mode 100644 index 0000000000..bc1ea7a8a9 --- /dev/null +++ b/java/sca/contrib/modules/binding-gdata-runtime/src/test/resources/org/apache/tuscany/sca/binding/gdata/ConsumerGoogleContacts.composite @@ -0,0 +1,32 @@ + + + + + + + + + + + + diff --git a/java/sca/contrib/modules/binding-gdata-runtime/src/test/resources/org/apache/tuscany/sca/binding/gdata/Provider.composite b/java/sca/contrib/modules/binding-gdata-runtime/src/test/resources/org/apache/tuscany/sca/binding/gdata/Provider.composite new file mode 100644 index 0000000000..a4cf00dc84 --- /dev/null +++ b/java/sca/contrib/modules/binding-gdata-runtime/src/test/resources/org/apache/tuscany/sca/binding/gdata/Provider.composite @@ -0,0 +1,33 @@ + + + + + + + + + + + + + diff --git a/java/sca/contrib/modules/binding-gdata/LICENSE b/java/sca/contrib/modules/binding-gdata/LICENSE new file mode 100644 index 0000000000..d645695673 --- /dev/null +++ b/java/sca/contrib/modules/binding-gdata/LICENSE @@ -0,0 +1,202 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/java/sca/contrib/modules/binding-gdata/META-INF/MANIFEST.MF b/java/sca/contrib/modules/binding-gdata/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..6d5d52037e --- /dev/null +++ b/java/sca/contrib/modules/binding-gdata/META-INF/MANIFEST.MF @@ -0,0 +1,23 @@ +Manifest-Version: 1.0 +Export-Package: org.apache.tuscany.sca.binding.gdata;uses:="org.apache + .tuscany.sca.assembly";version="2.0.0" +Private-Package: org.apache.tuscany.sca.binding.gdata.impl;version="1. + 4",org.apache.tuscany.sca.binding.gdata.xml;version="2.0.0" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA Gdata Binding Extension +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397266640 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA Gdata Binding Extension +Import-Package: javax.xml.namespace,javax.xml.stream,org.apache.tuscan + y.sca.assembly;version="2.0.0",org.apache.tuscany.sca.binding.gdata;ver + sion="1.4",org.apache.tuscany.sca.contribution.processor;version="1.4 + ",org.apache.tuscany.sca.contribution.resolver;version="2.0.0",org.apac + he.tuscany.sca.core;version="2.0.0",org.apache.tuscany.sca.policy;versi + on="1.4" +Bundle-SymbolicName: org.apache.tuscany.sca.binding.gdata +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/binding-gdata/NOTICE b/java/sca/contrib/modules/binding-gdata/NOTICE new file mode 100644 index 0000000000..841fb69681 --- /dev/null +++ b/java/sca/contrib/modules/binding-gdata/NOTICE @@ -0,0 +1,8 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + + + diff --git a/java/sca/contrib/modules/binding-gdata/pom.xml b/java/sca/contrib/modules/binding-gdata/pom.xml new file mode 100644 index 0000000000..299e24e619 --- /dev/null +++ b/java/sca/contrib/modules/binding-gdata/pom.xml @@ -0,0 +1,60 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + + tuscany-binding-gdata + Apache Tuscany SCA Gdata Binding Extension + + + + org.apache.tuscany.sca + tuscany-core-spi + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-assembly-xml + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-assembly + 2.0-SNAPSHOT + + + + junit + junit + 4.5 + test + + + + + diff --git a/java/sca/contrib/modules/binding-gdata/src/main/java/org/apache/tuscany/sca/binding/gdata/GdataBinding.java b/java/sca/contrib/modules/binding-gdata/src/main/java/org/apache/tuscany/sca/binding/gdata/GdataBinding.java new file mode 100644 index 0000000000..a3a0b834cd --- /dev/null +++ b/java/sca/contrib/modules/binding-gdata/src/main/java/org/apache/tuscany/sca/binding/gdata/GdataBinding.java @@ -0,0 +1,78 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.gdata; + +import org.apache.tuscany.sca.assembly.Binding; + +/** + * Gdata binding model. + * + * @version $Rev$ $Date$ + */ +public interface GdataBinding extends Binding { + + /** + * Returns the title of the GData collection. + * @return + */ + String getTitle(); + + /** + * Sets the title of the GData collection. + * @param title + */ + void setTitle(String title); + + /** + * Returns the username to be used when authenticating with GData Services + * @return + */ + String getUsername(); + + /** + * Sets the username to be used when authenticating with GData Services + * @param username + */ + void setUsername(String username); + + /** + * Returns the password to be used when authenticating with GData Services + * @return + */ + String getPassword(); + + /** + * Sets the password to be used when authenticating with GData Services + * @param password + */ + void setPassword(String password); + + /** + * Returns the type os service being used + * @return + */ + String getServiceType(); + + /** + * Sets the type of service being used + * @param serviceType + */ + void setServiceType(String serviceType); +} diff --git a/java/sca/contrib/modules/binding-gdata/src/main/java/org/apache/tuscany/sca/binding/gdata/GdataBindingFactory.java b/java/sca/contrib/modules/binding-gdata/src/main/java/org/apache/tuscany/sca/binding/gdata/GdataBindingFactory.java new file mode 100644 index 0000000000..5cfc688dcb --- /dev/null +++ b/java/sca/contrib/modules/binding-gdata/src/main/java/org/apache/tuscany/sca/binding/gdata/GdataBindingFactory.java @@ -0,0 +1,35 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.gdata; + +/** + * Factory for the GData binding + * + * @version $Rev$ $Date$ + */ +public interface GdataBindingFactory { + + /** + * Creates a new GData binding. + * @return the new GData binding + */ + GdataBinding createGdataBinding(); + +} diff --git a/java/sca/contrib/modules/binding-gdata/src/main/java/org/apache/tuscany/sca/binding/gdata/impl/GdataBindingFactoryImpl.java b/java/sca/contrib/modules/binding-gdata/src/main/java/org/apache/tuscany/sca/binding/gdata/impl/GdataBindingFactoryImpl.java new file mode 100644 index 0000000000..87f3597248 --- /dev/null +++ b/java/sca/contrib/modules/binding-gdata/src/main/java/org/apache/tuscany/sca/binding/gdata/impl/GdataBindingFactoryImpl.java @@ -0,0 +1,36 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.gdata.impl; + +import org.apache.tuscany.sca.binding.gdata.GdataBinding; +import org.apache.tuscany.sca.binding.gdata.GdataBindingFactory; + +/** + * Factory for the GData binding model. + * + * @version $Rev$ $Date$ + */ +public class GdataBindingFactoryImpl implements GdataBindingFactory { + + public GdataBinding createGdataBinding() { + return new GdataBindingImpl(); + } + +} diff --git a/java/sca/contrib/modules/binding-gdata/src/main/java/org/apache/tuscany/sca/binding/gdata/impl/GdataBindingImpl.java b/java/sca/contrib/modules/binding-gdata/src/main/java/org/apache/tuscany/sca/binding/gdata/impl/GdataBindingImpl.java new file mode 100644 index 0000000000..409fd497ac --- /dev/null +++ b/java/sca/contrib/modules/binding-gdata/src/main/java/org/apache/tuscany/sca/binding/gdata/impl/GdataBindingImpl.java @@ -0,0 +1,141 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.gdata.impl; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.tuscany.sca.binding.gdata.GdataBinding; +import org.apache.tuscany.sca.policy.Intent; +import org.apache.tuscany.sca.policy.IntentAttachPointType; +import org.apache.tuscany.sca.policy.PolicySet; +import org.apache.tuscany.sca.policy.PolicySetAttachPoint; + +/** + * Implementation of the GData binding model. + * + * @version $Rev$ $Date$ + */ +class GdataBindingImpl implements GdataBinding, PolicySetAttachPoint { + + private String name; + private String uri; + private String title; + private String username; + private String password; + private String serviceType; + + private List requiredIntents = new ArrayList(); + private List policySets = new ArrayList(); + private IntentAttachPointType intentAttachPointType; + private List applicablePolicySets = new ArrayList(); + + public String getName() { + return name; + } + + public String getURI() { + return uri; + } + + public String getTitle() { + return title; + } + + public String getUsername(){ + return username; + } + + public String getPassword(){ + return password; + } + + public String getServiceType(){ + return serviceType; + } + + public void setName(String name) { + this.name = name; + } + + public void setURI(String uri) { + this.uri = uri; + } + + public void setTitle(String title) { + this.title = title; + } + + public void setUsername(String username) { + this.username = username; + } + + public void setPassword(String password) { + this.password = password; + } + + public void setServiceType(String serviceType) { + this.serviceType = serviceType; + } + + public boolean isUnresolved() { + // The binding is always resolved + return false; + } + + public void setUnresolved(boolean unresolved) { + // The binding is always resolved + } + + //Policy related getters/setters + + public List getApplicablePolicySets() { + return applicablePolicySets; + } + + public List getPolicySets() { + return policySets; + } + + public List getRequiredIntents() { + return requiredIntents; + } + + public IntentAttachPointType getType() { + return intentAttachPointType; + } + + public void setType(IntentAttachPointType intentAttachPointType) { + this.intentAttachPointType = intentAttachPointType; + } + + public void setPolicySets(List policySets) { + this.policySets = policySets; + } + + public void setRequiredIntents(List intents) { + this.requiredIntents = intents; + } + + @Override + public Object clone() throws CloneNotSupportedException { + return super.clone(); + } +} \ No newline at end of file diff --git a/java/sca/contrib/modules/binding-gdata/src/main/java/org/apache/tuscany/sca/binding/gdata/xml/GdataBindingProcessor.java b/java/sca/contrib/modules/binding-gdata/src/main/java/org/apache/tuscany/sca/binding/gdata/xml/GdataBindingProcessor.java new file mode 100644 index 0000000000..660b96243e --- /dev/null +++ b/java/sca/contrib/modules/binding-gdata/src/main/java/org/apache/tuscany/sca/binding/gdata/xml/GdataBindingProcessor.java @@ -0,0 +1,121 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.gdata.xml; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; + +import org.apache.tuscany.sca.binding.gdata.GdataBinding; +import org.apache.tuscany.sca.binding.gdata.GdataBindingFactory; +import org.apache.tuscany.sca.contribution.processor.ContributionReadException; +import org.apache.tuscany.sca.contribution.processor.ContributionResolveException; +import org.apache.tuscany.sca.contribution.processor.ContributionWriteException; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.core.FactoryExtensionPoint; + +/** + * A processor for elements. + * + * @version $Rev$ $Date$ + */ +public class GdataBindingProcessor implements StAXArtifactProcessor { + + private QName BINDING_GDATA = new QName("http://tuscany.apache.org/xmlns/sca/1.0", "binding.gdata"); + + private final GdataBindingFactory factory; + + public GdataBindingProcessor(FactoryExtensionPoint modelFactories) { + this.factory = modelFactories.getFactory(GdataBindingFactory.class); + System.out.println("[Debug Info]GdataBindingProcessor reached"); + } + + public QName getArtifactType() { + return BINDING_GDATA; + } + + public Class getModelType() { + return GdataBinding.class; + } + + public GdataBinding read(XMLStreamReader reader) throws ContributionReadException, XMLStreamException { + GdataBinding gdataBinding = factory.createGdataBinding(); + + String name = reader.getAttributeValue(null, "name"); + if (name != null) { + gdataBinding.setName(name); + } + + String uri = reader.getAttributeValue(null, "uri"); + if (uri != null) { + gdataBinding.setURI(uri); + } + + String serviceType = reader.getAttributeValue(null, "serviceType"); + if (serviceType != null) { + gdataBinding.setServiceType(serviceType); + } + + String username = reader.getAttributeValue(null, "username"); + if (username != null) { + gdataBinding.setUsername(username); + } + + String password = reader.getAttributeValue(null, "password"); + if (password != null) { + gdataBinding.setPassword(password); + } + + + return gdataBinding; + } + + public void write(GdataBinding gdataBinding, XMLStreamWriter writer) throws ContributionWriteException, XMLStreamException { + writer.writeStartElement(BINDING_GDATA.getNamespaceURI(), BINDING_GDATA.getLocalPart()); + + if (gdataBinding.getName() != null) { + writer.writeAttribute("name", gdataBinding.getName()); + } + + if (gdataBinding.getURI() != null) { + writer.writeAttribute("uri", gdataBinding.getURI()); + } + + if (gdataBinding.getServiceType() != null) { + writer.writeAttribute("serviceType", gdataBinding.getServiceType()); + } + + if (gdataBinding.getUsername() != null) { + writer.writeAttribute("username", gdataBinding.getUsername()); + } + + if (gdataBinding.getPassword() != null) { + writer.writeAttribute("password", gdataBinding.getPassword()); + } + + writer.writeEndElement(); + } + + + public void resolve(GdataBinding gdataBinding, ModelResolver resolver) throws ContributionResolveException { + + } +} diff --git a/java/sca/contrib/modules/binding-gdata/src/main/resources/META-INF/services/org.apache.tuscany.sca.binding.gdata.GdataBindingFactory b/java/sca/contrib/modules/binding-gdata/src/main/resources/META-INF/services/org.apache.tuscany.sca.binding.gdata.GdataBindingFactory new file mode 100644 index 0000000000..21688a62a6 --- /dev/null +++ b/java/sca/contrib/modules/binding-gdata/src/main/resources/META-INF/services/org.apache.tuscany.sca.binding.gdata.GdataBindingFactory @@ -0,0 +1,18 @@ +# 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. + +# Implementation class for the model factory +org.apache.tuscany.sca.binding.gdata.impl.GdataBindingFactoryImpl \ No newline at end of file diff --git a/java/sca/contrib/modules/binding-gdata/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor b/java/sca/contrib/modules/binding-gdata/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor new file mode 100644 index 0000000000..e7c37c44fe --- /dev/null +++ b/java/sca/contrib/modules/binding-gdata/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for the artifact processor extension +org.apache.tuscany.sca.binding.gdata.xml.GdataBindingProcessor;qname=http://tuscany.apache.org/xmlns/sca/1.0#binding.gdata,model=org.apache.tuscany.sca.binding.gdata.GdataBinding,factory=org.apache.tuscany.sca.binding.gdata.GdataBindingFactory \ No newline at end of file diff --git a/java/sca/contrib/modules/binding-http-runtime/LICENSE b/java/sca/contrib/modules/binding-http-runtime/LICENSE new file mode 100644 index 0000000000..8aa906c321 --- /dev/null +++ b/java/sca/contrib/modules/binding-http-runtime/LICENSE @@ -0,0 +1,205 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + + diff --git a/java/sca/contrib/modules/binding-http-runtime/META-INF/MANIFEST.MF b/java/sca/contrib/modules/binding-http-runtime/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..38d5bca016 --- /dev/null +++ b/java/sca/contrib/modules/binding-http-runtime/META-INF/MANIFEST.MF @@ -0,0 +1,28 @@ +Manifest-Version: 1.0 +Private-Package: org.apache.tuscany.sca.binding.http.provider;version= + "1.4" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA HTTP Binding Runtime +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397277718 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA HTTP Binding Runtime +Import-Package: javax.servlet, + javax.servlet.http, + org.apache.tuscany.sca.assembly;version="2.0.0", + org.apache.tuscany.sca.binding.http;version="2.0.0", + org.apache.tuscany.sca.core;version="2.0.0", + org.apache.tuscany.sca.host.http;version="2.0.0", + org.apache.tuscany.sca.interfacedef;version="2.0.0", + org.apache.tuscany.sca.invocation;version="2.0.0", + org.apache.tuscany.sca.policy;version="2.0.0", + org.apache.tuscany.sca.policy.authentication.basic;version="2.0.0", + org.apache.tuscany.sca.provider;version="2.0.0", + org.apache.tuscany.sca.runtime;version="2.0.0", + org.oasisopen.sca.annotation;version="2.0.0";resolution:=optional +Bundle-SymbolicName: org.apache.tuscany.sca.binding.http.runtime +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/binding-http-runtime/NOTICE b/java/sca/contrib/modules/binding-http-runtime/NOTICE new file mode 100644 index 0000000000..25bb89c9b2 --- /dev/null +++ b/java/sca/contrib/modules/binding-http-runtime/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/binding-http-runtime/pom.xml b/java/sca/contrib/modules/binding-http-runtime/pom.xml new file mode 100644 index 0000000000..c78837d5cb --- /dev/null +++ b/java/sca/contrib/modules/binding-http-runtime/pom.xml @@ -0,0 +1,100 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + + tuscany-binding-http-runtime + Apache Tuscany SCA HTTP Binding Runtime + + + + org.apache.tuscany.sca + tuscany-binding-http + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-policy-security + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-core-spi + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-host-http + 2.0-SNAPSHOT + + + + javax.servlet + servlet-api + 2.5 + + + + org.apache.tuscany.sca + tuscany-node-impl + 2.0-SNAPSHOT + test + + + + org.apache.tuscany.sca + tuscany-host-jetty + 2.0-SNAPSHOT + test + + + + org.apache.tuscany.sca + tuscany-implementation-resource-runtime + 2.0-SNAPSHOT + test + + + + org.apache.tuscany.sca + tuscany-implementation-java-runtime + 2.0-SNAPSHOT + test + + + + junit + junit + 4.5 + test + + + + + diff --git a/java/sca/contrib/modules/binding-http-runtime/src/main/java/org/apache/tuscany/sca/binding/http/provider/HTTPBindingListenerServlet.java b/java/sca/contrib/modules/binding-http-runtime/src/main/java/org/apache/tuscany/sca/binding/http/provider/HTTPBindingListenerServlet.java new file mode 100644 index 0000000000..084f52026f --- /dev/null +++ b/java/sca/contrib/modules/binding-http-runtime/src/main/java/org/apache/tuscany/sca/binding/http/provider/HTTPBindingListenerServlet.java @@ -0,0 +1,516 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.http.provider; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URLDecoder; +import java.text.ParseException; +import java.util.List; + +import javax.servlet.ServletException; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.binding.http.HTTPCacheContext; +import org.apache.tuscany.sca.binding.http.util.HTTPHeadersParser; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.invocation.MessageFactory; +import org.apache.tuscany.sca.policy.Intent; +import org.apache.tuscany.sca.policy.PolicySet; +import org.apache.tuscany.sca.policy.PolicySetAttachPoint; +import org.apache.tuscany.sca.policy.authentication.basic.BasicAuthenticationPolicy; + +/** + * Servlet responsible for dispatching HTTP requests to the + * target component implementation. + * + * @version $Rev$ $Date$ + */ +public class HTTPBindingListenerServlet extends HttpServlet { + private static final long serialVersionUID = 2865466417329430610L; + + private static final QName AUTEHTICATION_INTENT = new QName("http://www.osoa.org/xmlns/sca/1.0","authentication"); + + transient private Binding binding; + + transient private boolean requiresAuthentication = false; + transient private BasicAuthenticationPolicy basicAuthenticationPolicy = null; + + private MessageFactory messageFactory; + private Invoker getInvoker; + private Invoker conditionalGetInvoker; + private Invoker putInvoker; + private Invoker conditionalPutInvoker; + private Invoker postInvoker; + private Invoker conditionalPostInvoker; + private Invoker deleteInvoker; + private Invoker conditionalDeleteInvoker; + + /** + * Constructs a new HTTPServiceListenerServlet. + */ + public HTTPBindingListenerServlet(Binding binding, MessageFactory messageFactory) { + this.binding = binding; + this.messageFactory = messageFactory; + + + // find out which policies are active + if (binding instanceof PolicySetAttachPoint) { + List intents = ((PolicySetAttachPoint)binding).getRequiredIntents(); + for(Intent intent : intents) { + if(intent.getName().equals(AUTEHTICATION_INTENT)) { + requiresAuthentication = true; + } + } + + + List policySets = ((PolicySetAttachPoint)binding).getApplicablePolicySets(); + for (PolicySet ps : policySets) { + for (Object p : ps.getPolicies()) { + if (BasicAuthenticationPolicy.class.isInstance(p)) { + basicAuthenticationPolicy = (BasicAuthenticationPolicy)p; + } else { + // etc. check for other types of policy being present + } + } + } + } + } + + + @Override + protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + if(requiresAuthentication) { + if(! hasAuthenticationHeader(request, response)) { + response.setHeader("WWW-Authenticate", "BASIC realm=\"Tuscany\""); + response.sendError(HttpServletResponse.SC_UNAUTHORIZED); + } + } + + super.service(request, response); + } + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + // Get the request path + String path = URLDecoder.decode(request.getRequestURI().substring(request.getServletPath().length()), "UTF-8"); + if (path.length() ==0) { + // Redirect to a URL ending with / to make relative hrefs work + // relative to the served resource. + response.sendRedirect(request.getRequestURL().append('/').toString()); + return; + } + + // Invoke the get operation on the service implementation + Message requestMessage = messageFactory.createMessage(); + + //store http headers to message + requestMessage.getHeaders().addAll(HTTPHeadersParser.getHeaders(request)); + + String id = path.substring(1); + + Message responseMessage = null; + HTTPCacheContext cacheContext = null; + try { + cacheContext = HTTPCacheContext.getCacheContextFromRequest(request); + } catch (ParseException e) { + } + + // Route message based on availability of cache info and cache methods + if (( cacheContext != null ) && (cacheContext.isEnabled()) && (conditionalGetInvoker != null )) { + requestMessage.setBody(new Object[] {id, cacheContext}); + responseMessage = conditionalGetInvoker.invoke(requestMessage); + } else { + requestMessage.setBody(new Object[] {id}); + responseMessage = getInvoker.invoke(requestMessage); + } + if (responseMessage.isFault()) { + Object body = responseMessage.getBody(); + + int index = -1; + if ( -1 < (index = body.getClass().getName().indexOf( "NotModifiedException")) ) { + if ( index > -1 ) + response.sendError( HttpServletResponse.SC_NOT_MODIFIED, body.toString().substring( index )); + else + response.sendError( HttpServletResponse.SC_NOT_MODIFIED ); + return; + } else if ( -1 < (index = body.getClass().getName().indexOf( "PreconditionFailedException")) ) { + if ( index > -1 ) + response.sendError( HttpServletResponse.SC_PRECONDITION_FAILED, body.toString().substring( index )); + else + response.sendError( HttpServletResponse.SC_PRECONDITION_FAILED ); + return; + } + + throw new ServletException((Throwable)responseMessage.getBody()); + } + + // Write the response from the service implementation to the response + // output stream + InputStream is = (InputStream)responseMessage.getBody(); + OutputStream os = response.getOutputStream(); + byte[] buffer = new byte[2048]; + for (;;) { + int n = is.read(buffer); + if (n <= 0) + break; + os.write(buffer, 0, n); + } + os.flush(); + os.close(); + } + + @Override + protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + // Get the request path + String path = URLDecoder.decode(request.getRequestURI().substring(request.getServletPath().length()), "UTF-8"); + if (path.length() ==0) { + // Redirect to a URL ending with / to make relative hrefs work + // relative to the served resource. + response.sendRedirect(request.getRequestURL().append('/').toString()); + return; + } + + // Invoke the get operation on the service implementation + Message requestMessage = messageFactory.createMessage(); + String id = path.substring(1); + + Message responseMessage = null; + HTTPCacheContext cacheContext = null; + try { + cacheContext = HTTPCacheContext.getCacheContextFromRequest(request); + } catch (ParseException e) { + } + + // Route message based on availability of cache info and cache methods + if (( cacheContext != null ) && (cacheContext.isEnabled()) && (conditionalDeleteInvoker != null )) { + requestMessage.setBody(new Object[] {id, cacheContext}); + responseMessage = conditionalDeleteInvoker.invoke(requestMessage); + } else { + requestMessage.setBody(new Object[] {id}); + responseMessage = deleteInvoker.invoke(requestMessage); + } + if (responseMessage.isFault()) { + Object body = responseMessage.getBody(); + + int index = -1; + if ( -1 < (index = body.getClass().getName().indexOf( "NotModifiedException")) ) { + if ( index > -1 ) + response.sendError( HttpServletResponse.SC_NOT_MODIFIED, body.toString().substring( index )); + else + response.sendError( HttpServletResponse.SC_NOT_MODIFIED ); + return; + } else if ( -1 < (index = body.getClass().getName().indexOf( "PreconditionFailedException")) ) { + if ( index > -1 ) + response.sendError( HttpServletResponse.SC_PRECONDITION_FAILED, body.toString().substring( index )); + else + response.sendError( HttpServletResponse.SC_PRECONDITION_FAILED ); + return; + } + + throw new ServletException((Throwable)responseMessage.getBody()); + } + + // Write the response from the service implementation to the response + // output stream + InputStream is = (InputStream)responseMessage.getBody(); + OutputStream os = response.getOutputStream(); + byte[] buffer = new byte[2048]; + for (;;) { + int n = is.read(buffer); + if (n <= 0) + break; + os.write(buffer, 0, n); + } + os.flush(); + os.close(); + } + + @Override + protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + // Get the request path + String path = URLDecoder.decode(request.getRequestURI().substring(request.getServletPath().length()), "UTF-8"); + if (path.length() ==0) { + // Redirect to a URL ending with / to make relative hrefs work + // relative to the served resource. + response.sendRedirect(request.getRequestURL().append('/').toString()); + return; + } + + // Invoke the get operation on the service implementation + Message requestMessage = messageFactory.createMessage(); + String id = path.substring(1); + + Message responseMessage = null; + HTTPCacheContext cacheContext = null; + try { + cacheContext = HTTPCacheContext.getCacheContextFromRequest(request); + } catch (ParseException e) { + } + + // Route message based on availability of cache info and cache methods + if (( cacheContext != null ) && (cacheContext.isEnabled()) && (conditionalPutInvoker != null )) { + requestMessage.setBody(new Object[] {id, cacheContext}); + responseMessage = conditionalPutInvoker.invoke(requestMessage); + } else { + requestMessage.setBody(new Object[] {id}); + responseMessage = putInvoker.invoke(requestMessage); + } + if (responseMessage.isFault()) { + Object body = responseMessage.getBody(); + + int index = -1; + if ( -1 < (index = body.getClass().getName().indexOf( "NotModifiedException")) ) { + if ( index > -1 ) + response.sendError( HttpServletResponse.SC_NOT_MODIFIED, body.toString().substring( index )); + else + response.sendError( HttpServletResponse.SC_NOT_MODIFIED ); + return; + } else if ( -1 < (index = body.getClass().getName().indexOf( "PreconditionFailedException")) ) { + if ( index > -1 ) + response.sendError( HttpServletResponse.SC_PRECONDITION_FAILED, body.toString().substring( index )); + else + response.sendError( HttpServletResponse.SC_PRECONDITION_FAILED ); + return; + } + + throw new ServletException((Throwable)responseMessage.getBody()); + } + + // Write the response from the service implementation to the response + // output stream + InputStream is = (InputStream)responseMessage.getBody(); + OutputStream os = response.getOutputStream(); + byte[] buffer = new byte[2048]; + for (;;) { + int n = is.read(buffer); + if (n <= 0) + break; + os.write(buffer, 0, n); + } + os.flush(); + os.close(); + } + + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + // Get the request path + String path = URLDecoder.decode(request.getRequestURI().substring(request.getServletPath().length()), "UTF-8"); + if (path.length() ==0) { + // Redirect to a URL ending with / to make relative hrefs work + // relative to the served resource. + response.sendRedirect(request.getRequestURL().append('/').toString()); + return; + } + + // Invoke the get operation on the service implementation + Message requestMessage = messageFactory.createMessage(); + // String id = path.substring(1); + + Message responseMessage = null; + HTTPCacheContext cacheContext = null; + try { + cacheContext = HTTPCacheContext.getCacheContextFromRequest(request); + } catch (ParseException e) { + } + + // Route message based on availability of cache info and cache methods + if (( cacheContext != null ) && (cacheContext.isEnabled()) && (conditionalPostInvoker != null )) { + requestMessage.setBody(new Object[] {cacheContext}); + responseMessage = conditionalPostInvoker.invoke(requestMessage); + } else { + requestMessage.setBody(new Object[] {}); + responseMessage = postInvoker.invoke(requestMessage); + } + if (responseMessage.isFault()) { + Object body = responseMessage.getBody(); + + int index = -1; + if ( -1 < (index = body.getClass().getName().indexOf( "NotModifiedException")) ) { + if ( index > -1 ) + response.sendError( HttpServletResponse.SC_NOT_MODIFIED, body.toString().substring( index )); + else + response.sendError( HttpServletResponse.SC_NOT_MODIFIED ); + return; + } else if ( -1 < (index = body.getClass().getName().indexOf( "PreconditionFailedException")) ) { + if ( index > -1 ) + response.sendError( HttpServletResponse.SC_PRECONDITION_FAILED, body.toString().substring( index )); + else + response.sendError( HttpServletResponse.SC_PRECONDITION_FAILED ); + return; + } + + throw new ServletException((Throwable)responseMessage.getBody()); + } + + + // Test if the ETag and LastModified are returned as a cache context. + Object body = responseMessage.getBody(); + if ( body.getClass() == HTTPCacheContext.class ) { + // Transfer to header if so. + HTTPCacheContext cc = (HTTPCacheContext)responseMessage.getBody(); + if (( cc != null ) && ( cc.isEnabled() )) { + String eTag = cc.getETag(); + if ( eTag != null ) + response.setHeader( "ETag", cc.getETag() ); + String lastModified = cc.getLastModified(); + if ( lastModified != null) + response.setHeader( "LastModified", cc.getLastModified() ); + } + } + } + + /** + * @return the getInvoker + */ + public Invoker getGetInvoker() { + return getInvoker; + } + + /** + * @param getInvoker the getInvoker to set + */ + public void setGetInvoker(Invoker getInvoker) { + this.getInvoker = getInvoker; + } + + /** + * @return the conditionalGetInvoker + */ + public Invoker getConditionalGetInvoker() { + return conditionalGetInvoker; + } + + /** + * @param conditionalGetInvoker the conditionalGetInvoker to set + */ + public void setConditionalGetInvoker(Invoker conditionalGetInvoker) { + this.conditionalGetInvoker = conditionalGetInvoker; + } + + /** + * @return the putInvoker + */ + public Invoker getPutInvoker() { + return putInvoker; + } + + /** + * @param putInvoker the putInvoker to set + */ + public void setPutInvoker(Invoker putInvoker) { + this.putInvoker = putInvoker; + } + + /** + * @return the conditionalPutInvoker + */ + public Invoker getConditionalPutInvoker() { + return conditionalPutInvoker; + } + + /** + * @param conditionalPutInvoker the conditionalPutInvoker to set + */ + public void setConditionalPutInvoker(Invoker conditionalPutInvoker) { + this.conditionalPutInvoker = conditionalPutInvoker; + } + + /** + * @return the postInvoker + */ + public Invoker getPostInvoker() { + return postInvoker; + } + + /** + * @param postInvoker the postInvoker to set + */ + public void setPostInvoker(Invoker postInvoker) { + this.postInvoker = postInvoker; + } + + /** + * @return the conditionalPostInvoker + */ + public Invoker getConditionalPostInvoker() { + return conditionalPostInvoker; + } + + /** + * @param conditionalPostInvoker the conditionalPostInvoker to set + */ + public void setConditionalPostInvoker(Invoker conditionalPostInvoker) { + this.conditionalPostInvoker = conditionalPostInvoker; + } + + /** + * @return the deleteInvoker + */ + public Invoker getDeleteInvoker() { + return deleteInvoker; + } + + /** + * @param deleteInvoker the deleteInvoker to set + */ + public void setDeleteInvoker(Invoker deleteInvoker) { + this.deleteInvoker = deleteInvoker; + } + + /** + * @return the conditionalDeleteInvoker + */ + public Invoker getConditionalDeleteInvoker() { + return conditionalDeleteInvoker; + } + + /** + * @param conditionalDeleteInvoker the conditionalDeleteInvoker to set + */ + public void setConditionalDeleteInvoker(Invoker conditionalDeleteInvoker) { + this.conditionalDeleteInvoker = conditionalDeleteInvoker; + } + + + /** + * Utility Methods related to Policy + */ + + + private boolean hasAuthenticationHeader(HttpServletRequest request, ServletResponse response) { + boolean result = false; + if(request.getHeader("Authorization") != null) { + result = true; + } + + return result; + } + + +} diff --git a/java/sca/contrib/modules/binding-http-runtime/src/main/java/org/apache/tuscany/sca/binding/http/provider/HTTPBindingProviderFactory.java b/java/sca/contrib/modules/binding-http-runtime/src/main/java/org/apache/tuscany/sca/binding/http/provider/HTTPBindingProviderFactory.java new file mode 100644 index 0000000000..eb496f2421 --- /dev/null +++ b/java/sca/contrib/modules/binding-http-runtime/src/main/java/org/apache/tuscany/sca/binding/http/provider/HTTPBindingProviderFactory.java @@ -0,0 +1,64 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.http.provider; + +import org.apache.tuscany.sca.binding.http.HTTPBinding; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.core.FactoryExtensionPoint; +import org.apache.tuscany.sca.host.http.ServletHost; +import org.apache.tuscany.sca.host.http.ServletHostExtensionPoint; +import org.apache.tuscany.sca.invocation.MessageFactory; +import org.apache.tuscany.sca.provider.BindingProviderFactory; +import org.apache.tuscany.sca.provider.ReferenceBindingProvider; +import org.apache.tuscany.sca.provider.ServiceBindingProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; + + +/** + * Factory for HTTP binding providers. + * + * @version $Rev$ $Date$ + */ +public class HTTPBindingProviderFactory implements BindingProviderFactory { + + private MessageFactory messageFactory; + private ServletHost servletHost; + + public HTTPBindingProviderFactory(ExtensionPointRegistry extensionPoints) { + ServletHostExtensionPoint servletHosts = extensionPoints.getExtensionPoint(ServletHostExtensionPoint.class); + this.servletHost = servletHosts.getServletHosts().get(0); + FactoryExtensionPoint modelFactories = extensionPoints.getExtensionPoint(FactoryExtensionPoint.class); + messageFactory = modelFactories.getFactory(MessageFactory.class); + } + + public ReferenceBindingProvider createReferenceBindingProvider(RuntimeComponent component, RuntimeComponentReference reference, HTTPBinding binding) { + return null; + } + + public ServiceBindingProvider createServiceBindingProvider(RuntimeComponent component, RuntimeComponentService service, HTTPBinding binding) { + return new HTTPServiceBindingProvider(component, service, binding, messageFactory, servletHost); + } + + public Class getModelType() { + return HTTPBinding.class; + } +} diff --git a/java/sca/contrib/modules/binding-http-runtime/src/main/java/org/apache/tuscany/sca/binding/http/provider/HTTPGetListenerServlet.java b/java/sca/contrib/modules/binding-http-runtime/src/main/java/org/apache/tuscany/sca/binding/http/provider/HTTPGetListenerServlet.java new file mode 100644 index 0000000000..e20d420d49 --- /dev/null +++ b/java/sca/contrib/modules/binding-http-runtime/src/main/java/org/apache/tuscany/sca/binding/http/provider/HTTPGetListenerServlet.java @@ -0,0 +1,94 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.http.provider; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URLDecoder; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.invocation.MessageFactory; + +/** + * Servlet responsible for dispatching HTTP GET requests to the + * target component implementation. + * + * @version $Rev$ $Date$ + */ +public class HTTPGetListenerServlet extends HttpServlet { + private static final long serialVersionUID = 2865466417329430610L; + + private MessageFactory messageFactory; + private Invoker getInvoker; + + /** + * Constructs a new HTTPServiceListenerServlet. + */ + public HTTPGetListenerServlet(Invoker getInvoker, MessageFactory messageFactory) { + this.getInvoker = getInvoker; + this.messageFactory = messageFactory; + } + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + // Get the request path + String path = URLDecoder.decode(request.getRequestURI().substring(request.getServletPath().length()), "UTF-8"); + if (path.length() ==0) { + + // Redirect to a URL ending with / to make relative hrefs work + // relative to the served resource. + response.sendRedirect(request.getRequestURL().append('/').toString()); + return; + } + + // Invoke the get operation on the service implementation + Message requestMessage = messageFactory.createMessage(); + String id = path.substring(1); + requestMessage.setBody(new Object[] {id}); + Message responseMessage = getInvoker.invoke(requestMessage); + if (responseMessage.isFault()) { + throw new ServletException((Throwable)responseMessage.getBody()); + } + + // Write the response from the service implementation to the response + // output stream + InputStream is = (InputStream)responseMessage.getBody(); + OutputStream os = response.getOutputStream(); + byte[] buffer = new byte[2048]; + for (;;) { + int n = is.read(buffer); + if (n <= 0) + break; + os.write(buffer, 0, n); + } + os.flush(); + os.close(); + + } + +} diff --git a/java/sca/contrib/modules/binding-http-runtime/src/main/java/org/apache/tuscany/sca/binding/http/provider/HTTPServiceBindingProvider.java b/java/sca/contrib/modules/binding-http-runtime/src/main/java/org/apache/tuscany/sca/binding/http/provider/HTTPServiceBindingProvider.java new file mode 100644 index 0000000000..8f91ff4343 --- /dev/null +++ b/java/sca/contrib/modules/binding-http-runtime/src/main/java/org/apache/tuscany/sca/binding/http/provider/HTTPServiceBindingProvider.java @@ -0,0 +1,137 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.http.provider; + +import javax.servlet.Servlet; + +import org.apache.tuscany.sca.binding.http.HTTPBinding; +import org.apache.tuscany.sca.host.http.ServletHost; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.InvocationChain; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.MessageFactory; +import org.apache.tuscany.sca.provider.ServiceBindingProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; +import org.apache.tuscany.sca.runtime.RuntimeWire; + +/** + * Implementation of an HTTP binding provider. + * + * @version $Rev$ $Date$ + */ +public class HTTPServiceBindingProvider implements ServiceBindingProvider { + private RuntimeComponentService service; + private HTTPBinding binding; + private MessageFactory messageFactory; + + private ServletHost servletHost; + private String servletMapping; + private HTTPBindingListenerServlet bindingListenerServlet; + + public HTTPServiceBindingProvider(RuntimeComponent component, + RuntimeComponentService service, + HTTPBinding binding, + MessageFactory messageFactory, + ServletHost servletHost) { + this.service = service; + this.binding = binding; + this.messageFactory = messageFactory; + this.servletHost = servletHost; + } + + public void start() { + // Get the invokers for the supported operations + RuntimeComponentService componentService = (RuntimeComponentService) service; + RuntimeWire wire = componentService.getRuntimeWire(binding); + Servlet servlet = null; + bindingListenerServlet = new HTTPBindingListenerServlet(binding, messageFactory ); + for (InvocationChain invocationChain : wire.getInvocationChains()) { + Operation operation = invocationChain.getTargetOperation(); + String operationName = operation.getName(); + if (operationName.equals("get")) { + Invoker getInvoker = invocationChain.getHeadInvoker(); + bindingListenerServlet.setGetInvoker(getInvoker); + servlet = bindingListenerServlet; + } else if (operationName.equals("conditionalGet")) { + Invoker conditionalGetInvoker = invocationChain.getHeadInvoker(); + bindingListenerServlet.setConditionalGetInvoker(conditionalGetInvoker); + servlet = bindingListenerServlet; + } else if (operationName.equals("delete")) { + Invoker deleteInvoker = invocationChain.getHeadInvoker(); + bindingListenerServlet.setDeleteInvoker(deleteInvoker); + servlet = bindingListenerServlet; + } else if (operationName.equals("conditionalDelete")) { + Invoker conditionalDeleteInvoker = invocationChain.getHeadInvoker(); + bindingListenerServlet.setConditionalDeleteInvoker(conditionalDeleteInvoker); + servlet = bindingListenerServlet; + } else if (operationName.equals("put")) { + Invoker putInvoker = invocationChain.getHeadInvoker(); + bindingListenerServlet.setPutInvoker(putInvoker); + servlet = bindingListenerServlet; + } else if (operationName.equals("conditionalPut")) { + Invoker conditionalPutInvoker = invocationChain.getHeadInvoker(); + bindingListenerServlet.setConditionalPutInvoker(conditionalPutInvoker); + servlet = bindingListenerServlet; + } else if (operationName.equals("post")) { + Invoker postInvoker = invocationChain.getHeadInvoker(); + bindingListenerServlet.setPostInvoker(postInvoker); + servlet = bindingListenerServlet; + } else if (operationName.equals("conditionalPost")) { + Invoker conditionalPostInvoker = invocationChain.getHeadInvoker(); + bindingListenerServlet.setConditionalPostInvoker(conditionalPostInvoker); + servlet = bindingListenerServlet; + } else if (operationName.equals("service")) { + Invoker serviceInvoker = invocationChain.getHeadInvoker(); + servlet = new HTTPServiceListenerServlet(binding, serviceInvoker, messageFactory); + break; + } + } + if (servlet == null) { + throw new IllegalStateException("No get or service method found on the service"); + } + + // Create our HTTP service listener Servlet and register it with the + // Servlet host + servletMapping = binding.getURI(); + if (!servletMapping.endsWith("/")) { + servletMapping += "/"; + } + if (!servletMapping.endsWith("*")) { + servletMapping += "*"; + } + servletHost.addServletMapping(servletMapping, servlet); + } + + public void stop() { + // Unregister the Servlet from the Servlet host + servletHost.removeServletMapping(servletMapping); + } + + public InterfaceContract getBindingInterfaceContract() { + return null; + } + + public boolean supportsOneWayInvocation() { + return false; + } + +} diff --git a/java/sca/contrib/modules/binding-http-runtime/src/main/java/org/apache/tuscany/sca/binding/http/provider/HTTPServiceListenerServlet.java b/java/sca/contrib/modules/binding-http-runtime/src/main/java/org/apache/tuscany/sca/binding/http/provider/HTTPServiceListenerServlet.java new file mode 100644 index 0000000000..493255655d --- /dev/null +++ b/java/sca/contrib/modules/binding-http-runtime/src/main/java/org/apache/tuscany/sca/binding/http/provider/HTTPServiceListenerServlet.java @@ -0,0 +1,136 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.http.provider; + +import java.io.IOException; +import java.util.List; + +import javax.servlet.Servlet; +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.invocation.MessageFactory; +import org.apache.tuscany.sca.policy.Intent; +import org.apache.tuscany.sca.policy.PolicySet; +import org.apache.tuscany.sca.policy.PolicySetAttachPoint; +import org.apache.tuscany.sca.policy.authentication.basic.BasicAuthenticationPolicy; + +/** + * Servlet responsible for dispatching HTTP service requests to the + * target component implementation. + * + * @version $Rev$ $Date$ + */ +public class HTTPServiceListenerServlet implements Servlet { + private static final QName AUTEHTICATION_INTENT = new QName("http://www.osoa.org/xmlns/sca/1.0","authentication"); + + transient private Binding binding; + transient private ServletConfig config; + transient private MessageFactory messageFactory; + transient private Invoker serviceInvoker; + + transient private boolean requiresAuthentication = false; + transient private BasicAuthenticationPolicy basicAuthenticationPolicy = null; + + /** + * Constructs a new HTTPServiceListenerServlet. + */ + public HTTPServiceListenerServlet(Binding binding, Invoker serviceInvoker, MessageFactory messageFactory) { + this.binding = binding; + this.serviceInvoker = serviceInvoker; + this.messageFactory = messageFactory; + + // find out which policies are active + if (binding instanceof PolicySetAttachPoint) { + List intents = ((PolicySetAttachPoint)binding).getRequiredIntents(); + for(Intent intent : intents) { + if(intent.getName().equals(AUTEHTICATION_INTENT)) { + requiresAuthentication = true; + } + } + + + List policySets = ((PolicySetAttachPoint)binding).getApplicablePolicySets(); + for (PolicySet ps : policySets) { + for (Object p : ps.getPolicies()) { + if (BasicAuthenticationPolicy.class.isInstance(p)) { + basicAuthenticationPolicy = (BasicAuthenticationPolicy)p; + } else { + // etc. check for other types of policy being present + } + } + } + } + } + + public ServletConfig getServletConfig() { + return config; + } + + public String getServletInfo() { + return ""; + } + + public void init(ServletConfig config) throws ServletException { + this.config = config; + } + + public void destroy() { + + } + + public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { + + if(requiresAuthentication) { + if(! hasAuthenticationHeader((HttpServletRequest)request, (HttpServletResponse)response)) { + ((HttpServletResponse)response).sendError(HttpServletResponse.SC_UNAUTHORIZED); + } + } + + // Dispatch the service interaction to the service invoker + Message requestMessage = messageFactory.createMessage(); + requestMessage.setBody(new Object[]{request, response}); + Message responseMessage = serviceInvoker.invoke(requestMessage); + if (responseMessage.isFault()) { + // Turn a fault into an exception + //throw new ServletException((Throwable)responseMessage.getBody()); + Throwable e = (Throwable)responseMessage.getBody(); + ((HttpServletResponse)response).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); + } + } + + + private boolean hasAuthenticationHeader(HttpServletRequest request, ServletResponse response) { + boolean result = false; + if(request.getHeader("Authorization") != null) { + result = true; + } + + return result; + } +} diff --git a/java/sca/contrib/modules/binding-http-runtime/src/main/java/org/apache/tuscany/sca/binding/http/util/HTTPHeadersParser.java b/java/sca/contrib/modules/binding-http-runtime/src/main/java/org/apache/tuscany/sca/binding/http/util/HTTPHeadersParser.java new file mode 100644 index 0000000000..1fe4600e31 --- /dev/null +++ b/java/sca/contrib/modules/binding-http-runtime/src/main/java/org/apache/tuscany/sca/binding/http/util/HTTPHeadersParser.java @@ -0,0 +1,50 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.http.util; + +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; + +import org.apache.tuscany.sca.binding.http.HTTPHeader; + +public class HTTPHeadersParser { + + /** + * Parse http request headers to a map + * + * @param request + * @return + */ + public static List getHeaders(HttpServletRequest request) { + List headers = new ArrayList(); + + Enumeration headerNames = request.getHeaderNames(); + while (headerNames.hasMoreElements()) { + String headerName = (String) headerNames.nextElement(); + Object headerValue = request.getHeader(headerName); + HTTPHeader header = new HTTPHeader(headerName, headerValue); + headers.add(header); + } + return headers; + } +} diff --git a/java/sca/contrib/modules/binding-http-runtime/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.BindingProviderFactory b/java/sca/contrib/modules/binding-http-runtime/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.BindingProviderFactory new file mode 100644 index 0000000000..0fa8d44c08 --- /dev/null +++ b/java/sca/contrib/modules/binding-http-runtime/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.BindingProviderFactory @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for the binding extension +org.apache.tuscany.sca.binding.http.provider.HTTPBindingProviderFactory;model=org.apache.tuscany.sca.binding.http.HTTPBinding diff --git a/java/sca/contrib/modules/binding-http-runtime/src/test/java/org/apache/tuscany/sca/binding/http/HTTPBindingCacheTestCaseFIXME.java b/java/sca/contrib/modules/binding-http-runtime/src/test/java/org/apache/tuscany/sca/binding/http/HTTPBindingCacheTestCaseFIXME.java new file mode 100644 index 0000000000..d4aac125e5 --- /dev/null +++ b/java/sca/contrib/modules/binding-http-runtime/src/test/java/org/apache/tuscany/sca/binding/http/HTTPBindingCacheTestCaseFIXME.java @@ -0,0 +1,853 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.http; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.net.Socket; +import java.text.MessageFormat; +import java.text.SimpleDateFormat; +import java.util.Date; + +import junit.framework.TestCase; + +/** + * HTTP binding unit tests. + * + * @version $Rev$ $Date$ + */ +public class HTTPBindingCacheTestCaseFIXME extends TestCase { + // RFC 822 date time + protected static final SimpleDateFormat dateFormat = new SimpleDateFormat( + "EEE, dd MMM yyyy HH:mm:ss Z"); + + // Request with no predicates in header. + private static final String REQUEST1 = "{0} /httpbinding/{1} HTTP/1.0\n" + + "Host: localhost\n" + "Content-Type: text/xml\n" + + "Connection: close\n" + "Content-Length: {2}" + "\n\n{3}"; + + // Request with predicates in header + private static final String REQUEST2 = "{0} /httpbinding/{1} HTTP/1.0\n" + + "Host: localhost\n" + "Content-Type: text/xml\n" + "{2}: {3}\n" // predicate (If-Match, If-None-Match, If-Modified-Since, If-NotModified-Since): value (date or ETag) + + "Connection: close\n" + "Content-Length: {4}" + "\n\n{5}"; + + private static final int HTTP_PORT = 8085; + +// private SCADomain scaDomain; +// +// @Override +// protected void setUp() throws Exception { +// scaDomain = SCADomain.newInstance("testCache.composite"); +// } +// +// @Override +// protected void tearDown() throws Exception { +// scaDomain.close(); +// } + + /** + * Test invoking a POJO get method implementation using the HTTP binding. + * @throws Exception + */ + public void testGet() throws Exception { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + int index = 0; + String content = ""; + String request = MessageFormat.format(REQUEST1, "GET", index, content + .getBytes().length, content); + os.write(request.getBytes()); + os.flush(); + + String document = read(client); + assertTrue(document.indexOf("

item=" + index) != -1); + } + + /** + * Test invoking a conditional method implementation using the HTTP binding. + * @throws Exception + */ + public void testConditionalGetIfModifiedNegative() throws Exception { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + int index = 0; + String content = ""; + String request = MessageFormat.format(REQUEST2, "GET", index, + "If-Modified-Since", dateFormat.format(new Date(0)), content + .getBytes().length, content); + os.write(request.getBytes()); + os.flush(); + + String document = read(client); + // Should return item + assertTrue(document.indexOf("

item=" + index) != -1); + // Should return code 304 Not Modified. + // assertTrue(document.indexOf("HTTP/1.1 304") != -1); + } + + /** + * Test invoking a conditional method implementation using the HTTP binding. + * @throws Exception + */ + public void testConditionalGetIfModifiedPositive() throws Exception { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + int index = 1; + String content = ""; + String request = MessageFormat.format(REQUEST2, "GET", index, + "If-Modified-Since", dateFormat.format(new Date(0)), content + .getBytes().length, content); + os.write(request.getBytes()); + os.flush(); + + String document = read(client); + // Should return item + // assertTrue(document.indexOf("

item=" + index) != -1); + // Should return code 304 Not Modified. + assertTrue(document.indexOf("HTTP/1.1 304") != -1); + } + + /** + * Test invoking a conditional method implementation using the HTTP binding. + * @throws Exception + */ + public void testConditionalGetIfUnmodifiedNegative() throws Exception { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + int index = 1; + String content = ""; + String request = MessageFormat.format(REQUEST2, "GET", index, + "If-Unmodified-Since", dateFormat.format(new Date()), content + .getBytes().length, content); + os.write(request.getBytes()); + os.flush(); + + String document = read(client); + // Should return item + assertTrue(document.indexOf("

item=" + index) != -1); + // Should return code 304 Not Modified. + // assertTrue(document.indexOf("HTTP/1.1 304") != -1); + } + + /** + * Test invoking a conditional method implementation using the HTTP binding. + * @throws Exception + */ + public void testConditionalGetIfUnmodifiedPositive() throws Exception { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + int index = 0; + String content = ""; + String request = MessageFormat.format(REQUEST2, "GET", index, + "If-Unmodified-Since", dateFormat.format(new Date(0)), content + .getBytes().length, content); + os.write(request.getBytes()); + os.flush(); + + String document = read(client); + // Should return item + // assertTrue(document.indexOf("

item=" + index) != -1); + // Should return code 412 PreconditionFailed. + assertTrue(document.indexOf("HTTP/1.1 412") != -1); + } + + /** + * Test invoking a conditional method implementation using the HTTP binding. + * @throws Exception + */ + public void testConditionalGetIfMatchNegative() throws Exception { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + int index = 1; + String content = ""; + String request = MessageFormat.format(REQUEST2, "GET", index, + "If-Match", "eTagXXX", content.getBytes().length, content); + os.write(request.getBytes()); + os.flush(); + + String document = read(client); + // Should return item + // assertTrue(document.indexOf("

item=" + index) != -1); + // Should return code 412 precondition failed. + assertTrue(document.indexOf("HTTP/1.1 412") != -1); + } + + /** + * Test invoking a conditional method implementation using the HTTP binding. + * @throws Exception + */ + public void testConditionalGetIfMatchPositive() throws Exception { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + int index = 0; + String content = ""; + String request = MessageFormat.format(REQUEST2, "GET", index, + "If-Match", "eTagXXX", content.getBytes().length, content); + os.write(request.getBytes()); + os.flush(); + + String document = read(client); + // Should return item + assertTrue(document.indexOf("

item=" + index) != -1); + // Should return code 412 PreconditionFailed. + // assertTrue(document.indexOf("HTTP/1.1 412") != -1); + } + + /** + * Test invoking a conditional method implementation using the HTTP binding. + * @throws Exception + */ + public void testConditionalGetIfNoneMatchNegative() throws Exception { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + int index = 1; + String content = ""; + String request = MessageFormat.format(REQUEST2, "GET", index, + "If-None-Match", "eTagXXX", content.getBytes().length, content); + os.write(request.getBytes()); + os.flush(); + + String document = read(client); + // Should return item + assertTrue(document.indexOf("

item=" + index) != -1); + // Should return code 412 precondition failed. + // assertTrue(document.indexOf("HTTP/1.1 412") != -1); + } + + /** + * Test invoking a conditional method implementation using the HTTP binding. + * @throws Exception + */ + public void testConditionalGetIfNoneMatchPositive() throws Exception { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + int index = 0; + String content = ""; + String request = MessageFormat.format(REQUEST2, "GET", index, + "If-None-Match", "eTagXXX", content.getBytes().length, content); + os.write(request.getBytes()); + os.flush(); + + String document = read(client); + // Should return item + // assertTrue(document.indexOf("

item=" + index) != -1); + // Should return code 412 PreconditionFailed. + assertTrue(document.indexOf("HTTP/1.1 412") != -1); + } + + /** + * Test invoking a POJO get method implementation using the HTTP binding. + * @throws Exception + */ + public void testDelete() throws Exception { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + int index = 0; + String content = ""; + String request = MessageFormat.format(REQUEST1, "DELETE", index, + content.getBytes().length, content); + os.write(request.getBytes()); + os.flush(); + + String document = read(client); + assertTrue(document.indexOf("deleted item=" + index) != -1); + } + + /** + * Test invoking a conditional method implementation using the HTTP binding. + * @throws Exception + */ + public void testConditionalDeleteIfModifiedNegative() throws Exception { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + int index = 0; + String content = ""; + String request = MessageFormat.format(REQUEST2, "DELETE", index, + "If-Modified-Since", dateFormat.format(new Date(0)), content + .getBytes().length, content); + os.write(request.getBytes()); + os.flush(); + + String document = read(client); + // Should return item + assertTrue(document.indexOf("deleted item=" + index) != -1); + // Should return code 304 Not Modified. + // assertTrue(document.indexOf("HTTP/1.1 304") != -1); + } + + /** + * Test invoking a conditional method implementation using the HTTP binding. + * @throws Exception + */ + public void testConditionalDeleteIfModifiedPositive() throws Exception { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + int index = 1; + String content = ""; + String request = MessageFormat.format(REQUEST2, "DELETE", index, + "If-Modified-Since", dateFormat.format(new Date(0)), content + .getBytes().length, content); + os.write(request.getBytes()); + os.flush(); + + String document = read(client); + // Should return item + // assertTrue(document.indexOf("deleted item=" + index) != -1); + // Should return code 304 Not Modified. + assertTrue(document.indexOf("HTTP/1.1 304") != -1); + } + + /** + * Test invoking a conditional method implementation using the HTTP binding. + * @throws Exception + */ + public void testConditionalDeleteIfUnmodifiedNegative() throws Exception { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + int index = 1; + String content = ""; + String request = MessageFormat.format(REQUEST2, "DELETE", index, + "If-Unmodified-Since", dateFormat.format(new Date()), content + .getBytes().length, content); + os.write(request.getBytes()); + os.flush(); + + String document = read(client); + // Should return item + assertTrue(document.indexOf("deleted item=" + index) != -1); + // Should return code 304 Not Modified. + // assertTrue(document.indexOf("HTTP/1.1 304") != -1); + } + + /** + * Test invoking a conditional method implementation using the HTTP binding. + * @throws Exception + */ + public void testConditionalDeleteIfUnmodifiedPositive() throws Exception { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + int index = 0; + String content = ""; + String request = MessageFormat.format(REQUEST2, "DELETE", index, + "If-Unmodified-Since", dateFormat.format(new Date(0)), content + .getBytes().length, content); + os.write(request.getBytes()); + os.flush(); + + String document = read(client); + // Should return item + // assertTrue(document.indexOf("deleted item=" + index) != -1); + // Should return code 412 PreconditionFailed. + assertTrue(document.indexOf("HTTP/1.1 412") != -1); + } + + /** + * Test invoking a conditional method implementation using the HTTP binding. + * @throws Exception + */ + public void testConditionalDeleteIfMatchNegative() throws Exception { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + int index = 1; + String content = ""; + String request = MessageFormat.format(REQUEST2, "DELETE", index, + "If-Match", "eTagXXX", content.getBytes().length, content); + os.write(request.getBytes()); + os.flush(); + + String document = read(client); + // Should return item + // assertTrue(document.indexOf("deleted item=" + index) != -1); + // Should return code 412 precondition failed. + assertTrue(document.indexOf("HTTP/1.1 412") != -1); + } + + /** + * Test invoking a conditional method implementation using the HTTP binding. + * @throws Exception + */ + public void testConditionalDeleteIfMatchPositive() throws Exception { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + int index = 0; + String content = ""; + String request = MessageFormat.format(REQUEST2, "DELETE", index, + "If-Match", "eTagXXX", content.getBytes().length, content); + os.write(request.getBytes()); + os.flush(); + + String document = read(client); + // Should return item + assertTrue(document.indexOf("deleted item=" + index) != -1); + // Should return code 412 PreconditionFailed. + // assertTrue(document.indexOf("HTTP/1.1 412") != -1); + } + + /** + * Test invoking a conditional method implementation using the HTTP binding. + * @throws Exception + */ + public void testConditionalDeleteIfNoneMatchNegative() throws Exception { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + int index = 1; + String content = ""; + String request = MessageFormat.format(REQUEST2, "DELETE", index, + "If-None-Match", "eTagXXX", content.getBytes().length, content); + os.write(request.getBytes()); + os.flush(); + + String document = read(client); + // Should return item + assertTrue(document.indexOf("deleted item=" + index) != -1); + // Should return code 412 precondition failed. + // assertTrue(document.indexOf("HTTP/1.1 412") != -1); + } + + /** + * Test invoking a conditional method implementation using the HTTP binding. + * @throws Exception + */ + public void testConditionalDeleteIfNoneMatchPositive() throws Exception { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + int index = 0; + String content = ""; + String request = MessageFormat.format(REQUEST2, "DELETE", index, + "If-None-Match", "eTagXXX", content.getBytes().length, content); + os.write(request.getBytes()); + os.flush(); + + String document = read(client); + // Should return item + // assertTrue(document.indexOf("deleted item=" + index) != -1); + // Should return code 412 PreconditionFailed. + assertTrue(document.indexOf("HTTP/1.1 412") != -1); + } + + /** + * Test invoking a POJO get method implementation using the HTTP binding. + * @throws Exception + */ + public void testPost() throws Exception { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + int index = 0; + String content = ""; + String request = MessageFormat.format(REQUEST1, "POST", index, content + .getBytes().length, content); + os.write(request.getBytes()); + os.flush(); + + String document = read(client); + assertTrue(document.indexOf("HTTP/1.1 200 OK") != -1); + } + + /** + * Test invoking a conditional method implementation using the HTTP binding. + * @throws Exception + */ + public void testConditionalPostIfModifiedNegative() throws Exception { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + int index = 0; + String content = ""; + String request = MessageFormat.format(REQUEST2, "POST", index, + "If-Modified-Since", dateFormat.format(new Date()), content + .getBytes().length, content); + os.write(request.getBytes()); + os.flush(); + + String document = read(client); + // Should return code 200 OK + // assertTrue(document.indexOf("posted item=" + index) != -1); + assertTrue(document.indexOf("HTTP/1.1 200 OK") != -1); + // Should return code 304 Not Modified. + // assertTrue(document.indexOf("HTTP/1.1 304") != -1); + } + + /** + * Test invoking a conditional method implementation using the HTTP binding. + * @throws Exception + */ + public void testConditionalPostIfModifiedPositive() throws Exception { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + int index = 1; + String content = ""; + String request = MessageFormat.format(REQUEST2, "POST", index, + "If-Modified-Since", dateFormat.format(new Date(0)), content + .getBytes().length, content); + os.write(request.getBytes()); + os.flush(); + + String document = read(client); + // Should return item + // assertTrue(document.indexOf("posted item=" + index) != -1); + // Should return code 304 Not Modified. + assertTrue(document.indexOf("HTTP/1.1 304") != -1); + } + + /** + * Test invoking a conditional method implementation using the HTTP binding. + * @throws Exception + */ + public void testConditionalPostIfUnmodifiedNegative() throws Exception { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + int index = 1; + String content = ""; + String request = MessageFormat.format(REQUEST2, "POST", index, + "If-Unmodified-Since", dateFormat.format(new Date()), content + .getBytes().length, content); + os.write(request.getBytes()); + os.flush(); + + String document = read(client); + // Should return code 200 OK + assertTrue(document.indexOf("HTTP/1.1 200 OK") != -1); + // Should return code 304 Not Modified. + // assertTrue(document.indexOf("HTTP/1.1 304") != -1); + } + + /** + * Test invoking a conditional method implementation using the HTTP binding. + * @throws Exception + */ + public void testConditionalPostIfUnmodifiedPositive() throws Exception { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + int index = 0; + String content = ""; + String request = MessageFormat.format(REQUEST2, "POST", index, + "If-Unmodified-Since", dateFormat.format(new Date(0)), content + .getBytes().length, content); + os.write(request.getBytes()); + os.flush(); + + String document = read(client); + // Should return item + // assertTrue(document.indexOf("posted item=" + index) != -1); + // Should return code 412 PreconditionFailed. + assertTrue(document.indexOf("HTTP/1.1 412") != -1); + } + + /** + * Test invoking a conditional method implementation using the HTTP binding. + * @throws Exception + */ + public void testConditionalPostIfMatchNegative() throws Exception { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + int index = 1; + String content = ""; + String request = MessageFormat.format(REQUEST2, "POST", index, + "If-Match", "eTagMatch", content.getBytes().length, content); + os.write(request.getBytes()); + os.flush(); + + String document = read(client); + // Should return code 200 OK. + assertTrue(document.indexOf("HTTP/1.1 200 OK") != -1); + // Should return code 412 precondition failed. + // assertTrue(document.indexOf("HTTP/1.1 412") != -1); + } + + /** + * Test invoking a conditional method implementation using the HTTP binding. + * @throws Exception + */ + public void testConditionalPostIfMatchPositive() throws Exception { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + int index = 0; + String content = ""; + String request = MessageFormat + .format(REQUEST2, "POST", index, "If-Match", "eTagNoneMatch", + content.getBytes().length, content); + os.write(request.getBytes()); + os.flush(); + + String document = read(client); + // Should return item + // assertTrue(document.indexOf("posted item=" + index) != -1); + // Should return code 412 PreconditionFailed. + assertTrue(document.indexOf("HTTP/1.1 412") != -1); + } + + /** + * Test invoking a conditional method implementation using the HTTP binding. + * @throws Exception + */ + public void testConditionalPostIfNoneMatchNegative() throws Exception { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + int index = 1; + String content = ""; + String request = MessageFormat.format(REQUEST2, "POST", index, + "If-None-Match", "eTagNoneMatch", content.getBytes().length, + content); + os.write(request.getBytes()); + os.flush(); + + String document = read(client); + // Should return code 200 OK + assertTrue(document.indexOf("HTTP/1.1 200 OK") != -1); + // Should return code 412 precondition failed. + // assertTrue(document.indexOf("HTTP/1.1 412") != -1); + } + + /** + * Test invoking a conditional method implementation using the HTTP binding. + * @throws Exception + */ + public void testConditionalPostIfNoneMatchPositive() throws Exception { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + int index = 0; + String content = ""; + String request = MessageFormat.format(REQUEST2, "POST", index, + "If-None-Match", "eTagMatch", content.getBytes().length, + content); + os.write(request.getBytes()); + os.flush(); + + String document = read(client); + // Should return item + // assertTrue(document.indexOf("posted item=" + index) != -1); + // Should return code 412 PreconditionFailed. + assertTrue(document.indexOf("HTTP/1.1 412") != -1); + } + + /** + * Test invoking a POJO get method implementation using the HTTP binding. + * @throws Exception + */ + public void testPut() throws Exception { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + int index = 0; + String content = ""; + String request = MessageFormat.format(REQUEST1, "PUT", index, content + .getBytes().length, content); + os.write(request.getBytes()); + os.flush(); + + String document = read(client); + assertTrue(document.indexOf("updated item=" + index) != -1); + } + + /** + * Test invoking a conditional method implementation using the HTTP binding. + * @throws Exception + */ + public void testConditionalPutIfModifiedNegative() throws Exception { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + int index = 0; + String content = ""; + String request = MessageFormat.format(REQUEST2, "PUT", index, + "If-Modified-Since", dateFormat.format(new Date(0)), content + .getBytes().length, content); + os.write(request.getBytes()); + os.flush(); + + String document = read(client); + // Should return item + assertTrue(document.indexOf("updated item=" + index) != -1); + // Should return code 304 Not Modified. + // assertTrue(document.indexOf("HTTP/1.1 304") != -1); + } + + /** + * Test invoking a conditional method implementation using the HTTP binding. + * @throws Exception + */ + public void testConditionalPutIfModifiedPositive() throws Exception { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + int index = 1; + String content = ""; + String request = MessageFormat.format(REQUEST2, "PUT", index, + "If-Modified-Since", dateFormat.format(new Date(0)), content + .getBytes().length, content); + os.write(request.getBytes()); + os.flush(); + + String document = read(client); + // Should return item + // assertTrue(document.indexOf("updated item=" + index) != -1); + // Should return code 304 Not Modified. + assertTrue(document.indexOf("HTTP/1.1 304") != -1); + } + + /** + * Test invoking a conditional method implementation using the HTTP binding. + * @throws Exception + */ + public void testConditionalPutIfUnmodifiedNegative() throws Exception { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + int index = 1; + String content = ""; + String request = MessageFormat.format(REQUEST2, "PUT", index, + "If-Unmodified-Since", dateFormat.format(new Date()), content + .getBytes().length, content); + os.write(request.getBytes()); + os.flush(); + + String document = read(client); + // Should return item + assertTrue(document.indexOf("updated item=" + index) != -1); + // Should return code 304 Not Modified. + // assertTrue(document.indexOf("HTTP/1.1 304") != -1); + } + + /** + * Test invoking a conditional method implementation using the HTTP binding. + * @throws Exception + */ + public void testConditionalPutIfUnmodifiedPositive() throws Exception { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + int index = 0; + String content = ""; + String request = MessageFormat.format(REQUEST2, "PUT", index, + "If-Unmodified-Since", dateFormat.format(new Date(0)), content + .getBytes().length, content); + os.write(request.getBytes()); + os.flush(); + + String document = read(client); + // Should return item + // assertTrue(document.indexOf("updated item=" + index) != -1); + // Should return code 412 PreconditionFailed. + assertTrue(document.indexOf("HTTP/1.1 412") != -1); + } + + /** + * Test invoking a conditional method implementation using the HTTP binding. + * @throws Exception + */ + public void testConditionalPutIfMatchNegative() throws Exception { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + int index = 1; + String content = ""; + String request = MessageFormat.format(REQUEST2, "PUT", index, + "If-Match", "eTagXXX", content.getBytes().length, content); + os.write(request.getBytes()); + os.flush(); + + String document = read(client); + // Should return item + // assertTrue(document.indexOf("updated item=" + index) != -1); + // Should return code 412 precondition failed. + assertTrue(document.indexOf("HTTP/1.1 412") != -1); + } + + /** + * Test invoking a conditional method implementation using the HTTP binding. + * @throws Exception + */ + public void testConditionalPutIfMatchPositive() throws Exception { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + int index = 0; + String content = ""; + String request = MessageFormat.format(REQUEST2, "PUT", index, + "If-Match", "eTagXXX", content.getBytes().length, content); + os.write(request.getBytes()); + os.flush(); + + String document = read(client); + // Should return item + assertTrue(document.indexOf("updated item=" + index) != -1); + // Should return code 412 PreconditionFailed. + // assertTrue(document.indexOf("HTTP/1.1 412") != -1); + } + + /** + * Test invoking a conditional method implementation using the HTTP binding. + * @throws Exception + */ + public void testConditionalPutIfNoneMatchNegative() throws Exception { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + int index = 1; + String content = ""; + String request = MessageFormat.format(REQUEST2, "PUT", index, + "If-None-Match", "eTagXXX", content.getBytes().length, content); + os.write(request.getBytes()); + os.flush(); + + String document = read(client); + // Should return item + assertTrue(document.indexOf("updated item=" + index) != -1); + // Should return code 412 precondition failed. + // assertTrue(document.indexOf("HTTP/1.1 412") != -1); + } + + /** + * Test invoking a conditional method implementation using the HTTP binding. + * @throws Exception + */ + public void testConditionalPutIfNoneMatchPositive() throws Exception { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + int index = 0; + String content = ""; + String request = MessageFormat.format(REQUEST2, "PUT", index, + "If-None-Match", "eTagXXX", content.getBytes().length, content); + os.write(request.getBytes()); + os.flush(); + + String document = read(client); + // Should return item + // assertTrue(document.indexOf("updated item=" + index) != -1); + // Should return code 412 PreconditionFailed. + assertTrue(document.indexOf("HTTP/1.1 412") != -1); + } + + /** + * Read response stream from the given socket. + * @param socket + * @return + * @throws IOException + */ + private static String read(Socket socket) throws IOException { + BufferedReader reader = null; + try { + reader = new BufferedReader(new InputStreamReader(socket + .getInputStream())); + StringBuffer sb = new StringBuffer(); + String str; + while ((str = reader.readLine()) != null) { + sb.append(str); + } + return sb.toString(); + } finally { + if (reader != null) { + reader.close(); + } + } + } +} diff --git a/java/sca/contrib/modules/binding-http-runtime/src/test/java/org/apache/tuscany/sca/binding/http/HTTPBindingTestCase.java b/java/sca/contrib/modules/binding-http-runtime/src/test/java/org/apache/tuscany/sca/binding/http/HTTPBindingTestCase.java new file mode 100644 index 0000000000..c6a5d64ce7 --- /dev/null +++ b/java/sca/contrib/modules/binding-http-runtime/src/test/java/org/apache/tuscany/sca/binding/http/HTTPBindingTestCase.java @@ -0,0 +1,153 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.http; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.net.Socket; +import java.text.MessageFormat; + +import org.apache.tuscany.sca.node.Contribution; +import org.apache.tuscany.sca.node.ContributionLocationHelper; +import org.apache.tuscany.sca.node.Node; +import org.apache.tuscany.sca.node.NodeFactory; + +import junit.framework.TestCase; + +/** + * HTTP binding unit tests. + * + * @version $Rev$ $Date$ + */ +public class HTTPBindingTestCase extends TestCase { + + private static final String REQUEST1_HEADER = + "GET /httpservice/test HTTP/1.0\n" + "Host: localhost\n" + + "Content-Type: text/xml\n" + + "Connection: close\n" + + "Content-Length: "; + private static final String REQUEST1_CONTENT = ""; + private static final String REQUEST1 = + REQUEST1_HEADER + REQUEST1_CONTENT.getBytes().length + "\n\n" + REQUEST1_CONTENT; + + private static final String REQUEST2_HEADER = + "GET /webcontent/test.html HTTP/1.0\n" + "Host: localhost\n" + + "Content-Type: text/xml\n" + + "Connection: close\n" + + "Content-Length: "; + private static final String REQUEST2_CONTENT = ""; + private static final String REQUEST2 = + REQUEST2_HEADER + REQUEST2_CONTENT.getBytes().length + "\n\n" + REQUEST2_CONTENT; + + private static final String REQUEST3_HEADER = + "GET /httpget/{0} HTTP/1.0\n" + "Host: localhost\n" + + "Content-Type: text/xml\n" + + "Connection: close\n" + + "Content-Length: "; + private static final String REQUEST3_CONTENT = ""; + private static final String REQUEST3 = + REQUEST3_HEADER + REQUEST3_CONTENT.getBytes().length + "\n\n" + REQUEST3_CONTENT; + + private static final int HTTP_PORT = 8085; + + private Node node; + + @Override + protected void setUp() throws Exception { + String contribution = ContributionLocationHelper.getContributionLocation(HTTPBindingCacheTestCaseFIXME.class); + node = NodeFactory.newInstance().createNode("test.composite", new Contribution("test", contribution)); + node.start(); + } + + @Override + protected void tearDown() throws Exception { + node.stop(); + node.destroy(); + } + + /** + * Test invoking a POJO service implementation using the HTTP binding. + * @throws Exception + */ + public void testServiceImplementation() throws Exception { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + os.write(REQUEST1.getBytes()); + os.flush(); + + String document = read(client); + assertTrue(document.indexOf("

hey") != -1); + } + + /** + * Test invoking a POJO get method implementation using the HTTP binding. + * @throws Exception + */ + public void testGetImplementation() throws Exception { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + int index = 0; + String request = MessageFormat.format( REQUEST3, index ); + os.write( request.getBytes()); + os.flush(); + + String document = read(client); + assertTrue(document.indexOf("

item=" + index) != -1); + } + + /** + * Test getting a static resource provided using the HTTP binding. + * @throws Exception + */ + public void testStaticResourceImplementation() throws Exception { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + os.write(REQUEST2.getBytes()); + os.flush(); + + String document = read(client); + assertTrue(document.indexOf("

hello") != -1); + } + + /** + * Read response stream from the given socket. + * @param socket + * @return + * @throws IOException + */ + private static String read(Socket socket) throws IOException { + BufferedReader reader = null; + try { + reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); + StringBuffer sb = new StringBuffer(); + String str; + while ((str = reader.readLine()) != null) { + sb.append(str); + } + return sb.toString(); + } finally { + if (reader != null) { + reader.close(); + } + } + } + +} diff --git a/java/sca/contrib/modules/binding-http-runtime/src/test/java/org/apache/tuscany/sca/binding/http/NotModifiedException.java b/java/sca/contrib/modules/binding-http-runtime/src/test/java/org/apache/tuscany/sca/binding/http/NotModifiedException.java new file mode 100644 index 0000000000..1d6efea2a1 --- /dev/null +++ b/java/sca/contrib/modules/binding-http-runtime/src/test/java/org/apache/tuscany/sca/binding/http/NotModifiedException.java @@ -0,0 +1,44 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.http; + +/** + * Indicates that a resource was not modified. + * + * @version $Rev$ $Date$ + */ +public class NotModifiedException extends Exception { + private static final long serialVersionUID = -5046027674128627383L; + + public NotModifiedException() { + } + + public NotModifiedException(String message) { + super(message); + } + + public NotModifiedException(Throwable cause) { + super(cause); + } + + public NotModifiedException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/java/sca/contrib/modules/binding-http-runtime/src/test/java/org/apache/tuscany/sca/binding/http/PreconditionFailedException.java b/java/sca/contrib/modules/binding-http-runtime/src/test/java/org/apache/tuscany/sca/binding/http/PreconditionFailedException.java new file mode 100644 index 0000000000..5728899ebe --- /dev/null +++ b/java/sca/contrib/modules/binding-http-runtime/src/test/java/org/apache/tuscany/sca/binding/http/PreconditionFailedException.java @@ -0,0 +1,44 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.http; + +/** + * Indicates that a resource was not modified. + * + * @version $Rev$ $Date$ + */ +public class PreconditionFailedException extends Exception { + private static final long serialVersionUID = -5046027674128627383L; + + public PreconditionFailedException() { + } + + public PreconditionFailedException(String message) { + super(message); + } + + public PreconditionFailedException(Throwable cause) { + super(cause); + } + + public PreconditionFailedException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/java/sca/contrib/modules/binding-http-runtime/src/test/java/org/apache/tuscany/sca/binding/http/TestBindingCacheImpl.java b/java/sca/contrib/modules/binding-http-runtime/src/test/java/org/apache/tuscany/sca/binding/http/TestBindingCacheImpl.java new file mode 100644 index 0000000000..f2456f3175 --- /dev/null +++ b/java/sca/contrib/modules/binding-http-runtime/src/test/java/org/apache/tuscany/sca/binding/http/TestBindingCacheImpl.java @@ -0,0 +1,241 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.http; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.Date; + +/** + * Test service implementation that implements a various conditional HTTP + * methods. For testing, the id==0 items are very old (Date(0)), not modified, + * and always match ETags and the id==1 items are always brand new (Date()), + * modified, and never match ETags. Using these ids one can test the + * LastModified and ETag headers of the requests. + * + * @version $Rev$ $Date$ + */ +public class TestBindingCacheImpl { + + /** + * Implements the HTTP get method of the collection implementation. + * @param id + * @return + */ + public InputStream get(String id) { + return new ByteArrayInputStream( + ("

item=" + id + "").getBytes()); + } + + /** + * Implements the HTTP conditional get method of the collection implementation. + * @param id + * @return + */ + public InputStream conditionalGet(String id, HTTPCacheContext cacheContext) + throws NotModifiedException, PreconditionFailedException { + + if (cacheContext != null) { + if (cacheContext.ifModifiedSince) { + if ((id.equals("1")) + && (0 > cacheContext.lastModifiedDate + .compareTo(new Date()))) + throw new NotModifiedException("item 1 was modified on " + + new Date()); + } + if (cacheContext.ifUnmodifiedSince) { + if ((id.equals("0")) + && (0 > cacheContext.lastModifiedDate + .compareTo(new Date()))) + throw new PreconditionFailedException( + "item 0 was modified on " + new Date(0)); + } + if (cacheContext.ifMatch) { + if (id.equals("1")) + throw new PreconditionFailedException( + "item 1 eTag does not match " + + cacheContext.getETag()); + } + if (cacheContext.ifNoneMatch) { + if (id.equals("0")) + throw new PreconditionFailedException( + "item 0 eTag matches " + cacheContext.getETag()); + } + } + return new ByteArrayInputStream( + ("

item=" + id + "").getBytes()); + } + + /** + * Implements the HTTP delete method of the collection implementation. + * @param id + * @return + */ + public InputStream delete(String id) { + return new ByteArrayInputStream( + ("

deleted item=" + id + "") + .getBytes()); + } + + /** + * Implements the HTTP conditional delete method of the collection implementation. + * @param id + * @return + */ + public InputStream conditionalDelete(String id, HTTPCacheContext cacheContext) + throws NotModifiedException, PreconditionFailedException { + + if (cacheContext != null) { + if (cacheContext.ifModifiedSince) { + if ((id.equals("1")) + && (0 > cacheContext.lastModifiedDate + .compareTo(new Date()))) + throw new NotModifiedException("item 1 was modified on " + + new Date()); + } + if (cacheContext.ifUnmodifiedSince) { + if ((id.equals("0")) + && (0 > cacheContext.lastModifiedDate + .compareTo(new Date()))) + throw new PreconditionFailedException( + "item 0 was modified on " + new Date(0)); + } + if (cacheContext.ifMatch) { + if (id.equals("1")) + throw new PreconditionFailedException( + "item 1 eTag does not match " + + cacheContext.getETag()); + } + if (cacheContext.ifNoneMatch) { + if (id.equals("0")) + throw new PreconditionFailedException( + "item 0 eTag matches " + cacheContext.getETag()); + } + } + return new ByteArrayInputStream( + ("

deleted item=" + id + "") + .getBytes()); + } + + /** + * Implements the HTTP post method of the collection implementation. + * @param id + * @return + */ + public InputStream post() { + int id = (new java.util.Random()).nextInt(Integer.MAX_VALUE); + return new ByteArrayInputStream( + ("

posted item=" + id + "") + .getBytes()); + } + + /** + * Implements the HTTP conditional post method of the collection implementation. + * @param id + * @return + */ + public HTTPCacheContext conditionalPost(HTTPCacheContext cacheContext) + throws NotModifiedException, PreconditionFailedException { + String id = "" + (new java.util.Random()).nextInt(Integer.MAX_VALUE); + + if (cacheContext != null) { + if (cacheContext.ifModifiedSince) { + if (0 >= cacheContext.lastModifiedDate.compareTo(new Date(0))) + throw new NotModifiedException("item was modified on " + + new Date()); + } + if (cacheContext.ifUnmodifiedSince) { + if ((0 >= cacheContext.lastModifiedDate.compareTo(new Date(0)))) + throw new PreconditionFailedException( + "item was modified on " + new Date(0)); + } + if (cacheContext.ifMatch) { + if (cacheContext.getETag().equalsIgnoreCase("ETagNoneMatch")) + throw new PreconditionFailedException( + "item eTag does not match " + + cacheContext.getETag()); + } + if (cacheContext.ifNoneMatch) { + if (cacheContext.getETag().equalsIgnoreCase("ETagMatch")) + throw new PreconditionFailedException("item eTag matches " + + cacheContext.getETag()); + } + } + + // Return the ETag and LastModfied fields by serialize to a byte array + HTTPCacheContext returnContext = new HTTPCacheContext(); + returnContext.setETag( "ETag" + (new java.util.Random()).nextInt(Integer.MAX_VALUE) ); + returnContext.setLastModified( new Date() ); + return returnContext; + } + + /** + * Implements the HTTP update/put method of the collection implementation. + * @param id + * @return + */ + public InputStream put(String id) { + return new ByteArrayInputStream( + ("

updated item=" + id + "") + .getBytes()); + } + + /** + * Implements the HTTP conditional update/put method of the collection implementation. + * @param id + * @return + */ + public InputStream conditionalPut(String id, HTTPCacheContext cacheContext) + throws NotModifiedException, PreconditionFailedException { + + if (cacheContext != null) { + if (cacheContext.ifModifiedSince) { + if ((id.equals("1")) + && (0 > cacheContext.lastModifiedDate + .compareTo(new Date()))) + throw new NotModifiedException("item 1 was modified on " + + new Date()); + } + if (cacheContext.ifUnmodifiedSince) { + if ((id.equals("0")) + && (0 > cacheContext.lastModifiedDate + .compareTo(new Date()))) + throw new PreconditionFailedException( + "item 0 was modified on " + new Date(0)); + } + if (cacheContext.ifMatch) { + if (id.equals("1")) + throw new PreconditionFailedException( + "item 1 eTag does not match " + + cacheContext.getETag()); + } + if (cacheContext.ifNoneMatch) { + if (id.equals("0")) + throw new PreconditionFailedException( + "item 0 eTag matches " + cacheContext.getETag()); + } + } + + return new ByteArrayInputStream( + ("

updated item=" + id + "") + .getBytes()); + } + +} diff --git a/java/sca/contrib/modules/binding-http-runtime/src/test/java/org/apache/tuscany/sca/binding/http/TestGetImpl.java b/java/sca/contrib/modules/binding-http-runtime/src/test/java/org/apache/tuscany/sca/binding/http/TestGetImpl.java new file mode 100644 index 0000000000..333bacbab3 --- /dev/null +++ b/java/sca/contrib/modules/binding-http-runtime/src/test/java/org/apache/tuscany/sca/binding/http/TestGetImpl.java @@ -0,0 +1,37 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.http; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; + +/** + * Test service implementation that implements a get method. + * + * @version $Rev$ $Date$ + */ +public class TestGetImpl { + + public InputStream get(String id) { + return new ByteArrayInputStream(("

item=" + id + "").getBytes()); + + } + +} diff --git a/java/sca/contrib/modules/binding-http-runtime/src/test/java/org/apache/tuscany/sca/binding/http/TestServiceCacheImpl.java b/java/sca/contrib/modules/binding-http-runtime/src/test/java/org/apache/tuscany/sca/binding/http/TestServiceCacheImpl.java new file mode 100644 index 0000000000..9dbd6724b0 --- /dev/null +++ b/java/sca/contrib/modules/binding-http-runtime/src/test/java/org/apache/tuscany/sca/binding/http/TestServiceCacheImpl.java @@ -0,0 +1,61 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.http; + +import java.io.IOException; + +import javax.servlet.Servlet; +import javax.servlet.ServletConfig; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; + +import org.oasisopen.sca.annotation.Service; + +/** + * Test service implementation. + * + * @version $Rev$ $Date$ + */ + +@Service(Servlet.class) +public class TestServiceCacheImpl implements Servlet { + + public void init(ServletConfig config) throws ServletException { + } + + public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { + //HttpServletResponse httpResponse = (HttpServletResponse)response; + response.getOutputStream().print("

hey"); + } + + public void destroy() { + } + + public ServletConfig getServletConfig() { + return null; + } + + public String getServletInfo() { + return null; + } + +} diff --git a/java/sca/contrib/modules/binding-http-runtime/src/test/java/org/apache/tuscany/sca/binding/http/TestServiceImpl.java b/java/sca/contrib/modules/binding-http-runtime/src/test/java/org/apache/tuscany/sca/binding/http/TestServiceImpl.java new file mode 100644 index 0000000000..90cca27655 --- /dev/null +++ b/java/sca/contrib/modules/binding-http-runtime/src/test/java/org/apache/tuscany/sca/binding/http/TestServiceImpl.java @@ -0,0 +1,61 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.http; + +import java.io.IOException; + +import javax.servlet.Servlet; +import javax.servlet.ServletConfig; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; + +import org.oasisopen.sca.annotation.Service; + +/** + * Test service implementation. + * + * @version $Rev$ $Date$ + */ + +@Service(Servlet.class) +public class TestServiceImpl implements Servlet { + + public void init(ServletConfig config) throws ServletException { + } + + public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { + //HttpServletResponse httpResponse = (HttpServletResponse)response; + response.getOutputStream().print("

hey"); + } + + public void destroy() { + } + + public ServletConfig getServletConfig() { + return null; + } + + public String getServletInfo() { + return null; + } + +} diff --git a/java/sca/contrib/modules/binding-http-runtime/src/test/resources/content/test.html b/java/sca/contrib/modules/binding-http-runtime/src/test/resources/content/test.html new file mode 100644 index 0000000000..f4b79d7f01 --- /dev/null +++ b/java/sca/contrib/modules/binding-http-runtime/src/test/resources/content/test.html @@ -0,0 +1,21 @@ + + +

hello + \ No newline at end of file diff --git a/java/sca/contrib/modules/binding-http-runtime/src/test/resources/test.composite b/java/sca/contrib/modules/binding-http-runtime/src/test/resources/test.composite new file mode 100644 index 0000000000..62c4af4e22 --- /dev/null +++ b/java/sca/contrib/modules/binding-http-runtime/src/test/resources/test.composite @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/java/sca/contrib/modules/binding-http-runtime/src/test/resources/testCache.composite b/java/sca/contrib/modules/binding-http-runtime/src/test/resources/testCache.composite new file mode 100644 index 0000000000..d805402c4f --- /dev/null +++ b/java/sca/contrib/modules/binding-http-runtime/src/test/resources/testCache.composite @@ -0,0 +1,33 @@ + + + + + + + + + + + + diff --git a/java/sca/contrib/modules/binding-http/LICENSE b/java/sca/contrib/modules/binding-http/LICENSE new file mode 100644 index 0000000000..8aa906c321 --- /dev/null +++ b/java/sca/contrib/modules/binding-http/LICENSE @@ -0,0 +1,205 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + + diff --git a/java/sca/contrib/modules/binding-http/META-INF/MANIFEST.MF b/java/sca/contrib/modules/binding-http/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..a68b0c1e8d --- /dev/null +++ b/java/sca/contrib/modules/binding-http/META-INF/MANIFEST.MF @@ -0,0 +1,22 @@ +Manifest-Version: 1.0 +Export-Package: org.apache.tuscany.sca.binding.http;uses:="org.apache. + tuscany.sca.assembly,javax.servlet.http";version="2.0.0" +Private-Package: org.apache.tuscany.sca.binding.http.impl;version="1.4 + " +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA HTTP Binding Model +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397256703 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA HTTP Binding Model +Import-Package: javax.servlet.http, + org.apache.tuscany.sca.assembly;version="2.0.0", + org.apache.tuscany.sca.assembly.xml;version="2.0.0", + org.apache.tuscany.sca.binding.http;version="2.0.0", + org.apache.tuscany.sca.policy;version="2.0.0" +Bundle-SymbolicName: org.apache.tuscany.sca.binding.http +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/binding-http/NOTICE b/java/sca/contrib/modules/binding-http/NOTICE new file mode 100644 index 0000000000..25bb89c9b2 --- /dev/null +++ b/java/sca/contrib/modules/binding-http/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/binding-http/pom.xml b/java/sca/contrib/modules/binding-http/pom.xml new file mode 100644 index 0000000000..a841f26df4 --- /dev/null +++ b/java/sca/contrib/modules/binding-http/pom.xml @@ -0,0 +1,72 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + + tuscany-binding-http + Apache Tuscany SCA HTTP Binding Model + + + + org.apache.tuscany.sca + tuscany-assembly + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-interface-java-xml + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-policy + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-data-api + 2.0-SNAPSHOT + + + + javax.servlet + servlet-api + 2.5 + + + + junit + junit + 4.5 + test + + + + + diff --git a/java/sca/contrib/modules/binding-http/src/main/java/org/apache/tuscany/sca/binding/http/HTTPBinding.java b/java/sca/contrib/modules/binding-http/src/main/java/org/apache/tuscany/sca/binding/http/HTTPBinding.java new file mode 100644 index 0000000000..6192b92dfe --- /dev/null +++ b/java/sca/contrib/modules/binding-http/src/main/java/org/apache/tuscany/sca/binding/http/HTTPBinding.java @@ -0,0 +1,31 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.http; + +import org.apache.tuscany.sca.assembly.Binding; + + +/** + * HTTP binding model. + * + * @version $Rev$ $Date$ +*/ +public interface HTTPBinding extends Binding { +} diff --git a/java/sca/contrib/modules/binding-http/src/main/java/org/apache/tuscany/sca/binding/http/HTTPBindingFactory.java b/java/sca/contrib/modules/binding-http/src/main/java/org/apache/tuscany/sca/binding/http/HTTPBindingFactory.java new file mode 100644 index 0000000000..e66896c68e --- /dev/null +++ b/java/sca/contrib/modules/binding-http/src/main/java/org/apache/tuscany/sca/binding/http/HTTPBindingFactory.java @@ -0,0 +1,35 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.http; + +/** + * Factory for the HTTP binding model. + * + * @version $Rev$ $Date$ + */ +public interface HTTPBindingFactory { + + /** + * Creates a new HTTP binding. + * @return a new HTTP binding + */ + HTTPBinding createHTTPBinding(); + +} diff --git a/java/sca/contrib/modules/binding-http/src/main/java/org/apache/tuscany/sca/binding/http/HTTPCacheContext.java b/java/sca/contrib/modules/binding-http/src/main/java/org/apache/tuscany/sca/binding/http/HTTPCacheContext.java new file mode 100644 index 0000000000..023423f0eb --- /dev/null +++ b/java/sca/contrib/modules/binding-http/src/main/java/org/apache/tuscany/sca/binding/http/HTTPCacheContext.java @@ -0,0 +1,257 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.http; + +import java.text.SimpleDateFormat; +import java.util.Date; + +import javax.servlet.http.HttpServletRequest; + +/** + * A class to store cache settings for Atom and HTTP requests and responses. + * + * Predicates are statements that work in conjunction with + * ETags and LastModified dates to determine if a precondition + * or postcondition is satisfied. + * See HTTP specification for how predicates wrk: + * http://tools.ietf.org/html/rfc2616 + * Example predicates in HTTP include If-Match, If-None-Match, + * If-Modified-Since, If-Unmodified-Since, If-Range. + + */ +public class HTTPCacheContext { + public static final SimpleDateFormat RFC822DateFormat = new SimpleDateFormat( "EEE, dd MMM yyyy HH:mm:ss Z" ); // RFC 822 date time + + public boolean enabled; + public String eTag; + public String lastModified; + public Date lastModifiedDate; + public boolean ifModifiedSince; + public boolean ifUnmodifiedSince; + public boolean ifMatch; + public boolean ifNoneMatch; + public boolean ifRange; + + /** + * An ETag is a unique ID for an item. It changes when + * a field in the item or the update date changes. + * See HTTP specification for how ETags work: + * http://tools.ietf.org/html/rfc2616 + * @return the eTag + */ + public String getETag() { + return eTag; + } + /** + * @param tag the eTag to set + */ + public void setETag(String tag) { + eTag = tag; + enabled = true; + } + /** + * The LastModified date is the time the item was last + * changed. See HTTP specification for how ETags work: + * http://tools.ietf.org/html/rfc2616 + * @return the lastModified + */ + public String getLastModified() { + return lastModified; + } + /** + * The LastModified date is the time the item was last + * changed. See HTTP specification for how ETags work: + * http://tools.ietf.org/html/rfc2616 + * @return the lastModified + */ + public Date getLastModifiedAsDate() { + return lastModifiedDate; + } + /** + * @param lastModified the lastModified to set + */ + public void setLastModified(String lastModified) throws java.text.ParseException { + this.lastModified = lastModified; + // Catch date formatting on input to help debugging. + lastModifiedDate = RFC822DateFormat.parse( lastModified ); + enabled = true; + } + + /** + * @param lastModified the lastModified to set + */ + public void setLastModified(Date updated) { + this.lastModified = RFC822DateFormat.format( updated ); + lastModifiedDate = updated; + enabled = true; + } + + /** + * @return the ifModifedSince + */ + public boolean isIfModifiedSince() { + return ifModifiedSince; + } + /** + * @param ifModifedSince the ifModifedSince to set + */ + public void setIfModifiedSince(boolean ifModifiedSince) { + this.ifModifiedSince = ifModifiedSince; + if ( ifModifiedSince ) + enabled = true; + } + /** + * @return the ifUnModifiedSince + */ + public boolean isIfUnmodifiedSince() { + return ifUnmodifiedSince; + } + /** + * @param ifUnModifiedSince the ifUnModifiedSince to set + */ + public void setIfUnmodifiedSince(boolean ifUnmodifiedSince) { + this.ifUnmodifiedSince = ifUnmodifiedSince; + if ( ifUnmodifiedSince ) + enabled = true; + } + /** + * @return the ifMatch + */ + public boolean isIfMatch() { + return ifMatch; + } + /** + * @param ifMatch the ifMatch to set + */ + public void setIfMatch(boolean ifMatch) { + this.ifMatch = ifMatch; + if ( ifMatch ) + enabled = true; + } + /** + * @return the ifNoneMatch + */ + public boolean isIfNoneMatch() { + return ifNoneMatch; + } + /** + * @param ifNoneMatch the ifNoneMatch to set + */ + public void setIfNoneMatch(boolean ifNoneMatch) { + this.ifNoneMatch = ifNoneMatch; + if ( ifNoneMatch ) + enabled = true; + } + /** + * @return the ifRange + */ + public boolean isIfRange() { + return ifRange; + } + /** + * @param ifRange the ifRange to set + */ + public void setIfRange(boolean ifRange) { + this.ifRange = ifRange; + if ( ifRange ) + enabled = true; + } + + public String toString() { + final String PREDPREFIX = ", predicates="; + StringBuffer sb = new StringBuffer(PREDPREFIX); + if ( ifMatch || ifNoneMatch || ifModifiedSince || ifUnmodifiedSince || ifRange ) { + if ( ifMatch ) { + if ( sb.length() > PREDPREFIX.length() ) sb.append( ", "); + sb.append("If-Match"); + } + if ( ifNoneMatch ) { + if ( sb.length() > PREDPREFIX.length() ) sb.append( ", "); + sb.append("If-None-Match"); + } + if ( ifModifiedSince ) { + if ( sb.length() > PREDPREFIX.length() ) sb.append( ", "); + sb.append("If-Modified-Since"); + } + if ( ifUnmodifiedSince ) { + if ( sb.length() > PREDPREFIX.length() ) sb.append( ", "); + sb.append("If-UnModified-Since"); + } + if ( ifRange ) { + if ( sb.length() > PREDPREFIX.length() ) sb.append( ", "); + sb.append("If-Range"); + } + } else { + sb.append("null"); + } + + return "eTag=" + eTag + ", lastModified=" + lastModified + + sb.toString(); + } + + /** + * Gets the cache context information (ETag, LastModified, predicates) from the Http request. + * @param request + * @return + */ + public static HTTPCacheContext getCacheContextFromRequest( HttpServletRequest request ) throws java.text.ParseException { + HTTPCacheContext context = new HTTPCacheContext(); + + String eTag = request.getHeader( "If-Match" ); + if ( eTag != null ) { + context.setETag( eTag ); + context.setIfMatch( true ); + } + eTag = request.getHeader( "If-None-Match" ); + if ( eTag != null ) { + context.setETag( eTag ); + context.setIfNoneMatch( true ); + } + String lastModifiedString = request.getHeader( "If-Modified-Since" ); + if ( lastModifiedString != null ) { + context.setLastModified( lastModifiedString ); + context.setIfModifiedSince( true ); + } + lastModifiedString = request.getHeader( "If-Unmodified-Since" ); + if ( lastModifiedString != null ) { + context.setLastModified( lastModifiedString ); + context.setIfUnmodifiedSince( true ); + } + lastModifiedString = request.getHeader( "If-Range" ); + if ( lastModifiedString != null ) { + context.setLastModified( lastModifiedString ); + context.setIfRange( true ); + } + return context; + } + /** + * Enabled is true whenever ETag, LastModified, or predicate is set. + * @return the enabled + */ + public boolean isEnabled() { + return enabled; + } + /** + * @param enabled the enabled to set + */ + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } +} diff --git a/java/sca/contrib/modules/binding-http/src/main/java/org/apache/tuscany/sca/binding/http/HTTPHeader.java b/java/sca/contrib/modules/binding-http/src/main/java/org/apache/tuscany/sca/binding/http/HTTPHeader.java new file mode 100644 index 0000000000..69e44cf35c --- /dev/null +++ b/java/sca/contrib/modules/binding-http/src/main/java/org/apache/tuscany/sca/binding/http/HTTPHeader.java @@ -0,0 +1,51 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.http; + +public class HTTPHeader { + private String name; + private Object value; + + public HTTPHeader() { + + } + + public HTTPHeader(String name, Object value) { + this.name = name; + this.value = value; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Object getValue() { + return value; + } + + public void setValue(Object value) { + this.value = value; + } + +} diff --git a/java/sca/contrib/modules/binding-http/src/main/java/org/apache/tuscany/sca/binding/http/impl/HTTPBindingFactoryImpl.java b/java/sca/contrib/modules/binding-http/src/main/java/org/apache/tuscany/sca/binding/http/impl/HTTPBindingFactoryImpl.java new file mode 100644 index 0000000000..678cd1a426 --- /dev/null +++ b/java/sca/contrib/modules/binding-http/src/main/java/org/apache/tuscany/sca/binding/http/impl/HTTPBindingFactoryImpl.java @@ -0,0 +1,36 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.http.impl; + +import org.apache.tuscany.sca.binding.http.HTTPBinding; +import org.apache.tuscany.sca.binding.http.HTTPBindingFactory; + +/** + * Factory for the HTTP binding model. + * + * @version $Rev$ $Date$ + */ +public class HTTPBindingFactoryImpl implements HTTPBindingFactory { + + public HTTPBinding createHTTPBinding() { + return new HTTPBindingImpl(); + } + +} diff --git a/java/sca/contrib/modules/binding-http/src/main/java/org/apache/tuscany/sca/binding/http/impl/HTTPBindingImpl.java b/java/sca/contrib/modules/binding-http/src/main/java/org/apache/tuscany/sca/binding/http/impl/HTTPBindingImpl.java new file mode 100644 index 0000000000..6d4bf92adc --- /dev/null +++ b/java/sca/contrib/modules/binding-http/src/main/java/org/apache/tuscany/sca/binding/http/impl/HTTPBindingImpl.java @@ -0,0 +1,108 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.http.impl; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.tuscany.sca.binding.http.HTTPBinding; +import org.apache.tuscany.sca.policy.Intent; +import org.apache.tuscany.sca.policy.IntentAttachPointType; +import org.apache.tuscany.sca.policy.PolicySet; +import org.apache.tuscany.sca.policy.PolicySetAttachPoint; + + +/** + * Implementation of the HTTP binding model. + * + * @version $Rev$ $Date$ + */ +class HTTPBindingImpl implements HTTPBinding, PolicySetAttachPoint { + + private String name; + private String uri; + + private List requiredIntents = new ArrayList(); + private List policySets = new ArrayList(); + private IntentAttachPointType intentAttachPointType; + private List applicablePolicySets = new ArrayList(); + + + public String getName() { + return name; + } + + public String getURI() { + return uri; + } + + public void setName(String name) { + this.name = name; + } + + public void setURI(String uri) { + this.uri = uri; + } + + + public boolean isUnresolved() { + return false; + } + + public void setUnresolved(boolean unresolved) { + // The sample binding is always resolved + } + + //Policy related getters/setters + + public List getPolicySets() { + return policySets; + } + + public List getRequiredIntents() { + return requiredIntents; + } + + public IntentAttachPointType getType() { + return intentAttachPointType; + } + + public void setType(IntentAttachPointType intentAttachPointType) { + this.intentAttachPointType = intentAttachPointType; + } + + public void setPolicySets(List policySets) { + this.policySets = policySets; + } + + public void setRequiredIntents(List intents) { + this.requiredIntents = intents; + } + + public List getApplicablePolicySets() { + return applicablePolicySets; + } + + @Override + public Object clone() throws CloneNotSupportedException { + return super.clone(); + } + +} diff --git a/java/sca/contrib/modules/binding-http/src/main/resources/META-INF/services/org.apache.tuscany.sca.binding.http.HTTPBindingFactory b/java/sca/contrib/modules/binding-http/src/main/resources/META-INF/services/org.apache.tuscany.sca.binding.http.HTTPBindingFactory new file mode 100644 index 0000000000..44da6b166c --- /dev/null +++ b/java/sca/contrib/modules/binding-http/src/main/resources/META-INF/services/org.apache.tuscany.sca.binding.http.HTTPBindingFactory @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for model factory +org.apache.tuscany.sca.binding.http.impl.HTTPBindingFactoryImpl diff --git a/java/sca/contrib/modules/binding-http/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor b/java/sca/contrib/modules/binding-http/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor new file mode 100644 index 0000000000..cc07784cb7 --- /dev/null +++ b/java/sca/contrib/modules/binding-http/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for the artifact processor extension +org.apache.tuscany.sca.assembly.xml.DefaultBeanModelProcessor;qname=http://tuscany.apache.org/xmlns/sca/1.0#binding.http,model=org.apache.tuscany.sca.binding.http.HTTPBinding,factory=org.apache.tuscany.sca.binding.http.HTTPBindingFactory diff --git a/java/sca/contrib/modules/binding-jms-policy/LICENSE b/java/sca/contrib/modules/binding-jms-policy/LICENSE new file mode 100644 index 0000000000..8aa906c321 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-policy/LICENSE @@ -0,0 +1,205 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + + diff --git a/java/sca/contrib/modules/binding-jms-policy/NOTICE b/java/sca/contrib/modules/binding-jms-policy/NOTICE new file mode 100644 index 0000000000..25bb89c9b2 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-policy/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/binding-jms-policy/pom.xml b/java/sca/contrib/modules/binding-jms-policy/pom.xml new file mode 100644 index 0000000000..56d79557b7 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-policy/pom.xml @@ -0,0 +1,94 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 1.4-SNAPSHOT + ../pom.xml + + tuscany-binding-jms-policy + Apache Tuscany Policy Model for JMS binding + + + + org.apache.tuscany.sca + tuscany-contribution + 1.4-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-assembly-xml + 1.4-SNAPSHOT + + + + org.apache.geronimo.specs + geronimo-jms_1.1_spec + 1.1 + provided + + + org.apache.geronimo.specs + geronimo-jms_1.1_spec + + + + + + org.apache.tuscany.sca + tuscany-binding-jms + 1.4-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-policy-reliability + 1.4-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-policy-security + 1.4-SNAPSHOT + + + + + + + org.apache.felix + maven-bundle-plugin + + + + ${tuscany.version} + org.apache.tuscany.sca.binding.jms.policy + ${pom.name} + org.apache.tuscany.sca.binding.jms.policy* + + + + + + + diff --git a/java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/JMSBindingDefinitionsProvider.java b/java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/JMSBindingDefinitionsProvider.java new file mode 100644 index 0000000000..de54545f7e --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/JMSBindingDefinitionsProvider.java @@ -0,0 +1,66 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.jms.policy; + +import java.net.URI; +import java.net.URL; +import java.security.AccessController; +import java.security.PrivilegedExceptionAction; + +import org.apache.tuscany.sca.contribution.processor.URLArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.URLArtifactProcessorExtensionPoint; +import org.apache.tuscany.sca.contribution.service.ContributionReadException; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.definitions.SCADefinitions; +import org.apache.tuscany.sca.provider.SCADefinitionsProvider; +import org.apache.tuscany.sca.provider.SCADefinitionsProviderException; + +/** + * Provider for Policy Intents and PolicySet definitions for the JMS binding + * + * @version $Rev$ $Date$ + */ +public class JMSBindingDefinitionsProvider implements SCADefinitionsProvider { + private String definitionsFile = "org/apache/tuscany/sca/binding/jms/policy/definitions.xml"; + URLArtifactProcessor urlArtifactProcessor = null; + + public JMSBindingDefinitionsProvider(ExtensionPointRegistry registry) { + URLArtifactProcessorExtensionPoint documentProcessors = registry.getExtensionPoint(URLArtifactProcessorExtensionPoint.class); + urlArtifactProcessor = (URLArtifactProcessor)documentProcessors.getProcessor(SCADefinitions.class); + } + + public SCADefinitions getSCADefinition() throws SCADefinitionsProviderException { + final URL definitionsFileUrl = getClass().getClassLoader().getResource(definitionsFile); + SCADefinitions scaDefn = null; + try { + final URI uri = new URI(definitionsFile); + // Allow bindings to read properties. Requires PropertyPermission read in security policy. + scaDefn = AccessController.doPrivileged(new PrivilegedExceptionAction() { + public SCADefinitions run() throws ContributionReadException { + return (SCADefinitions)urlArtifactProcessor.read(null, uri, definitionsFileUrl); + } + }); + } catch (Exception e) { + throw new SCADefinitionsProviderException(e); + } + return scaDefn; + } + +} diff --git a/java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/authentication/token/JMSTokenAuthenticationPolicy.java b/java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/authentication/token/JMSTokenAuthenticationPolicy.java new file mode 100644 index 0000000000..16ed2a53a4 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/authentication/token/JMSTokenAuthenticationPolicy.java @@ -0,0 +1,56 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms.policy.authentication.token; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.assembly.xml.Constants; +import org.apache.tuscany.sca.policy.Policy; + +/** + * Implementation for policies that could be injected as parameter + * into the axis2config. + * + * @version $Rev$ $Date$ + */ +public class JMSTokenAuthenticationPolicy implements Policy { + public static final QName JMS_TOKEN_AUTHENTICATION_POLICY_QNAME = new QName(Constants.SCA10_TUSCANY_NS, "jmsTokenAuthentication"); + public static final String JMS_TOKEN_AUTHENTICATION_TOKEN_NAME = "tokenName"; + + private QName tokenName; + + public QName getTokenName() { + return tokenName; + } + + public void setTokenName(QName tokenName) { + this.tokenName = tokenName; + } + + public QName getSchemaName() { + return JMS_TOKEN_AUTHENTICATION_POLICY_QNAME; + } + + public boolean isUnresolved() { + return false; + } + + public void setUnresolved(boolean unresolved) { + } +} diff --git a/java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/authentication/token/JMSTokenAuthenticationPolicyProcessor.java b/java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/authentication/token/JMSTokenAuthenticationPolicyProcessor.java new file mode 100644 index 0000000000..11747914da --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/authentication/token/JMSTokenAuthenticationPolicyProcessor.java @@ -0,0 +1,112 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms.policy.authentication.token; + +import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; +import static javax.xml.stream.XMLStreamConstants.START_ELEMENT; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; + +import org.apache.tuscany.sca.assembly.xml.Constants; +import org.apache.tuscany.sca.binding.jms.policy.header.JMSHeaderPolicy; +import org.apache.tuscany.sca.contribution.ModelFactoryExtensionPoint; +import org.apache.tuscany.sca.contribution.processor.BaseStAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.contribution.service.ContributionReadException; +import org.apache.tuscany.sca.contribution.service.ContributionResolveException; +import org.apache.tuscany.sca.contribution.service.ContributionWriteException; +import org.apache.tuscany.sca.monitor.Monitor; + +/** + * + * @version $Rev$ $Date$ + */ +public class JMSTokenAuthenticationPolicyProcessor extends BaseStAXArtifactProcessor implements StAXArtifactProcessor { + + public QName getArtifactType() { + return JMSTokenAuthenticationPolicy.JMS_TOKEN_AUTHENTICATION_POLICY_QNAME; + } + + public JMSTokenAuthenticationPolicyProcessor(ModelFactoryExtensionPoint modelFactories, Monitor monitor) { + } + + + public JMSTokenAuthenticationPolicy read(XMLStreamReader reader) throws ContributionReadException, XMLStreamException { + JMSTokenAuthenticationPolicy policy = new JMSTokenAuthenticationPolicy(); + int event = reader.getEventType(); + QName name = null; + + while (reader.hasNext()) { + event = reader.getEventType(); + switch (event) { + case START_ELEMENT : { + name = reader.getName(); + if ( name.equals(getArtifactType()) ) { + policy.setTokenName(getQName(reader, JMSTokenAuthenticationPolicy.JMS_TOKEN_AUTHENTICATION_TOKEN_NAME)); + } + break; + } + } + + if ( event == END_ELEMENT ) { + if ( getArtifactType().equals(reader.getName()) ) { + break; + } + } + + //Read the next element + if (reader.hasNext()) { + reader.next(); + } + } + + return policy; + } + + public void write(JMSTokenAuthenticationPolicy policy, XMLStreamWriter writer) + throws ContributionWriteException, XMLStreamException { + String prefix = "tuscany"; + writer.writeStartElement(prefix, + getArtifactType().getLocalPart(), + getArtifactType().getNamespaceURI()); + writer.writeNamespace("tuscany", Constants.SCA10_TUSCANY_NS); + + if ( policy.getTokenName() != null ) { + writer.writeAttribute(prefix, + getArtifactType().getNamespaceURI(), + JMSTokenAuthenticationPolicy.JMS_TOKEN_AUTHENTICATION_TOKEN_NAME, + policy.getTokenName().toString()); + } + + writer.writeEndElement(); + } + + public Class getModelType() { + return JMSTokenAuthenticationPolicy.class; + } + + public void resolve(JMSTokenAuthenticationPolicy arg0, ModelResolver arg1) throws ContributionResolveException { + + } + +} diff --git a/java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/authentication/token/JMSTokenAuthenticationPolicyProviderFactory.java b/java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/authentication/token/JMSTokenAuthenticationPolicyProviderFactory.java new file mode 100644 index 0000000000..fd77e57418 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/authentication/token/JMSTokenAuthenticationPolicyProviderFactory.java @@ -0,0 +1,75 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.jms.policy.authentication.token; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.assembly.Implementation; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.provider.PolicyProvider; +import org.apache.tuscany.sca.provider.PolicyProviderFactory; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; + +/** + * @version $Rev$ $Date$ + */ +public class JMSTokenAuthenticationPolicyProviderFactory implements PolicyProviderFactory { + private ExtensionPointRegistry registry; + + public JMSTokenAuthenticationPolicyProviderFactory(ExtensionPointRegistry registry) { + super(); + this.registry = registry; + } + + /** + * @see org.apache.tuscany.sca.provider.PolicyProviderFactory#createImplementationPolicyProvider(org.apache.tuscany.sca.runtime.RuntimeComponent, org.apache.tuscany.sca.assembly.Implementation) + */ + public PolicyProvider createImplementationPolicyProvider(RuntimeComponent component, Implementation implementation) { + return null;//new TokenAuthenticationImplementationPolicyProvider(component, implementation); + } + + /** + * @see org.apache.tuscany.sca.provider.PolicyProviderFactory#createReferencePolicyProvider(org.apache.tuscany.sca.runtime.RuntimeComponent, org.apache.tuscany.sca.runtime.RuntimeComponentReference, org.apache.tuscany.sca.assembly.Binding) + */ + public PolicyProvider createReferencePolicyProvider(RuntimeComponent component, + RuntimeComponentReference reference, + Binding binding) { + return new JMSTokenAuthenticationReferencePolicyProvider(component, reference, binding); + } + + /** + * @see org.apache.tuscany.sca.provider.PolicyProviderFactory#createServicePolicyProvider(org.apache.tuscany.sca.runtime.RuntimeComponent, org.apache.tuscany.sca.runtime.RuntimeComponentService, org.apache.tuscany.sca.assembly.Binding) + */ + public PolicyProvider createServicePolicyProvider(RuntimeComponent component, + RuntimeComponentService service, + Binding binding) { + return new JMSTokenAuthenticationServicePolicyProvider(component, service, binding); + } + + /** + * @see org.apache.tuscany.sca.provider.ProviderFactory#getModelType() + */ + public Class getModelType() { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/authentication/token/JMSTokenAuthenticationReferencePolicyInterceptor.java b/java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/authentication/token/JMSTokenAuthenticationReferencePolicyInterceptor.java new file mode 100644 index 0000000000..17b5da42be --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/authentication/token/JMSTokenAuthenticationReferencePolicyInterceptor.java @@ -0,0 +1,89 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms.policy.authentication.token; + + +import javax.security.auth.Subject; + +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.policy.PolicySet; +import org.apache.tuscany.sca.policy.SecurityUtil; +import org.apache.tuscany.sca.policy.authentication.token.TokenPrincipal; + +/** + * Policy handler to handle PolicySet related to Logging with the QName + * {http://tuscany.apache.org/xmlns/sca/1.0/impl/java}LoggingPolicy + * + * @version $Rev$ $Date$ + */ +public class JMSTokenAuthenticationReferencePolicyInterceptor implements Interceptor { + + private Invoker next; + private Operation operation; + private PolicySet policySet = null; + private String context; + private JMSTokenAuthenticationPolicy policy; + + public JMSTokenAuthenticationReferencePolicyInterceptor(String context, Operation operation, PolicySet policySet) { + super(); + this.operation = operation; + this.policySet = policySet; + this.context = context; + init(); + } + + private void init() { + if (policySet != null) { + for (Object policyObject : policySet.getPolicies()){ + if (policyObject instanceof JMSTokenAuthenticationPolicy){ + policy = (JMSTokenAuthenticationPolicy)policyObject; + break; + } + } + } + } + + public Message invoke(Message msg) { + // could call out here to some 3rd party system to get credentials + + if ( policy.getTokenName() != null){ + + Subject subject = SecurityUtil.getSubject(msg); + TokenPrincipal principal = SecurityUtil.getPrincipal(subject, TokenPrincipal.class); + + if (principal == null){ + principal = new TokenPrincipal("SomeJMSAuthorizationToken"); + subject.getPrincipals().add(principal); + } + } + + return getNext().invoke(msg); + } + + public Invoker getNext() { + return next; + } + + public void setNext(Invoker next) { + this.next = next; + } +} diff --git a/java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/authentication/token/JMSTokenAuthenticationReferencePolicyProvider.java b/java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/authentication/token/JMSTokenAuthenticationReferencePolicyProvider.java new file mode 100644 index 0000000000..610bf758d1 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/authentication/token/JMSTokenAuthenticationReferencePolicyProvider.java @@ -0,0 +1,90 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.jms.policy.authentication.token; + +import java.util.List; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.Phase; +import org.apache.tuscany.sca.policy.PolicySet; +import org.apache.tuscany.sca.policy.PolicySetAttachPoint; +import org.apache.tuscany.sca.policy.util.PolicyHandler; +import org.apache.tuscany.sca.provider.PolicyProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; + +/** + * @version $Rev$ $Date$ + */ +public class JMSTokenAuthenticationReferencePolicyProvider implements PolicyProvider { + private RuntimeComponent component; + private RuntimeComponentReference reference; + private Binding binding; + + public JMSTokenAuthenticationReferencePolicyProvider(RuntimeComponent component, + RuntimeComponentReference reference, + Binding binding) { + super(); + this.component = component; + this.reference = reference; + this.binding = binding; + } + + private PolicySet findPolicySet() { + if (binding instanceof PolicySetAttachPoint) { + List policySets = ((PolicySetAttachPoint)binding).getApplicablePolicySets(); + for (PolicySet ps : policySets) { + for (Object p : ps.getPolicies()) { + if (JMSTokenAuthenticationPolicy.class.isInstance(p)) { + return ps; + } + } + } + } + return null; + } + + private String getContext() { + return "component.reference: " + component.getURI() + + "#" + + reference.getName() + + "(" + + binding.getClass().getName() + + ")"; + } + + /** + * @see org.apache.tuscany.sca.provider.PolicyProvider#createInterceptor(org.apache.tuscany.sca.interfacedef.Operation) + */ + public Interceptor createInterceptor(Operation operation) { + PolicySet ps = findPolicySet(); + return ps == null ? null : new JMSTokenAuthenticationReferencePolicyInterceptor(getContext(), operation, ps); + } + + /** + * @see org.apache.tuscany.sca.provider.PolicyProvider#getPhase() + */ + public String getPhase() { + return Phase.REFERENCE_POLICY; + } + +} diff --git a/java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/authentication/token/JMSTokenAuthenticationServicePolicyInterceptor.java b/java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/authentication/token/JMSTokenAuthenticationServicePolicyInterceptor.java new file mode 100644 index 0000000000..ec3be6e165 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/authentication/token/JMSTokenAuthenticationServicePolicyInterceptor.java @@ -0,0 +1,89 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms.policy.authentication.token; + + +import java.security.Principal; + +import javax.security.auth.Subject; +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.assembly.xml.Constants; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.policy.PolicySet; +import org.apache.tuscany.sca.policy.SecurityUtil; +import org.apache.tuscany.sca.policy.authentication.token.TokenPrincipal; + +/** + * Policy handler to handle PolicySet related to Logging with the QName + * {http://tuscany.apache.org/xmlns/sca/1.0/impl/java}LoggingPolicy + * + * @version $Rev$ $Date$ + */ +public class JMSTokenAuthenticationServicePolicyInterceptor implements Interceptor { + private Invoker next; + private Operation operation; + private PolicySet policySet = null; + private String context; + private JMSTokenAuthenticationPolicy policy; + + public JMSTokenAuthenticationServicePolicyInterceptor(String context, Operation operation, PolicySet policySet) { + super(); + this.operation = operation; + this.policySet = policySet; + this.context = context; + init(); + } + + private void init() { + if (policySet != null) { + for (Object policyObject : policySet.getPolicies()){ + if (policyObject instanceof JMSTokenAuthenticationPolicy){ + policy = (JMSTokenAuthenticationPolicy)policyObject; + break; + } + } + } + } + + public Message invoke(Message msg) { + Subject subject = SecurityUtil.getSubject(msg); + TokenPrincipal principal = SecurityUtil.getPrincipal(subject, TokenPrincipal.class); + + if (principal != null) { + System.out.println("Token: " + principal.getName()); + + // call out here to some 3rd party system to do whatever you + // need to authenticate the principal + } + + return getNext().invoke(msg); + } + + public Invoker getNext() { + return next; + } + + public void setNext(Invoker next) { + this.next = next; + } +} diff --git a/java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/authentication/token/JMSTokenAuthenticationServicePolicyProvider.java b/java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/authentication/token/JMSTokenAuthenticationServicePolicyProvider.java new file mode 100644 index 0000000000..4278c1e595 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/authentication/token/JMSTokenAuthenticationServicePolicyProvider.java @@ -0,0 +1,88 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.jms.policy.authentication.token; + +import java.util.List; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.Phase; +import org.apache.tuscany.sca.policy.PolicySet; +import org.apache.tuscany.sca.policy.PolicySetAttachPoint; +import org.apache.tuscany.sca.policy.util.PolicyHandler; +import org.apache.tuscany.sca.provider.PolicyProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; + +/** + * @version $Rev$ $Date$ + */ +public class JMSTokenAuthenticationServicePolicyProvider implements PolicyProvider { + private RuntimeComponent component; + private RuntimeComponentService service; + private Binding binding; + + public JMSTokenAuthenticationServicePolicyProvider(RuntimeComponent component, RuntimeComponentService service, Binding binding) { + super(); + this.component = component; + this.service = service; + this.binding = binding; + } + + private PolicySet findPolicySet() { + if (binding instanceof PolicySetAttachPoint) { + List policySets = ((PolicySetAttachPoint)binding).getApplicablePolicySets(); + for (PolicySet ps : policySets) { + for (Object p : ps.getPolicies()) { + if (JMSTokenAuthenticationPolicy.class.isInstance(p)) { + return ps; + } + } + } + } + return null; + } + + private String getContext() { + return "component.service: " + component.getURI() + + "#" + + service.getName() + + "(" + + binding.getClass().getName() + + ")"; + } + + /** + * @see org.apache.tuscany.sca.provider.PolicyProvider#createInterceptor(org.apache.tuscany.sca.interfacedef.Operation) + */ + public Interceptor createInterceptor(Operation operation) { + PolicySet ps = findPolicySet(); + return ps == null ? null : new JMSTokenAuthenticationServicePolicyInterceptor(getContext(), operation, ps); + } + + /** + * @see org.apache.tuscany.sca.provider.PolicyProvider#getPhase() + */ + public String getPhase() { + return Phase.SERVICE_POLICY; + } + +} diff --git a/java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/header/JMSHeaderPolicy.java b/java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/header/JMSHeaderPolicy.java new file mode 100644 index 0000000000..1c16e3fa1b --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/header/JMSHeaderPolicy.java @@ -0,0 +1,131 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms.policy.header; + +import java.util.Hashtable; +import java.util.Map; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.assembly.xml.Constants; +import org.apache.tuscany.sca.policy.Policy; + +/** + * Implementation for policies that could be injected as parameter + * into the axis2config. + * + * @version $Rev$ $Date$ + */ +public class JMSHeaderPolicy implements Policy { + public static final QName JMS_HEADER_POLICY_QNAME = new QName(Constants.SCA10_TUSCANY_NS, "jmsHeader"); + public static final String JMS_HEADER_JMS_TYPE = "JMSType"; + public static final String JMS_HEADER_JMS_CORRELATION_ID = "JMSCorrelationID"; + public static final String JMS_HEADER_JMS_DELIVERY_MODE = "JMSDeliveryMode"; + public static final String JMS_HEADER_JMS_TIME_TO_LIVE = "JMSTimeToLive"; + public static final String JMS_HEADER_JMS_PRIORITY = "JMSPriority"; + public static final String JMS_HEADER_JMS_PROPERTY = "property"; + public static final String JMS_HEADER_JMS_PROPERTY_NAME = "name"; + + private String jmsType = null; + private String jmsCorrelationId = null; + private Boolean deliveryModePersistent = null; + private Long timeToLive = null; + private Integer jmsPriority = null; + private Map properties = new Hashtable(); + + public String getJmsType() { + return jmsType; + } + + public void setJmsType(String jmsType) { + this.jmsType = jmsType; + } + + public String getJmsCorrelationId() { + return jmsCorrelationId; + } + + public void setJmsCorrelationId(String jmsCorrelationId) { + this.jmsCorrelationId = jmsCorrelationId; + } + + public Boolean getDeliveryModePersistent() { + return deliveryModePersistent; + } + + public void setDeliveryModePersistent(Boolean deliveryModePersistent) { + this.deliveryModePersistent = deliveryModePersistent; + } + + public Long getTimeToLive() { + return timeToLive; + } + + public void setTimeToLive(Long timeToLive) { + this.timeToLive = timeToLive; + } + + public Integer getJmsPriority() { + return jmsPriority; + } + + public void setJmsPriority(Integer jmsPriority) { + this.jmsPriority = jmsPriority; + } + + public Map getProperties() { + return properties; + } + + public QName getSchemaName() { + return JMS_HEADER_POLICY_QNAME; + } + + public boolean isUnresolved() { + return false; + } + + public void setUnresolved(boolean unresolved) { + } + + @Override + public String toString() { + String result = "jmsHeader"; + + result += " JMSType "; + result += getJmsType(); + result += " JMSDeliveryMode "; + result += getJmsCorrelationId(); + result += " JMSDeliveryMode "; + result += getDeliveryModePersistent(); + result += " JMSTimeToLive "; + result += getTimeToLive(); + result += " JMSPriority "; + result += getJmsPriority(); + + for (String propertyName : properties.keySet()){ + result += " property "; + result += propertyName; + result += " "; + result += properties.get(propertyName); + } + + return result; + } +} diff --git a/java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/header/JMSHeaderPolicyProcessor.java b/java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/header/JMSHeaderPolicyProcessor.java new file mode 100644 index 0000000000..d6167b4895 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/header/JMSHeaderPolicyProcessor.java @@ -0,0 +1,210 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms.policy.header; + +import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; +import static javax.xml.stream.XMLStreamConstants.START_ELEMENT; + +import java.util.Hashtable; +import java.util.Map; +import java.util.logging.Level; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; + +import org.apache.tuscany.sca.assembly.builder.impl.ProblemImpl; +import org.apache.tuscany.sca.assembly.xml.Constants; +import org.apache.tuscany.sca.contribution.ModelFactoryExtensionPoint; +import org.apache.tuscany.sca.contribution.processor.BaseStAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.contribution.service.ContributionReadException; +import org.apache.tuscany.sca.contribution.service.ContributionResolveException; +import org.apache.tuscany.sca.contribution.service.ContributionWriteException; +import org.apache.tuscany.sca.monitor.Monitor; +import org.apache.tuscany.sca.monitor.Problem; +import org.apache.tuscany.sca.monitor.Problem.Severity; + +/** + * + * @version $Rev$ $Date$ + */ +public class JMSHeaderPolicyProcessor extends BaseStAXArtifactProcessor implements StAXArtifactProcessor { + + private Monitor monitor; + + public QName getArtifactType() { + return JMSHeaderPolicy.JMS_HEADER_POLICY_QNAME; + } + + public JMSHeaderPolicyProcessor(ModelFactoryExtensionPoint modelFactories, Monitor monitor) { + this.monitor = monitor; + } + + /** + * Marshals warnings into the monitor + * + * @param message + * @param model + * @param messageParameters + */ + protected void warning(String message, Object model, String... messageParameters) { + if (monitor != null){ + Problem problem = new ProblemImpl(this.getClass().getName(), "assembly-xml-validation-messages", Severity.WARNING, model, message, (Object[])messageParameters); + monitor.problem(problem); + } + } + + /** + * Marshals errors into the monitor + * + * @param problems + * @param message + * @param model + */ + protected void error(String message, Object model, Object... messageParameters) { + if (monitor != null) { + Problem problem = new ProblemImpl(this.getClass().getName(), "assembly-xml-validation-messages", Severity.ERROR, model, message, (Object[])messageParameters); + monitor.problem(problem); + } + } + + + public JMSHeaderPolicy read(XMLStreamReader reader) throws ContributionReadException, XMLStreamException { + JMSHeaderPolicy policy = new JMSHeaderPolicy(); + int event = reader.getEventType(); + QName name = null; + + while (reader.hasNext()) { + event = reader.getEventType(); + switch (event) { + case START_ELEMENT : { + name = reader.getName(); + if ( name.equals(getArtifactType()) ) { + + policy.setJmsType(getString(reader, JMSHeaderPolicy.JMS_HEADER_JMS_TYPE)); + policy.setJmsCorrelationId(getString(reader, JMSHeaderPolicy.JMS_HEADER_JMS_CORRELATION_ID)); + + String deliveryMode = getString(reader, JMSHeaderPolicy.JMS_HEADER_JMS_DELIVERY_MODE); + if (deliveryMode != null){ + if (deliveryMode.equals("PERSISTENT")) { + policy.setDeliveryModePersistent(true); + } else if (deliveryMode.equals("NON_PERSISTENT")){ + policy.setDeliveryModePersistent(false); + } else { + error("InvalidDeliveryMode", policy, deliveryMode); + } + } + + String timeToLive = getString(reader, JMSHeaderPolicy.JMS_HEADER_JMS_TIME_TO_LIVE); + + if ( timeToLive != null){ + try { + policy.setTimeToLive(Long.valueOf(timeToLive)); + } catch (NumberFormatException ex){ + error("InvalidTimeToLive", policy, timeToLive); + } + } + + String priority = getString(reader, JMSHeaderPolicy.JMS_HEADER_JMS_PRIORITY); + + if ( priority != null){ + try { + policy.setJmsPriority(Integer.valueOf(priority)); + } catch (NumberFormatException ex){ + error("InvalidPriority", policy, priority); + } + } + } else if (name.getLocalPart().equals(JMSHeaderPolicy.JMS_HEADER_JMS_PROPERTY)) { + String propertyName = getString(reader, JMSHeaderPolicy.JMS_HEADER_JMS_PROPERTY_NAME); + String propertyValue = reader.getElementText(); + policy.getProperties().put(propertyName, propertyValue); + } + break; + } + } + + if ( event == END_ELEMENT ) { + if ( getArtifactType().equals(reader.getName()) ) { + break; + } + } + + //Read the next element + if (reader.hasNext()) { + reader.next(); + } + } + + return policy; + } + + public void write(JMSHeaderPolicy policy, XMLStreamWriter writer) + throws ContributionWriteException, XMLStreamException { + String prefix = "tuscany"; + writer.writeStartElement(prefix, + getArtifactType().getLocalPart(), + getArtifactType().getNamespaceURI()); + writer.writeNamespace("tuscany", Constants.SCA10_TUSCANY_NS); + + if (policy.getJmsType() != null){ + writer.writeAttribute(JMSHeaderPolicy.JMS_HEADER_JMS_TYPE, policy.getJmsType()); + } + + if (policy.getJmsCorrelationId() != null){ + writer.writeAttribute(JMSHeaderPolicy.JMS_HEADER_JMS_CORRELATION_ID, policy.getJmsCorrelationId()); + } + + if (policy.getDeliveryModePersistent() == true){ + writer.writeAttribute(JMSHeaderPolicy.JMS_HEADER_JMS_DELIVERY_MODE, "PERSISTENT"); + } else { + writer.writeAttribute(JMSHeaderPolicy.JMS_HEADER_JMS_DELIVERY_MODE, "NON_PERSISTENT"); + } + + if (policy.getTimeToLive()!= null){ + writer.writeAttribute(JMSHeaderPolicy.JMS_HEADER_JMS_TIME_TO_LIVE, policy.getTimeToLive().toString()); + } + + if (policy.getJmsPriority()!= null){ + writer.writeAttribute(JMSHeaderPolicy.JMS_HEADER_JMS_PRIORITY, policy.getJmsPriority().toString()); + } + + for (String propertyName : policy.getProperties().keySet()){ + writer.writeStartElement(prefix, + JMSHeaderPolicy.JMS_HEADER_JMS_PROPERTY, + getArtifactType().getNamespaceURI()); + writer.writeAttribute(JMSHeaderPolicy.JMS_HEADER_JMS_PROPERTY_NAME, propertyName); + writer.writeCharacters(policy.getProperties().get(propertyName)); + writer.writeEndElement(); + } + + writer.writeEndElement(); + } + + public Class getModelType() { + return JMSHeaderPolicy.class; + } + + public void resolve(JMSHeaderPolicy arg0, ModelResolver arg1) throws ContributionResolveException { + + } + +} diff --git a/java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/header/JMSHeaderPolicyProviderFactory.java b/java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/header/JMSHeaderPolicyProviderFactory.java new file mode 100644 index 0000000000..ded3da05b9 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/header/JMSHeaderPolicyProviderFactory.java @@ -0,0 +1,75 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.jms.policy.header; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.assembly.Implementation; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.provider.PolicyProvider; +import org.apache.tuscany.sca.provider.PolicyProviderFactory; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; + +/** + * @version $Rev$ $Date$ + */ +public class JMSHeaderPolicyProviderFactory implements PolicyProviderFactory { + private ExtensionPointRegistry registry; + + public JMSHeaderPolicyProviderFactory(ExtensionPointRegistry registry) { + super(); + this.registry = registry; + } + + /** + * @see org.apache.tuscany.sca.provider.PolicyProviderFactory#createImplementationPolicyProvider(org.apache.tuscany.sca.runtime.RuntimeComponent, org.apache.tuscany.sca.assembly.Implementation) + */ + public PolicyProvider createImplementationPolicyProvider(RuntimeComponent component, Implementation implementation) { + return null; + } + + /** + * @see org.apache.tuscany.sca.provider.PolicyProviderFactory#createReferencePolicyProvider(org.apache.tuscany.sca.runtime.RuntimeComponent, org.apache.tuscany.sca.runtime.RuntimeComponentReference, org.apache.tuscany.sca.assembly.Binding) + */ + public PolicyProvider createReferencePolicyProvider(RuntimeComponent component, + RuntimeComponentReference reference, + Binding binding) { + return new JMSHeaderReferencePolicyProvider(component, reference, binding); + } + + /** + * @see org.apache.tuscany.sca.provider.PolicyProviderFactory#createServicePolicyProvider(org.apache.tuscany.sca.runtime.RuntimeComponent, org.apache.tuscany.sca.runtime.RuntimeComponentService, org.apache.tuscany.sca.assembly.Binding) + */ + public PolicyProvider createServicePolicyProvider(RuntimeComponent component, + RuntimeComponentService service, + Binding binding) { + return null; + } + + /** + * @see org.apache.tuscany.sca.provider.ProviderFactory#getModelType() + */ + public Class getModelType() { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/header/JMSHeaderReferencePolicyInterceptor.java b/java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/header/JMSHeaderReferencePolicyInterceptor.java new file mode 100644 index 0000000000..19069378ef --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/header/JMSHeaderReferencePolicyInterceptor.java @@ -0,0 +1,130 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms.policy.header; + + +import java.util.Map; + +import javax.jms.DeliveryMode; +import javax.jms.JMSException; +import javax.security.auth.Subject; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.binding.jms.impl.JMSBinding; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingException; +import org.apache.tuscany.sca.binding.jms.policy.JMSBindingDefinitionsProvider; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.policy.PolicySet; +import org.apache.tuscany.sca.policy.SecurityUtil; +import org.apache.tuscany.sca.policy.authentication.token.TokenPrincipal; +import org.apache.tuscany.sca.runtime.ReferenceParameters; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; + +/** + * Policy handler to handle PolicySet related to Logging with the QName + * {http://tuscany.apache.org/xmlns/sca/1.0/impl/java}LoggingPolicy + * + * @version $Rev$ $Date$ + */ +public class JMSHeaderReferencePolicyInterceptor implements Interceptor { + + private Invoker next; + private RuntimeComponent component; + private RuntimeComponentReference reference; + private JMSBinding jmsBinding; + private PolicySet policySet = null; + private String context; + private JMSHeaderPolicy jmsHeaderPolicy; + + public JMSHeaderReferencePolicyInterceptor(String context, RuntimeComponent component, RuntimeComponentReference reference, Binding binding, PolicySet policySet) { + super(); + this.component = component; + this.reference = reference; + this.jmsBinding = (JMSBinding)binding; + this.policySet = policySet; + this.context = context; + + init(); + } + + private void init() { + if (policySet != null) { + for (Object policyObject : policySet.getPolicies()){ + if (policyObject instanceof JMSHeaderPolicy){ + jmsHeaderPolicy = (JMSHeaderPolicy)policyObject; + break; + } + } + } + } + + public Message invoke(Message msg) { + try { + javax.jms.Message jmsMsg = msg.getBody(); + String operationName = msg.getOperation().getName(); + + if ((jmsHeaderPolicy != null) && + (jmsHeaderPolicy.getDeliveryModePersistent() != null)) { + if (jmsHeaderPolicy.getDeliveryModePersistent()) { + jmsMsg.setJMSDeliveryMode(DeliveryMode.PERSISTENT); + } else { + jmsMsg.setJMSDeliveryMode(DeliveryMode.NON_PERSISTENT); + } + + } + + if ((jmsHeaderPolicy != null) && + (jmsHeaderPolicy.getJmsCorrelationId() != null)) { + jmsMsg.setJMSCorrelationID(jmsHeaderPolicy.getJmsCorrelationId()); + } + + if ((jmsHeaderPolicy != null) && + (jmsHeaderPolicy.getJmsPriority() != null)) { + jmsMsg.setJMSPriority(jmsHeaderPolicy.getJmsPriority()); + } + + if ((jmsHeaderPolicy != null) && + (jmsHeaderPolicy.getJmsType() != null)) { + jmsMsg.setJMSType(jmsHeaderPolicy.getJmsType()); + } + + if (jmsHeaderPolicy != null){ + for (String propName : jmsHeaderPolicy.getProperties().keySet()) { + jmsMsg.setObjectProperty(propName, jmsHeaderPolicy.getProperties().get(propName)); + } + } + + return getNext().invoke(msg); + } catch (JMSException e) { + throw new JMSBindingException(e); + } + } + + public Invoker getNext() { + return next; + } + + public void setNext(Invoker next) { + this.next = next; + } +} diff --git a/java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/header/JMSHeaderReferencePolicyProvider.java b/java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/header/JMSHeaderReferencePolicyProvider.java new file mode 100644 index 0000000000..7a9318407e --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-policy/src/main/java/org/apache/tuscany/sca/binding/jms/policy/header/JMSHeaderReferencePolicyProvider.java @@ -0,0 +1,95 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.jms.policy.header; + +import java.util.List; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.Phase; +import org.apache.tuscany.sca.policy.PolicySet; +import org.apache.tuscany.sca.policy.PolicySetAttachPoint; +import org.apache.tuscany.sca.policy.util.PolicyHandler; +import org.apache.tuscany.sca.provider.PolicyProvider; +import org.apache.tuscany.sca.provider.PolicyProviderRRB; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; + +/** + * @version $Rev$ $Date$ + */ +public class JMSHeaderReferencePolicyProvider implements PolicyProviderRRB { + private RuntimeComponent component; + private RuntimeComponentReference reference; + private Binding binding; + + public JMSHeaderReferencePolicyProvider(RuntimeComponent component, + RuntimeComponentReference reference, + Binding binding) { + super(); + this.component = component; + this.reference = reference; + this.binding = binding; + } + + private PolicySet findPolicySet() { + if (binding instanceof PolicySetAttachPoint) { + List policySets = ((PolicySetAttachPoint)binding).getApplicablePolicySets(); + for (PolicySet ps : policySets) { + for (Object p : ps.getPolicies()) { + if (JMSHeaderPolicy.class.isInstance(p)) { + return ps; + } + } + } + } + return null; + } + + private String getContext() { + return "component.reference: " + component.getURI() + + "#" + + reference.getName() + + "(" + + binding.getClass().getName() + + ")"; + } + + /** + * @see org.apache.tuscany.sca.provider.PolicyProvider#createInterceptor(org.apache.tuscany.sca.interfacedef.Operation) + */ + public Interceptor createInterceptor(Operation operation) { + return null; + } + + public Interceptor createBindingInterceptor() { + PolicySet ps = findPolicySet(); + return ps == null ? null : new JMSHeaderReferencePolicyInterceptor(getContext(), component, reference, binding, ps); + } + + /** + * @see org.apache.tuscany.sca.provider.PolicyProvider#getPhase() + */ + public String getPhase() { + return Phase.REFERENCE_BINDING_POLICY; + } + +} diff --git a/java/sca/contrib/modules/binding-jms-policy/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor b/java/sca/contrib/modules/binding-jms-policy/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor new file mode 100644 index 0000000000..e6f22e327c --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-policy/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor @@ -0,0 +1,20 @@ +# 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. + +# Implementation class for the artifact processor extension +org.apache.tuscany.sca.binding.jms.policy.authentication.token.JMSTokenAuthenticationPolicyProcessor;qname=http://tuscany.apache.org/xmlns/sca/1.0#jmsTokenAuthentication,model=org.apache.tuscany.sca.binding.jms.policy.authentication.token.JMSTokenAuthenticationPolicy +org.apache.tuscany.sca.binding.jms.policy.header.JMSHeaderPolicyProcessor;qname=http://tuscany.apache.org/xmlns/sca/1.0#jmsHeader,model=org.apache.tuscany.sca.binding.jms.policy.header.JMSHeaderPolicy \ No newline at end of file diff --git a/java/sca/contrib/modules/binding-jms-policy/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.PolicyProviderFactory b/java/sca/contrib/modules/binding-jms-policy/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.PolicyProviderFactory new file mode 100644 index 0000000000..b04c71d8e3 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-policy/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.PolicyProviderFactory @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for the policy extension +org.apache.tuscany.sca.binding.jms.policy.authentication.token.JMSTokenAuthenticationPolicyProviderFactory;model=org.apache.tuscany.sca.binding.jms.policy.authentication.token.JMSTokenAuthenticationPolicy \ No newline at end of file diff --git a/java/sca/contrib/modules/binding-jms-policy/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.SCADefinitionsProvider b/java/sca/contrib/modules/binding-jms-policy/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.SCADefinitionsProvider new file mode 100644 index 0000000000..0598cdc368 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-policy/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.SCADefinitionsProvider @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for SCA Definitions Providers +org.apache.tuscany.sca.binding.jms.policy.JMSBindingDefinitionsProvider \ No newline at end of file diff --git a/java/sca/contrib/modules/binding-jms-policy/src/main/resources/binding-jms-policy-validation-messages.properties b/java/sca/contrib/modules/binding-jms-policy/src/main/resources/binding-jms-policy-validation-messages.properties new file mode 100644 index 0000000000..fd43b2c4e9 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-policy/src/main/resources/binding-jms-policy-validation-messages.properties @@ -0,0 +1,23 @@ +# +# +# 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. +# +# +InvalidDeliveryMode = JMSDeliveryMode must be either PERSISTENT or NON_PERSISTENT but found {0} +InvalidTimeToLive = JMSTimeToLive must be a long integer but found {0} +InvalidPriority = JMSPriority must be a integer but found {0} diff --git a/java/sca/contrib/modules/binding-jms-policy/src/main/resources/org/apache/tuscany/sca/binding/jms/policy/definitions.xml b/java/sca/contrib/modules/binding-jms-policy/src/main/resources/org/apache/tuscany/sca/binding/jms/policy/definitions.xml new file mode 100644 index 0000000000..66ec011844 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-policy/src/main/resources/org/apache/tuscany/sca/binding/jms/policy/definitions.xml @@ -0,0 +1,84 @@ + + + + + + + + + + + + Communication through this binding requires JMS + + + + + + + This intent is used to indicate the deliver mode + of the sent message + + + + + + Message are sent persistently + + + + + + Message are sent persistently + + + + + + + This intent is used to indicate the priority of the + sent message + + + + + + Messages are high priority + + + + + + Messages are meduim priority + + + + + + Messages are low priority + + + \ No newline at end of file diff --git a/java/sca/contrib/modules/binding-jms-policy/src/test/java/org/apache/tuscany/sca/binding/jms/policy/PolicyProcessorTestCase.java b/java/sca/contrib/modules/binding-jms-policy/src/test/java/org/apache/tuscany/sca/binding/jms/policy/PolicyProcessorTestCase.java new file mode 100644 index 0000000000..a9da07ca7d --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-policy/src/test/java/org/apache/tuscany/sca/binding/jms/policy/PolicyProcessorTestCase.java @@ -0,0 +1,91 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.jms.policy; + +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLOutputFactory; +import javax.xml.stream.XMLStreamConstants; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; + +import junit.framework.Assert; + +import org.apache.tuscany.sca.binding.jms.policy.authentication.token.JMSTokenAuthenticationPolicy; +import org.apache.tuscany.sca.binding.jms.policy.authentication.token.JMSTokenAuthenticationPolicyProcessor; +import org.apache.tuscany.sca.binding.jms.policy.header.JMSHeaderPolicy; +import org.apache.tuscany.sca.binding.jms.policy.header.JMSHeaderPolicyProcessor; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.policy.Policy; +import org.junit.Test; + +/** + * @version $Rev$ $Date$ + */ +public class PolicyProcessorTestCase { + private final static List SEQ = + Arrays.asList("property value", + ""); + + @Test + public void testRead() throws Exception { + List results = new ArrayList(); + Map processors = new HashMap(); + processors.put(JMSHeaderPolicy.JMS_HEADER_POLICY_QNAME, new JMSHeaderPolicyProcessor(null, null)); + processors.put(JMSTokenAuthenticationPolicy.JMS_TOKEN_AUTHENTICATION_POLICY_QNAME, new JMSTokenAuthenticationPolicyProcessor(null, null)); + + InputStream is = getClass().getResourceAsStream("mock_policy_definitions.xml"); + XMLInputFactory inputFactory = XMLInputFactory.newInstance(); + XMLStreamReader reader = inputFactory.createXMLStreamReader(is); + + XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); + + while (true) { + int event = reader.getEventType(); + if (event == XMLStreamConstants.START_ELEMENT) { + if ("policySet".equals(reader.getName().getLocalPart())) { + reader.nextTag(); + StAXArtifactProcessor processor = processors.get(reader.getName()); + Policy policy = (Policy)processor.read(reader); + + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + XMLStreamWriter writer = outputFactory.createXMLStreamWriter(outputStream); + processor.write(policy, writer); + writer.flush(); + results.add(outputStream.toString()); + } + } + if (reader.hasNext()) { + reader.next(); + } else { + break; + } + } + Assert.assertEquals(SEQ, results); + } +} diff --git a/java/sca/contrib/modules/binding-jms-policy/src/test/resources/org/apache/tuscany/sca/binding/jms/policy/mock_policy_definitions.xml b/java/sca/contrib/modules/binding-jms-policy/src/test/resources/org/apache/tuscany/sca/binding/jms/policy/mock_policy_definitions.xml new file mode 100644 index 0000000000..3631c682aa --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-policy/src/test/resources/org/apache/tuscany/sca/binding/jms/policy/mock_policy_definitions.xml @@ -0,0 +1,39 @@ + + + + + + + + property value + + + + + + + \ No newline at end of file diff --git a/java/sca/contrib/modules/binding-jms-runtime/LICENSE b/java/sca/contrib/modules/binding-jms-runtime/LICENSE new file mode 100644 index 0000000000..8aa906c321 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/LICENSE @@ -0,0 +1,205 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + + diff --git a/java/sca/contrib/modules/binding-jms-runtime/META-INF/MANIFEST.MF b/java/sca/contrib/modules/binding-jms-runtime/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..183f1446a6 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/META-INF/MANIFEST.MF @@ -0,0 +1,47 @@ +Manifest-Version: 1.0 +Export-Package: org.apache.tuscany.sca.binding.jms.provider;uses:="org + .apache.tuscany.sca.runtime,javax.jms,org.apache.tuscany.sca.provider + ,org.apache.tuscany.sca.core,org.apache.axiom.om,javax.xml.stream,org + .apache.tuscany.sca.binding.jms,org.apache.tuscany.sca.core.assembly, + org.oasisopen.sca,org.apache.tuscany.sca.core.invocation,javax.naming,org. + apache.tuscany.sca.assembly,org.apache.tuscany.sca.binding.ws.wsdlgen + ,org.apache.axiom.om.impl.builder,org.apache.tuscany.sca.interfacedef + .java,org.apache.tuscany.sca.monitor,org.apache.tuscany.sca.interface + def,org.apache.tuscany.sca.invocation,org.apache.tuscany.sca.binding. + ws,org.apache.tuscany.sca.work";version="2.0.0" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA JMS Binding Runtime +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397307750 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA JMS Binding Runtime +Import-Package: javax.jms, + javax.naming, + javax.xml.stream, + org.apache.axiom.om, + org.apache.axiom.om.impl.builder, + org.apache.tuscany.sca.assembly;version="2.0.0", + org.apache.tuscany.sca.binding.jms;version="2.0.0", + org.apache.tuscany.sca.binding.jms.provider;version="2.0.0", + org.apache.tuscany.sca.binding.jms.xml;version="2.0.0", + org.apache.tuscany.sca.binding.ws;version="2.0.0", + org.apache.tuscany.sca.binding.ws.wsdlgen;version="2.0.0", + org.apache.tuscany.sca.core;version="2.0.0", + org.apache.tuscany.sca.core.assembly;version="2.0.0", + org.apache.tuscany.sca.core.invocation;version="2.0.0", + org.apache.tuscany.sca.interfacedef;version="2.0.0", + org.apache.tuscany.sca.interfacedef.java;version="2.0.0", + org.apache.tuscany.sca.invocation;version="2.0.0", + org.apache.tuscany.sca.monitor;version="2.0.0", + org.apache.tuscany.sca.policy;version="2.0.0", + org.apache.tuscany.sca.provider;version="2.0.0", + org.apache.tuscany.sca.runtime;version="2.0.0", + org.apache.tuscany.sca.work;version="2.0.0", + org.oasisopen.sca;version="2.0.0", + org.oasisopen.sca.annotation;version="2.0.0";resolution:=optional +Bundle-SymbolicName: org.apache.tuscany.sca.binding.jms.runtime +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/binding-jms-runtime/NOTICE b/java/sca/contrib/modules/binding-jms-runtime/NOTICE new file mode 100644 index 0000000000..25bb89c9b2 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/binding-jms-runtime/pom.xml b/java/sca/contrib/modules/binding-jms-runtime/pom.xml new file mode 100644 index 0000000000..e4322210af --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/pom.xml @@ -0,0 +1,123 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + tuscany-binding-jms-runtime + Apache Tuscany SCA JMS Binding Runtime + + + + + org.apache.tuscany.sca + tuscany-binding-jms + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-binding-jms-policy + 1.4-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-sca-api + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-core-spi + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-core + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-interface-java + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-interface-wsdl + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-databinding-axiom + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-binding-ws-wsdlgen + 2.0-SNAPSHOT + + + + org.apache.geronimo.specs + geronimo-jms_1.1_spec + 1.1 + provided + + + org.apache.geronimo.specs + geronimo-jms_1.1_spec + + + + + + org.apache.tuscany.sca + tuscany-implementation-java-runtime + 2.0-SNAPSHOT + test + + + + org.apache.tuscany.sca + tuscany-node-impl + 2.0-SNAPSHOT + test + + + + junit + junit + 4.5 + test + + + + + diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/context/JMSBindingContext.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/context/JMSBindingContext.java new file mode 100644 index 0000000000..bc2e783569 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/context/JMSBindingContext.java @@ -0,0 +1,82 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms.context; + +import javax.jms.Destination; +import javax.jms.Message; +import javax.jms.Session; + +import org.apache.tuscany.sca.binding.jms.provider.JMSResourceFactory; + + +/** + * Context that the JMS binding puts on the Tuscany wire + * + * @version $Rev$ $Date$ + */ +public class JMSBindingContext { + + private Message jmsMsg; + private Session jmsSession; + private Destination requestDestination; + private Destination replyToDestination; + private JMSResourceFactory jmsResourceFactory; + + public Message getJmsMsg() { + return jmsMsg; + } + + public void setJmsMsg(Message jmsMsg) { + this.jmsMsg = jmsMsg; + } + + public Session getJmsSession() { + return jmsSession; + } + + public void setJmsSession(Session jmsSession) { + this.jmsSession = jmsSession; + } + + public Destination getRequestDestination() { + return requestDestination; + } + + public void setRequestDestination(Destination requestDestination) { + this.requestDestination = requestDestination; + } + + public Destination getReplyToDestination() { + return replyToDestination; + } + + public void setReplyToDestination(Destination replyToDestination) { + this.replyToDestination = replyToDestination; + } + + // TODO - difficult to get the resource factory into all the JMS providers + // so it's here for the moment + public JMSResourceFactory getJmsResourceFactory() { + return jmsResourceFactory; + } + + public void setJmsResourceFactory(JMSResourceFactory jmsResourceFactory) { + this.jmsResourceFactory = jmsResourceFactory; + } +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/headers/HeaderReferenceInterceptor.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/headers/HeaderReferenceInterceptor.java new file mode 100644 index 0000000000..8a73627ba3 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/headers/HeaderReferenceInterceptor.java @@ -0,0 +1,174 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms.headers; + + + + +import java.util.Map; + +import javax.jms.DeliveryMode; +import javax.jms.JMSException; +import javax.jms.Session; + +import org.apache.tuscany.sca.assembly.Reference; +import org.apache.tuscany.sca.assembly.WireFormat; +import org.apache.tuscany.sca.binding.jms.context.JMSBindingContext; +import org.apache.tuscany.sca.binding.jms.impl.JMSBinding; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingConstants; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingException; +import org.apache.tuscany.sca.binding.jms.provider.JMSBindingServiceBindingProvider; +import org.apache.tuscany.sca.binding.jms.provider.JMSMessageProcessor; +import org.apache.tuscany.sca.binding.jms.provider.JMSMessageProcessorUtil; +import org.apache.tuscany.sca.binding.jms.provider.JMSResourceFactory; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.interfacedef.java.JavaInterface; +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.runtime.ReferenceParameters; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; +import org.apache.tuscany.sca.runtime.RuntimeWire; + +/** + * + * @version $Rev$ $Date$ + */ +public class HeaderReferenceInterceptor implements Interceptor { + + private Invoker next; + private RuntimeWire runtimeWire; + private JMSResourceFactory jmsResourceFactory; + private JMSBinding jmsBinding; + private JMSMessageProcessor requestMessageProcessor; + private JMSMessageProcessor responseMessageProcessor; + private String correlationScheme; + private WireFormat requestWireFormat; + private WireFormat responseWireFormat; + + public HeaderReferenceInterceptor(JMSBinding jmsBinding, JMSResourceFactory jmsResourceFactory, RuntimeWire runtimeWire) { + super(); + this.jmsBinding = jmsBinding; + this.runtimeWire = runtimeWire; + this.jmsResourceFactory = jmsResourceFactory; + this.requestMessageProcessor = JMSMessageProcessorUtil.getRequestMessageProcessor(jmsBinding); + this.responseMessageProcessor = JMSMessageProcessorUtil.getResponseMessageProcessor(jmsBinding); + this.correlationScheme = jmsBinding.getCorrelationScheme(); + + } + + public Message invoke(Message msg) { + + return next.invoke(invokeRequest(msg)); + + } + + public Message invokeRequest(Message tuscanyMsg) { + try { + // get the jms context + JMSBindingContext context = (JMSBindingContext)tuscanyMsg.getHeaders().get(JMSBindingConstants.MSG_CTXT_POSITION); + javax.jms.Message jmsMsg = (javax.jms.Message)tuscanyMsg.getBody(); + + Operation operation = tuscanyMsg.getOperation(); + String operationName = operation.getName(); + RuntimeComponentReference reference = (RuntimeComponentReference)runtimeWire.getSource().getContract(); + + requestMessageProcessor.setOperationName(jmsBinding.getNativeOperationName(operationName), jmsMsg); + + if (jmsBinding.getOperationJMSDeliveryMode(operationName) != null) { + if (jmsBinding.getOperationJMSDeliveryMode(operationName)) { + jmsMsg.setJMSDeliveryMode(DeliveryMode.PERSISTENT); + } else { + jmsMsg.setJMSDeliveryMode(DeliveryMode.NON_PERSISTENT); + } + } + + if (jmsBinding.getOperationJMSCorrelationId(operationName) != null) { + jmsMsg.setJMSCorrelationID(jmsBinding.getOperationJMSCorrelationId(operationName)); + } + + if (jmsBinding.getOperationJMSPriority(operationName) != null) { + jmsMsg.setJMSPriority(jmsBinding.getOperationJMSPriority(operationName)); + } + + if (jmsBinding.getOperationJMSType(operationName) != null) { + jmsMsg.setJMSType(jmsBinding.getOperationJMSType(operationName)); + } + + ReferenceParameters parameters = tuscanyMsg.getFrom().getReferenceParameters(); + + Object conversationID = parameters.getConversationID(); + if (conversationID != null) { + jmsMsg.setStringProperty(JMSBindingConstants.CONVERSATION_ID_PROPERTY, conversationID.toString()); + } + + if (tuscanyMsg.getFrom().getCallbackEndpoint() != null) { + + if (parameters.getCallbackID() != null) { + jmsMsg.setStringProperty(JMSBindingConstants.CALLBACK_ID_PROPERTY, parameters.getCallbackID().toString()); + } + + String callbackDestName = getCallbackDestinationName(reference); + if (callbackDestName != null) { + jmsMsg.setStringProperty(JMSBindingConstants.CALLBACK_Q_PROPERTY, callbackDestName); + } + } + + for (String propName : jmsBinding.getPropertyNames()) { + Object value = jmsBinding.getProperty(propName); + jmsMsg.setObjectProperty(propName, value); + } + + Map operationProperties = jmsBinding.getOperationProperties(operationName); + if (operationProperties != null) { + for (String propName : operationProperties.keySet()) { + Object value = operationProperties.get(propName); + jmsMsg.setObjectProperty(propName, value); + } + } + + return tuscanyMsg; + } catch (JMSException e) { + throw new JMSBindingException(e); + } + } + + + protected String getCallbackDestinationName(RuntimeComponentReference reference) { + RuntimeComponentService s = (RuntimeComponentService)reference.getCallbackService(); + JMSBinding b = s.getBinding(JMSBinding.class); + if (b != null) { + JMSBindingServiceBindingProvider bp = (JMSBindingServiceBindingProvider)s.getBindingProvider(b); + return bp.getDestinationName(); + } + return null; + } + + + public Invoker getNext() { + return next; + } + + public void setNext(Invoker next) { + this.next = next; + } + + +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/operationselector/jmsdefault/OperationSelectorJMSDefaultProviderFactory.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/operationselector/jmsdefault/OperationSelectorJMSDefaultProviderFactory.java new file mode 100644 index 0000000000..a4d0ccafb3 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/operationselector/jmsdefault/OperationSelectorJMSDefaultProviderFactory.java @@ -0,0 +1,68 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.jms.operationselector.jmsdefault; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.binding.jms.impl.JMSBinding; +import org.apache.tuscany.sca.binding.jms.provider.JMSResourceFactory; +import org.apache.tuscany.sca.binding.jms.provider.JMSResourceFactoryExtensionPoint; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.provider.OperationSelectorProvider; +import org.apache.tuscany.sca.provider.OperationSelectorProviderFactory; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; + +/** + * @version $Rev$ $Date$ + */ +public class OperationSelectorJMSDefaultProviderFactory implements OperationSelectorProviderFactory { + private ExtensionPointRegistry registry; + + public OperationSelectorJMSDefaultProviderFactory(ExtensionPointRegistry registry) { + super(); + this.registry = registry; + } + + /** + */ + public OperationSelectorProvider createReferenceOperationSelectorProvider(RuntimeComponent component, + RuntimeComponentReference reference, + Binding binding) { + return null; + } + + /** + */ + public OperationSelectorProvider createServiceOperationSelectorProvider(RuntimeComponent component, + RuntimeComponentService service, + Binding binding) { + return new OperationSelectorJMSDefaultServiceProvider(component, service, binding); + } + + /** + * @see org.apache.tuscany.sca.provider.ProviderFactory#getModelType() + */ + public Class getModelType() { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/operationselector/jmsdefault/OperationSelectorJMSDefaultServiceInterceptor.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/operationselector/jmsdefault/OperationSelectorJMSDefaultServiceInterceptor.java new file mode 100644 index 0000000000..d765e08d79 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/operationselector/jmsdefault/OperationSelectorJMSDefaultServiceInterceptor.java @@ -0,0 +1,167 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms.operationselector.jmsdefault; + +import java.util.List; + +import javax.jms.Destination; +import javax.jms.JMSException; +import javax.jms.MessageProducer; +import javax.jms.Queue; +import javax.jms.Session; +import javax.jms.Topic; + +import org.apache.tuscany.sca.binding.jms.context.JMSBindingContext; +import org.apache.tuscany.sca.binding.jms.impl.JMSBinding; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingConstants; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingException; +import org.apache.tuscany.sca.binding.jms.provider.JMSMessageProcessor; +import org.apache.tuscany.sca.binding.jms.provider.JMSMessageProcessorUtil; +import org.apache.tuscany.sca.binding.jms.provider.JMSResourceFactory; +import org.apache.tuscany.sca.core.assembly.EndpointReferenceImpl; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.runtime.ReferenceParameters; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; +import org.apache.tuscany.sca.runtime.RuntimeWire; + +/** + * Policy handler to handle PolicySet related to Logging with the QName + * {http://tuscany.apache.org/xmlns/sca/1.0/impl/java}LoggingPolicy + * + * @version $Rev$ $Date$ + */ +public class OperationSelectorJMSDefaultServiceInterceptor implements Interceptor { + + private static final String ON_MESSAGE_METHOD_NAME = "onMessage"; + + private Invoker next; + private RuntimeWire runtimeWire; + private JMSResourceFactory jmsResourceFactory; + private JMSBinding jmsBinding; + private JMSMessageProcessor requestMessageProcessor; + private JMSMessageProcessor responseMessageProcessor; + private RuntimeComponentService service; + private List serviceOperations; + + + public OperationSelectorJMSDefaultServiceInterceptor(JMSBinding jmsBinding, JMSResourceFactory jmsResourceFactory, RuntimeWire runtimeWire) { + super(); + this.jmsBinding = jmsBinding; + this.runtimeWire = runtimeWire; + this.jmsResourceFactory = jmsResourceFactory; + this.requestMessageProcessor = JMSMessageProcessorUtil.getRequestMessageProcessor(jmsBinding); + this.responseMessageProcessor = JMSMessageProcessorUtil.getResponseMessageProcessor(jmsBinding); + this.service = (RuntimeComponentService)runtimeWire.getTarget().getContract(); + this.serviceOperations = service.getInterfaceContract().getInterface().getOperations(); + } + + public Message invoke(Message msg) { + return next.invoke(invokeRequest(msg)); + } + + public Message invokeRequest(Message msg) { + try { + // get the jms context + JMSBindingContext context = (JMSBindingContext)msg.getHeaders().get(JMSBindingConstants.MSG_CTXT_POSITION); + javax.jms.Message jmsMsg = context.getJmsMsg(); + + String operationName = requestMessageProcessor.getOperationName(jmsMsg); + Operation operation = getTargetOperation(operationName); + msg.setOperation(operation); + + ReferenceParameters parameters = msg.getFrom().getReferenceParameters(); + + if (service.getInterfaceContract().getCallbackInterface() != null) { + + String callbackdestName = jmsMsg.getStringProperty(JMSBindingConstants.CALLBACK_Q_PROPERTY); + if (callbackdestName == null && msg.getOperation().isNonBlocking()) { + // if the request has a replyTo but this service operation is oneway but the service uses callbacks + // then use the replyTo as the callback destination + Destination replyTo = jmsMsg.getJMSReplyTo(); + if (replyTo != null) { + callbackdestName = (replyTo instanceof Queue) ? ((Queue)replyTo).getQueueName() : ((Topic)replyTo).getTopicName(); + } + } + + if (callbackdestName != null) { + // append "jms:" to make it an absolute uri so the invoker can determine it came in on the request + // as otherwise the invoker should use the uri from the service callback binding + parameters.setCallbackReference(new EndpointReferenceImpl("jms:" + callbackdestName)); + } + + String callbackID = jmsMsg.getStringProperty(JMSBindingConstants.CALLBACK_ID_PROPERTY); + if (callbackID != null) { + parameters.setCallbackID(callbackID); + } + } + + return msg; + } catch (JMSException e) { + throw new JMSBindingException(e); + } + } + + protected Operation getTargetOperation(String operationName) { + Operation operation = null; + + if (serviceOperations.size() == 1) { + + // SCA JMS Binding Specification - Rule 1.5.1 line 203 + operation = serviceOperations.get(0); + + } else if (operationName != null) { + + // SCA JMS Binding Specification - Rule 1.5.1 line 205 + for (Operation op : serviceOperations) { + if (op.getName().equals(operationName)) { + operation = op; + break; + } + } + + } else { + + // SCA JMS Binding Specification - Rule 1.5.1 line 207 + for (Operation op : serviceOperations) { + if (op.getName().equals(ON_MESSAGE_METHOD_NAME)) { + operation = op; + break; + } + } + } + + if (operation == null) { + throw new JMSBindingException("Can't find operation " + (operationName != null ? operationName : ON_MESSAGE_METHOD_NAME)); + } + + return operation; + } + + public Invoker getNext() { + return next; + } + + public void setNext(Invoker next) { + this.next = next; + } + +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/operationselector/jmsdefault/OperationSelectorJMSDefaultServiceProvider.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/operationselector/jmsdefault/OperationSelectorJMSDefaultServiceProvider.java new file mode 100644 index 0000000000..54c3eb54eb --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/operationselector/jmsdefault/OperationSelectorJMSDefaultServiceProvider.java @@ -0,0 +1,59 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.jms.operationselector.jmsdefault; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.binding.jms.impl.JMSBinding; +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.Phase; +import org.apache.tuscany.sca.provider.OperationSelectorProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; + +/** + * @version $Rev$ $Date$ + */ +public class OperationSelectorJMSDefaultServiceProvider implements OperationSelectorProvider { + private RuntimeComponent component; + private RuntimeComponentService service; + private Binding binding; + + public OperationSelectorJMSDefaultServiceProvider(RuntimeComponent component, RuntimeComponentService service, Binding binding) { + super(); + this.component = component; + this.service = service; + this.binding = binding; + } + + /** + */ + public Interceptor createInterceptor() { + return new OperationSelectorJMSDefaultServiceInterceptor((JMSBinding)binding, + null, + service.getRuntimeWire(binding)); + } + + /** + */ + public String getPhase() { + return Phase.SERVICE_BINDING_OPERATION_SELECTOR; + } + +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/AbstractMessageProcessor.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/AbstractMessageProcessor.java new file mode 100644 index 0000000000..d73b51e9ae --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/AbstractMessageProcessor.java @@ -0,0 +1,117 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms.provider; + +import javax.jms.JMSException; +import javax.jms.Message; +import javax.jms.ObjectMessage; +import javax.jms.Session; + +import org.apache.tuscany.sca.binding.jms.JMSBinding; +import org.apache.tuscany.sca.binding.jms.JMSBindingException; +import org.apache.tuscany.sca.binding.jms.xml.JMSBindingConstants; +import org.oasisopen.sca.ServiceRuntimeException; + +/** + * Base MessageProcessor for the JMSBinding. + * + * @version $Rev$ $Date$ + */ +public abstract class AbstractMessageProcessor implements JMSMessageProcessor { + + protected String operationPropertyName; + protected boolean xmlFormat = true; + + public AbstractMessageProcessor(JMSBinding jmsBinding) { + this.operationPropertyName = jmsBinding.getOperationSelectorPropertyName(); + } + + /* + * (non-Javadoc) + * + * @see org.apache.tuscany.binding.jms.OperationAndDataBinding#getOperationName(javax.jms.Message) + */ + public String getOperationName(Message message) { + try { + + return message.getStringProperty(operationPropertyName); + + } catch (JMSException e) { + throw new JMSBindingException("Exception retreiving operation name from message", e); + } + } + + /* + * (non-Javadoc) + * + * @see org.apache.tuscany.binding.jms.OperationAndDataBinding#setOperationName(javax.jms.Message, java.lang.String) + */ + public void setOperationName(String operationName, Message message) { + try { + + message.setStringProperty(operationPropertyName, operationName); + + } catch (JMSException e) { + throw new JMSBindingException("Exception setting the operation name on message", e); + } + } + + /* + * (non-Javadoc) + * + * @see org.apache.tuscany.binding.jms.OperationAndDataBinding#extractPayload(javax.jms.Session, java.lang.Object) + */ + public Message insertPayloadIntoJMSMessage(Session session, Object o) { + return createJMSMessage(session, o); + } + + /* + * (non-Javadoc) + * + * @see org.apache.tuscany.binding.jms.OperationAndDataBinding#extractPayload(javax.jms.Message) + */ + public Object extractPayloadFromJMSMessage(Message msg) { + try { + if (msg.getBooleanProperty(JMSBindingConstants.FAULT_PROPERTY)) { + throw new ServiceRuntimeException("remote service exception, see nested exception", (Throwable)((ObjectMessage)msg).getObject()); + } + } catch (JMSException e) { + throw new JMSBindingException(e); + } + return extractPayload(msg); + } + + public Message createFaultMessage(Session session, Throwable o) { + try { + + ObjectMessage message = session.createObjectMessage(); + message.setObject(o); + message.setBooleanProperty(JMSBindingConstants.FAULT_PROPERTY, true); + return message; + + } catch (JMSException e) { + throw new JMSBindingException(e); + } + } + + protected abstract Object[] extractPayload(Message msg); + + protected abstract Message createJMSMessage(Session session, Object o); + +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/BytesMessageProcessor.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/BytesMessageProcessor.java new file mode 100644 index 0000000000..44b2e3b990 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/BytesMessageProcessor.java @@ -0,0 +1,75 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms.provider; + +import javax.jms.BytesMessage; +import javax.jms.JMSException; +import javax.jms.Message; +import javax.jms.Session; +import javax.jms.TextMessage; + +import org.apache.tuscany.sca.binding.jms.impl.JMSBinding; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingException; + +/** + * MessageProcessor for sending/receiving javax.jms.BytesMessage with the JMSBinding. + * + * @version $Rev$ $Date$ + */ +public class BytesMessageProcessor extends AbstractMessageProcessor { + + public BytesMessageProcessor(JMSBinding jmsBinding) { + super(jmsBinding); + } + + @Override + protected Object[] extractPayload(Message msg) { + try { + + if (!(msg instanceof BytesMessage)) { + throw new IllegalStateException("expecting JMS BytesMessage: " + msg); + } + + long noOfBytes = ((BytesMessage)msg).getBodyLength(); + byte [] bytes = new byte[(int)noOfBytes]; + ((BytesMessage)msg).readBytes(bytes); + return new Object[] {bytes}; + + } catch (JMSException e) { + throw new JMSBindingException(e); + } + } + + @Override + protected Message createJMSMessage(Session session, Object o) { + try { + + // TODO - an experiment. How to enforce a single + // byte array parameter + BytesMessage message = session.createBytesMessage(); + byte [] bytes = (byte[])((Object[])o)[0]; + message.writeBytes(bytes); + return message; + + } catch (JMSException e) { + throw new JMSBindingException(e); + } + } + +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/DefaultJMSBindingListener.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/DefaultJMSBindingListener.java new file mode 100644 index 0000000000..9b8bee92c9 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/DefaultJMSBindingListener.java @@ -0,0 +1,266 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms.provider; + +import java.lang.reflect.InvocationTargetException; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; + +import javax.jms.Destination; +import javax.jms.JMSException; +import javax.jms.Message; +import javax.jms.MessageListener; +import javax.jms.MessageProducer; +import javax.jms.Queue; +import javax.jms.Session; +import javax.jms.Topic; +import javax.naming.NamingException; +import javax.security.auth.Subject; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.binding.jms.impl.JMSBinding; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingConstants; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingException; +import org.apache.tuscany.sca.binding.jms.policy.authentication.token.JMSTokenAuthenticationPolicy; +import org.apache.tuscany.sca.core.assembly.EndpointReferenceImpl; +import org.apache.tuscany.sca.core.invocation.MessageImpl; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.policy.PolicySet; +import org.apache.tuscany.sca.policy.PolicySetAttachPoint; +import org.apache.tuscany.sca.policy.SecurityUtil; +import org.apache.tuscany.sca.policy.authentication.token.TokenPrincipal; +import org.apache.tuscany.sca.runtime.EndpointReference; +import org.apache.tuscany.sca.runtime.ReferenceParameters; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; + +/** + * Listener for the JMSBinding. + * + * @version $Rev$ $Date$ + */ +public class DefaultJMSBindingListener implements MessageListener { + + private static final Logger logger = Logger.getLogger(DefaultJMSBindingListener.class.getName()); + + private static final String ON_MESSAGE_METHOD_NAME = "onMessage"; + private JMSBinding jmsBinding; + private Binding targetBinding; + private JMSResourceFactory jmsResourceFactory; + private RuntimeComponentService service; + private JMSMessageProcessor requestMessageProcessor; + private JMSMessageProcessor responseMessageProcessor; + private String correlationScheme; + private List serviceOperations; + protected JMSTokenAuthenticationPolicy jmsTokenAuthenticationPolicy = null; + + public DefaultJMSBindingListener(JMSBinding jmsBinding, JMSResourceFactory jmsResourceFactory, RuntimeComponentService service, Binding targetBinding) throws NamingException { + this.jmsBinding = jmsBinding; + this.jmsResourceFactory = jmsResourceFactory; + this.service = service; + this.targetBinding = targetBinding; + requestMessageProcessor = JMSMessageProcessorUtil.getRequestMessageProcessor(jmsBinding); + responseMessageProcessor = JMSMessageProcessorUtil.getResponseMessageProcessor(jmsBinding); + correlationScheme = jmsBinding.getCorrelationScheme(); + serviceOperations = service.getInterfaceContract().getInterface().getOperations(); + + // find out which policies are active + if (jmsBinding instanceof PolicySetAttachPoint) { + List policySets = ((PolicySetAttachPoint)jmsBinding).getApplicablePolicySets(); + for (PolicySet ps : policySets) { + for (Object p : ps.getPolicies()) { + if (JMSTokenAuthenticationPolicy.class.isInstance(p)) { + jmsTokenAuthenticationPolicy = (JMSTokenAuthenticationPolicy)p; + }else { + // etc. check for other types of policy being present + } + } + } + } + + } + + public void onMessage(Message requestJMSMsg) { + logger.log(Level.FINE, "JMS service '" + service.getName() + "' received message " + requestJMSMsg); + try { + Object responsePayload = invokeService(requestJMSMsg); + sendReply(requestJMSMsg, responsePayload, false); + } catch (Throwable e) { + logger.log(Level.SEVERE, "Exception invoking service '" + service.getName(), e); + sendReply(requestJMSMsg, e, true); + } + } + + /** + * Turn the JMS message back into a Tuscany message and invoke the target component + * + * @param requestJMSMsg + * @return + * @throws JMSException + * @throws InvocationTargetException + */ + protected Object invokeService(Message requestJMSMsg) throws JMSException, InvocationTargetException { + + String operationName = requestMessageProcessor.getOperationName(requestJMSMsg); + Operation operation = getTargetOperation(operationName); + + MessageImpl tuscanyMsg = new MessageImpl(); + tuscanyMsg.setOperation(operation); + if ("onMessage".equals(operation.getName())) { + tuscanyMsg.setBody(new Object[]{requestJMSMsg}); + } else { + Object requestPayload = requestMessageProcessor.extractPayloadFromJMSMessage(requestJMSMsg); + tuscanyMsg.setBody(requestPayload); + } + + setHeaderProperties(requestJMSMsg, tuscanyMsg, operation); + + return service.getRuntimeWire(targetBinding).invoke(operation, tuscanyMsg); + } + + protected Operation getTargetOperation(String operationName) { + Operation operation = null; + + if (serviceOperations.size() == 1) { + + // SCA JMS Binding Specification - Rule 1.5.1 line 203 + operation = serviceOperations.get(0); + + } else if (operationName != null) { + + // SCA JMS Binding Specification - Rule 1.5.1 line 205 + for (Operation op : serviceOperations) { + if (op.getName().equals(operationName)) { + operation = op; + break; + } + } + + } else { + + // SCA JMS Binding Specification - Rule 1.5.1 line 207 + for (Operation op : serviceOperations) { + if (op.getName().equals(ON_MESSAGE_METHOD_NAME)) { + operation = op; + break; + } + } + } + + if (operation == null) { + throw new JMSBindingException("Can't find operation " + (operationName != null ? operationName : ON_MESSAGE_METHOD_NAME)); + } + + return operation; + } + + protected void setHeaderProperties(Message requestJMSMsg, MessageImpl tuscanyMsg, Operation operation) throws JMSException { + + EndpointReference from = new EndpointReferenceImpl(null); + tuscanyMsg.setFrom(from); + from.setCallbackEndpoint(new EndpointReferenceImpl("/")); // TODO: whats this for? + ReferenceParameters parameters = from.getReferenceParameters(); + + String conversationID = requestJMSMsg.getStringProperty(JMSBindingConstants.CONVERSATION_ID_PROPERTY); + if (conversationID != null) { + parameters.setConversationID(conversationID); + } + + if (service.getInterfaceContract().getCallbackInterface() != null) { + + String callbackdestName = requestJMSMsg.getStringProperty(JMSBindingConstants.CALLBACK_Q_PROPERTY); + if (callbackdestName == null && operation.isNonBlocking()) { + // if the request has a replyTo but this service operation is oneway but the service uses callbacks + // then use the replyTo as the callback destination + Destination replyTo = requestJMSMsg.getJMSReplyTo(); + if (replyTo != null) { + callbackdestName = (replyTo instanceof Queue) ? ((Queue)replyTo).getQueueName() : ((Topic)replyTo).getTopicName(); + } + } + + if (callbackdestName != null) { + // append "jms:" to make it an absolute uri so the invoker can determine it came in on the request + // as otherwise the invoker should use the uri from the service callback binding + parameters.setCallbackReference(new EndpointReferenceImpl("jms:" + callbackdestName)); + } + + String callbackID = requestJMSMsg.getStringProperty(JMSBindingConstants.CALLBACK_ID_PROPERTY); + if (callbackID != null) { + parameters.setCallbackID(callbackID); + } + } + + if (jmsTokenAuthenticationPolicy != null) { + String token = requestJMSMsg.getStringProperty(jmsTokenAuthenticationPolicy.getTokenName().toString()); + + Subject subject = SecurityUtil.getSubject(tuscanyMsg); + TokenPrincipal principal = SecurityUtil.getPrincipal(subject, TokenPrincipal.class); + + if (principal == null){ + principal = new TokenPrincipal(token); + subject.getPrincipals().add(principal); + } + + } + } + + protected void sendReply(Message requestJMSMsg, Object responsePayload, boolean isFault) { + try { + + if (requestJMSMsg.getJMSReplyTo() == null) { + // assume no reply is expected + if (responsePayload != null) { + logger.log(Level.FINE, "JMS service '" + service.getName() + "' dropped response as request has no replyTo"); + } + return; + } + + Session session = jmsResourceFactory.createSession(); + Message replyJMSMsg; + if (isFault) { + replyJMSMsg = responseMessageProcessor.createFaultMessage(session, (Throwable)responsePayload); + } else { + replyJMSMsg = responseMessageProcessor.insertPayloadIntoJMSMessage(session, responsePayload); + } + + replyJMSMsg.setJMSDeliveryMode(requestJMSMsg.getJMSDeliveryMode()); + replyJMSMsg.setJMSPriority(requestJMSMsg.getJMSPriority()); + + if (correlationScheme == null || JMSBindingConstants.CORRELATE_MSG_ID.equalsIgnoreCase(correlationScheme)) { + replyJMSMsg.setJMSCorrelationID(requestJMSMsg.getJMSMessageID()); + } else if (JMSBindingConstants.CORRELATE_CORRELATION_ID.equalsIgnoreCase(correlationScheme)) { + replyJMSMsg.setJMSCorrelationID(requestJMSMsg.getJMSCorrelationID()); + } + + Destination destination = requestJMSMsg.getJMSReplyTo(); + MessageProducer producer = session.createProducer(destination); + + producer.send(replyJMSMsg); + + producer.close(); + session.close(); + + } catch (JMSException e) { + throw new JMSBindingException(e); + } catch (NamingException e) { + throw new JMSBindingException(e); + } + } + +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/DefaultJMSResourceFactoryExtensionPoint.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/DefaultJMSResourceFactoryExtensionPoint.java new file mode 100644 index 0000000000..499f69a24b --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/DefaultJMSResourceFactoryExtensionPoint.java @@ -0,0 +1,30 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.jms.provider; + +import org.apache.tuscany.sca.binding.jms.impl.JMSBinding; + +public class DefaultJMSResourceFactoryExtensionPoint implements JMSResourceFactoryExtensionPoint { + + public JMSResourceFactory createJMSResourceFactory(JMSBinding binding) { + return new JMSResourceFactoryImpl(binding.getConnectionFactoryName(), binding.getInitialContextFactoryName(), binding.getJndiURL()); + } + +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/JMSBindingInvoker.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/JMSBindingInvoker.java new file mode 100644 index 0000000000..998ac904a8 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/JMSBindingInvoker.java @@ -0,0 +1,467 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms.provider; + +import java.lang.reflect.InvocationTargetException; +import java.util.List; +import java.util.Map; + +import javax.jms.DeliveryMode; +import javax.jms.Destination; +import javax.jms.JMSException; +import javax.jms.Message; +import javax.jms.MessageConsumer; +import javax.jms.MessageProducer; +import javax.jms.Session; +import javax.naming.NamingException; +import javax.security.auth.Subject; + +import org.apache.tuscany.sca.binding.jms.JMSBinding; +import org.apache.tuscany.sca.binding.jms.JMSBindingException; +import org.apache.tuscany.sca.binding.jms.xml.JMSBindingConstants; +import org.apache.tuscany.sca.binding.jms.policy.authentication.token.JMSTokenAuthenticationPolicy; +import org.apache.tuscany.sca.binding.jms.policy.header.JMSHeaderPolicy; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.interfacedef.java.JavaInterface; +import org.apache.tuscany.sca.invocation.DataExchangeSemantics; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.policy.PolicySet; +import org.apache.tuscany.sca.policy.PolicySetAttachPoint; +import org.apache.tuscany.sca.policy.SecurityUtil; +import org.apache.tuscany.sca.policy.authentication.token.TokenPrincipal; +import org.apache.tuscany.sca.runtime.ReferenceParameters; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; +import org.oasisopen.sca.ServiceRuntimeException; + +/** + * Invoker for the JMS binding. + * + * @version $Rev$ $Date$ + */ +public class JMSBindingInvoker implements Invoker, DataExchangeSemantics { + + protected Operation operation; + protected String operationName; + + protected JMSBinding jmsBinding; + protected JMSResourceFactory jmsResourceFactory; + protected JMSMessageProcessor requestMessageProcessor; + protected JMSMessageProcessor responseMessageProcessor; + protected Destination bindingRequestDest; + protected Destination bindingReplyDest; + protected RuntimeComponentReference reference; + protected JMSTokenAuthenticationPolicy jmsTokenAuthenticationPolicy = null; + protected JMSHeaderPolicy jmsHeaderPolicy = null; + + public JMSBindingInvoker(JMSBinding jmsBinding, Operation operation, JMSResourceFactory jmsResourceFactory, RuntimeComponentReference reference) { + + this.operation = operation; + operationName = operation.getName(); + + this.jmsBinding = jmsBinding; + this.jmsResourceFactory = jmsResourceFactory; + this.reference = reference; + this.requestMessageProcessor = JMSMessageProcessorUtil.getRequestMessageProcessor(jmsBinding); + this.responseMessageProcessor = JMSMessageProcessorUtil.getResponseMessageProcessor(jmsBinding); + + // find out which policies are active + if (jmsBinding instanceof PolicySetAttachPoint) { + List policySets = ((PolicySetAttachPoint)jmsBinding).getApplicablePolicySets(); + for (PolicySet ps : policySets) { + for (Object p : ps.getPolicies()) { + if (JMSTokenAuthenticationPolicy.class.isInstance(p)) { + jmsTokenAuthenticationPolicy = (JMSTokenAuthenticationPolicy)p; + }else if (JMSTokenAuthenticationPolicy.class.isInstance(p)) { + jmsHeaderPolicy = (JMSHeaderPolicy)p; + } else { + // etc. check for other types of policy being present + } + } + } + } + + try { + + bindingRequestDest = lookupDestination(); + bindingReplyDest = lookupResponseDestination(); + + } catch (NamingException e) { + throw new JMSBindingException(e); + } + + } + + /** + * Looks up the Destination Queue for the JMS Binding + * + * @return The Destination Queue + * @throws NamingException Failed to lookup Destination Queue + * @throws JMSBindingException Failed to lookup Destination Queue + * @see #lookupDestinationQueue(boolean) + */ + protected Destination lookupDestination() throws NamingException, JMSBindingException { + return lookupDestinationQueue(false); + } + + /** + * Looks up the Destination Response Queue for the JMS Binding + * + * @return The Destination Response Queue + * @throws NamingException Failed to lookup Destination Response Queue + * @throws JMSBindingException Failed to lookup Destination Response Queue + * @see #lookupDestinationQueue(boolean) + */ + protected Destination lookupResponseDestination() throws NamingException, JMSBindingException { + return lookupDestinationQueue(true); + } + + /** + * Looks up the Destination Queue for the JMS Binding. + *

+ * What happens in the look up will depend on the create mode specified for the JMS Binding: + *

    + *
  • always - the JMS queue is always created. It is an error if the queue already exists + *
  • ifnotexist - the JMS queue is created if it does not exist. It is not an error if the queue already exists + *
  • never - the JMS queue is never created. It is an error if the queue does not exist + *
+ * See the SCA JMS Binding specification for more information. + *

+ * + * @param isReponseQueue true if we are creating a response queue. + * false if we are creating a request queue + * @return The Destination queue. + * @throws NamingException Failed to lookup JMS queue + * @throws JMSBindingException Failed to lookup JMS Queue. Probable cause is that + * the JMS queue's current existence/non-existence is not compatible with + * the create mode specified on the binding + */ + protected Destination lookupDestinationQueue(boolean isReponseQueue) throws NamingException, JMSBindingException { + String queueName; + String queueType; + String qCreateMode; + + if (isReponseQueue) { + queueName = jmsBinding.getResponseDestinationName(); + queueType = "JMS Response Destination "; + qCreateMode = jmsBinding.getResponseDestinationCreate(); + if (JMSBindingConstants.DEFAULT_RESPONSE_DESTINATION_NAME.equals(queueName)) { + return null; + } + } else { + queueName = jmsBinding.getDestinationName(); + queueType = "JMS Destination "; + qCreateMode = jmsBinding.getDestinationCreate(); + } + + Destination dest = jmsResourceFactory.lookupDestination(queueName); + + if (qCreateMode.equals(JMSBindingConstants.CREATE_ALWAYS)) { + // In this mode, the queue must not already exist as we are creating it + if (dest != null) { + throw new JMSBindingException(queueType + queueName + + " already exists but has create mode of \"" + + qCreateMode + + "\" while registering binding " + + jmsBinding.getName() + + " invoker"); + } + // Create the queue + dest = jmsResourceFactory.createDestination(queueName); + + } else if (qCreateMode.equals(JMSBindingConstants.CREATE_IF_NOT_EXIST)) { + // In this mode, the queue may nor may not exist. It will be created if it does not exist + if (dest == null) { + dest = jmsResourceFactory.createDestination(queueName); + } + + } else if (qCreateMode.equals(JMSBindingConstants.CREATE_NEVER)) { + // In this mode, the queue must have already been created. + if (dest == null) { + throw new JMSBindingException(queueType + queueName + + " not found but create mode of \"" + + qCreateMode + + "\" while registering binding " + + jmsBinding.getName() + + " invoker"); + } + } + + // Make sure we ended up with a queue + if (dest == null) { + throw new JMSBindingException(queueType + queueName + + " not found with create mode of \"" + + qCreateMode + + "\" while registering binding " + + jmsBinding.getName() + + " invoker"); + } + + return dest; + } + + public org.apache.tuscany.sca.invocation.Message invoke(org.apache.tuscany.sca.invocation.Message tuscanyMsg) { + try { + + Object resp = invokeTarget(tuscanyMsg); + tuscanyMsg.setBody(resp); + + } catch (InvocationTargetException e) { + tuscanyMsg.setFaultBody(e.getCause()); + } catch (ServiceRuntimeException e) { + if (e.getCause() instanceof InvocationTargetException) { + if ((e.getCause().getCause() instanceof RuntimeException)) { + tuscanyMsg.setFaultBody(e.getCause()); + } else { + tuscanyMsg.setFaultBody(e.getCause().getCause()); + } + } else { + tuscanyMsg.setFaultBody(e); + } + } catch (Throwable e) { + tuscanyMsg.setFaultBody(e); + } + return tuscanyMsg; + } + + protected Object invokeTarget(org.apache.tuscany.sca.invocation.Message tuscanyMsg) throws InvocationTargetException { + try { + Session session = jmsResourceFactory.createSession(); + try { + + Destination replyToDest = getReplyToDestination(session); + + Message requestMsg = sendRequest(tuscanyMsg, session, replyToDest); + + if (replyToDest == null) { + return null; + } else { + Message replyMsg = receiveReply(session, replyToDest, requestMsg.getJMSMessageID()); + Object[] response = (Object[])responseMessageProcessor.extractPayloadFromJMSMessage(replyMsg); + return (response != null && response.length > 0) ? response[0] : null; + } + + } finally { + session.close(); + } + } catch (JMSException e) { + throw new InvocationTargetException(e); + } catch (NamingException e) { + throw new InvocationTargetException(e); + } + } + + protected Destination getReplyToDestination(Session session) throws JMSException, JMSBindingException, NamingException { + Destination replyToDest; + if (operation.isNonBlocking()) { + replyToDest = null; + } else { + if (bindingReplyDest != null) { + replyToDest = bindingReplyDest; + } else { + replyToDest = session.createTemporaryQueue(); + } + } + return replyToDest; + } + + protected Message sendRequest(org.apache.tuscany.sca.invocation.Message tuscanyMsg, Session session, Destination replyToDest) throws JMSException, JMSBindingException, + NamingException { + + Message requestMsg = requestMessageProcessor.insertPayloadIntoJMSMessage(session, tuscanyMsg.getBody()); + + setHeaders(tuscanyMsg, requestMsg); + + requestMsg.setJMSReplyTo(replyToDest); + + Destination requestDest = getRequestDestination(tuscanyMsg, session); + + MessageProducer producer = session.createProducer(requestDest); + + if (jmsBinding.getOperationJMSTimeToLive(operationName) != null) { + producer.setTimeToLive(jmsBinding.getOperationJMSTimeToLive(operationName)); + } + + try { + producer.send(requestMsg); + } finally { + producer.close(); + } + return requestMsg; + } + + protected Destination getRequestDestination(org.apache.tuscany.sca.invocation.Message tuscanyMsg, Session session) throws JMSBindingException, NamingException, JMSException { + Destination requestDestination; + if (reference.isCallback()) { + String toURI = tuscanyMsg.getTo().getURI(); + if (toURI != null && toURI.startsWith("jms:")) { + // the msg to uri contains the callback destination name + // this is an jms physical name not a jndi name so need to use session.createQueue + requestDestination = session.createQueue(toURI.substring(4)); + } else { + requestDestination = lookupDestination(); + } + } else { + requestDestination = bindingRequestDest; + } + + return requestDestination; + } + + protected void setHeaders(org.apache.tuscany.sca.invocation.Message tuscanyMsg, Message jmsMsg) throws JMSException { + + requestMessageProcessor.setOperationName(jmsBinding.getNativeOperationName(operationName), jmsMsg); + + if ((jmsHeaderPolicy != null) && + (jmsHeaderPolicy.getDeliveryModePersistent() != null)) { + if (jmsHeaderPolicy.getDeliveryModePersistent()) { + jmsMsg.setJMSDeliveryMode(DeliveryMode.PERSISTENT); + } else { + jmsMsg.setJMSDeliveryMode(DeliveryMode.NON_PERSISTENT); + } + + } else if (jmsBinding.getOperationJMSDeliveryMode(operationName) != null) { + if (jmsBinding.getOperationJMSDeliveryMode(operationName)) { + jmsMsg.setJMSDeliveryMode(DeliveryMode.PERSISTENT); + } else { + jmsMsg.setJMSDeliveryMode(DeliveryMode.NON_PERSISTENT); + } + } + + if ((jmsHeaderPolicy != null) && + (jmsHeaderPolicy.getJmsCorrelationId() != null)) { + jmsMsg.setJMSCorrelationID(jmsHeaderPolicy.getJmsCorrelationId()); + } else if (jmsBinding.getOperationJMSCorrelationId(operationName) != null) { + jmsMsg.setJMSCorrelationID(jmsBinding.getOperationJMSCorrelationId(operationName)); + } + + if ((jmsHeaderPolicy != null) && + (jmsHeaderPolicy.getJmsPriority() != null)) { + jmsMsg.setJMSPriority(jmsHeaderPolicy.getJmsPriority()); + } else if (jmsBinding.getOperationJMSPriority(operationName) != null) { + jmsMsg.setJMSPriority(jmsBinding.getOperationJMSPriority(operationName)); + } + + if ((jmsHeaderPolicy != null) && + (jmsHeaderPolicy.getJmsType() != null)) { + jmsMsg.setJMSType(jmsHeaderPolicy.getJmsType()); + } else if (jmsBinding.getOperationJMSType(operationName) != null) { + jmsMsg.setJMSType(jmsBinding.getOperationJMSType(operationName)); + } + + ReferenceParameters parameters = tuscanyMsg.getFrom().getReferenceParameters(); + + Object conversationID = parameters.getConversationID(); + if (conversationID != null) { + jmsMsg.setStringProperty(JMSBindingConstants.CONVERSATION_ID_PROPERTY, conversationID.toString()); + } + + if (hasCallback()) { + + if (parameters.getCallbackID() != null) { + jmsMsg.setStringProperty(JMSBindingConstants.CALLBACK_ID_PROPERTY, parameters.getCallbackID().toString()); + } + + String callbackDestName = getCallbackDestinationName(reference); + if (callbackDestName != null) { + jmsMsg.setStringProperty(JMSBindingConstants.CALLBACK_Q_PROPERTY, callbackDestName); + } + } + + if (jmsHeaderPolicy != null){ + for (String propName : jmsHeaderPolicy.getProperties().keySet()) { + jmsMsg.setObjectProperty(propName, jmsHeaderPolicy.getProperties().get(propName)); + } + } + + for (String propName : jmsBinding.getPropertyNames()) { + Object value = jmsBinding.getProperty(propName); + jmsMsg.setObjectProperty(propName, value); + } + + Map operationProperties = jmsBinding.getOperationProperties(operationName); + if (operationProperties != null) { + for (String propName : operationProperties.keySet()) { + Object value = operationProperties.get(propName); + jmsMsg.setObjectProperty(propName, value); + } + } + + if (jmsTokenAuthenticationPolicy != null) { + Subject subject = SecurityUtil.getSubject(tuscanyMsg); + TokenPrincipal principal = SecurityUtil.getPrincipal(subject, TokenPrincipal.class); + if (principal != null){ + jmsMsg.setStringProperty(jmsTokenAuthenticationPolicy.getTokenName().toString(), principal.getName()); + } + } + } + + protected boolean hasCallback() { + if (operation.getInterface() instanceof JavaInterface) { + JavaInterface jiface = (JavaInterface)operation.getInterface(); + if (jiface.getCallbackClass() != null) { + return true; + } + } + return false; + } + + protected Message receiveReply(Session session, Destination replyToDest, String requestMsgId) throws JMSException, NamingException { + String msgSelector = "JMSCorrelationID = '" + requestMsgId + "'"; + MessageConsumer consumer = session.createConsumer(replyToDest, msgSelector); + + long receiveWait; + if ((jmsHeaderPolicy != null) && + (jmsHeaderPolicy.getTimeToLive() != null)) { + receiveWait = jmsHeaderPolicy.getTimeToLive(); + } else if (jmsBinding.getOperationJMSTimeToLive(operationName) != null) { + receiveWait = jmsBinding.getOperationJMSTimeToLive(operationName) * 2; + } else { + receiveWait = JMSBindingConstants.DEFAULT_TIME_TO_LIVE; + } + + Message replyMsg; + try { + jmsResourceFactory.startConnection(); + replyMsg = consumer.receive(receiveWait); + } finally { + consumer.close(); + } + if (replyMsg == null) { + throw new JMSBindingException("No reply message received on " + replyToDest + " for message id " + requestMsgId); + } + return replyMsg; + } + + protected String getCallbackDestinationName(RuntimeComponentReference reference) { + RuntimeComponentService s = (RuntimeComponentService)reference.getCallbackService(); + JMSBinding b = s.getBinding(JMSBinding.class); + if (b != null) { + JMSBindingServiceBindingProvider bp = (JMSBindingServiceBindingProvider)s.getBindingProvider(b); + return bp.getDestinationName(); + } + return null; + } + + public boolean allowsPassByReference() { + // JMS always pass by value + return true; + } + +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/JMSBindingProviderFactory.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/JMSBindingProviderFactory.java new file mode 100644 index 0000000000..adadc51a66 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/JMSBindingProviderFactory.java @@ -0,0 +1,69 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.jms.provider; + +import org.apache.tuscany.sca.binding.jms.JMSBinding; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.core.UtilityExtensionPoint; +import org.apache.tuscany.sca.provider.BindingProviderFactory; +import org.apache.tuscany.sca.provider.ReferenceBindingProvider; +import org.apache.tuscany.sca.provider.ServiceBindingProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; +import org.apache.tuscany.sca.work.WorkScheduler; + +/** + * A factory from creating the JMS binding provider. + * + * @version $Rev$ $Date$ + */ +public class JMSBindingProviderFactory implements BindingProviderFactory { + + private WorkScheduler workScheduler; + private ExtensionPointRegistry extensionPoints; + private JMSResourceFactoryExtensionPoint jmsRFEP; + + public JMSBindingProviderFactory(ExtensionPointRegistry extensionPoints) { + this.extensionPoints = extensionPoints; + UtilityExtensionPoint utilities = extensionPoints.getExtensionPoint(UtilityExtensionPoint.class); + workScheduler = utilities.getUtility(WorkScheduler.class); + + jmsRFEP = (JMSResourceFactoryExtensionPoint)extensionPoints.getExtensionPoint(JMSResourceFactoryExtensionPoint.class); + if (jmsRFEP == null) { + jmsRFEP = new DefaultJMSResourceFactoryExtensionPoint(); + extensionPoints.addExtensionPoint(jmsRFEP); + } + } + + public ReferenceBindingProvider createReferenceBindingProvider(RuntimeComponent component, RuntimeComponentReference reference, JMSBinding binding) { + JMSResourceFactory jmsRF = jmsRFEP.createJMSResourceFactory(binding); + return new JMSBindingReferenceBindingProvider(component, reference, binding, extensionPoints, jmsRF); + } + + public ServiceBindingProvider createServiceBindingProvider(RuntimeComponent component, RuntimeComponentService service, JMSBinding binding) { + JMSResourceFactory jmsRF = jmsRFEP.createJMSResourceFactory(binding); + return new JMSBindingServiceBindingProvider(component, service, binding, binding, workScheduler, extensionPoints, jmsRF); + } + + public Class getModelType() { + return JMSBinding.class; + } +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/JMSBindingReferenceBindingProvider.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/JMSBindingReferenceBindingProvider.java new file mode 100644 index 0000000000..aa66542f38 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/JMSBindingReferenceBindingProvider.java @@ -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. + */ + +package org.apache.tuscany.sca.binding.jms.provider; + +import java.util.ArrayList; +import java.util.List; + +import javax.jms.JMSException; + +import org.apache.axiom.om.OMElement; +import org.apache.tuscany.sca.binding.jms.headers.HeaderReferenceInterceptor; +import org.apache.tuscany.sca.binding.jms.impl.JMSBinding; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingConstants; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingException; +import org.apache.tuscany.sca.binding.jms.operationselector.jmsdefault.OperationSelectorJMSDefault; +import org.apache.tuscany.sca.binding.jms.transport.TransportReferenceInterceptor; +import org.apache.tuscany.sca.binding.jms.wireformat.jmstextxml.WireFormatJMSTextXML; +import org.apache.tuscany.sca.binding.ws.WebServiceBinding; +import org.apache.tuscany.sca.binding.ws.WebServiceBindingFactory; +import org.apache.tuscany.sca.binding.ws.wsdlgen.BindingWSDLGenerator; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.InvocationChain; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Phase; +import org.apache.tuscany.sca.provider.OperationSelectorProvider; +import org.apache.tuscany.sca.provider.OperationSelectorProviderFactory; +import org.apache.tuscany.sca.provider.ProviderFactoryExtensionPoint; +import org.apache.tuscany.sca.provider.ReferenceBindingProvider; +import org.apache.tuscany.sca.provider.ReferenceBindingProviderRRB; +import org.apache.tuscany.sca.provider.WireFormatProvider; +import org.apache.tuscany.sca.provider.WireFormatProviderFactory; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeWire; + +/** + * Implementation of the JMS reference binding provider. + * + * @version $Rev$ $Date$ + */ +public class JMSBindingReferenceBindingProvider implements ReferenceBindingProviderRRB { + + private RuntimeComponentReference reference; + private JMSBinding jmsBinding; + private List jmsBindingInvokers = new ArrayList(); + private JMSResourceFactory jmsResourceFactory; + private RuntimeComponent component; + private InterfaceContract interfaceContract; + private ExtensionPointRegistry extensions; + + private ProviderFactoryExtensionPoint providerFactories; + + private WireFormatProviderFactory requestWireFormatProviderFactory; + private WireFormatProvider requestWireFormatProvider; + + private WireFormatProviderFactory responseWireFormatProviderFactory; + private WireFormatProvider responseWireFormatProvider; + + public JMSBindingReferenceBindingProvider(RuntimeComponent component, RuntimeComponentReference reference, JMSBinding binding, ExtensionPointRegistry extensions, JMSResourceFactory jmsResourceFactory) { + this.reference = reference; + this.jmsBinding = binding; + this.extensions = extensions; + this.component = component; + this.jmsResourceFactory = jmsResourceFactory; + + // Get the factories/providers for operation selection + this.providerFactories = extensions.getExtensionPoint(ProviderFactoryExtensionPoint.class); + + // Get the factories/providers for wire format + this.requestWireFormatProviderFactory = + (WireFormatProviderFactory)providerFactories.getProviderFactory(jmsBinding.getRequestWireFormat().getClass()); + if (this.requestWireFormatProviderFactory != null){ + this.requestWireFormatProvider = requestWireFormatProviderFactory.createReferenceWireFormatProvider(component, reference, jmsBinding); + } + + this.responseWireFormatProviderFactory = + (WireFormatProviderFactory)providerFactories.getProviderFactory(jmsBinding.getResponseWireFormat().getClass()); + if (this.responseWireFormatProviderFactory != null){ + this.responseWireFormatProvider = responseWireFormatProviderFactory.createReferenceWireFormatProvider(component, reference, jmsBinding); + } + } + + public Invoker createInvoker(Operation operation) { + + if (jmsBinding.getDestinationName().equals(JMSBindingConstants.DEFAULT_DESTINATION_NAME)) { + if (!reference.isCallback()) { + throw new JMSBindingException("No destination specified for reference " + reference.getName()); + } + } + + Invoker invoker = null; + invoker = new RRBJMSBindingInvoker(jmsBinding, operation, jmsResourceFactory, reference); + + return invoker; + } + + public boolean supportsOneWayInvocation() { + return true; + } + + public InterfaceContract getBindingInterfaceContract() { + if (interfaceContract == null){ + interfaceContract = this.requestWireFormatProvider.getWireFormatInterfaceContract(); + } + return interfaceContract; + } + + public void start() { + + } + + public void stop() { + try { + jmsResourceFactory.closeConnection(); + } catch (JMSException e) { + throw new JMSBindingException(e); + } + } + + /* + * set up the reference binding wire with the right set of jms reference + * interceptors + */ + public void configureBindingChain(RuntimeWire runtimeWire) { + + InvocationChain bindingChain = runtimeWire.getBindingInvocationChain(); + + // add transport interceptor + bindingChain.addInterceptor(Phase.REFERENCE_BINDING_TRANSPORT, + new TransportReferenceInterceptor(jmsBinding, + jmsResourceFactory, + runtimeWire) ); + + // add request wire format + bindingChain.addInterceptor(requestWireFormatProvider.getPhase(), + requestWireFormatProvider.createInterceptor()); + + // add response wire format, but only add it if it's different from the request + if (!jmsBinding.getRequestWireFormat().equals(jmsBinding.getResponseWireFormat())){ + bindingChain.addInterceptor(responseWireFormatProvider.getPhase(), + responseWireFormatProvider.createInterceptor()); + } + + // add the header processor that comes after the wire formatter + bindingChain.addInterceptor(Phase.REFERENCE_BINDING_WIREFORMAT, + new HeaderReferenceInterceptor(jmsBinding, + jmsResourceFactory, + runtimeWire) ); + } + +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/JMSBindingServiceBindingProvider.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/JMSBindingServiceBindingProvider.java new file mode 100644 index 0000000000..da6c6d260d --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/JMSBindingServiceBindingProvider.java @@ -0,0 +1,359 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.jms.provider; + +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; + +import javax.jms.Destination; +import javax.jms.JMSException; +import javax.jms.Message; +import javax.jms.MessageConsumer; +import javax.jms.MessageListener; +import javax.jms.Queue; +import javax.jms.Session; +import javax.jms.Topic; +import javax.naming.NamingException; + +import org.apache.axiom.om.OMElement; +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.assembly.OperationSelector; +import org.apache.tuscany.sca.assembly.WireFormat; +import org.apache.tuscany.sca.binding.jms.impl.JMSBinding; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingConstants; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingException; +import org.apache.tuscany.sca.binding.jms.operationselector.jmsdefault.OperationSelectorJMSDefault; +import org.apache.tuscany.sca.binding.jms.operationselector.jmsdefault.OperationSelectorJMSDefaultServiceInterceptor; +import org.apache.tuscany.sca.binding.jms.transport.TransportReferenceInterceptor; +import org.apache.tuscany.sca.binding.jms.transport.TransportServiceInterceptor; +import org.apache.tuscany.sca.binding.jms.wireformat.jmstextxml.WireFormatJMSTextXML; +import org.apache.tuscany.sca.binding.ws.WebServiceBinding; +import org.apache.tuscany.sca.binding.ws.WebServiceBindingFactory; +import org.apache.tuscany.sca.binding.ws.wsdlgen.BindingWSDLGenerator; +import org.apache.tuscany.sca.contribution.ModelFactoryExtensionPoint; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.invocation.InvocationChain; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.MessageFactory; +import org.apache.tuscany.sca.invocation.Phase; +import org.apache.tuscany.sca.provider.BindingProviderFactory; +import org.apache.tuscany.sca.provider.OperationSelectorProvider; +import org.apache.tuscany.sca.provider.OperationSelectorProviderFactory; +import org.apache.tuscany.sca.provider.ProviderFactoryExtensionPoint; +import org.apache.tuscany.sca.provider.ServiceBindingProvider; +import org.apache.tuscany.sca.provider.ServiceBindingProviderRRB; +import org.apache.tuscany.sca.provider.WireFormatProvider; +import org.apache.tuscany.sca.provider.WireFormatProviderFactory; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; +import org.apache.tuscany.sca.runtime.RuntimeWire; +import org.apache.tuscany.sca.work.WorkScheduler; + +/** + * Implementation of the JMS service binding provider. + * + * @version $Rev$ $Date$ + */ +public class JMSBindingServiceBindingProvider implements ServiceBindingProviderRRB { + private static final Logger logger = Logger.getLogger(JMSBindingServiceBindingProvider.class.getName()); + + private RuntimeComponentService service; + private Binding targetBinding; + private JMSBinding jmsBinding; + private JMSResourceFactory jmsResourceFactory; + private MessageConsumer consumer; + private WorkScheduler workScheduler; + private boolean running; + + private Destination destination; + + private ExtensionPointRegistry extensionPoints; + + private RuntimeComponent component; + private InterfaceContract wsdlInterfaceContract; + + + private ProviderFactoryExtensionPoint providerFactories; + private ModelFactoryExtensionPoint modelFactories; + + private MessageFactory messageFactory; + + private OperationSelectorProviderFactory operationSelectorProviderFactory; + private OperationSelectorProvider operationSelectorProvider; + + private WireFormatProviderFactory requestWireFormatProviderFactory; + private WireFormatProvider requestWireFormatProvider; + + private WireFormatProviderFactory responseWireFormatProviderFactory; + private WireFormatProvider responseWireFormatProvider; + + public JMSBindingServiceBindingProvider(RuntimeComponent component, RuntimeComponentService service, Binding targetBinding, JMSBinding binding, WorkScheduler workScheduler, ExtensionPointRegistry extensionPoints, JMSResourceFactory jmsResourceFactory) { + this.component = component; + this.service = service; + this.jmsBinding = binding; + this.workScheduler = workScheduler; + this.targetBinding = targetBinding; + this.extensionPoints = extensionPoints; + this.jmsResourceFactory = jmsResourceFactory; + + if (jmsBinding.getDestinationName().equals(JMSBindingConstants.DEFAULT_DESTINATION_NAME)) { + if (!service.isCallback()) { + // use the SCA service name as the default destination name + jmsBinding.setDestinationName(service.getName()); + } + } + + // Get Message factory + modelFactories = extensionPoints.getExtensionPoint(ModelFactoryExtensionPoint.class); + messageFactory = modelFactories.getFactory(MessageFactory.class); + + // Get the factories/providers for operation selection + this.providerFactories = extensionPoints.getExtensionPoint(ProviderFactoryExtensionPoint.class); + this.operationSelectorProviderFactory = + (OperationSelectorProviderFactory)providerFactories.getProviderFactory(jmsBinding.getOperationSelector().getClass()); + if (this.operationSelectorProviderFactory != null){ + this.operationSelectorProvider = operationSelectorProviderFactory.createServiceOperationSelectorProvider(component, service, jmsBinding); + } + + // Get the factories/providers for wire format + this.requestWireFormatProviderFactory = + (WireFormatProviderFactory)providerFactories.getProviderFactory(jmsBinding.getRequestWireFormat().getClass()); + if (this.requestWireFormatProviderFactory != null){ + this.requestWireFormatProvider = requestWireFormatProviderFactory.createServiceWireFormatProvider(component, service, jmsBinding); + } + + this.responseWireFormatProviderFactory = + (WireFormatProviderFactory)providerFactories.getProviderFactory(jmsBinding.getResponseWireFormat().getClass()); + if (this.responseWireFormatProviderFactory != null){ + this.responseWireFormatProvider = responseWireFormatProviderFactory.createServiceWireFormatProvider(component, service, jmsBinding); + } + } + + public InterfaceContract getBindingInterfaceContract() { + return requestWireFormatProvider.getWireFormatInterfaceContract(); + } + + public boolean supportsOneWayInvocation() { + return true; + } + + public void start() { + this.running = true; + + try { + registerListerner(); + } catch (Exception e) { + throw new JMSBindingException("Error starting JMSServiceBinding", e); + } + } + + public void stop() { + this.running = false; + try { + consumer.close(); + jmsResourceFactory.closeConnection(); + } catch (Exception e) { + // if using an embedded broker then when shutting down Tuscany the broker may get closed + // before this stop method is called. I can't see how to detect that so for now just + // ignore the exception if the message is that the transport is already disposed + if (!"Transport disposed.".equals(e.getMessage())) { + throw new JMSBindingException("Error stopping JMSServiceBinding", e); + } + } + } + + private void registerListerner() throws NamingException, JMSException { + + Session session = jmsResourceFactory.createSession(); + destination = lookupDestinationQueue(); + if (destination == null) { + destination = session.createTemporaryQueue(); + } + + if (jmsBinding.getJMSSelector() != null) { + consumer = session.createConsumer(destination, jmsBinding.getJMSSelector()); + } else { + consumer = session.createConsumer(destination); + } + + MessageListener tmpListener = null; + + /* + * TODO turn on RRB version of JMS binding + */ + tmpListener = new RRBJMSBindingListener(jmsBinding, jmsResourceFactory, service, targetBinding, messageFactory); + //tmpListener = new DefaultJMSBindingListener(jmsBinding, jmsResourceFactory, service, targetBinding); + + final MessageListener listener = tmpListener; + + try { + + consumer.setMessageListener(listener); + jmsResourceFactory.startConnection(); + + } catch (javax.jms.IllegalStateException e) { + + // setMessageListener not allowed in JEE container so use Tuscany threads + + jmsResourceFactory.startConnection(); + workScheduler.scheduleWork(new Runnable() { + public void run() { + try { + while (running) { + final Message msg = consumer.receive(); + workScheduler.scheduleWork(new Runnable() { + public void run() { + try { + listener.onMessage(msg); + } catch (Exception e) { + e.printStackTrace(); + } + } + }); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + }); + } + logger.log(Level.INFO, "JMS " + (service.isCallback() ? "callback service" : "service") + + " '" + + service.getName() + + "' listening on destination " + + ((destination instanceof Queue) ? ((Queue)destination).getQueueName() : ((Topic)destination).getTopicName())); + } + + /** + * Looks up the Destination Queue for the JMS Binding. + *

+ * What happens in the look up will depend on the create mode specified for the JMS Binding: + *

    + *
  • always - the JMS queue is always created. It is an error if the queue already exists + *
  • ifnotexist - the JMS queue is created if it does not exist. It is not an error if the queue already exists + *
  • never - the JMS queue is never created. It is an error if the queue does not exist + *
+ * See the SCA JMS Binding specification for more information. + *

+ * + * @return The Destination queue. + * @throws NamingException Failed to lookup JMS queue + * @throws JMSBindingException Failed to lookup JMS Queue. Probable cause is that the JMS queue's current existence/non-existence is not + * compatible with the create mode specified on the binding + */ + private Destination lookupDestinationQueue() throws NamingException, JMSBindingException { + + if (service.isCallback() && JMSBindingConstants.DEFAULT_DESTINATION_NAME.equals(jmsBinding.getDestinationName())) { + // if its a callback service returning null indicates to use a temporary queue + return null; + } + + Destination destination = jmsResourceFactory.lookupDestination(jmsBinding.getDestinationName()); + + String qCreateMode = jmsBinding.getDestinationCreate(); + if (qCreateMode.equals(JMSBindingConstants.CREATE_ALWAYS)) { + // In this mode, the queue must not already exist as we are creating it + if (destination != null) { + throw new JMSBindingException("JMS Destination " + jmsBinding.getDestinationName() + + " already exists but has create mode of \"" + + qCreateMode + + "\" while registering service " + + service.getName() + + " listener"); + } + + // Create the queue + destination = jmsResourceFactory.createDestination(jmsBinding.getDestinationName()); + + } else if (qCreateMode.equals(JMSBindingConstants.CREATE_IF_NOT_EXIST)) { + // In this mode, the queue may nor may not exist. It will be created if it does not exist + if (destination == null) { + destination = jmsResourceFactory.createDestination(jmsBinding.getDestinationName()); + } + + } else if (qCreateMode.equals(JMSBindingConstants.CREATE_NEVER)) { + // In this mode, the queue must have already been created. + if (destination == null) { + throw new JMSBindingException("JMS Destination " + jmsBinding.getDestinationName() + + " not found but create mode of \"" + + qCreateMode + + "\" while registering service " + + service.getName() + + " listener"); + } + } + + // Make sure we ended up with a queue + if (destination == null) { + throw new JMSBindingException("JMS Destination " + jmsBinding.getDestinationName() + + " not found with create mode of \"" + + qCreateMode + + "\" while registering service " + + service.getName() + + " listener"); + } + + return destination; + } + + public String getDestinationName() { + try { + if (destination instanceof Queue) { + return ((Queue)destination).getQueueName(); + } else if (destination instanceof Topic) { + return ((Topic)destination).getTopicName(); + } else { + return null; + } + } catch (JMSException e) { + throw new JMSBindingException(e); + } + } + + /* + * RRB test methods + */ + public void configureBindingChain(RuntimeWire runtimeWire) { + + InvocationChain bindingChain = runtimeWire.getBindingInvocationChain(); + + // add transport interceptor + bindingChain.addInterceptor(Phase.SERVICE_BINDING_TRANSPORT, + new TransportServiceInterceptor(jmsBinding, + jmsResourceFactory, + runtimeWire) ); + + // add operation selector interceptor + bindingChain.addInterceptor(operationSelectorProvider.getPhase(), + operationSelectorProvider.createInterceptor()); + + // add request wire format + bindingChain.addInterceptor(requestWireFormatProvider.getPhase(), + requestWireFormatProvider.createInterceptor()); + + // add response wire format, but only add it if it's different from the request + if (!jmsBinding.getRequestWireFormat().equals(jmsBinding.getResponseWireFormat())){ + bindingChain.addInterceptor(responseWireFormatProvider.getPhase(), + responseWireFormatProvider.createInterceptor()); + } + } +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/JMSMessageProcessor.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/JMSMessageProcessor.java new file mode 100644 index 0000000000..821b9d7873 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/JMSMessageProcessor.java @@ -0,0 +1,55 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms.provider; + +import javax.jms.Message; +import javax.jms.Session; + +/** + * Interface for a component that does operation selection and message payload processing + * + * @version $Rev$ $Date$ + */ +public interface JMSMessageProcessor { + + /** + * Get the operation name from a JMS Message + */ + String getOperationName(Message message); + + /** + * Set the operation name on a JMS Message + */ + void setOperationName(String operationName, Message message); + + /** + * Extracts the payload from a JMS Message + */ + Object extractPayloadFromJMSMessage(Message msg); + + /** + * Create a JMS Message containing the payload + */ + Message insertPayloadIntoJMSMessage(Session session, Object payload); + + /** + * Create a JMS Message for reporting an exception + */ + Message createFaultMessage(Session session, Throwable responsePayload); +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/JMSMessageProcessorUtil.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/JMSMessageProcessorUtil.java new file mode 100644 index 0000000000..09fe7310e6 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/JMSMessageProcessorUtil.java @@ -0,0 +1,75 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.jms.provider; + +import java.lang.reflect.Constructor; + +import org.apache.tuscany.sca.binding.jms.JMSBinding; +import org.apache.tuscany.sca.binding.jms.JMSBindingException; + +/** + * Utility methods to load JMS message processors. + * + * @version $Rev: $ $Date: $ + */ +public class JMSMessageProcessorUtil { + + /** + * Used to create instances of the JMSResourceFactory and RequestMessageProcessor and ResponseMessageProcessor from + * string based class name provided in the configuration + * + * @param cl ClassLoader + * @param className the string based class name to load and instantiate + * @return the new object + */ + private static Object instantiate(ClassLoader cl, String className, JMSBinding binding) { + Object instance; + if (cl == null) { + cl = binding.getClass().getClassLoader(); + } + + try { + Class clazz; + + try { + clazz = cl.loadClass(className); + } catch (ClassNotFoundException e) { + clazz = binding.getClass().getClassLoader().loadClass(className); + } + + Constructor constructor = clazz.getDeclaredConstructor(new Class[] {JMSBinding.class}); + instance = constructor.newInstance(binding); + + } catch (Throwable e) { + throw new JMSBindingException("Exception instantiating OperationAndDataBinding class", e); + } + + return instance; + } + + public static JMSMessageProcessor getRequestMessageProcessor(JMSBinding binding) { + return (JMSMessageProcessor)instantiate(null, binding.getRequestMessageProcessorName(), binding); + } + + public static JMSMessageProcessor getResponseMessageProcessor(JMSBinding binding) { + return (JMSMessageProcessor)instantiate(null, binding.getResponseMessageProcessorName(), binding); + } + +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/JMSResourceFactory.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/JMSResourceFactory.java new file mode 100644 index 0000000000..773be84c7f --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/JMSResourceFactory.java @@ -0,0 +1,67 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.jms.provider; + +import javax.jms.Connection; +import javax.jms.Destination; +import javax.jms.JMSException; +import javax.jms.Session; +import javax.naming.NamingException; + +public interface JMSResourceFactory { + + /* + * This is a simple implementation where a connection is created per binding Ideally the resource factory should be + * able to leverage the host environment to provide connection pooling if it can. E.g. if Tuscany is running inside + * an AppServer Then we could leverage the JMS resources it provides + * + * @see org.apache.tuscany.binding.jms.JMSResourceFactory#getConnection() + */ + public abstract Connection getConnection() throws NamingException, JMSException; + + /* + * (non-Javadoc) + * + * @see org.apache.tuscany.binding.jms.JMSResourceFactory#createSession() + */ + public abstract Session createSession() throws JMSException, NamingException; + + /* + * (non-Javadoc) + * + * @see org.apache.tuscany.binding.jms.JMSResourceFactory#startConnection() + */ + public abstract void startConnection() throws JMSException, NamingException; + + /* + * (non-Javadoc) + * + * @see org.apache.tuscany.binding.jms.JMSResourceFactory#closeConnection() + */ + public abstract void closeConnection() throws JMSException; + + public abstract Destination lookupDestination(String destName) throws NamingException; + + /** + * You can create a destination in ActiveMQ (and have it appear in JNDI) by putting "dynamicQueues/" in front of the queue name being looked up + */ + public abstract Destination createDestination(String jndiName) throws NamingException; + +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/JMSResourceFactoryExtensionPoint.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/JMSResourceFactoryExtensionPoint.java new file mode 100644 index 0000000000..57fbfb3215 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/JMSResourceFactoryExtensionPoint.java @@ -0,0 +1,28 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.jms.provider; + +import org.apache.tuscany.sca.binding.jms.impl.JMSBinding; + +public interface JMSResourceFactoryExtensionPoint { + + JMSResourceFactory createJMSResourceFactory(JMSBinding binding); + +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/JMSResourceFactoryImpl.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/JMSResourceFactoryImpl.java new file mode 100644 index 0000000000..d0624fb52e --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/JMSResourceFactoryImpl.java @@ -0,0 +1,223 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms.provider; + +import java.util.Properties; + +import javax.jms.Connection; +import javax.jms.ConnectionFactory; +import javax.jms.Destination; +import javax.jms.JMSException; +import javax.jms.Session; +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; + +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingConstants; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingException; + +/** + * Abstracts away any JMS provide specific feature from the JMS binding + * + * @version $Rev$ $Date$ + */ +public class JMSResourceFactoryImpl implements JMSResourceFactory { + + protected String initialContextFactoryName; + protected String connectionFactoryName = "ConnectionFactory"; + protected String jndiURL; + + protected Connection connection; + protected Context context; + protected boolean isConnectionStarted; + + public JMSResourceFactoryImpl(String connectionFactoryName, String initialContextFactoryName, String jndiURL) { + if (connectionFactoryName != null && connectionFactoryName.trim().length() > 0) { + this.connectionFactoryName = connectionFactoryName.trim(); + } + if (initialContextFactoryName != null && initialContextFactoryName.trim().length() > 0) { + this.initialContextFactoryName = initialContextFactoryName.trim(); + } + if (jndiURL != null) { + this.jndiURL = jndiURL.trim(); + } + } + + /* + * This is a simple implementation where a connection is created per binding Ideally the resource factory should be + * able to leverage the host environment to provide connection pooling if it can. E.g. if Tuscany is running inside + * an AppServer Then we could leverage the JMS resources it provides + * + * @see org.apache.tuscany.sca.binding.jms.provider.JMSResourceFactory#getConnection() + */ + public Connection getConnection() throws NamingException, JMSException { + if (connection == null) { + createConnection(); + } + return connection; + } + + /* + * (non-Javadoc) + * + * @see org.apache.tuscany.sca.binding.jms.provider.JMSResourceFactory#createSession() + */ + public Session createSession() throws JMSException, NamingException { + return getConnection().createSession(false, Session.AUTO_ACKNOWLEDGE); + } + + /* + * (non-Javadoc) + * + * @see org.apache.tuscany.sca.binding.jms.provider.JMSResourceFactory#startConnection() + */ + public void startConnection() throws JMSException, NamingException { + if (!isConnectionStarted) { + getConnection().start(); + isConnectionStarted = true; + } + } + + /* + * (non-Javadoc) + * + * @see org.apache.tuscany.sca.binding.jms.provider.JMSResourceFactory#closeConnection() + */ + public void closeConnection() throws JMSException { + if (connection != null) { + try { + connection.close(); + } catch (JMSException e) { + // if using an embedded broker then when shutting down Tuscany the broker may get closed + // before this stop method is called. I can't see how to detect that so for now just + // ignore the exception if the message is that the transport is already disposed + if (!e.getMessage().contains("disposed")) { + throw e; + } + } + } + } + + protected void createConnection() throws NamingException, JMSException { + ConnectionFactory connectionFactory = (ConnectionFactory)jndiLookUp(connectionFactoryName); + if (connectionFactory == null) { + throw new JMSBindingException("connection factory not found: " + connectionFactoryName); + } + connection = connectionFactory.createConnection(); + } + + protected synchronized Context getInitialContext() throws NamingException { + if (context == null) { + Properties props = new Properties(); + + if (initialContextFactoryName != null) { + props.setProperty(Context.INITIAL_CONTEXT_FACTORY, initialContextFactoryName); + } + if (jndiURL != null) { + props.setProperty(Context.PROVIDER_URL, jndiURL); + } + + initJREEnvironment(props); + + context = new InitialContext(props); + } + return context; + } + + /** + * If using the WAS JMS Client with a non-IBM JRE then an additional + * environment property needs to be set to initialize the ORB correctly. + * See: http://www-1.ibm.com/support/docview.wss?uid=swg24012804 + */ + protected void initJREEnvironment(Properties props) { + if ("com.ibm.websphere.naming.WsnInitialContextFactory".equals(props.get(Context.INITIAL_CONTEXT_FACTORY))) { + String vendor = System.getProperty("java.vendor"); + if (vendor == null || !vendor.contains("IBM")) { + props.setProperty("com.ibm.CORBA.ORBInit", "com.ibm.ws.sib.client.ORB"); + } + } + } + + /* (non-Javadoc) + * @see org.apache.tuscany.sca.binding.jms.provider.JMSResourceFactory#lookupDestination(java.lang.String) + */ + public Destination lookupDestination(String destName) throws NamingException { + if (JMSBindingConstants.DEFAULT_DESTINATION_NAME.equals(destName)) { + return null; + } + + Destination dest = (Destination)jndiLookUp(destName); + if (dest == null) { + dest = lookupPhysical(destName); + } + return dest; + } + + protected Destination lookupPhysical(String jndiName) { + + // TODO: the SCA JMS spec says a destination name may be a non-jndi plain destination name + +// Session session = null; +// try { +// +// Destination dest; +// session = createSession(); +// dest = session.createQueue(jndiName); +// return dest; +// +// } catch (JMSException e) { +// throw new JMSBindingException(e); +// } catch (NamingException e) { +// throw new JMSBindingException(e); +// } finally { +// if (session != null) { +// try { +// session.close(); +// } catch (JMSException e) { +// throw new JMSBindingException(e); +// } +// } +// } + return null; + } + + /* (non-Javadoc) + * @see org.apache.tuscany.sca.binding.jms.provider.JMSResourceFactory#createDestination(java.lang.String) + */ + public Destination createDestination(String jndiName) throws NamingException { + return lookupDestination("dynamicQueues/" + jndiName); + } + + protected Object jndiLookUp(String name) { + Object o = null; + try { + o = getInitialContext().lookup("java:comp/env/" + name); + } catch (Exception ex) { + // ignore + } + if (o == null) { + try { + o = getInitialContext().lookup(name); + } catch (NamingException ex) { + // ignore + } + } + return o; + } +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/ObjectMessageProcessor.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/ObjectMessageProcessor.java new file mode 100644 index 0000000000..477ec2c2ae --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/ObjectMessageProcessor.java @@ -0,0 +1,75 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms.provider; + +import java.io.Serializable; + +import javax.jms.JMSException; +import javax.jms.Message; +import javax.jms.ObjectMessage; +import javax.jms.Session; + +import org.apache.tuscany.sca.binding.jms.JMSBinding; +import org.apache.tuscany.sca.binding.jms.JMSBindingException; + +/** + * MessageProcessor for sending/receiving Serializable objects with the JMSBinding. + * + * @version $Rev$ $Date$ + */ +public class ObjectMessageProcessor extends AbstractMessageProcessor { + + public ObjectMessageProcessor(JMSBinding jmsBinding) { + super(jmsBinding); + } + + @Override + protected Object[] extractPayload(Message msg) { + try { + + Object o = ((ObjectMessage)msg).getObject(); + if (o != null && o.getClass().isArray()) { + return (Object[])o; + } else { + return new Object[] { o}; + } + + } catch (JMSException e) { + throw new JMSBindingException(e); + } + } + + @Override + protected Message createJMSMessage(Session session, Object o) { + try { + + if (!(o instanceof Serializable)) { + throw new IllegalStateException("JMS ObjectMessage payload not Serializable: " + o); + } + + ObjectMessage message = session.createObjectMessage(); + message.setObject((Serializable)o); + return message; + + } catch (JMSException e) { + throw new JMSBindingException(e); + } + } + +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/RRBJMSBindingInvoker.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/RRBJMSBindingInvoker.java new file mode 100644 index 0000000000..33d4366fe6 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/RRBJMSBindingInvoker.java @@ -0,0 +1,279 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms.provider; + +import java.lang.reflect.InvocationTargetException; +import java.util.List; +import java.util.Map; + +import javax.jms.DeliveryMode; +import javax.jms.Destination; +import javax.jms.JMSException; +import javax.jms.Message; +import javax.jms.MessageConsumer; +import javax.jms.MessageProducer; +import javax.jms.Session; +import javax.naming.NamingException; +import javax.security.auth.Subject; + +import org.apache.tuscany.sca.binding.jms.context.JMSBindingContext; +import org.apache.tuscany.sca.binding.jms.impl.JMSBinding; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingConstants; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingException; +import org.apache.tuscany.sca.binding.jms.policy.authentication.token.JMSTokenAuthenticationPolicy; +import org.apache.tuscany.sca.binding.jms.policy.header.JMSHeaderPolicy; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.interfacedef.java.JavaInterface; +import org.apache.tuscany.sca.invocation.DataExchangeSemantics; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.policy.PolicySet; +import org.apache.tuscany.sca.policy.PolicySetAttachPoint; +import org.apache.tuscany.sca.policy.SecurityUtil; +import org.apache.tuscany.sca.policy.authentication.token.TokenPrincipal; +import org.apache.tuscany.sca.runtime.ReferenceParameters; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; +import org.apache.tuscany.sca.runtime.RuntimeWire; +import org.oasisopen.sca.ServiceRuntimeException; + +/** + * Invoker for the JMS binding. + * + * @version $Rev$ $Date$ + */ +public class RRBJMSBindingInvoker implements Invoker, DataExchangeSemantics { + + protected Operation operation; + protected String operationName; + + protected JMSBinding jmsBinding; + protected JMSResourceFactory jmsResourceFactory; + protected JMSMessageProcessor requestMessageProcessor; + protected JMSMessageProcessor responseMessageProcessor; + protected Destination bindingRequestDest; + protected Destination bindingReplyDest; + protected RuntimeComponentReference reference; + protected RuntimeWire runtimeWire; + + public RRBJMSBindingInvoker(JMSBinding jmsBinding, Operation operation, JMSResourceFactory jmsResourceFactory, RuntimeComponentReference reference) { + + this.operation = operation; + operationName = operation.getName(); + + this.jmsBinding = jmsBinding; + this.jmsResourceFactory = jmsResourceFactory; + this.reference = reference; + this.runtimeWire = reference.getRuntimeWire(jmsBinding); + this.requestMessageProcessor = JMSMessageProcessorUtil.getRequestMessageProcessor(jmsBinding); + this.responseMessageProcessor = JMSMessageProcessorUtil.getResponseMessageProcessor(jmsBinding); + + try { + bindingRequestDest = lookupDestination(); + bindingReplyDest = lookupResponseDestination(); + } catch (NamingException e) { + throw new JMSBindingException(e); + } + } + + /** + * Looks up the Destination Queue for the JMS Binding + * + * @return The Destination Queue + * @throws NamingException Failed to lookup Destination Queue + * @throws JMSBindingException Failed to lookup Destination Queue + * @see #lookupDestinationQueue(boolean) + */ + protected Destination lookupDestination() throws NamingException, JMSBindingException { + return lookupDestinationQueue(false); + } + + /** + * Looks up the Destination Response Queue for the JMS Binding + * + * @return The Destination Response Queue + * @throws NamingException Failed to lookup Destination Response Queue + * @throws JMSBindingException Failed to lookup Destination Response Queue + * @see #lookupDestinationQueue(boolean) + */ + protected Destination lookupResponseDestination() throws NamingException, JMSBindingException { + return lookupDestinationQueue(true); + } + + /** + * Looks up the Destination Queue for the JMS Binding. + *

+ * What happens in the look up will depend on the create mode specified for the JMS Binding: + *

    + *
  • always - the JMS queue is always created. It is an error if the queue already exists + *
  • ifnotexist - the JMS queue is created if it does not exist. It is not an error if the queue already exists + *
  • never - the JMS queue is never created. It is an error if the queue does not exist + *
+ * See the SCA JMS Binding specification for more information. + *

+ * + * @param isReponseQueue true if we are creating a response queue. + * false if we are creating a request queue + * @return The Destination queue. + * @throws NamingException Failed to lookup JMS queue + * @throws JMSBindingException Failed to lookup JMS Queue. Probable cause is that + * the JMS queue's current existence/non-existence is not compatible with + * the create mode specified on the binding + */ + protected Destination lookupDestinationQueue(boolean isReponseQueue) throws NamingException, JMSBindingException { + String queueName; + String queueType; + String qCreateMode; + + if (isReponseQueue) { + queueName = jmsBinding.getResponseDestinationName(); + queueType = "JMS Response Destination "; + qCreateMode = jmsBinding.getResponseDestinationCreate(); + if (JMSBindingConstants.DEFAULT_RESPONSE_DESTINATION_NAME.equals(queueName)) { + return null; + } + } else { + queueName = jmsBinding.getDestinationName(); + queueType = "JMS Destination "; + qCreateMode = jmsBinding.getDestinationCreate(); + } + + Destination dest = jmsResourceFactory.lookupDestination(queueName); + + if (qCreateMode.equals(JMSBindingConstants.CREATE_ALWAYS)) { + // In this mode, the queue must not already exist as we are creating it + if (dest != null) { + throw new JMSBindingException(queueType + queueName + + " already exists but has create mode of \"" + + qCreateMode + + "\" while registering binding " + + jmsBinding.getName() + + " invoker"); + } + // Create the queue + dest = jmsResourceFactory.createDestination(queueName); + + } else if (qCreateMode.equals(JMSBindingConstants.CREATE_IF_NOT_EXIST)) { + // In this mode, the queue may nor may not exist. It will be created if it does not exist + if (dest == null) { + dest = jmsResourceFactory.createDestination(queueName); + } + + } else if (qCreateMode.equals(JMSBindingConstants.CREATE_NEVER)) { + // In this mode, the queue must have already been created. + if (dest == null) { + throw new JMSBindingException(queueType + queueName + + " not found but create mode of \"" + + qCreateMode + + "\" while registering binding " + + jmsBinding.getName() + + " invoker"); + } + } + + // Make sure we ended up with a queue + if (dest == null) { + throw new JMSBindingException(queueType + queueName + + " not found with create mode of \"" + + qCreateMode + + "\" while registering binding " + + jmsBinding.getName() + + " invoker"); + } + + return dest; + } + + public org.apache.tuscany.sca.invocation.Message invoke(org.apache.tuscany.sca.invocation.Message tuscanyMsg) { + try { + // create a jms session to cover the creation and sending of the message + Session session = jmsResourceFactory.createSession(); + + // populate the message context with JMS binding information + JMSBindingContext context = new JMSBindingContext(); + tuscanyMsg.getHeaders().add(JMSBindingConstants.MSG_CTXT_POSITION, context); + + context.setJmsSession(session); + context.setRequestDestination(getRequestDestination(tuscanyMsg, session)); + context.setReplyToDestination(getReplyToDestination(session)); + context.setJmsResourceFactory(jmsResourceFactory); + + try { + tuscanyMsg = runtimeWire.getBindingInvocationChain().getHeadInvoker().invoke(tuscanyMsg); + } catch (ServiceRuntimeException e) { + if (e.getCause() instanceof InvocationTargetException) { + if ((e.getCause().getCause() instanceof RuntimeException)) { + tuscanyMsg.setFaultBody(e.getCause()); + } else { + tuscanyMsg.setFaultBody(e.getCause().getCause()); + } + } else { + tuscanyMsg.setFaultBody(e); + } + } catch (IllegalStateException e) { + tuscanyMsg.setFaultBody(e); + } catch (Throwable e) { + tuscanyMsg.setFaultBody(e); + } finally { + session.close(); + } + + return tuscanyMsg; + } catch (Exception e) { + throw new JMSBindingException(e); + } + } + + protected Destination getRequestDestination(org.apache.tuscany.sca.invocation.Message tuscanyMsg, Session session) throws JMSBindingException, NamingException, JMSException { + Destination requestDestination; + if (reference.isCallback()) { + String toURI = tuscanyMsg.getTo().getURI(); + if (toURI != null && toURI.startsWith("jms:")) { + // the msg to uri contains the callback destination name + // this is an jms physical name not a jndi name so need to use session.createQueue + requestDestination = session.createQueue(toURI.substring(4)); + } else { + requestDestination = lookupDestination(); + } + } else { + requestDestination = bindingRequestDest; + } + + return requestDestination; + } + + protected Destination getReplyToDestination(Session session) throws JMSException, JMSBindingException, NamingException { + Destination replyToDest; + if (operation.isNonBlocking()) { + replyToDest = null; + } else { + if (bindingReplyDest != null) { + replyToDest = bindingReplyDest; + } else { + replyToDest = session.createTemporaryQueue(); + } + } + return replyToDest; + } + + public boolean allowsPassByReference() { + // JMS always pass by value + return true; + } + +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/RRBJMSBindingListener.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/RRBJMSBindingListener.java new file mode 100644 index 0000000000..5306e050e7 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/RRBJMSBindingListener.java @@ -0,0 +1,122 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms.provider; + +import java.lang.reflect.InvocationTargetException; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; + +import javax.jms.Destination; +import javax.jms.JMSException; +import javax.jms.Message; +import javax.jms.MessageListener; +import javax.jms.MessageProducer; +import javax.jms.Queue; +import javax.jms.Session; +import javax.jms.Topic; +import javax.naming.NamingException; +import javax.security.auth.Subject; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.binding.jms.context.JMSBindingContext; +import org.apache.tuscany.sca.binding.jms.impl.JMSBinding; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingConstants; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingException; +import org.apache.tuscany.sca.binding.jms.policy.authentication.token.JMSTokenAuthenticationPolicy; +import org.apache.tuscany.sca.core.assembly.EndpointReferenceImpl; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.InvocationChain; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.MessageFactory; +import org.apache.tuscany.sca.policy.PolicySet; +import org.apache.tuscany.sca.policy.PolicySetAttachPoint; +import org.apache.tuscany.sca.policy.SecurityUtil; +import org.apache.tuscany.sca.policy.authentication.token.TokenPrincipal; +import org.apache.tuscany.sca.runtime.EndpointReference; +import org.apache.tuscany.sca.runtime.ReferenceParameters; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; + +/** + * TODO RRB experiement + * Listener for the JMSBinding. + * + * @version $Rev$ $Date$ + */ +public class RRBJMSBindingListener implements MessageListener { + + private static final Logger logger = Logger.getLogger(RRBJMSBindingListener.class.getName()); + + private JMSBinding jmsBinding; + private Binding targetBinding; + private JMSResourceFactory jmsResourceFactory; + private RuntimeComponentService service; + private JMSMessageProcessor requestMessageProcessor; + private JMSMessageProcessor responseMessageProcessor; + private String correlationScheme; + private List serviceOperations; + private MessageFactory messageFactory; + + + public RRBJMSBindingListener(JMSBinding jmsBinding, JMSResourceFactory jmsResourceFactory, RuntimeComponentService service, Binding targetBinding, MessageFactory messageFactory) throws NamingException { + this.jmsBinding = jmsBinding; + this.jmsResourceFactory = jmsResourceFactory; + this.service = service; + this.targetBinding = targetBinding; + this.messageFactory = messageFactory; + + requestMessageProcessor = JMSMessageProcessorUtil.getRequestMessageProcessor(jmsBinding); + responseMessageProcessor = JMSMessageProcessorUtil.getResponseMessageProcessor(jmsBinding); + correlationScheme = jmsBinding.getCorrelationScheme(); + serviceOperations = service.getInterfaceContract().getInterface().getOperations(); + + } + + public void onMessage(Message requestJMSMsg) { + logger.log(Level.FINE, "JMS service '" + service.getName() + "' received message " + requestJMSMsg); + try { + invokeService(requestJMSMsg); + } catch (Throwable e) { + logger.log(Level.SEVERE, "Exception send fault response '" + service.getName(), e); + } + } + + protected void invokeService(Message requestJMSMsg) throws JMSException, InvocationTargetException { + + // create the tuscany message + org.apache.tuscany.sca.invocation.Message tuscanyMsg = messageFactory.createMessage(); + + // populate the message context with JMS binding information + JMSBindingContext context = new JMSBindingContext(); + tuscanyMsg.getHeaders().add(context); + + context.setJmsMsg(requestJMSMsg); + context.setJmsResourceFactory(jmsResourceFactory); + context.setReplyToDestination(requestJMSMsg.getJMSReplyTo()); + + // set the message body + tuscanyMsg.setBody(requestJMSMsg); + + // call the runtime wire - the response is handled by the + // transport interceptor + service.getRuntimeWire(targetBinding).invoke(tuscanyMsg); + + } + +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/TextMessageProcessor.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/TextMessageProcessor.java new file mode 100644 index 0000000000..32d024ec32 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/TextMessageProcessor.java @@ -0,0 +1,68 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms.provider; + +import javax.jms.JMSException; +import javax.jms.Message; +import javax.jms.Session; +import javax.jms.TextMessage; + +import org.apache.tuscany.sca.binding.jms.JMSBinding; +import org.apache.tuscany.sca.binding.jms.JMSBindingException; + +/** + * MessageProcessor for sending/receiving javax.jms.TextMessage with the JMSBinding. + * + * @version $Rev$ $Date$ + */ +public class TextMessageProcessor extends AbstractMessageProcessor { + + public TextMessageProcessor(JMSBinding jmsBinding) { + super(jmsBinding); + } + + @Override + protected Object[] extractPayload(Message msg) { + try { + + if (!(msg instanceof TextMessage)) { + throw new IllegalStateException("expecting JMS TextMessage: " + msg); + } + + return new Object[] {((TextMessage)msg).getText()}; + + } catch (JMSException e) { + throw new JMSBindingException(e); + } + } + + @Override + protected Message createJMSMessage(Session session, Object o) { + try { + + TextMessage message = session.createTextMessage(); + message.setText(String.valueOf(o)); + return message; + + } catch (JMSException e) { + throw new JMSBindingException(e); + } + } + +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/XMLTextMessageProcessor.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/XMLTextMessageProcessor.java new file mode 100644 index 0000000000..6e5556df01 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/provider/XMLTextMessageProcessor.java @@ -0,0 +1,90 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms.provider; + +import java.io.StringReader; + +import javax.jms.JMSException; +import javax.jms.Message; +import javax.jms.Session; +import javax.jms.TextMessage; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.impl.builder.StAXOMBuilder; +import org.apache.tuscany.sca.binding.jms.JMSBinding; +import org.apache.tuscany.sca.binding.jms.JMSBindingException; + +/** + * MessageProcessor for sending/receiving XML javax.jms.TextMessage with the JMSBinding. + * + * @version $Rev$ $Date$ + */ +public class XMLTextMessageProcessor extends AbstractMessageProcessor { + + public XMLTextMessageProcessor(JMSBinding jmsBinding) { + super(jmsBinding); + } + + @Override + protected Object[] extractPayload(Message msg) { + try { + + String xml = ((TextMessage)msg).getText(); + Object[] os; + if (xml != null) { + XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(xml)); + StAXOMBuilder builder = new StAXOMBuilder(reader); + os = new Object[] {builder.getDocumentElement()}; + } else { + os = new Object[] {}; + } + return os; + + } catch (XMLStreamException e) { + throw new JMSBindingException(e); + } catch (JMSException e) { + throw new JMSBindingException(e); + } + } + + @Override + protected Message createJMSMessage(Session session, Object o) { + try { + + TextMessage message = session.createTextMessage(); + + if (o instanceof OMElement) { + message.setText(o.toString()); + } else if ((o instanceof Object[]) && ((Object[])o)[0] instanceof OMElement) { + message.setText(((Object[])o)[0].toString()); + } else if (o != null) { + throw new IllegalStateException("expecting OMElement payload: " + o); + } + + return message; + + } catch (JMSException e) { + throw new JMSBindingException(e); + } + } + +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/transport/TransportReferenceInterceptor.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/transport/TransportReferenceInterceptor.java new file mode 100644 index 0000000000..e84279cae1 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/transport/TransportReferenceInterceptor.java @@ -0,0 +1,186 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms.transport; + +import java.util.List; + +import javax.jms.JMSException; +import javax.jms.MessageConsumer; +import javax.jms.MessageProducer; +import javax.jms.Session; +import javax.naming.NamingException; + + +import org.apache.tuscany.sca.binding.jms.context.JMSBindingContext; +import org.apache.tuscany.sca.binding.jms.impl.JMSBinding; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingConstants; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingException; +import org.apache.tuscany.sca.binding.jms.policy.authentication.token.JMSTokenAuthenticationPolicy; +import org.apache.tuscany.sca.binding.jms.policy.header.JMSHeaderPolicy; +import org.apache.tuscany.sca.binding.jms.provider.JMSMessageProcessor; +import org.apache.tuscany.sca.binding.jms.provider.JMSMessageProcessorUtil; +import org.apache.tuscany.sca.binding.jms.provider.JMSResourceFactory; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.policy.PolicySet; +import org.apache.tuscany.sca.policy.PolicySetAttachPoint; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; +import org.apache.tuscany.sca.runtime.RuntimeWire; + +/** + * Policy handler to handle PolicySet related to Logging with the QName + * {http://tuscany.apache.org/xmlns/sca/1.0/impl/java}LoggingPolicy + * + * @version $Rev$ $Date$ + */ +public class TransportReferenceInterceptor implements Interceptor { + + private static final String ON_MESSAGE_METHOD_NAME = "onMessage"; + + private Invoker next; + private RuntimeWire runtimeWire; + private JMSResourceFactory jmsResourceFactory; + private JMSBinding jmsBinding; + private JMSMessageProcessor requestMessageProcessor; + private JMSMessageProcessor responseMessageProcessor; + private RuntimeComponentReference reference; + protected JMSHeaderPolicy jmsHeaderPolicy = null; + + + public TransportReferenceInterceptor(JMSBinding jmsBinding, JMSResourceFactory jmsResourceFactory, RuntimeWire runtimeWire) { + super(); + this.jmsBinding = jmsBinding; + this.runtimeWire = runtimeWire; + this.jmsResourceFactory = jmsResourceFactory; + this.requestMessageProcessor = JMSMessageProcessorUtil.getRequestMessageProcessor(jmsBinding); + this.responseMessageProcessor = JMSMessageProcessorUtil.getResponseMessageProcessor(jmsBinding); + this.reference = (RuntimeComponentReference)runtimeWire.getSource().getContract(); + + // find out if the header policy is active + if (jmsBinding instanceof PolicySetAttachPoint) { + List policySets = ((PolicySetAttachPoint)jmsBinding).getApplicablePolicySets(); + for (PolicySet ps : policySets) { + for (Object p : ps.getPolicies()) { + if (JMSHeaderPolicy.class.isInstance(p)) { + jmsHeaderPolicy = (JMSHeaderPolicy)p; + } + } + } + } + } + + public Message invoke(Message msg) { + Message responseMsg = invokeRequest(msg); + + // get the jms context + JMSBindingContext context = (JMSBindingContext)msg.getHeaders().get(JMSBindingConstants.MSG_CTXT_POSITION); + + if (context.getReplyToDestination() == null) { + responseMsg.setBody(null); + } else { + responseMsg = invokeResponse(msg); + } + + return responseMsg; + } + + public Message invokeRequest(Message msg) { + try { + // get the jms context + JMSBindingContext context = (JMSBindingContext)msg.getHeaders().get(JMSBindingConstants.MSG_CTXT_POSITION); + Session session = context.getJmsSession(); + + MessageProducer producer = session.createProducer(context.getRequestDestination()); + + if (jmsBinding.getOperationJMSTimeToLive(msg.getOperation().getName()) != null) { + producer.setTimeToLive(jmsBinding.getOperationJMSTimeToLive(msg.getOperation().getName())); + } + + try { + producer.send((javax.jms.Message)msg.getBody()); + } finally { + producer.close(); + } + return msg; + } catch (JMSException e) { + throw new JMSBindingException(e); + } + } + + public Message invokeResponse(Message msg) { + try { + // get the jms context + JMSBindingContext context = (JMSBindingContext)msg.getHeaders().get(JMSBindingConstants.MSG_CTXT_POSITION); + Session session = context.getJmsSession(); + + javax.jms.Message requestMessage = (javax.jms.Message)msg.getBody(); + + String operationName = msg.getOperation().getName(); + + String msgSelector = "JMSCorrelationID = '" + + requestMessage.getJMSMessageID() + + "'"; + MessageConsumer consumer = session.createConsumer(context.getReplyToDestination(), msgSelector); + + long receiveWait; + + if ((jmsHeaderPolicy != null) && + (jmsHeaderPolicy.getTimeToLive() != null)) { + receiveWait = jmsHeaderPolicy.getTimeToLive(); + } else if (jmsBinding.getOperationJMSTimeToLive(operationName) != null) { + receiveWait = jmsBinding.getOperationJMSTimeToLive(operationName) * 2; + } else { + receiveWait = JMSBindingConstants.DEFAULT_TIME_TO_LIVE; + } + + javax.jms.Message replyMsg; + try { + context.getJmsResourceFactory().startConnection(); + //jmsResourceFactory.startConnection(); + replyMsg = consumer.receive(receiveWait); + } finally { + consumer.close(); + } + if (replyMsg == null) { + throw new JMSBindingException("No reply message received on " + + context.getReplyToDestination() + + " for message id " + + requestMessage.getJMSMessageID()); + } + + msg.setBody(replyMsg); + return msg; + } catch (JMSException e) { + throw new JMSBindingException(e); + } catch (NamingException e) { + throw new JMSBindingException(e); + } + } + + public Invoker getNext() { + return next; + } + + public void setNext(Invoker next) { + this.next = next; + } +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/transport/TransportServiceInterceptor.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/transport/TransportServiceInterceptor.java new file mode 100644 index 0000000000..ed17140ac3 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/transport/TransportServiceInterceptor.java @@ -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. + */ +package org.apache.tuscany.sca.binding.jms.transport; + +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; + +import javax.jms.Destination; +import javax.jms.JMSException; +import javax.jms.MessageProducer; +import javax.jms.Queue; +import javax.jms.Session; +import javax.jms.Topic; +import javax.naming.NamingException; +import javax.security.auth.Subject; + +import org.apache.tuscany.sca.binding.jms.context.JMSBindingContext; +import org.apache.tuscany.sca.binding.jms.impl.JMSBinding; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingConstants; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingException; +import org.apache.tuscany.sca.binding.jms.provider.DefaultJMSBindingListener; +import org.apache.tuscany.sca.binding.jms.provider.JMSMessageProcessor; +import org.apache.tuscany.sca.binding.jms.provider.JMSMessageProcessorUtil; +import org.apache.tuscany.sca.binding.jms.provider.JMSResourceFactory; +import org.apache.tuscany.sca.core.assembly.EndpointReferenceImpl; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.policy.SecurityUtil; +import org.apache.tuscany.sca.policy.authentication.token.TokenPrincipal; +import org.apache.tuscany.sca.runtime.EndpointReference; +import org.apache.tuscany.sca.runtime.ReferenceParameters; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; +import org.apache.tuscany.sca.runtime.RuntimeWire; + +/** + * Policy handler to handle PolicySet related to Logging with the QName + * {http://tuscany.apache.org/xmlns/sca/1.0/impl/java}LoggingPolicy + * + * @version $Rev$ $Date$ + */ +public class TransportServiceInterceptor implements Interceptor { + private static final Logger logger = Logger.getLogger(TransportServiceInterceptor.class.getName()); + + private Invoker next; + private RuntimeWire runtimeWire; + private JMSResourceFactory jmsResourceFactory; + private JMSBinding jmsBinding; + private JMSMessageProcessor requestMessageProcessor; + private JMSMessageProcessor responseMessageProcessor; + private RuntimeComponentService service; + private String correlationScheme; + + + public TransportServiceInterceptor(JMSBinding jmsBinding, JMSResourceFactory jmsResourceFactory, RuntimeWire runtimeWire) { + super(); + this.jmsBinding = jmsBinding; + this.runtimeWire = runtimeWire; + this.jmsResourceFactory = jmsResourceFactory; + this.requestMessageProcessor = JMSMessageProcessorUtil.getRequestMessageProcessor(jmsBinding); + this.responseMessageProcessor = JMSMessageProcessorUtil.getResponseMessageProcessor(jmsBinding); + this.service = (RuntimeComponentService)runtimeWire.getTarget().getContract(); + this.correlationScheme = jmsBinding.getCorrelationScheme(); + } + + public Message invoke(Message msg) { + try { + return invokeResponse(next.invoke(invokeRequest(msg))); + } catch (Throwable e) { + logger.log(Level.SEVERE, "Exception invoking service '" + service.getName(), e); + JMSBindingContext context = (JMSBindingContext)msg.getHeaders().get(JMSBindingConstants.MSG_CTXT_POSITION); + javax.jms.Message replyJMSMsg = responseMessageProcessor.createFaultMessage(context.getJmsSession(), + (Throwable)e); + msg.setBody(replyJMSMsg); + invokeResponse(msg); + return msg; + } + } + + public Message invokeRequest(Message msg) { + try { + JMSBindingContext context = (JMSBindingContext)msg.getHeaders().get(JMSBindingConstants.MSG_CTXT_POSITION); + javax.jms.Message requestJMSMsg = context.getJmsMsg(); + context.setJmsSession(context.getJmsResourceFactory().createSession()); + + EndpointReference from = new EndpointReferenceImpl(null); + msg.setFrom(from); + from.setCallbackEndpoint(new EndpointReferenceImpl("/")); // TODO: whats this for? + ReferenceParameters parameters = from.getReferenceParameters(); + + String conversationID = requestJMSMsg.getStringProperty(JMSBindingConstants.CONVERSATION_ID_PROPERTY); + if (conversationID != null) { + parameters.setConversationID(conversationID); + } + + return msg; + } catch (JMSException e) { + throw new JMSBindingException(e); + } catch (NamingException e) { + throw new JMSBindingException(e); + } + } + + public Message invokeResponse(Message msg) { + try { + JMSBindingContext context = (JMSBindingContext)msg.getHeaders().get(JMSBindingConstants.MSG_CTXT_POSITION); + Session session = context.getJmsSession(); + javax.jms.Message requestJMSMsg = context.getJmsMsg(); + javax.jms.Message responseJMSMsg = msg.getBody(); + + + if (requestJMSMsg.getJMSReplyTo() == null) { + // assume no reply is expected + if (msg.getBody() != null) { + logger.log(Level.FINE, "JMS service '" + service.getName() + "' dropped response as request has no replyTo"); + } + return msg; + } + + responseJMSMsg.setJMSDeliveryMode(requestJMSMsg.getJMSDeliveryMode()); + responseJMSMsg.setJMSPriority(requestJMSMsg.getJMSPriority()); + + if (correlationScheme == null || + JMSBindingConstants.CORRELATE_MSG_ID.equalsIgnoreCase(correlationScheme)) { + responseJMSMsg.setJMSCorrelationID(requestJMSMsg.getJMSMessageID()); + } else if (JMSBindingConstants.CORRELATE_CORRELATION_ID.equalsIgnoreCase(correlationScheme)) { + responseJMSMsg.setJMSCorrelationID(requestJMSMsg.getJMSCorrelationID()); + } + + MessageProducer producer = session.createProducer(context.getReplyToDestination()); + + producer.send((javax.jms.Message)msg.getBody()); + + producer.close(); + session.close(); + + return msg; + + } catch (JMSException e) { + throw new JMSBindingException(e); + } + } + + public Invoker getNext() { + return next; + } + + public void setNext(Invoker next) { + this.next = next; + } + +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsbytes/WireFormatJMSBytesProviderFactory.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsbytes/WireFormatJMSBytesProviderFactory.java new file mode 100644 index 0000000000..9f554b50e9 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsbytes/WireFormatJMSBytesProviderFactory.java @@ -0,0 +1,65 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.jms.wireformat.jmsbytes; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.provider.WireFormatProvider; +import org.apache.tuscany.sca.provider.WireFormatProviderFactory; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; + +/** + * @version $Rev$ $Date$ + */ +public class WireFormatJMSBytesProviderFactory implements WireFormatProviderFactory { + private ExtensionPointRegistry registry; + + public WireFormatJMSBytesProviderFactory(ExtensionPointRegistry registry) { + super(); + this.registry = registry; + } + + /** + */ + public WireFormatProvider createReferenceWireFormatProvider(RuntimeComponent component, + RuntimeComponentReference reference, + Binding binding) { + return new WireFormatJMSBytesReferenceProvider(registry, component, reference, binding); + } + + /** + */ + public WireFormatProvider createServiceWireFormatProvider(RuntimeComponent component, + RuntimeComponentService service, + Binding binding) { + return new WireFormatJMSBytesServiceProvider(registry, component, service, binding); + } + + /** + * @see org.apache.tuscany.sca.provider.ProviderFactory#getModelType() + */ + public Class getModelType() { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsbytes/WireFormatJMSBytesReferenceInterceptor.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsbytes/WireFormatJMSBytesReferenceInterceptor.java new file mode 100644 index 0000000000..f990a9a0ba --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsbytes/WireFormatJMSBytesReferenceInterceptor.java @@ -0,0 +1,111 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms.wireformat.jmsbytes; + + +import javax.jms.JMSException; +import javax.jms.Session; + +import org.apache.tuscany.sca.assembly.WireFormat; +import org.apache.tuscany.sca.binding.jms.context.JMSBindingContext; +import org.apache.tuscany.sca.binding.jms.impl.JMSBinding; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingConstants; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingException; +import org.apache.tuscany.sca.binding.jms.provider.JMSMessageProcessor; +import org.apache.tuscany.sca.binding.jms.provider.JMSMessageProcessorUtil; +import org.apache.tuscany.sca.binding.jms.provider.JMSResourceFactory; +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.runtime.RuntimeWire; + +/** + * + * @version $Rev$ $Date$ + */ +public class WireFormatJMSBytesReferenceInterceptor implements Interceptor { + + private Invoker next; + private RuntimeWire runtimeWire; + private JMSResourceFactory jmsResourceFactory; + private JMSBinding jmsBinding; + private JMSMessageProcessor requestMessageProcessor; + private JMSMessageProcessor responseMessageProcessor; + + public WireFormatJMSBytesReferenceInterceptor(JMSBinding jmsBinding, JMSResourceFactory jmsResourceFactory, RuntimeWire runtimeWire) { + super(); + this.jmsBinding = jmsBinding; + this.runtimeWire = runtimeWire; + this.jmsResourceFactory = jmsResourceFactory; + this.requestMessageProcessor = JMSMessageProcessorUtil.getRequestMessageProcessor(jmsBinding); + this.responseMessageProcessor = JMSMessageProcessorUtil.getResponseMessageProcessor(jmsBinding); + } + + public Message invoke(Message msg) { + if (jmsBinding.getRequestWireFormat() instanceof WireFormatJMSBytes){ + msg = invokeRequest(msg); + } + + msg = getNext().invoke(msg); + + if (jmsBinding.getResponseWireFormat() instanceof WireFormatJMSBytes){ + msg = invokeResponse(msg); + } + + return msg; + } + + public Message invokeRequest(Message msg) { + try { + // get the jms context + JMSBindingContext context = (JMSBindingContext)msg.getHeaders().get(JMSBindingConstants.MSG_CTXT_POSITION); + Session session = context.getJmsSession(); + + javax.jms.Message requestMsg = requestMessageProcessor.insertPayloadIntoJMSMessage(session, msg.getBody()); + msg.setBody(requestMsg); + + requestMsg.setJMSReplyTo(context.getReplyToDestination()); + + return msg; + } catch (JMSException e) { + throw new JMSBindingException(e); + } + } + + public Message invokeResponse(Message msg) { + if (msg.getBody() != null){ + Object[] response = (Object[])responseMessageProcessor.extractPayloadFromJMSMessage((javax.jms.Message)msg.getBody()); + if (response != null && response.length > 0){ + msg.setBody(response[0]); + } else { + msg.setBody(null); + } + } + + return msg; + } + + public Invoker getNext() { + return next; + } + + public void setNext(Invoker next) { + this.next = next; + } +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsbytes/WireFormatJMSBytesReferenceProvider.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsbytes/WireFormatJMSBytesReferenceProvider.java new file mode 100644 index 0000000000..65de548e58 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsbytes/WireFormatJMSBytesReferenceProvider.java @@ -0,0 +1,94 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.jms.wireformat.jmsbytes; + +import java.util.List; + +import org.apache.axiom.om.OMElement; +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.binding.jms.impl.JMSBinding; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingConstants; +import org.apache.tuscany.sca.binding.jms.provider.JMSMessageProcessorUtil; +import org.apache.tuscany.sca.binding.jms.provider.XMLTextMessageProcessor; +import org.apache.tuscany.sca.binding.jms.wireformat.jmstextxml.WireFormatJMSTextXML; +import org.apache.tuscany.sca.binding.ws.WebServiceBinding; +import org.apache.tuscany.sca.binding.ws.WebServiceBindingFactory; +import org.apache.tuscany.sca.binding.ws.wsdlgen.BindingWSDLGenerator; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.Phase; +import org.apache.tuscany.sca.policy.PolicySet; +import org.apache.tuscany.sca.policy.PolicySetAttachPoint; +import org.apache.tuscany.sca.policy.util.PolicyHandler; +import org.apache.tuscany.sca.provider.PolicyProvider; +import org.apache.tuscany.sca.provider.WireFormatProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; + +/** + * @version $Rev$ $Date$ + */ +public class WireFormatJMSBytesReferenceProvider implements WireFormatProvider { + private ExtensionPointRegistry registry; + private RuntimeComponent component; + private RuntimeComponentReference reference; + private JMSBinding binding; + private InterfaceContract interfaceContract; + + public WireFormatJMSBytesReferenceProvider(ExtensionPointRegistry registry, + RuntimeComponent component, + RuntimeComponentReference reference, + Binding binding) { + super(); + this.registry = registry; + this.component = component; + this.reference = reference; + this.binding = (JMSBinding)binding; + + // configure the reference based on this wire format + + // currently maintaining the message processor structure which + // contains the details of jms message processing however overried + // any message processors specied in the SCDL in this case + this.binding.setRequestMessageProcessorName(JMSBindingConstants.BYTES_MP_CLASSNAME); + this.binding.setResponseMessageProcessorName(JMSBindingConstants.BYTES_MP_CLASSNAME); + + // just point to the reference interface contract so no + // databinding transformation takes place + interfaceContract = reference.getInterfaceContract(); + } + + public InterfaceContract getWireFormatInterfaceContract() { + return interfaceContract; + } + + public Interceptor createInterceptor() { + return new WireFormatJMSBytesReferenceInterceptor(binding, + null, + reference.getRuntimeWire(binding)); + } + + public String getPhase() { + return Phase.REFERENCE_BINDING_WIREFORMAT; + } + +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsbytes/WireFormatJMSBytesServiceInterceptor.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsbytes/WireFormatJMSBytesServiceInterceptor.java new file mode 100644 index 0000000000..7c7c622fbc --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsbytes/WireFormatJMSBytesServiceInterceptor.java @@ -0,0 +1,111 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms.wireformat.jmsbytes; + +import javax.jms.JMSException; +import javax.jms.Session; + +import org.apache.tuscany.sca.assembly.WireFormat; +import org.apache.tuscany.sca.binding.jms.context.JMSBindingContext; +import org.apache.tuscany.sca.binding.jms.impl.JMSBinding; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingConstants; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingException; +import org.apache.tuscany.sca.binding.jms.provider.JMSMessageProcessor; +import org.apache.tuscany.sca.binding.jms.provider.JMSMessageProcessorUtil; +import org.apache.tuscany.sca.binding.jms.provider.JMSResourceFactory; +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.runtime.RuntimeWire; + +/** + * Policy handler to handle PolicySet related to Logging with the QName + * {http://tuscany.apache.org/xmlns/sca/1.0/impl/java}LoggingPolicy + * + * @version $Rev$ $Date$ + */ +public class WireFormatJMSBytesServiceInterceptor implements Interceptor { + private Invoker next; + private RuntimeWire runtimeWire; + private JMSResourceFactory jmsResourceFactory; + private JMSBinding jmsBinding; + private JMSMessageProcessor requestMessageProcessor; + private JMSMessageProcessor responseMessageProcessor; + + public WireFormatJMSBytesServiceInterceptor(JMSBinding jmsBinding, JMSResourceFactory jmsResourceFactory, RuntimeWire runtimeWire) { + super(); + this.jmsBinding = jmsBinding; + this.runtimeWire = runtimeWire; + this.jmsResourceFactory = jmsResourceFactory; + this.requestMessageProcessor = JMSMessageProcessorUtil.getRequestMessageProcessor(jmsBinding); + this.responseMessageProcessor = JMSMessageProcessorUtil.getResponseMessageProcessor(jmsBinding); + } + + public Message invoke(Message msg) { + if (jmsBinding.getRequestWireFormat() instanceof WireFormatJMSBytes){ + msg = invokeRequest(msg); + } + + msg = getNext().invoke(msg); + + if (jmsBinding.getResponseWireFormat() instanceof WireFormatJMSBytes){ + msg = invokeResponse(msg); + } + + return msg; + } + + public Message invokeRequest(Message msg) { + // get the jms context + JMSBindingContext context = (JMSBindingContext)msg.getHeaders().get(JMSBindingConstants.MSG_CTXT_POSITION); + javax.jms.Message jmsMsg = context.getJmsMsg(); + + Object requestPayload = requestMessageProcessor.extractPayloadFromJMSMessage(jmsMsg); + msg.setBody(requestPayload); + + return msg; + } + + public Message invokeResponse(Message msg) { + // get the jms context + JMSBindingContext context = (JMSBindingContext)msg.getHeaders().get(JMSBindingConstants.MSG_CTXT_POSITION); + javax.jms.Message requestJMSMsg = context.getJmsMsg(); + Session session = context.getJmsSession(); + + javax.jms.Message responseJMSMsg; + if (msg.isFault()) { + responseJMSMsg = responseMessageProcessor.createFaultMessage(session, (Throwable)msg.getBody()); + } else { + Object[] response = {msg.getBody()}; + responseJMSMsg = responseMessageProcessor.insertPayloadIntoJMSMessage(session, response); + } + + msg.setBody(responseJMSMsg); + + return msg; + } + + public Invoker getNext() { + return next; + } + + public void setNext(Invoker next) { + this.next = next; + } +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsbytes/WireFormatJMSBytesServiceProvider.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsbytes/WireFormatJMSBytesServiceProvider.java new file mode 100644 index 0000000000..60ea1c7ff4 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsbytes/WireFormatJMSBytesServiceProvider.java @@ -0,0 +1,91 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.jms.wireformat.jmsbytes; + +import java.util.List; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.binding.jms.impl.JMSBinding; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingConstants; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.Phase; +import org.apache.tuscany.sca.policy.PolicySet; +import org.apache.tuscany.sca.policy.PolicySetAttachPoint; +import org.apache.tuscany.sca.policy.util.PolicyHandler; +import org.apache.tuscany.sca.provider.PolicyProvider; +import org.apache.tuscany.sca.provider.WireFormatProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; + +/** + * @version $Rev$ $Date$ + */ +public class WireFormatJMSBytesServiceProvider implements WireFormatProvider { + private ExtensionPointRegistry registry; + private RuntimeComponent component; + private RuntimeComponentService service; + private JMSBinding binding; + private InterfaceContract interfaceContract; + + public WireFormatJMSBytesServiceProvider(ExtensionPointRegistry registry, + RuntimeComponent component, + RuntimeComponentService service, + Binding binding) { + super(); + this.registry = registry; + this.component = component; + this.service = service; + this.binding = (JMSBinding)binding; + + // configure the service based on this wire format + + // currently maintaining the message processor structure which + // contains the details of jms message processing however overried + // any message processors specied in the SCDL in this case + this.binding.setRequestMessageProcessorName(JMSBindingConstants.BYTES_MP_CLASSNAME); + this.binding.setResponseMessageProcessorName(JMSBindingConstants.BYTES_MP_CLASSNAME); + + // just point to the reference interface contract so no + // databinding transformation takes place + interfaceContract = service.getInterfaceContract(); + } + + public InterfaceContract getWireFormatInterfaceContract() { + return interfaceContract; + } + + /** + */ + public Interceptor createInterceptor() { + return new WireFormatJMSBytesServiceInterceptor((JMSBinding)binding, + null, + service.getRuntimeWire(binding)); + } + + /** + */ + public String getPhase() { + return Phase.SERVICE_BINDING_WIREFORMAT; + } + +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsobject/WireFormatJMSObjectProviderFactory.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsobject/WireFormatJMSObjectProviderFactory.java new file mode 100644 index 0000000000..5811ca53e0 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsobject/WireFormatJMSObjectProviderFactory.java @@ -0,0 +1,65 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.jms.wireformat.jmsobject; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.provider.WireFormatProvider; +import org.apache.tuscany.sca.provider.WireFormatProviderFactory; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; + +/** + * @version $Rev$ $Date$ + */ +public class WireFormatJMSObjectProviderFactory implements WireFormatProviderFactory { + private ExtensionPointRegistry registry; + + public WireFormatJMSObjectProviderFactory(ExtensionPointRegistry registry) { + super(); + this.registry = registry; + } + + /** + */ + public WireFormatProvider createReferenceWireFormatProvider(RuntimeComponent component, + RuntimeComponentReference reference, + Binding binding) { + return new WireFormatJMSObjectReferenceProvider(registry, component, reference, binding); + } + + /** + */ + public WireFormatProvider createServiceWireFormatProvider(RuntimeComponent component, + RuntimeComponentService service, + Binding binding) { + return new WireFormatJMSObjectServiceProvider(registry, component, service, binding); + } + + /** + * @see org.apache.tuscany.sca.provider.ProviderFactory#getModelType() + */ + public Class getModelType() { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsobject/WireFormatJMSObjectReferenceInterceptor.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsobject/WireFormatJMSObjectReferenceInterceptor.java new file mode 100644 index 0000000000..9653c0d51e --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsobject/WireFormatJMSObjectReferenceInterceptor.java @@ -0,0 +1,111 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms.wireformat.jmsobject; + + +import javax.jms.JMSException; +import javax.jms.Session; + +import org.apache.tuscany.sca.assembly.WireFormat; +import org.apache.tuscany.sca.binding.jms.context.JMSBindingContext; +import org.apache.tuscany.sca.binding.jms.impl.JMSBinding; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingConstants; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingException; +import org.apache.tuscany.sca.binding.jms.provider.JMSMessageProcessor; +import org.apache.tuscany.sca.binding.jms.provider.JMSMessageProcessorUtil; +import org.apache.tuscany.sca.binding.jms.provider.JMSResourceFactory; +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.runtime.RuntimeWire; + +/** + * + * @version $Rev$ $Date$ + */ +public class WireFormatJMSObjectReferenceInterceptor implements Interceptor { + + private Invoker next; + private RuntimeWire runtimeWire; + private JMSResourceFactory jmsResourceFactory; + private JMSBinding jmsBinding; + private JMSMessageProcessor requestMessageProcessor; + private JMSMessageProcessor responseMessageProcessor; + + public WireFormatJMSObjectReferenceInterceptor(JMSBinding jmsBinding, JMSResourceFactory jmsResourceFactory, RuntimeWire runtimeWire) { + super(); + this.jmsBinding = jmsBinding; + this.runtimeWire = runtimeWire; + this.jmsResourceFactory = jmsResourceFactory; + this.requestMessageProcessor = JMSMessageProcessorUtil.getRequestMessageProcessor(jmsBinding); + this.responseMessageProcessor = JMSMessageProcessorUtil.getResponseMessageProcessor(jmsBinding); + } + + public Message invoke(Message msg) { + if (jmsBinding.getRequestWireFormat() instanceof WireFormatJMSObject){ + msg = invokeRequest(msg); + } + + msg = getNext().invoke(msg); + + if (jmsBinding.getResponseWireFormat() instanceof WireFormatJMSObject){ + msg = invokeResponse(msg); + } + + return msg; + } + + public Message invokeRequest(Message msg) { + try { + // get the jms context + JMSBindingContext context = (JMSBindingContext)msg.getHeaders().get(JMSBindingConstants.MSG_CTXT_POSITION); + Session session = context.getJmsSession(); + + javax.jms.Message requestMsg = requestMessageProcessor.insertPayloadIntoJMSMessage(session, msg.getBody()); + msg.setBody(requestMsg); + + requestMsg.setJMSReplyTo(context.getReplyToDestination()); + + return msg; + } catch (JMSException e) { + throw new JMSBindingException(e); + } + } + + public Message invokeResponse(Message msg) { + if (msg.getBody() != null){ + Object[] response = (Object[])responseMessageProcessor.extractPayloadFromJMSMessage((javax.jms.Message)msg.getBody()); + if (response != null && response.length > 0){ + msg.setBody(response[0]); + } else { + msg.setBody(null); + } + } + + return msg; + } + + public Invoker getNext() { + return next; + } + + public void setNext(Invoker next) { + this.next = next; + } +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsobject/WireFormatJMSObjectReferenceProvider.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsobject/WireFormatJMSObjectReferenceProvider.java new file mode 100644 index 0000000000..b993ae9067 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsobject/WireFormatJMSObjectReferenceProvider.java @@ -0,0 +1,94 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.jms.wireformat.jmsobject; + +import java.util.List; + +import org.apache.axiom.om.OMElement; +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.binding.jms.impl.JMSBinding; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingConstants; +import org.apache.tuscany.sca.binding.jms.provider.JMSMessageProcessorUtil; +import org.apache.tuscany.sca.binding.jms.provider.XMLTextMessageProcessor; +import org.apache.tuscany.sca.binding.jms.wireformat.jmstextxml.WireFormatJMSTextXML; +import org.apache.tuscany.sca.binding.ws.WebServiceBinding; +import org.apache.tuscany.sca.binding.ws.WebServiceBindingFactory; +import org.apache.tuscany.sca.binding.ws.wsdlgen.BindingWSDLGenerator; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.Phase; +import org.apache.tuscany.sca.policy.PolicySet; +import org.apache.tuscany.sca.policy.PolicySetAttachPoint; +import org.apache.tuscany.sca.policy.util.PolicyHandler; +import org.apache.tuscany.sca.provider.PolicyProvider; +import org.apache.tuscany.sca.provider.WireFormatProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; + +/** + * @version $Rev$ $Date$ + */ +public class WireFormatJMSObjectReferenceProvider implements WireFormatProvider { + private ExtensionPointRegistry registry; + private RuntimeComponent component; + private RuntimeComponentReference reference; + private JMSBinding binding; + private InterfaceContract interfaceContract; + + public WireFormatJMSObjectReferenceProvider(ExtensionPointRegistry registry, + RuntimeComponent component, + RuntimeComponentReference reference, + Binding binding) { + super(); + this.registry = registry; + this.component = component; + this.reference = reference; + this.binding = (JMSBinding)binding; + + // configure the reference based on this wire format + + // currently maintaining the message processor structure which + // contains the details of jms message processing however overried + // any message processors specied in the SCDL in this case + this.binding.setRequestMessageProcessorName(JMSBindingConstants.OBJECT_MP_CLASSNAME); + this.binding.setResponseMessageProcessorName(JMSBindingConstants.OBJECT_MP_CLASSNAME); + + // just point to the reference interface contract so no + // databinding transformation takes place + interfaceContract = reference.getInterfaceContract(); + } + + public InterfaceContract getWireFormatInterfaceContract() { + return interfaceContract; + } + + public Interceptor createInterceptor() { + return new WireFormatJMSObjectReferenceInterceptor(binding, + null, + reference.getRuntimeWire(binding)); + } + + public String getPhase() { + return Phase.REFERENCE_BINDING_WIREFORMAT; + } + +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsobject/WireFormatJMSObjectServiceInterceptor.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsobject/WireFormatJMSObjectServiceInterceptor.java new file mode 100644 index 0000000000..4bfbd2be0e --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsobject/WireFormatJMSObjectServiceInterceptor.java @@ -0,0 +1,111 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms.wireformat.jmsobject; + +import javax.jms.JMSException; +import javax.jms.Session; + +import org.apache.tuscany.sca.assembly.WireFormat; +import org.apache.tuscany.sca.binding.jms.context.JMSBindingContext; +import org.apache.tuscany.sca.binding.jms.impl.JMSBinding; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingConstants; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingException; +import org.apache.tuscany.sca.binding.jms.provider.JMSMessageProcessor; +import org.apache.tuscany.sca.binding.jms.provider.JMSMessageProcessorUtil; +import org.apache.tuscany.sca.binding.jms.provider.JMSResourceFactory; +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.runtime.RuntimeWire; + +/** + * Policy handler to handle PolicySet related to Logging with the QName + * {http://tuscany.apache.org/xmlns/sca/1.0/impl/java}LoggingPolicy + * + * @version $Rev$ $Date$ + */ +public class WireFormatJMSObjectServiceInterceptor implements Interceptor { + private Invoker next; + private RuntimeWire runtimeWire; + private JMSResourceFactory jmsResourceFactory; + private JMSBinding jmsBinding; + private JMSMessageProcessor requestMessageProcessor; + private JMSMessageProcessor responseMessageProcessor; + + public WireFormatJMSObjectServiceInterceptor(JMSBinding jmsBinding, JMSResourceFactory jmsResourceFactory, RuntimeWire runtimeWire) { + super(); + this.jmsBinding = jmsBinding; + this.runtimeWire = runtimeWire; + this.jmsResourceFactory = jmsResourceFactory; + this.requestMessageProcessor = JMSMessageProcessorUtil.getRequestMessageProcessor(jmsBinding); + this.responseMessageProcessor = JMSMessageProcessorUtil.getResponseMessageProcessor(jmsBinding); + } + + public Message invoke(Message msg) { + if (jmsBinding.getRequestWireFormat() instanceof WireFormatJMSObject){ + msg = invokeRequest(msg); + } + + msg = getNext().invoke(msg); + + if (jmsBinding.getResponseWireFormat() instanceof WireFormatJMSObject){ + msg = invokeResponse(msg); + } + + return msg; + } + + public Message invokeRequest(Message msg) { + // get the jms context + JMSBindingContext context = (JMSBindingContext)msg.getHeaders().get(JMSBindingConstants.MSG_CTXT_POSITION); + javax.jms.Message jmsMsg = context.getJmsMsg(); + + Object requestPayload = requestMessageProcessor.extractPayloadFromJMSMessage(jmsMsg); + msg.setBody(requestPayload); + + return msg; + } + + public Message invokeResponse(Message msg) { + // get the jms context + JMSBindingContext context = (JMSBindingContext)msg.getHeaders().get(JMSBindingConstants.MSG_CTXT_POSITION); + javax.jms.Message requestJMSMsg = context.getJmsMsg(); + Session session = context.getJmsSession(); + + javax.jms.Message responseJMSMsg; + if (msg.isFault()) { + responseJMSMsg = responseMessageProcessor.createFaultMessage(session, (Throwable)msg.getBody()); + } else { + Object[] response = {msg.getBody()}; + responseJMSMsg = responseMessageProcessor.insertPayloadIntoJMSMessage(session, response); + } + + msg.setBody(responseJMSMsg); + + return msg; + } + + public Invoker getNext() { + return next; + } + + public void setNext(Invoker next) { + this.next = next; + } +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsobject/WireFormatJMSObjectServiceProvider.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsobject/WireFormatJMSObjectServiceProvider.java new file mode 100644 index 0000000000..9def71a6e0 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsobject/WireFormatJMSObjectServiceProvider.java @@ -0,0 +1,91 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.jms.wireformat.jmsobject; + +import java.util.List; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.binding.jms.impl.JMSBinding; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingConstants; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.Phase; +import org.apache.tuscany.sca.policy.PolicySet; +import org.apache.tuscany.sca.policy.PolicySetAttachPoint; +import org.apache.tuscany.sca.policy.util.PolicyHandler; +import org.apache.tuscany.sca.provider.PolicyProvider; +import org.apache.tuscany.sca.provider.WireFormatProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; + +/** + * @version $Rev$ $Date$ + */ +public class WireFormatJMSObjectServiceProvider implements WireFormatProvider { + private ExtensionPointRegistry registry; + private RuntimeComponent component; + private RuntimeComponentService service; + private JMSBinding binding; + private InterfaceContract interfaceContract; + + public WireFormatJMSObjectServiceProvider(ExtensionPointRegistry registry, + RuntimeComponent component, + RuntimeComponentService service, + Binding binding) { + super(); + this.registry = registry; + this.component = component; + this.service = service; + this.binding = (JMSBinding)binding; + + // configure the service based on this wire format + + // currently maintaining the message processor structure which + // contains the details of jms message processing however overried + // any message processors specied in the SCDL in this case + this.binding.setRequestMessageProcessorName(JMSBindingConstants.OBJECT_MP_CLASSNAME); + this.binding.setResponseMessageProcessorName(JMSBindingConstants.OBJECT_MP_CLASSNAME); + + // just point to the reference interface contract so no + // databinding transformation takes place + interfaceContract = service.getInterfaceContract(); + } + + public InterfaceContract getWireFormatInterfaceContract() { + return interfaceContract; + } + + /** + */ + public Interceptor createInterceptor() { + return new WireFormatJMSObjectServiceInterceptor((JMSBinding)binding, + null, + service.getRuntimeWire(binding)); + } + + /** + */ + public String getPhase() { + return Phase.SERVICE_BINDING_WIREFORMAT; + } + +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstext/WireFormatJMSTextProviderFactory.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstext/WireFormatJMSTextProviderFactory.java new file mode 100644 index 0000000000..5480cc8165 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstext/WireFormatJMSTextProviderFactory.java @@ -0,0 +1,65 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.jms.wireformat.jmstext; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.provider.WireFormatProvider; +import org.apache.tuscany.sca.provider.WireFormatProviderFactory; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; + +/** + * @version $Rev$ $Date$ + */ +public class WireFormatJMSTextProviderFactory implements WireFormatProviderFactory { + private ExtensionPointRegistry registry; + + public WireFormatJMSTextProviderFactory(ExtensionPointRegistry registry) { + super(); + this.registry = registry; + } + + /** + */ + public WireFormatProvider createReferenceWireFormatProvider(RuntimeComponent component, + RuntimeComponentReference reference, + Binding binding) { + return new WireFormatJMSTextReferenceProvider(registry, component, reference, binding); + } + + /** + */ + public WireFormatProvider createServiceWireFormatProvider(RuntimeComponent component, + RuntimeComponentService service, + Binding binding) { + return new WireFormatJMSTextServiceProvider(registry, component, service, binding); + } + + /** + * @see org.apache.tuscany.sca.provider.ProviderFactory#getModelType() + */ + public Class getModelType() { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstext/WireFormatJMSTextReferenceInterceptor.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstext/WireFormatJMSTextReferenceInterceptor.java new file mode 100644 index 0000000000..e317f42266 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstext/WireFormatJMSTextReferenceInterceptor.java @@ -0,0 +1,112 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms.wireformat.jmstext; + + +import javax.jms.JMSException; +import javax.jms.Session; + +import org.apache.tuscany.sca.assembly.WireFormat; +import org.apache.tuscany.sca.binding.jms.context.JMSBindingContext; +import org.apache.tuscany.sca.binding.jms.impl.JMSBinding; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingConstants; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingException; +import org.apache.tuscany.sca.binding.jms.provider.JMSMessageProcessor; +import org.apache.tuscany.sca.binding.jms.provider.JMSMessageProcessorUtil; +import org.apache.tuscany.sca.binding.jms.provider.JMSResourceFactory; +import org.apache.tuscany.sca.binding.jms.wireformat.jmstextxml.WireFormatJMSTextXML; +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.runtime.RuntimeWire; + +/** + * + * @version $Rev$ $Date$ + */ +public class WireFormatJMSTextReferenceInterceptor implements Interceptor { + + private Invoker next; + private RuntimeWire runtimeWire; + private JMSResourceFactory jmsResourceFactory; + private JMSBinding jmsBinding; + private JMSMessageProcessor requestMessageProcessor; + private JMSMessageProcessor responseMessageProcessor; + + public WireFormatJMSTextReferenceInterceptor(JMSBinding jmsBinding, JMSResourceFactory jmsResourceFactory, RuntimeWire runtimeWire) { + super(); + this.jmsBinding = jmsBinding; + this.runtimeWire = runtimeWire; + this.jmsResourceFactory = jmsResourceFactory; + this.requestMessageProcessor = JMSMessageProcessorUtil.getRequestMessageProcessor(jmsBinding); + this.responseMessageProcessor = JMSMessageProcessorUtil.getResponseMessageProcessor(jmsBinding); + } + + public Message invoke(Message msg) { + if (jmsBinding.getRequestWireFormat() instanceof WireFormatJMSText){ + msg = invokeRequest(msg); + } + + msg = getNext().invoke(msg); + + if (jmsBinding.getResponseWireFormat() instanceof WireFormatJMSText){ + msg = invokeResponse(msg); + } + + return msg; + } + + public Message invokeRequest(Message msg) { + try { + // get the jms context + JMSBindingContext context = (JMSBindingContext)msg.getHeaders().get(JMSBindingConstants.MSG_CTXT_POSITION); + Session session = context.getJmsSession(); + + javax.jms.Message requestMsg = requestMessageProcessor.insertPayloadIntoJMSMessage(session, msg.getBody()); + msg.setBody(requestMsg); + + requestMsg.setJMSReplyTo(context.getReplyToDestination()); + + return msg; + } catch (JMSException e) { + throw new JMSBindingException(e); + } + } + + public Message invokeResponse(Message msg) { + if (msg.getBody() != null){ + Object[] response = (Object[])responseMessageProcessor.extractPayloadFromJMSMessage((javax.jms.Message)msg.getBody()); + if (response != null && response.length > 0){ + msg.setBody(response[0]); + } else { + msg.setBody(null); + } + } + + return msg; + } + + public Invoker getNext() { + return next; + } + + public void setNext(Invoker next) { + this.next = next; + } +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstext/WireFormatJMSTextReferenceProvider.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstext/WireFormatJMSTextReferenceProvider.java new file mode 100644 index 0000000000..7e749a96d6 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstext/WireFormatJMSTextReferenceProvider.java @@ -0,0 +1,95 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.jms.wireformat.jmstext; + +import java.util.List; + +import org.apache.axiom.om.OMElement; +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.binding.jms.impl.JMSBinding; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingConstants; +import org.apache.tuscany.sca.binding.jms.provider.JMSMessageProcessorUtil; +import org.apache.tuscany.sca.binding.jms.provider.XMLTextMessageProcessor; +import org.apache.tuscany.sca.binding.jms.wireformat.jmstextxml.WireFormatJMSTextXML; +import org.apache.tuscany.sca.binding.ws.WebServiceBinding; +import org.apache.tuscany.sca.binding.ws.WebServiceBindingFactory; +import org.apache.tuscany.sca.binding.ws.wsdlgen.BindingWSDLGenerator; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.Phase; +import org.apache.tuscany.sca.policy.PolicySet; +import org.apache.tuscany.sca.policy.PolicySetAttachPoint; +import org.apache.tuscany.sca.policy.util.PolicyHandler; +import org.apache.tuscany.sca.provider.PolicyProvider; +import org.apache.tuscany.sca.provider.WireFormatProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; + +/** + * @version $Rev$ $Date$ + */ +public class WireFormatJMSTextReferenceProvider implements WireFormatProvider { + private ExtensionPointRegistry registry; + private RuntimeComponent component; + private RuntimeComponentReference reference; + private JMSBinding binding; + private InterfaceContract interfaceContract; + + public WireFormatJMSTextReferenceProvider(ExtensionPointRegistry registry, + RuntimeComponent component, + RuntimeComponentReference reference, + Binding binding) { + super(); + this.registry = registry; + this.component = component; + this.reference = reference; + this.binding = (JMSBinding)binding; + + // configure the reference based on this wire format + + // currently maintaining the message processor structure which + // contains the details of jms message processing however overried + // any message processors specied in the SCDL in this case + this.binding.setRequestMessageProcessorName(JMSBindingConstants.TEXT_MP_CLASSNAME); + this.binding.setResponseMessageProcessorName(JMSBindingConstants.TEXT_MP_CLASSNAME); + + + // just point to the reference interface contract so no + // databinding transformation takes place + interfaceContract = reference.getInterfaceContract(); + } + + public InterfaceContract getWireFormatInterfaceContract() { + return interfaceContract; + } + + public Interceptor createInterceptor() { + return new WireFormatJMSTextReferenceInterceptor(binding, + null, + reference.getRuntimeWire(binding)); + } + + public String getPhase() { + return Phase.REFERENCE_BINDING_WIREFORMAT; + } + +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstext/WireFormatJMSTextServiceInterceptor.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstext/WireFormatJMSTextServiceInterceptor.java new file mode 100644 index 0000000000..3dc2d0199d --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstext/WireFormatJMSTextServiceInterceptor.java @@ -0,0 +1,111 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms.wireformat.jmstext; + +import javax.jms.JMSException; +import javax.jms.Session; + +import org.apache.tuscany.sca.assembly.WireFormat; +import org.apache.tuscany.sca.binding.jms.context.JMSBindingContext; +import org.apache.tuscany.sca.binding.jms.impl.JMSBinding; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingConstants; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingException; +import org.apache.tuscany.sca.binding.jms.provider.JMSMessageProcessor; +import org.apache.tuscany.sca.binding.jms.provider.JMSMessageProcessorUtil; +import org.apache.tuscany.sca.binding.jms.provider.JMSResourceFactory; +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.runtime.RuntimeWire; + +/** + * Policy handler to handle PolicySet related to Logging with the QName + * {http://tuscany.apache.org/xmlns/sca/1.0/impl/java}LoggingPolicy + * + * @version $Rev$ $Date$ + */ +public class WireFormatJMSTextServiceInterceptor implements Interceptor { + private Invoker next; + private RuntimeWire runtimeWire; + private JMSResourceFactory jmsResourceFactory; + private JMSBinding jmsBinding; + private JMSMessageProcessor requestMessageProcessor; + private JMSMessageProcessor responseMessageProcessor; + + public WireFormatJMSTextServiceInterceptor(JMSBinding jmsBinding, JMSResourceFactory jmsResourceFactory, RuntimeWire runtimeWire) { + super(); + this.jmsBinding = jmsBinding; + this.runtimeWire = runtimeWire; + this.jmsResourceFactory = jmsResourceFactory; + this.requestMessageProcessor = JMSMessageProcessorUtil.getRequestMessageProcessor(jmsBinding); + this.responseMessageProcessor = JMSMessageProcessorUtil.getResponseMessageProcessor(jmsBinding); + } + + public Message invoke(Message msg) { + if (jmsBinding.getRequestWireFormat() instanceof WireFormatJMSText){ + msg = invokeRequest(msg); + } + + msg = getNext().invoke(msg); + + if (jmsBinding.getResponseWireFormat() instanceof WireFormatJMSText){ + msg = invokeResponse(msg); + } + + return msg; + } + + public Message invokeRequest(Message msg) { + // get the jms context + JMSBindingContext context = (JMSBindingContext)msg.getHeaders().get(JMSBindingConstants.MSG_CTXT_POSITION); + javax.jms.Message jmsMsg = context.getJmsMsg(); + + Object requestPayload = requestMessageProcessor.extractPayloadFromJMSMessage(jmsMsg); + msg.setBody(requestPayload); + + return msg; + } + + public Message invokeResponse(Message msg) { + // get the jms context + JMSBindingContext context = (JMSBindingContext)msg.getHeaders().get(JMSBindingConstants.MSG_CTXT_POSITION); + javax.jms.Message requestJMSMsg = context.getJmsMsg(); + Session session = context.getJmsSession(); + + javax.jms.Message responseJMSMsg; + if (msg.isFault()) { + responseJMSMsg = responseMessageProcessor.createFaultMessage(session, (Throwable)msg.getBody()); + } else { + Object[] response = {msg.getBody()}; + responseJMSMsg = responseMessageProcessor.insertPayloadIntoJMSMessage(session, response); + } + + msg.setBody(responseJMSMsg); + + return msg; + } + + public Invoker getNext() { + return next; + } + + public void setNext(Invoker next) { + this.next = next; + } +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstext/WireFormatJMSTextServiceProvider.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstext/WireFormatJMSTextServiceProvider.java new file mode 100644 index 0000000000..6f9f0c9da9 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstext/WireFormatJMSTextServiceProvider.java @@ -0,0 +1,91 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.jms.wireformat.jmstext; + +import java.util.List; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.binding.jms.impl.JMSBinding; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingConstants; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.Phase; +import org.apache.tuscany.sca.policy.PolicySet; +import org.apache.tuscany.sca.policy.PolicySetAttachPoint; +import org.apache.tuscany.sca.policy.util.PolicyHandler; +import org.apache.tuscany.sca.provider.PolicyProvider; +import org.apache.tuscany.sca.provider.WireFormatProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; + +/** + * @version $Rev$ $Date$ + */ +public class WireFormatJMSTextServiceProvider implements WireFormatProvider { + private ExtensionPointRegistry registry; + private RuntimeComponent component; + private RuntimeComponentService service; + private JMSBinding binding; + private InterfaceContract interfaceContract; + + public WireFormatJMSTextServiceProvider(ExtensionPointRegistry registry, + RuntimeComponent component, + RuntimeComponentService service, + Binding binding) { + super(); + this.registry = registry; + this.component = component; + this.service = service; + this.binding = (JMSBinding)binding; + + // configure the service based on this wire format + + // currently maintaining the message processor structure which + // contains the details of jms message processing however overried + // any message processors specied in the SCDL in this case + this.binding.setRequestMessageProcessorName(JMSBindingConstants.TEXT_MP_CLASSNAME); + this.binding.setResponseMessageProcessorName(JMSBindingConstants.TEXT_MP_CLASSNAME); + + // just point to the reference interface contract so no + // databinding transformation takes place + interfaceContract = service.getInterfaceContract(); + } + + public InterfaceContract getWireFormatInterfaceContract() { + return interfaceContract; + } + + /** + */ + public Interceptor createInterceptor() { + return new WireFormatJMSTextServiceInterceptor((JMSBinding)binding, + null, + service.getRuntimeWire(binding)); + } + + /** + */ + public String getPhase() { + return Phase.SERVICE_BINDING_WIREFORMAT; + } + +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstextxml/WireFormatJMSTextXMLProviderFactory.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstextxml/WireFormatJMSTextXMLProviderFactory.java new file mode 100644 index 0000000000..6bef4e8160 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstextxml/WireFormatJMSTextXMLProviderFactory.java @@ -0,0 +1,72 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.jms.wireformat.jmstextxml; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.binding.jms.impl.JMSBinding; +import org.apache.tuscany.sca.binding.jms.provider.JMSResourceFactory; +import org.apache.tuscany.sca.binding.jms.provider.JMSResourceFactoryExtensionPoint; +import org.apache.tuscany.sca.binding.jms.wireformat.jmstextxml.WireFormatJMSTextXML; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.provider.WireFormatProvider; +import org.apache.tuscany.sca.provider.WireFormatProviderFactory; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; + +/** + * @version $Rev$ $Date$ + */ +public class WireFormatJMSTextXMLProviderFactory implements WireFormatProviderFactory { + private ExtensionPointRegistry registry; + private JMSResourceFactoryExtensionPoint jmsRFEP; + + public WireFormatJMSTextXMLProviderFactory(ExtensionPointRegistry registry) { + super(); + this.registry = registry; + jmsRFEP = (JMSResourceFactoryExtensionPoint)registry.getExtensionPoint(JMSResourceFactoryExtensionPoint.class); + } + + /** + */ + public WireFormatProvider createReferenceWireFormatProvider(RuntimeComponent component, + RuntimeComponentReference reference, + Binding binding) { + return new WireFormatJMSTextXMLReferenceProvider(registry, component, reference, binding); + } + + /** + */ + public WireFormatProvider createServiceWireFormatProvider(RuntimeComponent component, + RuntimeComponentService service, + Binding binding) { + JMSResourceFactory jmsRF = jmsRFEP.createJMSResourceFactory((JMSBinding)binding); + return new WireFormatJMSTextXMLServiceProvider(registry, component, service, binding, jmsRF); + } + + /** + * @see org.apache.tuscany.sca.provider.ProviderFactory#getModelType() + */ + public Class getModelType() { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstextxml/WireFormatJMSTextXMLReferenceInterceptor.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstextxml/WireFormatJMSTextXMLReferenceInterceptor.java new file mode 100644 index 0000000000..86a5bbb4b2 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstextxml/WireFormatJMSTextXMLReferenceInterceptor.java @@ -0,0 +1,125 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms.wireformat.jmstextxml; + + + + +import java.util.Map; + +import javax.jms.DeliveryMode; +import javax.jms.JMSException; +import javax.jms.Session; + +import org.apache.tuscany.sca.assembly.Reference; +import org.apache.tuscany.sca.assembly.WireFormat; +import org.apache.tuscany.sca.binding.jms.context.JMSBindingContext; +import org.apache.tuscany.sca.binding.jms.impl.JMSBinding; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingConstants; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingException; +import org.apache.tuscany.sca.binding.jms.provider.JMSBindingServiceBindingProvider; +import org.apache.tuscany.sca.binding.jms.provider.JMSMessageProcessor; +import org.apache.tuscany.sca.binding.jms.provider.JMSMessageProcessorUtil; +import org.apache.tuscany.sca.binding.jms.provider.JMSResourceFactory; +import org.apache.tuscany.sca.binding.jms.wireformat.jmstextxml.WireFormatJMSTextXML; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.interfacedef.java.JavaInterface; +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.runtime.ReferenceParameters; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; +import org.apache.tuscany.sca.runtime.RuntimeWire; + +/** + * + * @version $Rev$ $Date$ + */ +public class WireFormatJMSTextXMLReferenceInterceptor implements Interceptor { + + private Invoker next; + private RuntimeWire runtimeWire; + private JMSResourceFactory jmsResourceFactory; + private JMSBinding jmsBinding; + private JMSMessageProcessor requestMessageProcessor; + private JMSMessageProcessor responseMessageProcessor; + + + public WireFormatJMSTextXMLReferenceInterceptor(JMSBinding jmsBinding, JMSResourceFactory jmsResourceFactory, RuntimeWire runtimeWire) { + super(); + this.jmsBinding = jmsBinding; + this.runtimeWire = runtimeWire; + this.jmsResourceFactory = jmsResourceFactory; + this.requestMessageProcessor = JMSMessageProcessorUtil.getRequestMessageProcessor(jmsBinding); + this.responseMessageProcessor = JMSMessageProcessorUtil.getResponseMessageProcessor(jmsBinding); + } + + public Message invoke(Message msg) { + if (jmsBinding.getRequestWireFormat() instanceof WireFormatJMSTextXML){ + msg = invokeRequest(msg); + } + + msg = getNext().invoke(msg); + + if (jmsBinding.getResponseWireFormat() instanceof WireFormatJMSTextXML){ + msg = invokeResponse(msg); + } + + return msg; + } + + public Message invokeRequest(Message msg) { + try { + // get the jms context + JMSBindingContext context = (JMSBindingContext)msg.getHeaders().get(JMSBindingConstants.MSG_CTXT_POSITION); + Session session = context.getJmsSession(); + + javax.jms.Message requestMsg = requestMessageProcessor.insertPayloadIntoJMSMessage(session, msg.getBody()); + msg.setBody(requestMsg); + + requestMsg.setJMSReplyTo(context.getReplyToDestination()); + + return msg; + } catch (JMSException e) { + throw new JMSBindingException(e); + } + } + + public Message invokeResponse(Message msg) { + if (msg.getBody() != null){ + Object[] response = (Object[])responseMessageProcessor.extractPayloadFromJMSMessage((javax.jms.Message)msg.getBody()); + if (response != null && response.length > 0){ + msg.setBody(response[0]); + } else { + msg.setBody(null); + } + } + + return msg; + } + + public Invoker getNext() { + return next; + } + + public void setNext(Invoker next) { + this.next = next; + } +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstextxml/WireFormatJMSTextXMLReferenceProvider.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstextxml/WireFormatJMSTextXMLReferenceProvider.java new file mode 100644 index 0000000000..b97084b5ad --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstextxml/WireFormatJMSTextXMLReferenceProvider.java @@ -0,0 +1,110 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.jms.wireformat.jmstextxml; + +import java.util.List; + +import org.apache.axiom.om.OMElement; +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.binding.jms.impl.JMSBinding; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingConstants; +import org.apache.tuscany.sca.binding.ws.WebServiceBinding; +import org.apache.tuscany.sca.binding.ws.WebServiceBindingFactory; +import org.apache.tuscany.sca.binding.ws.wsdlgen.BindingWSDLGenerator; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.Phase; +import org.apache.tuscany.sca.policy.PolicySet; +import org.apache.tuscany.sca.policy.PolicySetAttachPoint; +import org.apache.tuscany.sca.policy.util.PolicyHandler; +import org.apache.tuscany.sca.provider.PolicyProvider; +import org.apache.tuscany.sca.provider.WireFormatProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; + +/** + * @version $Rev$ $Date$ + */ +public class WireFormatJMSTextXMLReferenceProvider implements WireFormatProvider { + private ExtensionPointRegistry registry; + private RuntimeComponent component; + private RuntimeComponentReference reference; + private JMSBinding binding; + private InterfaceContract interfaceContract; + + public WireFormatJMSTextXMLReferenceProvider(ExtensionPointRegistry registry, + RuntimeComponent component, + RuntimeComponentReference reference, + Binding binding) { + super(); + this.registry = registry; + this.component = component; + this.reference = reference; + this.binding = (JMSBinding)binding; + + // configure the reference based on this wire format + + // currently maintaining the message processor structure which + // contains the details of jms message processing so set the message + // type here if not set explicitly in SCDL + if (this.binding.getRequestMessageProcessorName().equals(JMSBindingConstants.XML_MP_CLASSNAME) ){ + this.binding.setRequestMessageProcessorName(JMSBindingConstants.XML_MP_CLASSNAME); + this.binding.setResponseMessageProcessorName(JMSBindingConstants.XML_MP_CLASSNAME); + } + + // set the binding interface contract to represent the WSDL for the + // xml messages that will be sent + if (reference.getInterfaceContract() != null && + !isOnMessage()) { + WebServiceBindingFactory wsFactory = registry.getExtensionPoint(WebServiceBindingFactory.class); + WebServiceBinding wsBinding = wsFactory.createWebServiceBinding(); + BindingWSDLGenerator.generateWSDL(component, reference, wsBinding, registry, null); + interfaceContract = wsBinding.getBindingInterfaceContract(); + interfaceContract.getInterface().resetDataBinding(OMElement.class.getName()); + } else { + interfaceContract = reference.getInterfaceContract(); + } + } + + protected boolean isOnMessage() { + InterfaceContract ic = reference.getInterfaceContract(); + if (ic.getInterface().getOperations().size() != 1) { + return false; + } + return "onMessage".equals(ic.getInterface().getOperations().get(0).getName()); + } + + public InterfaceContract getWireFormatInterfaceContract() { + return interfaceContract; + } + + public Interceptor createInterceptor() { + return new WireFormatJMSTextXMLReferenceInterceptor((JMSBinding)binding, + null, + reference.getRuntimeWire(binding)); + } + + public String getPhase() { + return Phase.REFERENCE_BINDING_WIREFORMAT; + } + +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstextxml/WireFormatJMSTextXMLServiceInterceptor.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstextxml/WireFormatJMSTextXMLServiceInterceptor.java new file mode 100644 index 0000000000..ffec9d67f8 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstextxml/WireFormatJMSTextXMLServiceInterceptor.java @@ -0,0 +1,118 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms.wireformat.jmstextxml; + +import javax.jms.JMSException; +import javax.jms.Session; +import javax.naming.NamingException; + +import org.apache.tuscany.sca.assembly.WireFormat; +import org.apache.tuscany.sca.binding.jms.context.JMSBindingContext; +import org.apache.tuscany.sca.binding.jms.impl.JMSBinding; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingConstants; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingException; +import org.apache.tuscany.sca.binding.jms.provider.JMSMessageProcessor; +import org.apache.tuscany.sca.binding.jms.provider.JMSMessageProcessorUtil; +import org.apache.tuscany.sca.binding.jms.provider.JMSResourceFactory; +import org.apache.tuscany.sca.binding.jms.wireformat.jmstextxml.WireFormatJMSTextXML; +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.runtime.RuntimeWire; + +/** + * Policy handler to handle PolicySet related to Logging with the QName + * {http://tuscany.apache.org/xmlns/sca/1.0/impl/java}LoggingPolicy + * + * @version $Rev$ $Date$ + */ +public class WireFormatJMSTextXMLServiceInterceptor implements Interceptor { + private Invoker next; + private RuntimeWire runtimeWire; + private JMSResourceFactory jmsResourceFactory; + private JMSBinding jmsBinding; + private JMSMessageProcessor requestMessageProcessor; + private JMSMessageProcessor responseMessageProcessor; + + public WireFormatJMSTextXMLServiceInterceptor(JMSBinding jmsBinding, JMSResourceFactory jmsResourceFactory, RuntimeWire runtimeWire) { + super(); + this.jmsBinding = jmsBinding; + this.runtimeWire = runtimeWire; + this.jmsResourceFactory = jmsResourceFactory; + this.requestMessageProcessor = JMSMessageProcessorUtil.getRequestMessageProcessor(jmsBinding); + this.responseMessageProcessor = JMSMessageProcessorUtil.getResponseMessageProcessor(jmsBinding); + } + + public Message invoke(Message msg) { + + if (jmsBinding.getRequestWireFormat() instanceof WireFormatJMSTextXML){ + msg = invokeRequest(msg); + } + + msg = getNext().invoke(msg); + + if (jmsBinding.getResponseWireFormat() instanceof WireFormatJMSTextXML){ + msg = invokeResponse(msg); + } + + return msg; + } + + public Message invokeRequest(Message msg) { + // get the jms context + JMSBindingContext context = (JMSBindingContext)msg.getHeaders().get(JMSBindingConstants.MSG_CTXT_POSITION); + javax.jms.Message jmsMsg = context.getJmsMsg(); + + if ("onMessage".equals(msg.getOperation().getName())) { + msg.setBody(new Object[]{jmsMsg}); + } else { + Object requestPayload = requestMessageProcessor.extractPayloadFromJMSMessage(jmsMsg); + msg.setBody(requestPayload); + } + + return msg; + } + + public Message invokeResponse(Message msg) { + + // get the jms context + JMSBindingContext context = (JMSBindingContext)msg.getHeaders().get(JMSBindingConstants.MSG_CTXT_POSITION); + javax.jms.Message requestJMSMsg = context.getJmsMsg(); + Session session = context.getJmsSession(); + + javax.jms.Message responseJMSMsg; + if (msg.isFault()) { + responseJMSMsg = responseMessageProcessor.createFaultMessage(session, (Throwable)msg.getBody()); + } else { + responseJMSMsg = responseMessageProcessor.insertPayloadIntoJMSMessage(session, msg.getBody()); + } + + msg.setBody(responseJMSMsg); + + return msg; + } + + public Invoker getNext() { + return next; + } + + public void setNext(Invoker next) { + this.next = next; + } +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstextxml/WireFormatJMSTextXMLServiceProvider.java b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstextxml/WireFormatJMSTextXMLServiceProvider.java new file mode 100644 index 0000000000..651a96f596 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstextxml/WireFormatJMSTextXMLServiceProvider.java @@ -0,0 +1,113 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.jms.wireformat.jmstextxml; + +import java.util.List; + +import org.apache.axiom.om.OMElement; +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.binding.jms.impl.JMSBinding; +import org.apache.tuscany.sca.binding.jms.impl.JMSBindingConstants; +import org.apache.tuscany.sca.binding.jms.provider.JMSResourceFactory; +import org.apache.tuscany.sca.binding.ws.WebServiceBinding; +import org.apache.tuscany.sca.binding.ws.WebServiceBindingFactory; +import org.apache.tuscany.sca.binding.ws.wsdlgen.BindingWSDLGenerator; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.Phase; +import org.apache.tuscany.sca.policy.PolicySet; +import org.apache.tuscany.sca.policy.PolicySetAttachPoint; +import org.apache.tuscany.sca.policy.util.PolicyHandler; +import org.apache.tuscany.sca.provider.PolicyProvider; +import org.apache.tuscany.sca.provider.WireFormatProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; + +/** + * @version $Rev$ $Date$ + */ +public class WireFormatJMSTextXMLServiceProvider implements WireFormatProvider { + private ExtensionPointRegistry registry; + private RuntimeComponent component; + private RuntimeComponentService service; + private JMSBinding binding; + private JMSResourceFactory jmsResourceFactory; + private InterfaceContract interfaceContract; + + public WireFormatJMSTextXMLServiceProvider(ExtensionPointRegistry registry, + RuntimeComponent component, + RuntimeComponentService service, + Binding binding, + JMSResourceFactory jmsResourceFactory) { + super(); + this.component = component; + this.service = service; + this.binding = (JMSBinding)binding; + this.jmsResourceFactory = jmsResourceFactory; + + // configure the service based on this wire format + + // currently maintaining the message processor structure which + // contains the details of jms message processing so set the message + // type here if not set explicitly in SCDL + if (this.binding.getRequestMessageProcessorName().equals(JMSBindingConstants.XML_MP_CLASSNAME) ){ + this.binding.setRequestMessageProcessorName(JMSBindingConstants.XML_MP_CLASSNAME); + this.binding.setResponseMessageProcessorName(JMSBindingConstants.XML_MP_CLASSNAME); + } + + // set the binding interface contract to represent the WSDL for the + // xml messages that will be sent + if (service.getInterfaceContract() != null && + !isOnMessage()) { + WebServiceBindingFactory wsFactory = registry.getExtensionPoint(WebServiceBindingFactory.class); + WebServiceBinding wsBinding = wsFactory.createWebServiceBinding(); + BindingWSDLGenerator.generateWSDL(component, service, wsBinding, registry, null); + interfaceContract = wsBinding.getBindingInterfaceContract(); + interfaceContract.getInterface().resetDataBinding(OMElement.class.getName()); + } else { + interfaceContract = service.getInterfaceContract(); + } + } + + protected boolean isOnMessage() { + InterfaceContract ic = service.getInterfaceContract(); + if (ic.getInterface().getOperations().size() != 1) { + return false; + } + return "onMessage".equals(ic.getInterface().getOperations().get(0).getName()); + } + + public InterfaceContract getWireFormatInterfaceContract() { + return interfaceContract; + } + + public Interceptor createInterceptor() { + return new WireFormatJMSTextXMLServiceInterceptor((JMSBinding)binding, + jmsResourceFactory, + service.getRuntimeWire(binding)); + } + + public String getPhase() { + return Phase.SERVICE_BINDING_WIREFORMAT; + } + +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.BindingProviderFactory b/java/sca/contrib/modules/binding-jms-runtime/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.BindingProviderFactory new file mode 100644 index 0000000000..4cb8e90b7a --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.BindingProviderFactory @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for the binding extension +org.apache.tuscany.sca.binding.jms.provider.JMSBindingProviderFactory;model=org.apache.tuscany.sca.binding.jms.JMSBinding diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.OperationSelectorProviderFactory b/java/sca/contrib/modules/binding-jms-runtime/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.OperationSelectorProviderFactory new file mode 100644 index 0000000000..50dfcdf9a0 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.OperationSelectorProviderFactory @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for the binding extension +org.apache.tuscany.sca.binding.jms.operationselector.jmsdefault.OperationSelectorJMSDefaultProviderFactory;model=org.apache.tuscany.sca.binding.jms.operationselector.jmsdefault.OperationSelectorJMSDefault diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.WireFormatProviderFactory b/java/sca/contrib/modules/binding-jms-runtime/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.WireFormatProviderFactory new file mode 100644 index 0000000000..c82d4e7cab --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.WireFormatProviderFactory @@ -0,0 +1,22 @@ +# 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. + +# Implementation class for the binding extension +org.apache.tuscany.sca.binding.jms.wireformat.jmstextxml.WireFormatJMSTextXMLProviderFactory;model=org.apache.tuscany.sca.binding.jms.wireformat.jmstextxml.WireFormatJMSTextXML +org.apache.tuscany.sca.binding.jms.wireformat.jmsbytes.WireFormatJMSBytesProviderFactory;model=org.apache.tuscany.sca.binding.jms.wireformat.jmsbytes.WireFormatJMSBytes +org.apache.tuscany.sca.binding.jms.wireformat.jmstext.WireFormatJMSTextProviderFactory;model=org.apache.tuscany.sca.binding.jms.wireformat.jmstext.WireFormatJMSText +org.apache.tuscany.sca.binding.jms.wireformat.jmsobject.WireFormatJMSObjectProviderFactory;model=org.apache.tuscany.sca.binding.jms.wireformat.jmsobject.WireFormatJMSObject diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/test/java/org/apache/tuscany/sca/binding/jms/HelloWorldClientImpl.java b/java/sca/contrib/modules/binding-jms-runtime/src/test/java/org/apache/tuscany/sca/binding/jms/HelloWorldClientImpl.java new file mode 100644 index 0000000000..a3a2f0bf1e --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/test/java/org/apache/tuscany/sca/binding/jms/HelloWorldClientImpl.java @@ -0,0 +1,43 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms; + +import org.oasisopen.sca.annotation.Reference; +import org.oasisopen.sca.annotation.Service; + +/** + * This class implements the HelloWorld service. + * + * @version $Rev$ $Date$ + */ +@Service(HelloWorldService.class) +public class HelloWorldClientImpl implements HelloWorldService { + + private HelloWorldService serviceA; + + @Reference + public void setServiceA(HelloWorldService service) { + this.serviceA = service; + } + + public String sayHello(String name) { + return serviceA.sayHello(name); + } + +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/test/java/org/apache/tuscany/sca/binding/jms/HelloWorldService.java b/java/sca/contrib/modules/binding-jms-runtime/src/test/java/org/apache/tuscany/sca/binding/jms/HelloWorldService.java new file mode 100644 index 0000000000..d68270f7df --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/test/java/org/apache/tuscany/sca/binding/jms/HelloWorldService.java @@ -0,0 +1,31 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms; + +import org.oasisopen.sca.annotation.Remotable; + +/** + * Interface for the HelloWorld Service. + * + * @version $Rev$ $Date$ + */ +@Remotable +public interface HelloWorldService { + String sayHello(String name); +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/test/java/org/apache/tuscany/sca/binding/jms/HelloWorldServiceImpl.java b/java/sca/contrib/modules/binding-jms-runtime/src/test/java/org/apache/tuscany/sca/binding/jms/HelloWorldServiceImpl.java new file mode 100644 index 0000000000..a8808c1bd1 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/test/java/org/apache/tuscany/sca/binding/jms/HelloWorldServiceImpl.java @@ -0,0 +1,32 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms; + +/** + * Implementation of the HelloWorldService. + * + * @version $Rev$ $Date$ + */ +public class HelloWorldServiceImpl implements HelloWorldService { + + public String sayHello(String name) { + return "jmsHello " + name; + } + +} diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/test/resources/simple/client.composite b/java/sca/contrib/modules/binding-jms-runtime/src/test/resources/simple/client.composite new file mode 100644 index 0000000000..dcea428493 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/test/resources/simple/client.composite @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/java/sca/contrib/modules/binding-jms-runtime/src/test/resources/simple/service.composite b/java/sca/contrib/modules/binding-jms-runtime/src/test/resources/simple/service.composite new file mode 100644 index 0000000000..44b7b29610 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms-runtime/src/test/resources/simple/service.composite @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + diff --git a/java/sca/contrib/modules/binding-jms/LICENSE b/java/sca/contrib/modules/binding-jms/LICENSE new file mode 100644 index 0000000000..8aa906c321 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms/LICENSE @@ -0,0 +1,205 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + + diff --git a/java/sca/contrib/modules/binding-jms/META-INF/MANIFEST.MF b/java/sca/contrib/modules/binding-jms/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..0eb40a9005 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms/META-INF/MANIFEST.MF @@ -0,0 +1,30 @@ +Manifest-Version: 1.0 +Export-Package: org.apache.tuscany.sca.binding.jms;version="2.0.0";uses:="org.apache.tuscany.sca.assembly", + org.apache.tuscany.sca.binding.jms.xml;version="2.0.0" +Private-Package: org.apache.tuscany.sca.binding.jms.impl;version="2.0.0" + ,org.apache.tuscany.sca.binding.jms.xml;version="2.0.0" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA JMS Binding Model +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397280359 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA JMS Binding Model +Import-Package: javax.xml.namespace, + javax.xml.stream, + + org.apache.tuscany.sca.assembly;version="2.0.0", + org.apache.tuscany.sca.assembly.xml;version="2.0.0", + org.apache.tuscany.sca.binding.jms;version="2.0.0", + org.apache.tuscany.sca.binding.jms.xml;version="2.0.0", + org.apache.tuscany.sca.contribution.processor;version="2.0.0", + org.apache.tuscany.sca.contribution.resolver;version="2.0.0", + org.apache.tuscany.sca.core;version="2.0.0", + org.apache.tuscany.sca.interfacedef;version="2.0.0", + org.apache.tuscany.sca.monitor;version="2.0.0", + org.apache.tuscany.sca.policy;version="2.0.0" +Bundle-SymbolicName: org.apache.tuscany.sca.binding.jms +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/binding-jms/NOTICE b/java/sca/contrib/modules/binding-jms/NOTICE new file mode 100644 index 0000000000..25bb89c9b2 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/binding-jms/pom.xml b/java/sca/contrib/modules/binding-jms/pom.xml new file mode 100644 index 0000000000..ba4bb7763e --- /dev/null +++ b/java/sca/contrib/modules/binding-jms/pom.xml @@ -0,0 +1,48 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + tuscany-binding-jms + Apache Tuscany SCA JMS Binding Model + + + + + org.apache.tuscany.sca + tuscany-assembly-xml + 2.0-SNAPSHOT + + + + junit + junit + 4.5 + test + + + + + diff --git a/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/JMSBinding.java b/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/JMSBinding.java new file mode 100644 index 0000000000..ddc41a463a --- /dev/null +++ b/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/JMSBinding.java @@ -0,0 +1,241 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.apache.tuscany.sca.assembly.Binding; + +/** + * Models a binding to a JMS resource. + * + * @version $Rev$ $Date$ + */ + +public interface JMSBinding extends Binding { + + public Object clone() throws CloneNotSupportedException; + + /** + * Returns the binding URI. + * + * @return the binding URI + */ + public String getURI(); + + /** + * Sets the binding URI. + * + * @param uri the binding URI + */ + public void setURI(String uri); + + /** + * Returns the binding name. + * + * @return the binding name + */ + public String getName(); + + /** + * Sets the binding name. + * + * @param name the binding name + */ + public void setName(String name); + + public boolean isUnresolved(); + + public void setUnresolved(boolean unresolved); + + public List getExtensions(); + + // Methods for getting/setting JMS binding model information + // as derived from the XML of the binding.jms element + + public void setCorrelationScheme(String correlationScheme); + + public String getCorrelationScheme(); + + public String getInitialContextFactoryName(); + + public void setInitialContextFactoryName(String initialContextFactoryName); + + public String getJndiURL(); + + public void setJndiURL(String jndiURL); + + public String getDestinationName(); + + public void setDestinationName(String destinationName); + + public String getDestinationType(); + + public void setDestinationType(String destinationType); + + public String getDestinationCreate(); + + public void setDestinationCreate(String create); + + public String getConnectionFactoryName(); + + public void setConnectionFactoryName(String connectionFactoryName); + + public String getConnectionFactoryCreate(); + + public void setConnectionFactoryCreate(String create); + + public String getActivationSpecName(); + + public void setActivationSpecName(String activationSpecName); + + public String getActivationSpecCreate(); + + public void setActivationSpecCreate(String create); + + public String getResponseDestinationName(); + + public void setResponseDestinationName(String name); + + public String getResponseDestinationType(); + + public void setResponseDestinationType(String type); + + public String getResponseDestinationCreate(); + + public void setResponseDestinationCreate(String create); + + public String getResponseConnectionFactoryName(); + + public void setResponseConnectionFactoryName(String connectionFactoryName); + + public String getResponseConnectionFactoryCreate(); + + public void setResponseConnectionFactoryCreate(String create); + + public String getResponseActivationSpecName(); + + public void setResponseActivationSpecName(String activationSpecName); + + public String getResponseActivationSpecCreate(); + + public void setResponseActivationSpecCreate(String create); + + public String getJmsResourceFactoryName(); + + public void setJmsResourceFactoryName(String jmsResourceFactoryName); + + public void setRequestMessageProcessorName(String name); + + public String getRequestMessageProcessorName(); + + public void setResponseMessageProcessorName(String name); + + public String getResponseMessageProcessorName(); + + public String getOperationSelectorPropertyName(); + + public void setOperationSelectorPropertyName(String operationSelectorPropertyName); + + public String getOperationSelectorName(); + + public void setOperationSelectorName(String operationSelectorName); + + public String getReplyTo(); + + public void setReplyTo(String replyTo); + + public String getJMSType(); + + public void setJMSType(String jmsType); + + public String getJMSCorrelationId(); + + public void setJMSCorrelationId(String jmsCorrelationId); + + public Boolean isdeliveryModePersistent(); + + public void setJMSDeliveryMode(boolean persistent); + + public Integer getJMSPriority(); + + public void setJMSPriority(int jmsPriority); + + public Long getJMSTimeToLive(); + + public void setJMSTimeToLive(long timeToLive); + + public Set getPropertyNames(); + + public Object getProperty(String name); + + public void setProperty(String name, Object value); + + public Map getOperationProperties(String opName); + + public void setOperationProperty(String opName, String propName, Object value); + + public boolean hasNativeOperationName(String opName); + + public String getNativeOperationName(String opName); + + public void setNativeOperationName(String opName, String nativeOpName); + + public String getOperationJMSType(String opName); + + public void setOperationJMSType(String opName, String jmsType); + + public String getOperationJMSCorrelationId(String opName); + + public void setOperationJMSCorrelationId(String opName, String jmsCorrelationId); + + public Boolean getOperationJMSDeliveryMode(String opName); + + public void setOperationJMSDeliveryMode(String opName, boolean b); + + public Long getOperationJMSTimeToLive(String opName); + + public void setOperationJMSTimeToLive(String opName, Long ttl); + + public Integer getOperationJMSPriority(String opName); + + public void setOperationJMSPriority(String opName, int p); + + public String getJMSSelector(); + + public void setJMSSelector(String jmsSelector); + + public String getRequestConnectionName(); + + public void setRequestConnectionName(String requestConnectionName); + + public void setResponseConnectionName(String responseConnectionName); + + public String getResponseConnectionName(); + + public void setRequestConnectionBinding(JMSBinding binding); + + public JMSBinding getRequestConnectionBinding(); + + public void setResponseConnectionBinding(JMSBinding binding); + + public JMSBinding getResponseConnectionBinding(); +} diff --git a/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/JMSBindingException.java b/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/JMSBindingException.java new file mode 100644 index 0000000000..74f030ca21 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/JMSBindingException.java @@ -0,0 +1,45 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms; + +/** + * Base exception for the JMSBinding. + * + * @version $Rev$ $Date$ + */ +public class JMSBindingException extends RuntimeException { + private static final long serialVersionUID = 1L; + + public JMSBindingException() { + super(); + } + + public JMSBindingException(String arg0, Throwable arg1) { + super(arg0, arg1); + } + + public JMSBindingException(String arg0) { + super(arg0); + } + + public JMSBindingException(Throwable arg0) { + super(arg0); + } + +} diff --git a/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/JMSBindingFactory.java b/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/JMSBindingFactory.java new file mode 100644 index 0000000000..d96dadf8c5 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/JMSBindingFactory.java @@ -0,0 +1,31 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms; + +/** + * Factroy interface to create JMSBinding model + * + */ +public interface JMSBindingFactory { + /** + * Create an instance of JMSBinding + * @return A new instance of JMSBinding + */ + JMSBinding createJMSBinding(); +} diff --git a/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/impl/JMSBindingFactoryImpl.java b/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/impl/JMSBindingFactoryImpl.java new file mode 100644 index 0000000000..b67ee97eb3 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/impl/JMSBindingFactoryImpl.java @@ -0,0 +1,34 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms.impl; + +import org.apache.tuscany.sca.binding.jms.JMSBinding; +import org.apache.tuscany.sca.binding.jms.JMSBindingFactory; + +/** + * Default implementation of JMSBindingFactory + * + */ +public class JMSBindingFactoryImpl implements JMSBindingFactory { + + public JMSBinding createJMSBinding() { + return new JMSBindingImpl(); + } + +} diff --git a/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/impl/JMSBindingImpl.java b/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/impl/JMSBindingImpl.java new file mode 100644 index 0000000000..b6bb6fe67c --- /dev/null +++ b/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/impl/JMSBindingImpl.java @@ -0,0 +1,573 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms.impl; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.apache.tuscany.sca.binding.jms.JMSBinding; +import org.apache.tuscany.sca.binding.jms.xml.JMSBindingConstants; + +/** + * Models a binding to a JMS resource. + * + * @version $Rev$ $Date$ + */ + +public class JMSBindingImpl implements JMSBinding { + + @Override + public Object clone() throws CloneNotSupportedException { + return super.clone(); + } + + // properties required to implement the Tuscany binding extension SPI + private String uri = null; + private String name = null; + private boolean unresolved = false; + private List extensions = new ArrayList(); + + // Properties required to describe the JMS binding model + + private String correlationScheme = JMSBindingConstants.CORRELATE_MSG_ID; + private String initialContextFactoryName; + private String jndiURL; + + private String destinationName = JMSBindingConstants.DEFAULT_DESTINATION_NAME; + private String destinationType = JMSBindingConstants.DESTINATION_TYPE_QUEUE; + private String destinationCreate = JMSBindingConstants.CREATE_IF_NOT_EXIST; + + private String connectionFactoryName = JMSBindingConstants.DEFAULT_CONNECTION_FACTORY_NAME; + private String connectionFactoryCreate = JMSBindingConstants.CREATE_IF_NOT_EXIST; + + private String activationSpecName = null; + private String activationSpecCreate = null; + + private String responseActivationSpecName = null; + private String responseActivationSpecCreate = null; + + private String responseDestinationName = JMSBindingConstants.DEFAULT_RESPONSE_DESTINATION_NAME; + private String responseDestinationType = JMSBindingConstants.DESTINATION_TYPE_QUEUE; + private String responseDestinationCreate = JMSBindingConstants.CREATE_IF_NOT_EXIST; + + private String responseConnectionFactoryName = JMSBindingConstants.DEFAULT_CONNECTION_FACTORY_NAME; + private String responseConnectionFactoryCreate = JMSBindingConstants.CREATE_IF_NOT_EXIST; + + // Provides the name of the factory that interfaces to the JMS API for us. + private String jmsResourceFactoryName = JMSBindingConstants.DEFAULT_RF_CLASSNAME; + + // Message processors used to deal with the request and response messages + public String requestMessageProcessorName = JMSBindingConstants.DEFAULT_MP_CLASSNAME; + public String responseMessageProcessorName = JMSBindingConstants.DEFAULT_MP_CLASSNAME; + + // The JMS message property used to hold the name of the operation being called + private String operationSelectorPropertyName = JMSBindingConstants.DEFAULT_OPERATION_PROP_NAME; + + // If the operation selector is derived automatically from the service interface it's stored here + private String operationSelectorName = null; + + private String replyTo; + private String jmsType; + private String jmsCorrelationId; + private Boolean deliveryModePersistent; + private Long timeToLive; + private Integer jmsPriority; + + private Map properties = new HashMap(); + private Map> operationProperties = new HashMap>(); + private Map nativeOperationNames = new HashMap(); + private Map operationJMSTypes = new HashMap(); + private Map operationJMSCorrelationIds = new HashMap(); + private Map operationJMSDeliveryModes = new HashMap(); + private Map operationJMSTimeToLives = new HashMap(); + private Map operationJMSPriorities = new HashMap(); + private String jmsSelector; + private String requestConnectionName; + private String responseConnectionName; + private JMSBinding requestConnectionBinding; + private JMSBinding responseConnectionBinding; + + public JMSBindingImpl() { + super(); + } + + /** + * Returns the binding URI. + * + * @return the binding URI + */ + public String getURI() { + return this.uri; + } + + /** + * Sets the binding URI. + * + * @param uri the binding URI + */ + public void setURI(String uri) { + this.uri = uri; + } + + /** + * Returns the binding name. + * + * @return the binding name + */ + public String getName() { + return this.name; + } + + /** + * Sets the binding name. + * + * @param name the binding name + */ + public void setName(String name) { + this.name = name; + } + + public boolean isUnresolved() { + return this.unresolved; + } + + public void setUnresolved(boolean unresolved) { + this.unresolved = unresolved; + } + + public List getExtensions() { + return extensions; + } + + // Methods for getting/setting JMS binding model information + // as derived from the XML of the binding.jms element + + public void setCorrelationScheme(String correlationScheme) { + this.correlationScheme = correlationScheme; + } + + public String getCorrelationScheme() { + return correlationScheme; + } + + public String getInitialContextFactoryName() { + return initialContextFactoryName; + } + + public void setInitialContextFactoryName(String initialContextFactoryName) { + this.initialContextFactoryName = initialContextFactoryName; + } + + public String getJndiURL() { + return this.jndiURL; + } + + public void setJndiURL(String jndiURL) { + this.jndiURL = jndiURL; + } + + public String getDestinationName() { + if (requestConnectionBinding != null && requestConnectionBinding.getDestinationName() != null) { + return requestConnectionBinding.getDestinationName(); + } else { + return destinationName; + } + } + + public void setDestinationName(String destinationName) { + this.destinationName = destinationName; + } + + public String getDestinationType() { + if (requestConnectionBinding != null && requestConnectionBinding.getDestinationType() != null) { + return requestConnectionBinding.getDestinationType(); + } else { + return destinationType; + } + } + + public void setDestinationType(String destinationType) { + this.destinationType = destinationType; + } + + public String getDestinationCreate() { + if (requestConnectionBinding != null && requestConnectionBinding.getDestinationCreate() != null) { + return requestConnectionBinding.getDestinationCreate(); + } else { + return this.destinationCreate; + } + } + + public void setDestinationCreate(String create) { + this.destinationCreate = create; + } + + public String getConnectionFactoryName() { + if (requestConnectionBinding != null && requestConnectionBinding.getConnectionFactoryName() != null) { + return requestConnectionBinding.getConnectionFactoryName(); + } else { + return connectionFactoryName; + } + } + + public void setConnectionFactoryName(String connectionFactoryName) { + this.connectionFactoryName = connectionFactoryName; + } + + public String getConnectionFactoryCreate() { + if (requestConnectionBinding != null && requestConnectionBinding.getConnectionFactoryCreate() != null) { + return requestConnectionBinding.getConnectionFactoryCreate(); + } else { + return this.connectionFactoryCreate; + } + } + + public void setConnectionFactoryCreate(String create) { + this.connectionFactoryCreate = create; + } + + public String getActivationSpecName() { + if (requestConnectionBinding != null && requestConnectionBinding.getActivationSpecName() != null) { + return requestConnectionBinding.getActivationSpecName(); + } else { + return activationSpecName; + } + } + + public void setActivationSpecName(String activationSpecName) { + this.activationSpecName = activationSpecName; + } + + public String getActivationSpecCreate() { + if (requestConnectionBinding != null && requestConnectionBinding.getActivationSpecCreate() != null) { + return requestConnectionBinding.getActivationSpecCreate(); + } else { + return this.activationSpecCreate; + } + } + + public void setActivationSpecCreate(String create) { + this.activationSpecCreate = create; + } + + public String getResponseDestinationName() { + if (requestConnectionBinding != null && requestConnectionBinding.getResponseDestinationName() != null) { + return requestConnectionBinding.getResponseDestinationName(); + } else { + return this.responseDestinationName; + } + } + + public void setResponseDestinationName(String name) { + this.responseDestinationName = name; + } + + public String getResponseDestinationType() { + if (requestConnectionBinding != null && requestConnectionBinding.getResponseDestinationType() != null) { + return requestConnectionBinding.getResponseDestinationType(); + } else { + return this.responseDestinationType; + } + } + + public void setResponseDestinationType(String type) { + this.responseDestinationType = type; + } + + public String getResponseDestinationCreate() { + if (requestConnectionBinding != null && requestConnectionBinding.getResponseDestinationCreate() != null) { + return requestConnectionBinding.getResponseDestinationCreate(); + } else { + return this.responseDestinationCreate; + } + } + + public void setResponseDestinationCreate(String create) { + this.responseDestinationCreate = create; + } + + public String getResponseConnectionFactoryName() { + if (requestConnectionBinding != null && requestConnectionBinding.getResponseConnectionFactoryName() != null) { + return requestConnectionBinding.getResponseConnectionFactoryName(); + } else { + return responseConnectionFactoryName; + } + } + + public void setResponseConnectionFactoryName(String connectionFactoryName) { + this.responseConnectionFactoryName = connectionFactoryName; + } + + public String getResponseConnectionFactoryCreate() { + if (requestConnectionBinding != null && requestConnectionBinding.getResponseConnectionFactoryCreate() != null) { + return requestConnectionBinding.getResponseConnectionFactoryCreate(); + } else { + return this.responseConnectionFactoryCreate; + } + } + + public void setResponseConnectionFactoryCreate(String create) { + this.responseConnectionFactoryCreate = create; + } + + public String getResponseActivationSpecName() { + if (requestConnectionBinding != null && requestConnectionBinding.getResponseActivationSpecName() != null) { + return requestConnectionBinding.getResponseActivationSpecName(); + } else { + return responseActivationSpecName; + } + } + + public void setResponseActivationSpecName(String activationSpecName) { + this.responseActivationSpecName = activationSpecName; + } + + public String getResponseActivationSpecCreate() { + if (requestConnectionBinding != null && requestConnectionBinding.getResponseActivationSpecCreate() != null) { + return requestConnectionBinding.getResponseActivationSpecCreate(); + } else { + return this.responseActivationSpecCreate; + } + } + + public void setResponseActivationSpecCreate(String create) { + this.responseActivationSpecCreate = create; + } + + public String getJmsResourceFactoryName() { + return jmsResourceFactoryName; + } + + public void setJmsResourceFactoryName(String jmsResourceFactoryName) { + this.jmsResourceFactoryName = jmsResourceFactoryName; + } + + public void setRequestMessageProcessorName(String name) { + this.requestMessageProcessorName = name; + } + + public String getRequestMessageProcessorName() { + return requestMessageProcessorName; + } + + public void setResponseMessageProcessorName(String name) { + this.responseMessageProcessorName = name; + } + + public String getResponseMessageProcessorName() { + return responseMessageProcessorName; + } + + public String getOperationSelectorPropertyName() { + return operationSelectorPropertyName; + } + + public void setOperationSelectorPropertyName(String operationSelectorPropertyName) { + this.operationSelectorPropertyName = operationSelectorPropertyName; + } + + public String getOperationSelectorName() { + return operationSelectorName; + } + + public void setOperationSelectorName(String operationSelectorName) { + this.operationSelectorName = operationSelectorName; + } + + public String getReplyTo() { + return replyTo; + } + + public void setReplyTo(String replyTo) { + this.replyTo = replyTo; + } + + public String getJMSType() { + return jmsType; + } + public void setJMSType(String jmsType) { + this.jmsType = jmsType; + } + + public String getJMSCorrelationId() { + return jmsCorrelationId; + } + + public void setJMSCorrelationId(String jmsCorrelationId) { + this.jmsCorrelationId = jmsCorrelationId; + } + + public Boolean isdeliveryModePersistent() { + return deliveryModePersistent; + } + public void setJMSDeliveryMode(boolean persistent) { + this.deliveryModePersistent = Boolean.valueOf(persistent); + } + + public Integer getJMSPriority() { + return jmsPriority; + } + + public void setJMSPriority(int jmsPriority) { + this.jmsPriority = Integer.valueOf(jmsPriority); + } + + public Long getJMSTimeToLive() { + return timeToLive.longValue(); + } + + public void setJMSTimeToLive(long timeToLive) { + this.timeToLive = Long.valueOf(timeToLive); + } + + public Set getPropertyNames() { + return properties.keySet(); + } + + public Object getProperty(String name) { + return properties.get(name); + } + + public void setProperty(String name, Object value) { + properties.put(name, value); + } + + public Map getOperationProperties(String opName) { + return operationProperties.get(opName); + } + + public void setOperationProperty(String opName, String propName, Object value) { + Map props = operationProperties.get(opName); + if (props == null) { + props = new HashMap(); + operationProperties.put(opName, props); + } + props.put(propName, value); + } + + public boolean hasNativeOperationName(String opName) { + return nativeOperationNames.containsKey(opName); + } + + public String getNativeOperationName(String opName) { + if (nativeOperationNames.containsKey(opName)) { + return nativeOperationNames.get(opName); + } else { + return opName; + } + } + + public void setNativeOperationName(String opName, String nativeOpName) { + this.nativeOperationNames .put(opName, nativeOpName); + } + + public String getOperationJMSType(String opName) { + if (operationJMSTypes.containsKey(opName)) { + return operationJMSTypes.get(opName); + } else { + return jmsType; + } + } + public void setOperationJMSType(String opName, String jmsType) { + this.operationJMSTypes.put(opName, jmsType); + } + + public String getOperationJMSCorrelationId(String opName) { + if (operationJMSCorrelationIds.containsKey(opName)) { + return operationJMSCorrelationIds.get(opName); + } else { + return jmsCorrelationId; + } + } + public void setOperationJMSCorrelationId(String opName, String jmsCorrelationId) { + operationJMSCorrelationIds.put(opName, jmsCorrelationId); + } + + public Boolean getOperationJMSDeliveryMode(String opName) { + if (operationJMSDeliveryModes.containsKey(opName)) { + return operationJMSDeliveryModes.get(opName); + } else { + return deliveryModePersistent; + } + } + public void setOperationJMSDeliveryMode(String opName, boolean b) { + operationJMSDeliveryModes.put(opName, b); + } + + public Long getOperationJMSTimeToLive(String opName) { + if (operationJMSTimeToLives.containsKey(opName)) { + return operationJMSTimeToLives.get(opName); + } else { + return timeToLive; + } + } + public void setOperationJMSTimeToLive(String opName, Long ttl) { + operationJMSTimeToLives.put(opName, ttl); + } + + public Integer getOperationJMSPriority(String opName) { + if (operationJMSPriorities.containsKey(opName)) { + return operationJMSPriorities.get(opName); + } else { + return jmsPriority; + } + } + public void setOperationJMSPriority(String opName, int p) { + operationJMSPriorities.put(opName, p); + } + + public String getJMSSelector() { + return jmsSelector; + } + public void setJMSSelector(String jmsSelector) { + this.jmsSelector = jmsSelector; + } + + public String getRequestConnectionName() { + return requestConnectionName; + } + + public void setRequestConnectionName(String requestConnectionName) { + this.requestConnectionName = requestConnectionName; + } + + public void setResponseConnectionName(String responseConnectionName) { + this.responseConnectionName = responseConnectionName; + } + public String getResponseConnectionName() { + return responseConnectionName; + } + + public void setRequestConnectionBinding(JMSBinding binding) { + this.requestConnectionBinding = binding; + } + public JMSBinding getRequestConnectionBinding() { + return requestConnectionBinding; + } + + public void setResponseConnectionBinding(JMSBinding binding) { + this.responseConnectionBinding = binding; + } + public JMSBinding getResponseConnectionBinding() { + return responseConnectionBinding; + } +} diff --git a/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/operationselector/jmsdefault/OperationSelectorJMSDefault.java b/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/operationselector/jmsdefault/OperationSelectorJMSDefault.java new file mode 100644 index 0000000000..71d1298c9b --- /dev/null +++ b/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/operationselector/jmsdefault/OperationSelectorJMSDefault.java @@ -0,0 +1,45 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms.operationselector.jmsdefault; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.assembly.xml.Constants; +import org.apache.tuscany.sca.assembly.OperationSelector; + +/** + * Implementation for policies that could be injected as parameter + * into the axis2config. + * + * @version $Rev$ $Date$ + */ +public class OperationSelectorJMSDefault implements OperationSelector { + public static final QName OPERATION_SELECTOR_JMS_DEFAULT_QNAME = new QName(Constants.SCA10_TUSCANY_NS, "operationSelector.JMSDefault"); + + public QName getSchemaName() { + return OPERATION_SELECTOR_JMS_DEFAULT_QNAME; + } + + public boolean isUnresolved() { + return false; + } + + public void setUnresolved(boolean unresolved) { + } +} diff --git a/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/operationselector/jmsdefault/OperationSelectorJMSDefaultProcessor.java b/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/operationselector/jmsdefault/OperationSelectorJMSDefaultProcessor.java new file mode 100644 index 0000000000..4a8e4a1bd2 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/operationselector/jmsdefault/OperationSelectorJMSDefaultProcessor.java @@ -0,0 +1,76 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms.operationselector.jmsdefault; + + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; + +import org.apache.tuscany.sca.assembly.xml.Constants; +import org.apache.tuscany.sca.contribution.ModelFactoryExtensionPoint; +import org.apache.tuscany.sca.contribution.processor.BaseStAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.contribution.service.ContributionReadException; +import org.apache.tuscany.sca.contribution.service.ContributionResolveException; +import org.apache.tuscany.sca.contribution.service.ContributionWriteException; +import org.apache.tuscany.sca.monitor.Monitor; + +/** + * + * @version $Rev$ $Date$ + */ +public class OperationSelectorJMSDefaultProcessor extends BaseStAXArtifactProcessor implements StAXArtifactProcessor { + + public QName getArtifactType() { + return OperationSelectorJMSDefault.OPERATION_SELECTOR_JMS_DEFAULT_QNAME; + } + + public OperationSelectorJMSDefaultProcessor(ModelFactoryExtensionPoint modelFactories, Monitor monitor) { + } + + + public OperationSelectorJMSDefault read(XMLStreamReader reader) throws ContributionReadException, XMLStreamException { + OperationSelectorJMSDefault wireFormat = new OperationSelectorJMSDefault(); + + return wireFormat; + } + + public void write(OperationSelectorJMSDefault wireFormat, XMLStreamWriter writer) + throws ContributionWriteException, XMLStreamException { + String prefix = "tuscany"; + writer.writeStartElement(prefix, + getArtifactType().getLocalPart(), + getArtifactType().getNamespaceURI()); + writer.writeNamespace("tuscany", Constants.SCA10_TUSCANY_NS); + + writer.writeEndElement(); + } + + public Class getModelType() { + return OperationSelectorJMSDefault.class; + } + + public void resolve(OperationSelectorJMSDefault arg0, ModelResolver arg1) throws ContributionResolveException { + + } + +} diff --git a/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsbytes/WireFormatJMSBytes.java b/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsbytes/WireFormatJMSBytes.java new file mode 100644 index 0000000000..84d1a2740f --- /dev/null +++ b/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsbytes/WireFormatJMSBytes.java @@ -0,0 +1,45 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms.wireformat.jmsbytes; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.assembly.xml.Constants; +import org.apache.tuscany.sca.assembly.WireFormat; + +/** + * Implementation for policies that could be injected as parameter + * into the axis2config. + * + * @version $Rev$ $Date$ + */ +public class WireFormatJMSBytes implements WireFormat { + public static final QName WIRE_FORMAT_JMS_BYTES_QNAME = new QName(Constants.SCA10_TUSCANY_NS, "wireFormat.jmsBytes"); + + public QName getSchemaName() { + return WIRE_FORMAT_JMS_BYTES_QNAME; + } + + public boolean isUnresolved() { + return false; + } + + public void setUnresolved(boolean unresolved) { + } +} diff --git a/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsbytes/WireFormatJMSBytesProcessor.java b/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsbytes/WireFormatJMSBytesProcessor.java new file mode 100644 index 0000000000..2d807d49cb --- /dev/null +++ b/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsbytes/WireFormatJMSBytesProcessor.java @@ -0,0 +1,78 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms.wireformat.jmsbytes; + +import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; +import static javax.xml.stream.XMLStreamConstants.START_ELEMENT; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; + +import org.apache.tuscany.sca.assembly.xml.Constants; +import org.apache.tuscany.sca.contribution.ModelFactoryExtensionPoint; +import org.apache.tuscany.sca.contribution.processor.BaseStAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.contribution.service.ContributionReadException; +import org.apache.tuscany.sca.contribution.service.ContributionResolveException; +import org.apache.tuscany.sca.contribution.service.ContributionWriteException; +import org.apache.tuscany.sca.monitor.Monitor; + +/** + * + * @version $Rev$ $Date$ + */ +public class WireFormatJMSBytesProcessor extends BaseStAXArtifactProcessor implements StAXArtifactProcessor { + + public QName getArtifactType() { + return WireFormatJMSBytes.WIRE_FORMAT_JMS_BYTES_QNAME; + } + + public WireFormatJMSBytesProcessor(ModelFactoryExtensionPoint modelFactories, Monitor monitor) { + } + + + public WireFormatJMSBytes read(XMLStreamReader reader) throws ContributionReadException, XMLStreamException { + WireFormatJMSBytes wireFormat = new WireFormatJMSBytes(); + + return wireFormat; + } + + public void write(WireFormatJMSBytes wireFormat, XMLStreamWriter writer) + throws ContributionWriteException, XMLStreamException { + String prefix = "tuscany"; + writer.writeStartElement(prefix, + getArtifactType().getLocalPart(), + getArtifactType().getNamespaceURI()); + writer.writeNamespace("tuscany", Constants.SCA10_TUSCANY_NS); + + writer.writeEndElement(); + } + + public Class getModelType() { + return WireFormatJMSBytes.class; + } + + public void resolve(WireFormatJMSBytes arg0, ModelResolver arg1) throws ContributionResolveException { + + } + +} diff --git a/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsobject/WireFormatJMSObject.java b/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsobject/WireFormatJMSObject.java new file mode 100644 index 0000000000..7e39f696bd --- /dev/null +++ b/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsobject/WireFormatJMSObject.java @@ -0,0 +1,45 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms.wireformat.jmsobject; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.assembly.xml.Constants; +import org.apache.tuscany.sca.assembly.WireFormat; + +/** + * Implementation for policies that could be injected as parameter + * into the axis2config. + * + * @version $Rev$ $Date$ + */ +public class WireFormatJMSObject implements WireFormat { + public static final QName WIRE_FORMAT_JMS_BYTES_QNAME = new QName(Constants.SCA10_TUSCANY_NS, "wireFormat.jmsObject"); + + public QName getSchemaName() { + return WIRE_FORMAT_JMS_BYTES_QNAME; + } + + public boolean isUnresolved() { + return false; + } + + public void setUnresolved(boolean unresolved) { + } +} diff --git a/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsobject/WireFormatJMSObjectProcessor.java b/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsobject/WireFormatJMSObjectProcessor.java new file mode 100644 index 0000000000..806b713931 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmsobject/WireFormatJMSObjectProcessor.java @@ -0,0 +1,78 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms.wireformat.jmsobject; + +import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; +import static javax.xml.stream.XMLStreamConstants.START_ELEMENT; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; + +import org.apache.tuscany.sca.assembly.xml.Constants; +import org.apache.tuscany.sca.contribution.ModelFactoryExtensionPoint; +import org.apache.tuscany.sca.contribution.processor.BaseStAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.contribution.service.ContributionReadException; +import org.apache.tuscany.sca.contribution.service.ContributionResolveException; +import org.apache.tuscany.sca.contribution.service.ContributionWriteException; +import org.apache.tuscany.sca.monitor.Monitor; + +/** + * + * @version $Rev$ $Date$ + */ +public class WireFormatJMSObjectProcessor extends BaseStAXArtifactProcessor implements StAXArtifactProcessor { + + public QName getArtifactType() { + return WireFormatJMSObject.WIRE_FORMAT_JMS_BYTES_QNAME; + } + + public WireFormatJMSObjectProcessor(ModelFactoryExtensionPoint modelFactories, Monitor monitor) { + } + + + public WireFormatJMSObject read(XMLStreamReader reader) throws ContributionReadException, XMLStreamException { + WireFormatJMSObject wireFormat = new WireFormatJMSObject(); + + return wireFormat; + } + + public void write(WireFormatJMSObject wireFormat, XMLStreamWriter writer) + throws ContributionWriteException, XMLStreamException { + String prefix = "tuscany"; + writer.writeStartElement(prefix, + getArtifactType().getLocalPart(), + getArtifactType().getNamespaceURI()); + writer.writeNamespace("tuscany", Constants.SCA10_TUSCANY_NS); + + writer.writeEndElement(); + } + + public Class getModelType() { + return WireFormatJMSObject.class; + } + + public void resolve(WireFormatJMSObject arg0, ModelResolver arg1) throws ContributionResolveException { + + } + +} diff --git a/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstext/WireFormatJMSText.java b/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstext/WireFormatJMSText.java new file mode 100644 index 0000000000..fff33df1f4 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstext/WireFormatJMSText.java @@ -0,0 +1,45 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms.wireformat.jmstext; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.assembly.xml.Constants; +import org.apache.tuscany.sca.assembly.WireFormat; + +/** + * Implementation for policies that could be injected as parameter + * into the axis2config. + * + * @version $Rev$ $Date$ + */ +public class WireFormatJMSText implements WireFormat { + public static final QName WIRE_FORMAT_JMS_BYTES_QNAME = new QName(Constants.SCA10_TUSCANY_NS, "wireFormat.jmsText"); + + public QName getSchemaName() { + return WIRE_FORMAT_JMS_BYTES_QNAME; + } + + public boolean isUnresolved() { + return false; + } + + public void setUnresolved(boolean unresolved) { + } +} diff --git a/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstext/WireFormatJMSTextProcessor.java b/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstext/WireFormatJMSTextProcessor.java new file mode 100644 index 0000000000..9b675df290 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstext/WireFormatJMSTextProcessor.java @@ -0,0 +1,78 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms.wireformat.jmstext; + +import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; +import static javax.xml.stream.XMLStreamConstants.START_ELEMENT; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; + +import org.apache.tuscany.sca.assembly.xml.Constants; +import org.apache.tuscany.sca.contribution.ModelFactoryExtensionPoint; +import org.apache.tuscany.sca.contribution.processor.BaseStAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.contribution.service.ContributionReadException; +import org.apache.tuscany.sca.contribution.service.ContributionResolveException; +import org.apache.tuscany.sca.contribution.service.ContributionWriteException; +import org.apache.tuscany.sca.monitor.Monitor; + +/** + * + * @version $Rev$ $Date$ + */ +public class WireFormatJMSTextProcessor extends BaseStAXArtifactProcessor implements StAXArtifactProcessor { + + public QName getArtifactType() { + return WireFormatJMSText.WIRE_FORMAT_JMS_BYTES_QNAME; + } + + public WireFormatJMSTextProcessor(ModelFactoryExtensionPoint modelFactories, Monitor monitor) { + } + + + public WireFormatJMSText read(XMLStreamReader reader) throws ContributionReadException, XMLStreamException { + WireFormatJMSText wireFormat = new WireFormatJMSText(); + + return wireFormat; + } + + public void write(WireFormatJMSText wireFormat, XMLStreamWriter writer) + throws ContributionWriteException, XMLStreamException { + String prefix = "tuscany"; + writer.writeStartElement(prefix, + getArtifactType().getLocalPart(), + getArtifactType().getNamespaceURI()); + writer.writeNamespace("tuscany", Constants.SCA10_TUSCANY_NS); + + writer.writeEndElement(); + } + + public Class getModelType() { + return WireFormatJMSText.class; + } + + public void resolve(WireFormatJMSText arg0, ModelResolver arg1) throws ContributionResolveException { + + } + +} diff --git a/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstextxml/WireFormatJMSTextXML.java b/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstextxml/WireFormatJMSTextXML.java new file mode 100644 index 0000000000..23a53b9d96 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstextxml/WireFormatJMSTextXML.java @@ -0,0 +1,48 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms.wireformat.jmstextxml; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.assembly.xml.Constants; +import org.apache.tuscany.sca.assembly.WireFormat; + +/** + * + * @version $Rev$ $Date$ + */ +public class WireFormatJMSTextXML implements WireFormat { + public static final QName WIRE_FORMAT_JMS_DEFAULT_QNAME = new QName(Constants.SCA10_TUSCANY_NS, "wireFormat.jmsTextXML"); + + public QName getSchemaName() { + return WIRE_FORMAT_JMS_DEFAULT_QNAME; + } + + public boolean isUnresolved() { + return false; + } + + public void setUnresolved(boolean unresolved) { + } + + @Override + public boolean equals(Object obj) { + return this.getClass() == obj.getClass(); + } +} diff --git a/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstextxml/WireFormatJMSTextXMLProcessor.java b/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstextxml/WireFormatJMSTextXMLProcessor.java new file mode 100644 index 0000000000..8248fc771a --- /dev/null +++ b/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/wireformat/jmstextxml/WireFormatJMSTextXMLProcessor.java @@ -0,0 +1,78 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms.wireformat.jmstextxml; + +import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; +import static javax.xml.stream.XMLStreamConstants.START_ELEMENT; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; + +import org.apache.tuscany.sca.assembly.xml.Constants; +import org.apache.tuscany.sca.contribution.ModelFactoryExtensionPoint; +import org.apache.tuscany.sca.contribution.processor.BaseStAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.contribution.service.ContributionReadException; +import org.apache.tuscany.sca.contribution.service.ContributionResolveException; +import org.apache.tuscany.sca.contribution.service.ContributionWriteException; +import org.apache.tuscany.sca.monitor.Monitor; + +/** + * + * @version $Rev$ $Date$ + */ +public class WireFormatJMSTextXMLProcessor extends BaseStAXArtifactProcessor implements StAXArtifactProcessor { + + public QName getArtifactType() { + return WireFormatJMSTextXML.WIRE_FORMAT_JMS_DEFAULT_QNAME; + } + + public WireFormatJMSTextXMLProcessor(ModelFactoryExtensionPoint modelFactories, Monitor monitor) { + } + + + public WireFormatJMSTextXML read(XMLStreamReader reader) throws ContributionReadException, XMLStreamException { + WireFormatJMSTextXML wireFormat = new WireFormatJMSTextXML(); + + return wireFormat; + } + + public void write(WireFormatJMSTextXML wireFormat, XMLStreamWriter writer) + throws ContributionWriteException, XMLStreamException { + String prefix = "tuscany"; + writer.writeStartElement(prefix, + getArtifactType().getLocalPart(), + getArtifactType().getNamespaceURI()); + writer.writeNamespace("tuscany", Constants.SCA10_TUSCANY_NS); + + writer.writeEndElement(); + } + + public Class getModelType() { + return WireFormatJMSTextXML.class; + } + + public void resolve(WireFormatJMSTextXML arg0, ModelResolver arg1) throws ContributionResolveException { + + } + +} diff --git a/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/xml/JMSBindingConstants.java b/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/xml/JMSBindingConstants.java new file mode 100644 index 0000000000..e299e54cbe --- /dev/null +++ b/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/xml/JMSBindingConstants.java @@ -0,0 +1,72 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jms.xml; + +import java.util.Arrays; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.assembly.xml.Constants; + +/** + * Constants for the JMS binding. + * + * @version $Rev$ $Date$ + */ +public interface JMSBindingConstants { + + // Constants used when describing the JMS binding + // model and for setting up defaults + String BINDING_JMS = "binding.jms"; + QName BINDING_JMS_QNAME = new QName(Constants.SCA10_NS, BINDING_JMS); + String CORRELATE_MSG_ID = "requestmsgidtocorrelid"; + String CORRELATE_CORRELATION_ID = "requestcorrelidtocorrelid"; + String CORRELATE_NONE = "none"; + List VALID_CORRELATION_SCHEMES = + Arrays.asList(new String[] {CORRELATE_MSG_ID, CORRELATE_CORRELATION_ID, CORRELATE_NONE}); + String DESTINATION_TYPE_QUEUE = "queue"; // 0 + String DESTINATION_TYPE_TOPIC = "topic"; // 1 + List VALID_DESTINATION_TYPES = + Arrays.asList(new String[] {DESTINATION_TYPE_QUEUE, DESTINATION_TYPE_TOPIC}); + String CREATE_ALWAYS = "always"; + String CREATE_NEVER = "never"; + String CREATE_IF_NOT_EXIST = "ifnotexist"; + String DEFAULT_DESTINATION_NAME = "NODESTINATION"; + String DEFAULT_RESPONSE_DESTINATION_NAME = "NORESPONSEDESTINATION"; + String DEFAULT_CONNECTION_FACTORY_NAME = "ConnectionFactory"; + String DEFAULT_CONTEXT_FACTORY_NAME = "org.apache.activemq.jndi.ActiveMQInitialContextFactory"; + String DEFAULT_JNDI_URL = "tcp://localhost:61616"; + int DEFAULT_TIME_TO_LIVE = 20000; // in milliseconds + int DEFAULT_PRIORITY = 1; + int NON_PERSISTENT = 1; // Maps to javax.jms.DeliveryMode + String DEFAULT_RF_CLASSNAME = "org.apache.tuscany.sca.host.jms.activemq.JMSResourceFactoryImpl"; + String XML_MP_CLASSNAME = "org.apache.tuscany.sca.binding.jms.provider.XMLTextMessageProcessor"; + String TEXT_MP_CLASSNAME = "org.apache.tuscany.sca.binding.jms.provider.TextMessageProcessor"; + String OBJECT_MP_CLASSNAME = "org.apache.tuscany.sca.binding.jms.provider.ObjectMessageProcessor"; + String DEFAULT_MP_CLASSNAME = XML_MP_CLASSNAME; + String DEFAULT_OPERATION_PROP_NAME = "scaOperationName"; + + String FAULT_PROPERTY = "org_apache_tuscany_sca_fault"; + + String CALLBACK_ID_PROPERTY = "CallbackID"; + String CALLBACK_Q_PROPERTY = "scaCallbackQueue "; + String CONVERSATION_ID_PROPERTY = "scaConversationId"; + +} diff --git a/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/xml/JMSBindingProcessor.java b/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/xml/JMSBindingProcessor.java new file mode 100644 index 0000000000..6b39a9d8d1 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms/src/main/java/org/apache/tuscany/sca/binding/jms/xml/JMSBindingProcessor.java @@ -0,0 +1,688 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.jms.xml; + +import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; +import static javax.xml.stream.XMLStreamConstants.START_ELEMENT; + +import java.util.Map; +import java.util.StringTokenizer; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; + +import org.apache.tuscany.sca.assembly.xml.Constants; +import org.apache.tuscany.sca.assembly.xml.PolicyAttachPointProcessor; +import org.apache.tuscany.sca.binding.jms.JMSBinding; +import org.apache.tuscany.sca.binding.jms.JMSBindingException; +import org.apache.tuscany.sca.binding.jms.JMSBindingFactory; +import org.apache.tuscany.sca.contribution.processor.ContributionReadException; +import org.apache.tuscany.sca.contribution.processor.ContributionResolveException; +import org.apache.tuscany.sca.contribution.processor.ContributionWriteException; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.resolver.DefaultModelResolver; +import org.apache.tuscany.sca.contribution.resolver.ExtensibleModelResolver; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.core.FactoryExtensionPoint; +import org.apache.tuscany.sca.monitor.Monitor; +import org.apache.tuscany.sca.monitor.Problem; +import org.apache.tuscany.sca.monitor.Problem.Severity; +import org.apache.tuscany.sca.policy.PolicyFactory; + +/** + * A processor to read the XML that describes the JMS binding... + * + * + * + * + * * + * ? + * + * + * * + * ? + * + * + * * + * ? + * + * + * + * * + * ? + * + * + * * + * ? + * + * + * * + * ? + * ? + * + * + * + * + * + * ? + * * + * ? + * + * + * * + * ? + * + * + * * + * + * * + * ? + * * + * + * + * @version $Rev$ $Date$ + */ + +public class JMSBindingProcessor implements StAXArtifactProcessor { + + private PolicyFactory policyFactory; + private PolicyAttachPointProcessor policyProcessor; + private Monitor monitor; + private JMSBindingFactory jmsBindingFactory; + + public JMSBindingProcessor(FactoryExtensionPoint modelFactories, Monitor monitor) { + this.policyFactory = modelFactories.getFactory(PolicyFactory.class); + this.policyProcessor = new PolicyAttachPointProcessor(policyFactory); + this.jmsBindingFactory = modelFactories.getFactory(JMSBindingFactory.class); + this.monitor = monitor; + } + + /** + * Report a error. + * + * @param problems + * @param message + * @param model + */ + private void warning(String message, Object model, Object... messageParameters) { + if (monitor != null) { + Problem problem = monitor.createProblem(this.getClass().getName(), "binding-jms-validation-messages", Severity.WARNING, model, message, (Object[])messageParameters); + monitor.problem(problem); + } + } + + /** + * Report a error. + * + * @param problems + * @param message + * @param model + */ + private void error(String message, Object model, Object... messageParameters) { + if (monitor != null) { + Problem problem = monitor.createProblem(this.getClass().getName(), "binding-jms-validation-messages", Severity.ERROR, model, message, (Object[])messageParameters); + monitor.problem(problem); + } + } + + public QName getArtifactType() { + return JMSBindingConstants.BINDING_JMS_QNAME; + } + + public Class getModelType() { + return JMSBinding.class; + } + + public JMSBinding read(XMLStreamReader reader) throws ContributionReadException, XMLStreamException { + JMSBinding jmsBinding = jmsBindingFactory.createJMSBinding(); + + // Read policies + policyProcessor.readPolicies(jmsBinding, reader); + + // Read binding name + String name = reader.getAttributeValue(null, "name"); + if (name != null) { + jmsBinding.setName(name); + } + + // Read binding URI + String uri = reader.getAttributeValue(null, "uri"); + if (uri != null && uri.length() > 0) { + parseURI(uri, jmsBinding); + } + + // Read correlation scheme + String correlationScheme = reader.getAttributeValue(null, "correlationScheme"); + if (correlationScheme != null && correlationScheme.length() > 0) { + if (JMSBindingConstants.VALID_CORRELATION_SCHEMES.contains(correlationScheme.toLowerCase())) { + jmsBinding.setCorrelationScheme(correlationScheme); + } else { + error("InvalidCorrelationScheme", reader, correlationScheme); + } + } + + // Read initial context factory + String initialContextFactory = reader.getAttributeValue(null, "initialContextFactory"); + if (initialContextFactory != null && initialContextFactory.length() > 0) { + jmsBinding.setInitialContextFactoryName(initialContextFactory); + } + + // Read JNDI URL + String jndiURL = reader.getAttributeValue(null, "jndiURL"); + if (jndiURL != null && jndiURL.length() > 0) { + jmsBinding.setJndiURL(jndiURL); + } + + // Read message processor class name + String messageProcessorName = reader.getAttributeValue(null, "messageProcessor"); + if (messageProcessorName != null && messageProcessorName.length() > 0) { + if ("XMLTextMessage".equalsIgnoreCase(messageProcessorName)) { + messageProcessorName = JMSBindingConstants.XML_MP_CLASSNAME; + } else if ("TextMessage".equalsIgnoreCase(messageProcessorName)) { + messageProcessorName = JMSBindingConstants.TEXT_MP_CLASSNAME; + } else if ("ObjectMessage".equalsIgnoreCase(messageProcessorName)) { + messageProcessorName = JMSBindingConstants.OBJECT_MP_CLASSNAME; + } + jmsBinding.setRequestMessageProcessorName(messageProcessorName); + jmsBinding.setResponseMessageProcessorName(messageProcessorName); + + } + + String requestConnectionName = reader.getAttributeValue(null, "requestConnection"); + if (requestConnectionName != null && requestConnectionName.length() > 0) { + jmsBinding.setRequestConnectionName(requestConnectionName); + } + String responseConnectionName = reader.getAttributeValue(null, "responseConnection"); + if (responseConnectionName != null && responseConnectionName.length() > 0) { + jmsBinding.setResponseConnectionName(responseConnectionName); + } + + // Read sub-elements of binding.jms + boolean endFound = false; + while (!endFound) { + int fg = reader.next(); + switch (fg) { + case START_ELEMENT: + String elementName = reader.getName().getLocalPart(); + if ("destination".equals(elementName)) { + parseDestination(reader, jmsBinding); + } else if ("connectionFactory".equals(elementName)) { + parseConnectionFactory(reader, jmsBinding); + } else if ("activationSpec".equals(elementName)) { + parseActivationSpec(reader, jmsBinding); + } else if ("response".equals(elementName)) { + parseResponse(reader, jmsBinding); + } else if ("resourceAdapter".equals(elementName)) { + parseResourceAdapter(reader, jmsBinding); + } else if ("headers".equals(elementName)) { + parseHeaders(reader, jmsBinding); + } else if ("operationProperties".equals(elementName)) { + parseOperationProperties(reader, jmsBinding); + } else if ("SubscriptionHeaders".equals(elementName)) { + parseSubscriptionHeaders(reader, jmsBinding); + } + reader.next(); + break; + case END_ELEMENT: + QName x = reader.getName(); + if (x.equals(JMSBindingConstants.BINDING_JMS_QNAME)) { + endFound = true; + } else { + error("UnexpectedElement", reader, x.toString()); + } + } + } + + validate(); + + return jmsBinding; + } + + protected void parseURI(String uri, JMSBinding jmsBinding) { + if (!uri.startsWith("jms:")) { + error("MustStartWithSchema", jmsBinding, uri); + return; + } + int i = uri.indexOf('?'); + if (i >= 0) { + StringTokenizer st = new StringTokenizer(uri.substring(i+1),"&"); + while (st.hasMoreTokens()) { + String s = st.nextToken(); + if (s.startsWith("connectionFactoryName=")) { + jmsBinding.setConnectionFactoryName(s.substring(22)); + } else { + error("UnknownTokenInURI", jmsBinding, s, uri); + //throw new JMSBindingException("unknown token '" + s + "' in uri: " + uri); + return; + } + } + jmsBinding.setDestinationName(uri.substring(4, i)); + } else { + jmsBinding.setDestinationName(uri.substring(4)); + } + } + + public void resolve(JMSBinding model, ModelResolver resolver) throws ContributionResolveException { + if (model.getRequestConnectionName() != null) { + model.setRequestConnectionBinding(getConnectionBinding(model.getRequestConnectionName(), resolver)); + } + if (model.getResponseConnectionName() != null) { + model.setResponseConnectionBinding(getConnectionBinding(model.getResponseConnectionName(), resolver)); + } + } + + @SuppressWarnings("unchecked") + private JMSBinding getConnectionBinding(String bindingName, ModelResolver resolver) { + if (resolver instanceof ExtensibleModelResolver) { + DefaultModelResolver dr = (DefaultModelResolver)((ExtensibleModelResolver) resolver).getDefaultModelResolver(); + Map models = dr.getModels(); + for (Object o : models.keySet()) { + if (o instanceof JMSBinding) { + JMSBinding binding = (JMSBinding) o; + if (bindingName.equals(binding.getName())) { + return binding; + } + } + } + } + return null; + } + + public void write(JMSBinding rmiBinding, XMLStreamWriter writer) throws ContributionWriteException, + XMLStreamException { + // Write a + writer.writeStartElement(Constants.SCA10_NS, JMSBindingConstants.BINDING_JMS); + + // FIXME Implement + + writer.writeEndElement(); + } + + private void parseDestination(XMLStreamReader reader, JMSBinding jmsBinding) throws XMLStreamException { + String name = reader.getAttributeValue(null, "name"); + if (name != null && name.length() > 0) { + jmsBinding.setDestinationName(name); + } + + String type = reader.getAttributeValue(null, "type"); + if (type != null && type.length() > 0) { + warning("DoesntProcessDestinationType", jmsBinding); + if (JMSBindingConstants.DESTINATION_TYPE_QUEUE.equalsIgnoreCase(type)) { + jmsBinding.setDestinationType(JMSBindingConstants.DESTINATION_TYPE_QUEUE); + } else if (JMSBindingConstants.DESTINATION_TYPE_TOPIC.equalsIgnoreCase(type)) { + jmsBinding.setDestinationType(JMSBindingConstants.DESTINATION_TYPE_TOPIC); + } else { + warning("InvalidDestinationType", reader, type); + } + } + + String create = reader.getAttributeValue(null, "create"); + if (create != null && create.length() > 0) { + jmsBinding.setDestinationCreate(create); + } + } + + private void parseConnectionFactory(XMLStreamReader reader, JMSBinding jmsBinding) { + String name = reader.getAttributeValue(null, "name"); + if (name != null && name.length() > 0) { + jmsBinding.setConnectionFactoryName(name); + } else { + error("MissingConnectionFactoryName", reader); + } + } + + private void parseActivationSpec(XMLStreamReader reader, JMSBinding jmsBinding) { + String name = reader.getAttributeValue(null, "name"); + if (name != null && name.length() > 0) { + warning("DoesntProcessActivationSpec", jmsBinding); + jmsBinding.setActivationSpecName(name); + } else { + warning("MissingActivationSpecName", reader); + } + } + + private void parseResponseDestination(XMLStreamReader reader, JMSBinding jmsBinding) throws XMLStreamException { + String name = reader.getAttributeValue(null, "name"); + if (name != null && name.length() > 0) { + jmsBinding.setResponseDestinationName(name); + } + + String type = reader.getAttributeValue(null, "type"); + if (type != null && type.length() > 0) { + warning("DoesntProcessResponseDestinationType", jmsBinding); + if (JMSBindingConstants.DESTINATION_TYPE_QUEUE.equalsIgnoreCase(type)) { + jmsBinding.setResponseDestinationType(JMSBindingConstants.DESTINATION_TYPE_QUEUE); + } else if (JMSBindingConstants.DESTINATION_TYPE_TOPIC.equalsIgnoreCase(type)) { + jmsBinding.setResponseDestinationType(JMSBindingConstants.DESTINATION_TYPE_TOPIC); + } else { + warning("InvalidResponseDestinationType", reader, type); + } + } + + String create = reader.getAttributeValue(null, "create"); + if (create != null && create.length() > 0) { + jmsBinding.setResponseDestinationCreate(create); + } + } + + private void parseResponseConnectionFactory(XMLStreamReader reader, JMSBinding jmsBinding) { + String name = reader.getAttributeValue(null, "name"); + if (name != null && name.length() > 0) { + warning("DoesntProcessResponseConnectionFactory", jmsBinding); + jmsBinding.setResponseConnectionFactoryName(name); + } else { + warning("MissingResponseConnectionFactory", reader); + } + } + + private void parseResponseActivationSpec(XMLStreamReader reader, JMSBinding jmsBinding) { + String name = reader.getAttributeValue(null, "name"); + if (name != null && name.length() > 0) { + warning("DoesntProcessResponseActivationSpec", jmsBinding); + jmsBinding.setResponseActivationSpecName(name); + } else { + warning("MissingResponseActivationSpec", reader); + } + } + + private void parseResponse(XMLStreamReader reader, JMSBinding jmsBinding) throws XMLStreamException { + // Read sub-elements of response + while (true) { + switch (reader.next()) { + case START_ELEMENT: + String elementName = reader.getName().getLocalPart(); + if ("destination".equals(elementName)) { + parseResponseDestination(reader, jmsBinding); + } else if ("connectionFactory".equals(elementName)) { + parseResponseConnectionFactory(reader, jmsBinding); + } else if ("activationSpec".equals(elementName)) { + parseResponseActivationSpec(reader, jmsBinding); + } + reader.next(); + break; + case END_ELEMENT: + QName x = reader.getName(); + if (x.getLocalPart().equals("response")) { + return; + } else { + error("UnexpectedResponseElement", reader, x.toString()); + } + } + } + } + + private void parseResourceAdapter(XMLStreamReader reader, JMSBinding jmsBinding) throws XMLStreamException { + warning("DoesntProcessResourceAdapter", jmsBinding); + } + + /** + * + * * + * ? + */ + private void parseHeaders(XMLStreamReader reader, JMSBinding jmsBinding) throws XMLStreamException { + + String jmsType = reader.getAttributeValue(null, "JMSType"); + if (jmsType != null && jmsType.length() > 0) { + jmsBinding.setJMSType(jmsType); + } + + String jmsCorrelationId = reader.getAttributeValue(null, "JMSCorrelationID"); + if (jmsCorrelationId != null && jmsCorrelationId.length() > 0) { + jmsBinding.setJMSCorrelationId(jmsCorrelationId); + } + + String jmsDeliveryMode = reader.getAttributeValue(null, "JMSDeliveryMode"); + if (jmsDeliveryMode != null && jmsDeliveryMode.length() > 0) { + if ("PERSISTENT".equalsIgnoreCase(jmsDeliveryMode)) { + jmsBinding.setJMSDeliveryMode(true); + } else if ("NON_PERSISTENT".equalsIgnoreCase(jmsDeliveryMode)) { + jmsBinding.setJMSDeliveryMode(false); + } else { + warning("InvalidJMSDeliveryMode", jmsBinding, jmsDeliveryMode); + } + } + + String jmsTimeToLive = reader.getAttributeValue(null, "JMSTimeToLive"); + if (jmsTimeToLive != null && jmsTimeToLive.length() > 0) { + jmsBinding.setJMSTimeToLive(Long.parseLong(jmsTimeToLive)); + } + + String jmsPriority = reader.getAttributeValue(null, "JMSPriority"); + if (jmsPriority != null && jmsPriority.length() > 0) { + int p = Integer.parseInt(jmsPriority); + if (p >= 0 && p <= 9) { + jmsBinding.setJMSPriority(p); + } else { + warning("InvalidJMSPriority", jmsBinding, jmsPriority); + } + } + + while (true) { + switch (reader.next()) { + case START_ELEMENT: + if (reader.getName().getLocalPart().equals("property")) { + parseProperty(reader, jmsBinding); + } + break; + case END_ELEMENT: + QName x = reader.getName(); + if (x.getLocalPart().equals("headers")) { + return; + } else { + error("UnexpectedResponseElement", reader, x.toString()); + } + } + } + } + + private void parseProperty(XMLStreamReader reader, JMSBinding jmsBinding) throws XMLStreamException { + String name = reader.getAttributeValue(null, "name"); + String type = reader.getAttributeValue(null, "type"); + if (name != null && name.length() > 0) { + Object value = reader.getElementText(); + if ("boolean".equalsIgnoreCase(type)) { + value = Boolean.parseBoolean((String)value); + } else if ("byte".equalsIgnoreCase(type)) { + value = Byte.parseByte(((String)value)); + } else if ("short".equalsIgnoreCase(type)) { + value = Short.parseShort((String)value); + } else if ("int".equalsIgnoreCase(type)) { + value = Integer.parseInt((String)value); + } else if ("long".equalsIgnoreCase(type)) { + value = Long.parseLong((String)value); + } else if ("float".equalsIgnoreCase(type)) { + value = Float.parseFloat((String)value); + } else if ("double".equalsIgnoreCase(type)) { + value = Double.parseDouble((String)value); + } else if ("String".equalsIgnoreCase(type)) { + // its already a string + } + jmsBinding.setProperty(name, value); + } + } + + /** + * + * * + * + * * + * ? + * * + */ + private void parseOperationProperties(XMLStreamReader reader, JMSBinding jmsBinding) throws XMLStreamException { + String opName = reader.getAttributeValue(null, "name"); + if (opName == null || opName.length() < 1) { + warning("MissingJMSOperationPropertyName", jmsBinding); + return; + } + String nativeOpName = reader.getAttributeValue(null, "nativeOperation"); + if (nativeOpName != null && nativeOpName.length() > 0) { + jmsBinding.setNativeOperationName(opName, nativeOpName); + } + + while (true) { + switch (reader.next()) { + case START_ELEMENT: + if (reader.getName().getLocalPart().equals("headers")) { + parseOperationHeaders(reader, jmsBinding, opName); + } + break; + case END_ELEMENT: + QName x = reader.getName(); + if (x.getLocalPart().equals("operationProperties")) { + return; + } else { + error("UnexpectedResponseElement", reader, x.toString()); + } + } + } + } + + private void parseOperationHeaders(XMLStreamReader reader, JMSBinding jmsBinding, String opName) throws XMLStreamException { + String jmsType = reader.getAttributeValue(null, "JMSType"); + if (jmsType != null && jmsType.length() > 0) { + jmsBinding.setOperationJMSType(opName, jmsType); + } + + String jmsCorrelationId = reader.getAttributeValue(null, "JMSCorrelationID"); + if (jmsCorrelationId != null && jmsCorrelationId.length() > 0) { + jmsBinding.setOperationJMSCorrelationId(opName, jmsCorrelationId); + } + + String jmsDeliveryMode = reader.getAttributeValue(null, "JMSDeliveryMode"); + if (jmsDeliveryMode != null && jmsDeliveryMode.length() > 0) { + if ("PERSISTENT".equalsIgnoreCase(jmsDeliveryMode)) { + jmsBinding.setJMSDeliveryMode(true); + } else if ("NON_PERSISTENT".equalsIgnoreCase(jmsDeliveryMode)) { + jmsBinding.setOperationJMSDeliveryMode(opName, false); + } else { + warning("InvalidOPJMSDeliveryMode", jmsBinding, jmsDeliveryMode); + } + } + + String jmsTimeToLive = reader.getAttributeValue(null, "JMSTimeToLive"); + if (jmsTimeToLive != null && jmsTimeToLive.length() > 0) { + jmsBinding.setOperationJMSTimeToLive(opName, Long.parseLong(jmsTimeToLive)); + } + + String jmsPriority = reader.getAttributeValue(null, "JMSPriority"); + if (jmsPriority != null && jmsPriority.length() > 0) { + int p = Integer.parseInt(jmsPriority); + if (p >= 0 && p <= 9) { + jmsBinding.setOperationJMSPriority(opName, p); + } else { + warning("InvalidOPJMSPriority", jmsBinding, jmsPriority); + } + } + + while (true) { + switch (reader.next()) { + case START_ELEMENT: + if (reader.getName().getLocalPart().equals("property")) { + parseOperationPropertyProperties(reader, jmsBinding, opName); + } + break; + case END_ELEMENT: + QName x = reader.getName(); + if (x.getLocalPart().equals("headers")) { + return; + } else { + error("UnexpectedResponseElement", reader, x.toString()); + } + } + } + } + + private void parseOperationPropertyProperties(XMLStreamReader reader, JMSBinding jmsBinding, String opName) throws XMLStreamException { + String propName = reader.getAttributeValue(null, "name"); + String type = reader.getAttributeValue(null, "type"); + if (propName != null && propName.length() > 0) { + Object value = reader.getElementText(); + if ("boolean".equalsIgnoreCase(type)) { + value = Boolean.parseBoolean((String)value); + } else if ("byte".equalsIgnoreCase(type)) { + value = Byte.parseByte(((String)value)); + } else if ("short".equalsIgnoreCase(type)) { + value = Short.parseShort((String)value); + } else if ("int".equalsIgnoreCase(type)) { + value = Integer.parseInt((String)value); + } else if ("long".equalsIgnoreCase(type)) { + value = Long.parseLong((String)value); + } else if ("float".equalsIgnoreCase(type)) { + value = Float.parseFloat((String)value); + } else if ("double".equalsIgnoreCase(type)) { + value = Double.parseDouble((String)value); + } else if ("String".equalsIgnoreCase(type)) { + // its already a string + } + jmsBinding.setOperationProperty(opName, propName, value); + } + } + + private void parseSubscriptionHeaders(XMLStreamReader reader, JMSBinding jmsBinding) { + String jmsSelector = reader.getAttributeValue(null, "JMSSelector"); + if (jmsSelector != null && jmsSelector.length() > 0) { + jmsBinding.setJMSSelector(jmsSelector); + } + } + + /** + * The validation rules for the JMS model are relatively complicated to they all live together here + */ + public void validate() throws JMSBindingException { + /* + * first fix up anything now the model has been read + */ + + /* + * Now some cross field validation + */ + + // connection factory doesn't contradict destination type + // connection factory and activation Specification are mutually exclusive + // TODO check Specification for all validations + } + +} diff --git a/java/sca/contrib/modules/binding-jms/src/main/resources/META-INF/services/org.apache.tuscany.sca.binding.jms.JMSBindingFactory b/java/sca/contrib/modules/binding-jms/src/main/resources/META-INF/services/org.apache.tuscany.sca.binding.jms.JMSBindingFactory new file mode 100644 index 0000000000..f2d2c4bce1 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms/src/main/resources/META-INF/services/org.apache.tuscany.sca.binding.jms.JMSBindingFactory @@ -0,0 +1,17 @@ +# 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. +org.apache.tuscany.sca.binding.jms.impl.JMSBindingFactoryImpl \ No newline at end of file diff --git a/java/sca/contrib/modules/binding-jms/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor b/java/sca/contrib/modules/binding-jms/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor new file mode 100644 index 0000000000..e5b8a96783 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor @@ -0,0 +1,25 @@ +# 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. + +# Implementation class for the artifact processor extension +org.apache.tuscany.sca.binding.jms.impl.JMSBindingProcessor;qname=http://www.osoa.org/xmlns/sca/1.0#binding.jms,model=org.apache.tuscany.sca.binding.jms.impl.JMSBinding +org.apache.tuscany.sca.binding.jms.wireformat.jmstextxml.WireFormatJMSTextXMLProcessor;qname=http://tuscany.apache.org/xmlns/sca/1.0#wireFormat.jmsTextXML,model=org.apache.tuscany.sca.binding.jms.wireformat.jmstextxml.WireFormatJMSTextXML +org.apache.tuscany.sca.binding.jms.wireformat.jmsbytes.WireFormatJMSBytesProcessor;qname=http://tuscany.apache.org/xmlns/sca/1.0#wireFormat.jmsBytes,model=org.apache.tuscany.sca.binding.jms.wireformat.jmsbytes.WireFormatJMSBytes +org.apache.tuscany.sca.binding.jms.wireformat.jmstext.WireFormatJMSTextProcessor;qname=http://tuscany.apache.org/xmlns/sca/1.0#wireFormat.jmsText,model=org.apache.tuscany.sca.binding.jms.wireformat.jmstext.WireFormatJMSText +org.apache.tuscany.sca.binding.jms.wireformat.jmsobject.WireFormatJMSObjectProcessor;qname=http://tuscany.apache.org/xmlns/sca/1.0#wireFormat.jmsObject,model=org.apache.tuscany.sca.binding.jms.wireformat.jmsobject.WireFormatJMSObject +org.apache.tuscany.sca.binding.jms.operationselector.jmsdefault.OperationSelectorJMSDefaultProcessor;qname=http://tuscany.apache.org/xmlns/sca/1.0#operationSelector.jmsDefault,model=org.apache.tuscany.sca.binding.jms.operationselector.jmsdefault.OperationSelectorJMSDefault + diff --git a/java/sca/contrib/modules/binding-jms/src/main/resources/binding-jms-validation-messages.properties b/java/sca/contrib/modules/binding-jms/src/main/resources/binding-jms-validation-messages.properties new file mode 100644 index 0000000000..2f1048e601 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms/src/main/resources/binding-jms-validation-messages.properties @@ -0,0 +1,47 @@ +# +# +# 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. +# +# +DoesntProcessOperationProperties = JMS Binding doesn't process operationProperties yet +DoesntProcessHeaders = JMS Binding doesn't process headers yet +DoesntProcessResourceAdapter = JMS Binding doesn't process resourceAdapter yet +DoesntProcessResponseConnectionFactory = JMS Binding doesn't process response connectionFactory yet +DoesntProcessResponseActivationSpec = JMS Binding doesn't process response activationSpec yet +DoesntProcessResponseDestinationType = JMS Binding doesn't process response destination type yet +DoesntProcessActivationSpec = JMS Binding doesn't process activationSpec yet +DoesntProcessDestinationType = JMS Binding doesn't process destination type yet +MissingConnectionFactoryName = Missing ConnectionFactory Name +MissingResponseConnectionFactory = Missing response connectionFactory name +InvalidResponseDestinationType = Invalid response destination type: {0} +InvalidDestinationType = Invalid destination type: {0} +MissingActivationSpecName = Missing ActivationSpec Name +MissingResponseActivationSpec = Missing response ActivationSpec name +UnknownTokenInURI = Unknown token {0} in uri: {1} +MustStartWithSchema = URI must start with the scheme 'jms:' for uri: {0} +InvalidCorrelationScheme = Invalid correlationScheme: {0} +UnexpectedElement = Incomplete binding.jms definition found unexpected element: {0} +UnexpectedResponseElement = Incomplete binding.jms/response definition found unexpected element: {0} +InvalidJMSDeliveryMode = Invalid JMSDeliveryMode: {0} +InvalidJMSPriority = Invalid JMSPriority: {0} +MissingJMSOperationPropertyName = Missing JMSOperationProperty Name +InvalidOPJMSDeliveryMode = Invalid OPJMSDeliveryMode: {0} +InvalidOPJMSPriority = Invalid OPJMSPriority: {0} + + + diff --git a/java/sca/contrib/modules/binding-jms/src/test/java/org/apache/tuscany/sca/binding/jms/impl/JMSBindingProcessorTestCase.java b/java/sca/contrib/modules/binding-jms/src/test/java/org/apache/tuscany/sca/binding/jms/impl/JMSBindingProcessorTestCase.java new file mode 100644 index 0000000000..6d59e41534 --- /dev/null +++ b/java/sca/contrib/modules/binding-jms/src/test/java/org/apache/tuscany/sca/binding/jms/impl/JMSBindingProcessorTestCase.java @@ -0,0 +1,211 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.jms.impl; + +import java.io.StringReader; +import java.util.Map; + +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamReader; + +import junit.framework.TestCase; + +import org.apache.tuscany.sca.assembly.Composite; +import org.apache.tuscany.sca.contribution.processor.DefaultStAXArtifactProcessorExtensionPoint; +import org.apache.tuscany.sca.contribution.processor.ExtensibleStAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessorExtensionPoint; +import org.apache.tuscany.sca.core.DefaultExtensionPointRegistry; +import org.apache.tuscany.sca.core.UtilityExtensionPoint; +import org.apache.tuscany.sca.monitor.DefaultMonitorFactory; +import org.apache.tuscany.sca.monitor.Monitor; +import org.apache.tuscany.sca.monitor.MonitorFactory; + +/** + * Tests for JMS binding xml + */ +public class JMSBindingProcessorTestCase extends TestCase { + + private static final String COMPOSITE = + "" + + "" + + " " + + " " + + " " + + " " + + " " + + " " + + ""; + + private static final String HEADERS1 = + "" + + "" + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + ""; + + private static final String PROPERTIES1 = + "" + + "" + + " " + + " " + + " " + + " " + + " " + + " bla" + + " 42" + + " " + + " " + + " " + + " " + + ""; + + private static final String OP_PROPERTIES1 = + "" + + "" + + " " + + " " + + " " + + " " + + " " + + " " + + " bla" + + " 42" + + " " + + " " + + " " + + " " + + " op2bla" + + " 77" + + " " + + " " + + " " + + " " + + " " + + ""; + + private static final String SELECTOR = + "" + + "" + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + ""; + + private XMLInputFactory inputFactory; + private StAXArtifactProcessor staxProcessor; + private Monitor monitor; + + @Override + protected void setUp() throws Exception { + DefaultExtensionPointRegistry extensionPoints = new DefaultExtensionPointRegistry(); + inputFactory = XMLInputFactory.newInstance(); + // Create a monitor + UtilityExtensionPoint utilities = extensionPoints.getExtensionPoint(UtilityExtensionPoint.class); + MonitorFactory monitorFactory = new DefaultMonitorFactory(); + if (monitorFactory != null) { + monitor = monitorFactory.createMonitor(); + utilities.addUtility(monitorFactory); + } + StAXArtifactProcessorExtensionPoint staxProcessors = new DefaultStAXArtifactProcessorExtensionPoint(extensionPoints); + staxProcessor = new ExtensibleStAXArtifactProcessor(staxProcessors, inputFactory, null, monitor); + } + + /** + * Test parsing valid composite definition. Valid composite populated with correct values expected. + * @throws Exception + */ + public void testLoadValidComposite() throws Exception { + XMLStreamReader reader = inputFactory.createXMLStreamReader(new StringReader(COMPOSITE)); + + Composite composite = (Composite)staxProcessor.read(reader); + JMSBindingImpl binding = (JMSBindingImpl) composite.getComponents().get(0).getServices().get(0).getBindings().get(0); + + assertNotNull(binding); + assertEquals("testQueue", binding.getDestinationName()); + } + + public void testHeaders1() throws Exception { + XMLStreamReader reader = inputFactory.createXMLStreamReader(new StringReader(HEADERS1)); + + Composite composite = (Composite)staxProcessor.read(reader); + JMSBindingImpl binding = (JMSBindingImpl) composite.getComponents().get(0).getServices().get(0).getBindings().get(0); + + assertNotNull(binding); + assertEquals("myType", binding.getJMSType()); + assertEquals("myCorrelId", binding.getJMSCorrelationId()); + assertTrue(binding.isdeliveryModePersistent()); + assertEquals(54321, binding.getJMSTimeToLive().longValue()); + assertEquals(5, binding.getJMSPriority().intValue()); + } + + public void testProperties1() throws Exception { + XMLStreamReader reader = inputFactory.createXMLStreamReader(new StringReader(PROPERTIES1)); + + Composite composite = (Composite)staxProcessor.read(reader); + JMSBindingImpl binding = (JMSBindingImpl) composite.getComponents().get(0).getServices().get(0).getBindings().get(0); + + assertNotNull(binding); + assertEquals("bla", binding.getProperty("p1")); + assertEquals(42, ((Integer)binding.getProperty("intProp")).intValue()); + } + + public void testOpProperties1() throws Exception { + XMLStreamReader reader = inputFactory.createXMLStreamReader(new StringReader(OP_PROPERTIES1)); + + Composite composite = (Composite)staxProcessor.read(reader); + JMSBindingImpl binding = (JMSBindingImpl) composite.getComponents().get(0).getServices().get(0).getBindings().get(0); + + assertNotNull(binding); + + Map op1Props = binding.getOperationProperties("op1"); + assertEquals("op1Type", binding.getOperationJMSType("op1")); + assertEquals("bla", op1Props.get("p1")); + assertEquals(42, ((Integer)op1Props.get("intProp")).intValue()); + + assertEquals("op2Type", binding.getOperationJMSType("op2")); + Map op2Props = binding.getOperationProperties("op2"); + assertEquals("op2bla", op2Props.get("p2")); + assertEquals(77, ((Integer)op2Props.get("intProp")).intValue()); + } + + public void testSubscriptionHeaders () throws Exception { + XMLStreamReader reader = inputFactory.createXMLStreamReader(new StringReader(SELECTOR)); + + Composite composite = (Composite)staxProcessor.read(reader); + JMSBindingImpl binding = (JMSBindingImpl) composite.getComponents().get(0).getServices().get(0).getBindings().get(0); + + assertNotNull(binding); + + assertEquals("prop1 = 2", binding.getJMSSelector()); + } +} diff --git a/java/sca/contrib/modules/binding-jsonrpc-runtime/LICENSE b/java/sca/contrib/modules/binding-jsonrpc-runtime/LICENSE new file mode 100644 index 0000000000..8aa906c321 --- /dev/null +++ b/java/sca/contrib/modules/binding-jsonrpc-runtime/LICENSE @@ -0,0 +1,205 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + + diff --git a/java/sca/contrib/modules/binding-jsonrpc-runtime/META-INF/MANIFEST.MF b/java/sca/contrib/modules/binding-jsonrpc-runtime/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..6bfa1e2eea --- /dev/null +++ b/java/sca/contrib/modules/binding-jsonrpc-runtime/META-INF/MANIFEST.MF @@ -0,0 +1,41 @@ +Manifest-Version: 1.0 +Export-Package: org.apache.tuscany.sca.binding.jsonrpc.provider;uses:= + "org.apache.tuscany.sca.runtime,org.apache.tuscany.sca.assembly,org.a + pache.tuscany.sca.provider,org.json,org.apache.tuscany.sca.core,org.a + pache.tuscany.sca.interfacedef.java,org.apache.tuscany.sca.interfaced + ef,javax.servlet,org.apache.tuscany.sca.invocation,com.metaparadigm.j + sonrpc,org.apache.tuscany.sca.binding.jsonrpc,org.apache.tuscany.sca. + host.http,org.oasisopen.sca,javax.servlet.http";version="2.0.0" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA JSON-RPC Binding Runtime +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397318078 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA JSON-RPC Binding Runtime +Import-Package: com.metaparadigm.jsonrpc, + javax.servlet, + javax.servlet.http, + + org.apache.tuscany.sca.assembly;version="2.0.0", + org.apache.tuscany.sca.binding.jsonrpc;version="2.0.0", + org.apache.tuscany.sca.binding.jsonrpc.provider;version="2.0.0", + org.apache.tuscany.sca.core;version="2.0.0", + org.apache.tuscany.sca.databinding.javabeans;version="2.0.0", + org.apache.tuscany.sca.databinding.json;version="2.0.0", + org.apache.tuscany.sca.host.http;version="2.0.0", + org.apache.tuscany.sca.interfacedef;version="2.0.0", + org.apache.tuscany.sca.interfacedef.java;version="2.0.0", + org.apache.tuscany.sca.invocation;version="2.0.0", + org.apache.tuscany.sca.policy;version="2.0.0", + org.apache.tuscany.sca.provider;version="2.0.0", + org.apache.tuscany.sca.runtime;version="2.0.0", + org.json, + + org.oasisopen.sca;version="2.0.0", + org.oasisopen.sca.annotation;version="2.0.0";resolution:=optional +Bundle-SymbolicName: org.apache.tuscany.sca.binding.jsonrpc.runtime +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/binding-jsonrpc-runtime/NOTICE b/java/sca/contrib/modules/binding-jsonrpc-runtime/NOTICE new file mode 100644 index 0000000000..25bb89c9b2 --- /dev/null +++ b/java/sca/contrib/modules/binding-jsonrpc-runtime/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/binding-jsonrpc-runtime/pom.xml b/java/sca/contrib/modules/binding-jsonrpc-runtime/pom.xml new file mode 100644 index 0000000000..c799bd309a --- /dev/null +++ b/java/sca/contrib/modules/binding-jsonrpc-runtime/pom.xml @@ -0,0 +1,136 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + + tuscany-binding-jsonrpc-runtime + Apache Tuscany SCA JSON-RPC Binding Runtime + + + + org.apache.tuscany.sca + tuscany-binding-jsonrpc + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-core-spi + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-core + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-databinding + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-databinding-json + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-host-http + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-host-jetty + 2.0-SNAPSHOT + test + + + + com.metaparadigm + json-rpc + 1.0 + + + + javax.servlet + servlet-api + 2.4 + provided + + + + commons-logging + commons-logging + 1.1.1 + + + commons-logging + commons-logging + + + javax.servlet + servlet-api + + + + + + + org.apache.tuscany.sca + tuscany-node-impl + 2.0-SNAPSHOT + test + + + + org.apache.tuscany.sca + tuscany-implementation-java-runtime + 2.0-SNAPSHOT + test + + + + junit + junit + 4.5 + test + + + + httpunit + httpunit + 1.6.1 + test + + + + + diff --git a/java/sca/contrib/modules/binding-jsonrpc-runtime/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/provider/JSONRPCBindingInvoker.java b/java/sca/contrib/modules/binding-jsonrpc-runtime/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/provider/JSONRPCBindingInvoker.java new file mode 100644 index 0000000000..a9fff462fa --- /dev/null +++ b/java/sca/contrib/modules/binding-jsonrpc-runtime/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/provider/JSONRPCBindingInvoker.java @@ -0,0 +1,45 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.jsonrpc.provider; + +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; + +/** + * Invoker for the JSONRPC Binding + * + * @version $Rev$ $Date$ + */ +public class JSONRPCBindingInvoker implements Invoker { + Operation operation; + String uri; + + public JSONRPCBindingInvoker(Operation operation, String uri) { + this.operation = operation; + this.uri = uri; + } + + public Message invoke(Message msg) { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/java/sca/contrib/modules/binding-jsonrpc-runtime/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/provider/JSONRPCBindingProviderFactory.java b/java/sca/contrib/modules/binding-jsonrpc-runtime/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/provider/JSONRPCBindingProviderFactory.java new file mode 100644 index 0000000000..eb85453bbb --- /dev/null +++ b/java/sca/contrib/modules/binding-jsonrpc-runtime/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/provider/JSONRPCBindingProviderFactory.java @@ -0,0 +1,64 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.jsonrpc.provider; + +import org.apache.tuscany.sca.binding.jsonrpc.JSONRPCBinding; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.host.http.ServletHost; +import org.apache.tuscany.sca.host.http.ServletHostExtensionPoint; +import org.apache.tuscany.sca.provider.BindingProviderFactory; +import org.apache.tuscany.sca.provider.ReferenceBindingProvider; +import org.apache.tuscany.sca.provider.ServiceBindingProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; + +/** + * JSON-RPC Provider Factory + * + * @version $Rev$ $Date$ + */ +public class JSONRPCBindingProviderFactory implements BindingProviderFactory { + + private ServletHost servletHost; + + public JSONRPCBindingProviderFactory(ExtensionPointRegistry extensionPoints) { + ServletHostExtensionPoint servletHosts = extensionPoints.getExtensionPoint(ServletHostExtensionPoint.class); + this.servletHost = servletHosts.getServletHosts().get(0); + } + + public ReferenceBindingProvider createReferenceBindingProvider(RuntimeComponent component, + RuntimeComponentReference reference, + JSONRPCBinding binding) { + + return new JSONRPCReferenceBindingProvider(component, reference, binding); + } + + public ServiceBindingProvider createServiceBindingProvider(RuntimeComponent component, + RuntimeComponentService service, + JSONRPCBinding binding) { + return new JSONRPCServiceBindingProvider(component, service, binding, servletHost); + } + + public Class getModelType() { + return JSONRPCBinding.class; + } + +} diff --git a/java/sca/contrib/modules/binding-jsonrpc-runtime/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/provider/JSONRPCReferenceBindingProvider.java b/java/sca/contrib/modules/binding-jsonrpc-runtime/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/provider/JSONRPCReferenceBindingProvider.java new file mode 100644 index 0000000000..e2528f59e5 --- /dev/null +++ b/java/sca/contrib/modules/binding-jsonrpc-runtime/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/provider/JSONRPCReferenceBindingProvider.java @@ -0,0 +1,70 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.jsonrpc.provider; + +import org.apache.tuscany.sca.binding.jsonrpc.JSONRPCBinding; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.provider.ReferenceBindingProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; + +/** + * Implementation of the JSONRPC Binding Provider for References + * + * @version $Rev$ $Date$ + */ +public class JSONRPCReferenceBindingProvider implements ReferenceBindingProvider { + + private RuntimeComponentReference reference; + private JSONRPCBinding binding; + + public JSONRPCReferenceBindingProvider(RuntimeComponent component, + RuntimeComponentReference reference, + JSONRPCBinding binding) { + this.reference = reference; + this.binding = binding; + + } + + public InterfaceContract getBindingInterfaceContract() { + return reference.getInterfaceContract(); + } + + public Invoker createInvoker(Operation operation) { + return new JSONRPCBindingInvoker(operation, binding.getURI()); + } + + public void start() { + // TODO Auto-generated method stub + + } + + public void stop() { + // TODO Auto-generated method stub + + } + + public boolean supportsOneWayInvocation() { + return false; + } + +} diff --git a/java/sca/contrib/modules/binding-jsonrpc-runtime/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/provider/JSONRPCServiceBindingProvider.java b/java/sca/contrib/modules/binding-jsonrpc-runtime/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/provider/JSONRPCServiceBindingProvider.java new file mode 100644 index 0000000000..8d9f8193e9 --- /dev/null +++ b/java/sca/contrib/modules/binding-jsonrpc-runtime/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/provider/JSONRPCServiceBindingProvider.java @@ -0,0 +1,184 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.jsonrpc.provider; + +import java.net.URI; +import java.util.ArrayList; +import java.util.List; + +import org.apache.tuscany.sca.binding.jsonrpc.JSONRPCBinding; +import org.apache.tuscany.sca.databinding.javabeans.SimpleJavaDataBinding; +import org.apache.tuscany.sca.databinding.json.JSONDataBinding; +import org.apache.tuscany.sca.host.http.ServletHost; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.Interface; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.interfacedef.java.JavaInterface; +import org.apache.tuscany.sca.provider.ServiceBindingProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; + +/** + * Implementation of the JSONRPC Binding Provider for Services + * + * @version $Rev$ $Date$ + */ +public class JSONRPCServiceBindingProvider implements ServiceBindingProvider { + + // Path to the scaDomain.js script + // Note: this is the same as the Ajax binding to keep the client code + // the same for clients using either the ajax or jsonrpc binding + private static final String SCA_DOMAIN_SCRIPT = "/SCADomain/scaDomain.js"; + + private RuntimeComponent component; + private RuntimeComponentService service; + private InterfaceContract serviceContract; + private JSONRPCBinding binding; + private ServletHost servletHost; + private List servletMappings = new ArrayList(); + private String domainScriptMapping; + + public JSONRPCServiceBindingProvider(RuntimeComponent component, + RuntimeComponentService service, + JSONRPCBinding binding, + ServletHost servletHost) { + this.component = component; + this.service = service; + this.binding = binding; + this.servletHost = servletHost; + + //clone the service contract to avoid databinding issues + try { + this.serviceContract = (InterfaceContract)service.getInterfaceContract().clone(); + } catch(CloneNotSupportedException e) { + this.serviceContract = service.getInterfaceContract(); + } + + setDataBinding(serviceContract.getInterface()); + } + + public InterfaceContract getBindingInterfaceContract() { + return service.getInterfaceContract(); + } + + public boolean supportsOneWayInvocation() { + return false; + } + + public void start() { + // Set default databinding to json + serviceContract.getInterface().resetDataBinding(JSONDataBinding.NAME); + + // Determine the service business interface + Class serviceInterface = getTargetJavaClass(serviceContract.getInterface()); + + // Create a Java proxy to the target service + Object proxy = component.getComponentContext().createSelfReference(serviceInterface, service).getService(); + + // Create and register a Servlet for this service + JSONRPCServiceServlet serviceServlet = + new JSONRPCServiceServlet(binding, service, serviceContract, serviceInterface, proxy); + String mapping = binding.getURI(); + if (!mapping.endsWith("/")) { + mapping += "/"; + } + if (!mapping.endsWith("*")) { + mapping += "*"; + } + + servletHost.addServletMapping(mapping, serviceServlet); + servletMappings.add(mapping); + servletHost.addServletMapping(binding.getURI(), serviceServlet); + servletMappings.add(binding.getURI()); + + // Register service to scaDomain.js + int port; + URI uri = URI.create(servletHost.getURLMapping(binding.getURI()).toString()); + port = uri.getPort(); + if (port == -1) { + port = servletHost.getDefaultPort(); + } + + // get the ScaDomainScriptServlet, if it doesn't yet exist create one + // this uses removeServletMapping / addServletMapping as there is no getServletMapping facility + domainScriptMapping = URI.create("http://localhost:" + port + SCA_DOMAIN_SCRIPT).toString(); + ScaDomainScriptServlet scaDomainServlet = + (ScaDomainScriptServlet)servletHost.getServletMapping(domainScriptMapping); + if (scaDomainServlet == null) { + scaDomainServlet = new ScaDomainScriptServlet(); + servletHost.addServletMapping(domainScriptMapping, scaDomainServlet); + } + + // Add this service to the SCA Domain Script Servlet + scaDomainServlet.addService(binding.getName()); + } + + public void stop() { + + // Remove the Servlet mappings we've added + for (String mapping: servletMappings) { + servletHost.removeServletMapping(mapping); + } + + // Unregister the service from the SCA Domain Script Servlet + ScaDomainScriptServlet scaDomainServlet = (ScaDomainScriptServlet) servletHost.getServletMapping(domainScriptMapping); + if (scaDomainServlet != null) { + scaDomainServlet.removeService(binding.getName()); + + // Remove the Servlet if there's no more registered services + if (scaDomainServlet.getServiceNames().isEmpty()) { + servletHost.removeServletMapping(domainScriptMapping); + } + } + + } + + private Class getTargetJavaClass(Interface targetInterface) { + // TODO: right now assume that the target is always a Java + // Implementation. Need to figure out how to generate Java + // Interface in cases where the target is not a Java Implementation + return ((JavaInterface)targetInterface).getJavaClass(); + } + + private void setDataBinding(Interface interfaze) { + List operations = interfaze.getOperations(); + for (Operation operation : operations) { + operation.setDataBinding(JSONDataBinding.NAME); + DataType> inputType = operation.getInputType(); + if (inputType != null) { + List logical = inputType.getLogical(); + for (DataType inArg : logical) { + if (!SimpleJavaDataBinding.NAME.equals(inArg.getDataBinding())) { + inArg.setDataBinding(JSONDataBinding.NAME); + } + } + } + DataType outputType = operation.getOutputType(); + if (outputType != null) { + if (!SimpleJavaDataBinding.NAME.equals(outputType.getDataBinding())) { + outputType.setDataBinding(JSONDataBinding.NAME); + } + } + } + } + + +} diff --git a/java/sca/contrib/modules/binding-jsonrpc-runtime/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/provider/JSONRPCServiceServlet.java b/java/sca/contrib/modules/binding-jsonrpc-runtime/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/provider/JSONRPCServiceServlet.java new file mode 100644 index 0000000000..37a598e1ac --- /dev/null +++ b/java/sca/contrib/modules/binding-jsonrpc-runtime/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/provider/JSONRPCServiceServlet.java @@ -0,0 +1,282 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jsonrpc.provider; + +import java.io.BufferedReader; +import java.io.CharArrayWriter; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.UnsupportedEncodingException; +import java.lang.reflect.InvocationTargetException; +import java.util.List; + +import javax.servlet.ServletConfig; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; +import org.apache.tuscany.sca.runtime.RuntimeWire; +import org.json.JSONArray; +import org.json.JSONObject; +import org.oasisopen.sca.ServiceRuntimeException; + +import com.metaparadigm.jsonrpc.JSONRPCBridge; +import com.metaparadigm.jsonrpc.JSONRPCResult; +import com.metaparadigm.jsonrpc.JSONRPCServlet; + +/** + * Servlet that handles JSON-RPC requests invoking SCA services. + * + * There is an instance of this Servlet for each + * + * @version $Rev$ $Date$ + */ +public class JSONRPCServiceServlet extends JSONRPCServlet { + private static final long serialVersionUID = 1L; + + transient Binding binding; + transient String serviceName; + transient Object serviceInstance; + transient RuntimeComponentService componentService; + transient InterfaceContract serviceContract; + transient Class serviceInterface; + + public JSONRPCServiceServlet(Binding binding, + RuntimeComponentService componentService, + InterfaceContract serviceContract, + Class serviceInterface, + Object serviceInstance) { + this.binding = binding; + this.serviceName = binding.getName(); + this.componentService = componentService; + this.serviceContract = serviceContract; + this.serviceInterface = serviceInterface; + this.serviceInstance = serviceInstance; + } + + /** + * Override to do nothing as the JSONRPCServlet is setup by the + * service method in this class. + */ + @Override + public void init(ServletConfig config) { + } + + @Override + public void service(HttpServletRequest request, HttpServletResponse response) throws IOException { + if ("smd".equals(request.getQueryString())) { + handleSMDRequest(request, response); + } else { + try { + handleServiceRequest(request, response); + } finally { + HttpSession session = request.getSession(false); + if (session != null) { + session.removeAttribute("JSONRPCBridge"); + } + } + } + } + + private void handleServiceRequest(HttpServletRequest request, HttpServletResponse response) + throws IOException { + // Encode using UTF-8, although We are actually ASCII clean as + // all unicode data is JSON escaped using backslash u. This is + // less data efficient for foreign character sets but it is + // needed to support naughty browsers such as Konqueror and Safari + // which do not honour the charset set in the response + response.setContentType("text/plain;charset=utf-8"); + OutputStream out = response.getOutputStream(); + + // Decode using the charset in the request if it exists otherwise + // use UTF-8 as this is what all browser implementations use. + // The JSON-RPC-Java JavaScript client is ASCII clean so it + // although here we can correctly handle data from other clients + // that do not escape non ASCII data + String charset = request.getCharacterEncoding(); + if (charset == null) { + charset = "UTF-8"; + } + BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream(), charset)); + + // Read the request + CharArrayWriter data = new CharArrayWriter(); + char[] buf = new char[4096]; + int ret; + while ((ret = in.read(buf, 0, 4096)) != -1) { + data.write(buf, 0, ret); + } + + JSONObject jsonReq = null; + String method = null; + try { + jsonReq = new JSONObject(data.toString()); + method = jsonReq.getString("method"); + } catch (Exception e) { + //FIXME Exceptions are not handled correctly here + // They should be reported to the client JavaScript as proper + // JavaScript exceptions. + throw new RuntimeException("Unable to parse request", e); + } + + + // check if it's a system request + // or a method invocation + byte[] bout; + if (method.startsWith("system.")) { + bout = handleJSONRPCSystemInvocation(request, response, data.toString()); + } else { + bout = handleJSONRPCMethodInvocation(request, response, jsonReq); + } + + // Send response to client + out.write(bout); + out.flush(); + out.close(); + } + + /** + * handles requests for the SMD descriptor for a service + */ + protected void handleSMDRequest(HttpServletRequest request, HttpServletResponse response) throws IOException, + UnsupportedEncodingException { + String serviceUrl = request.getRequestURL().toString(); + String smd = JavaToSmd.interfaceToSmd(serviceInterface, serviceUrl); + + response.setContentType("text/plain;charset=utf-8"); + OutputStream out = response.getOutputStream(); + byte[] bout = smd.getBytes("UTF-8"); + out.write(bout); + out.flush(); + out.close(); + } + + protected byte[] handleJSONRPCSystemInvocation(HttpServletRequest request, HttpServletResponse response, String requestData) throws IOException, + UnsupportedEncodingException { + /* + * Create a new bridge for every request to avoid all the problems with + * JSON-RPC-Java storing the bridge in the session + */ + HttpSession session = request.getSession(); + + JSONRPCBridge jsonrpcBridge = new JSONRPCBridge(); + jsonrpcBridge.registerObject("Service", serviceInstance, serviceInterface); + session.setAttribute("JSONRPCBridge", jsonrpcBridge); + + org.json.JSONObject jsonReq = null; + com.metaparadigm.jsonrpc.JSONRPCResult jsonResp = null; + try { + jsonReq = new org.json.JSONObject(requestData); + } catch (java.text.ParseException e) { + throw new RuntimeException("Unable to parse request", e); + } + + String method = jsonReq.getString("method"); + if ((method != null) && (method.indexOf('.') < 0)) { + jsonReq.putOpt("method", "Service" + "." + method); + } + + // invoke the request + jsonResp = jsonrpcBridge.call(new Object[] {request}, jsonReq); + + return jsonResp.toString().getBytes("UTF-8"); + } + + protected byte[] handleJSONRPCMethodInvocation(HttpServletRequest request, HttpServletResponse response, JSONObject jsonReq) throws IOException, + UnsupportedEncodingException { + + String method = null; + Object[] args = null; + Object id = null; + try { + // Extract the method + method = jsonReq.getString("method"); + if ((method != null) && (method.indexOf('.') < 0)) { + jsonReq.putOpt("method", "Service" + "." + method); + } + + // Extract the arguments + JSONArray array = jsonReq.getJSONArray("params"); + args = new Object[array.length()]; + for (int i = 0; i < args.length; i++) { + args[i] = array.get(i); + } + id = jsonReq.get("id"); + + } catch (Exception e) { + throw new RuntimeException("Unable to find json method name", e); + } + + // invoke the request + RuntimeWire wire = componentService.getRuntimeWire(binding, serviceContract); + Operation jsonOperation = findOperation(method); + Object result = null; + + try { + JSONObject jsonResponse = new JSONObject(); + result = wire.invoke(jsonOperation, args); + + try { + jsonResponse.put("result", result); + jsonResponse.putOpt("id", id); + //get response to send to client + return jsonResponse.toString().getBytes("UTF-8"); + } catch (Exception e) { + throw new ServiceRuntimeException("Unable to create JSON response", e); + } + } catch (InvocationTargetException e) { + JSONRPCResult errorResult = new JSONRPCResult(JSONRPCResult.CODE_REMOTE_EXCEPTION, id, e.getCause() ); + return errorResult.toString().getBytes("UTF-8"); + } catch(RuntimeException e) { + JSONRPCResult errorResult = new JSONRPCResult(JSONRPCResult.CODE_REMOTE_EXCEPTION, id, e.getCause()); + return errorResult.toString().getBytes("UTF-8"); + } + } + + /** + * Find the operation from the component service contract + * @param componentService + * @param method + * @return + */ + private Operation findOperation(String method) { + if (method.contains(".")) { + method = method.substring(method.lastIndexOf(".") + 1); + } + + List operations = serviceContract.getInterface().getOperations(); + //componentService.getBindingProvider(binding).getBindingInterfaceContract().getInterface().getOperations(); + + + Operation result = null; + for (Operation o : operations) { + if (o.getName().equalsIgnoreCase(method)) { + result = o; + break; + } + } + + return result; + } +} diff --git a/java/sca/contrib/modules/binding-jsonrpc-runtime/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/provider/JavaToSmd.java b/java/sca/contrib/modules/binding-jsonrpc-runtime/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/provider/JavaToSmd.java new file mode 100644 index 0000000000..64339fda7b --- /dev/null +++ b/java/sca/contrib/modules/binding-jsonrpc-runtime/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/provider/JavaToSmd.java @@ -0,0 +1,56 @@ +/* + * 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. + */ + package org.apache.tuscany.sca.binding.jsonrpc.provider; + +import java.lang.reflect.Method; + +/** + * Utility class to create a Simple Method Description (SMD) descriptor + * from a Java class. See http://dojo.jot.com/SMD. + * + * TODO: Change to work from the Tuscany Interface instead of a Java class + * + * @version $Rev$ $Date$ + */ +class JavaToSmd { + + static String interfaceToSmd(Class klazz, String serviceUrl) { + String name = klazz.getSimpleName(); + Method[] methods = klazz.getMethods(); + + StringBuffer smdSb = new StringBuffer(); + smdSb.append("{\"SMDVersion\":\".1\",\"objectName\":\"" + name + "\",\"serviceType\":\"JSON-RPC\",\"serviceURL\":\""+ serviceUrl + "\",\"methods\":["); + for (int i = 0; i < methods.length; i++) { + if (i != 0) smdSb.append(","); + Class[] params = methods[i].getParameterTypes(); + smdSb.append("{\"name\":\""+methods[i].getName() + "\",\"parameters\":["); + for (int j = 0; j < params.length; j++) { + if (j != 0) smdSb.append(","); + // right now Dojo doesn't look at the type value, so we'll default it to STRING + // also, since we can't introspect the method parameter names we'll just create an incrementing parameter name + smdSb.append("{\"name\":\"param" + j + "\",\"type\":\"STRING\"}"); + } + smdSb.append("]}"); + } + smdSb.append("]}"); + + return smdSb.toString(); + } + +} diff --git a/java/sca/contrib/modules/binding-jsonrpc-runtime/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/provider/ScaDomainScriptServlet.java b/java/sca/contrib/modules/binding-jsonrpc-runtime/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/provider/ScaDomainScriptServlet.java new file mode 100644 index 0000000000..999588abf1 --- /dev/null +++ b/java/sca/contrib/modules/binding-jsonrpc-runtime/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/provider/ScaDomainScriptServlet.java @@ -0,0 +1,114 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jsonrpc.provider; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * Servlet to handle requests for the scaDomain.js script. + * + * This script wrappers the JSON-RPC-Java jsonrpc.js script + * adding in at the bottom the JavaScript to create and initialize + * the variables representing the SCA services. + * + * @version $Rev$ $Date$ + */ +public class ScaDomainScriptServlet extends HttpServlet { + private static final long serialVersionUID = 1L; + + protected transient List serviceNames; + + public ScaDomainScriptServlet() { + serviceNames = new ArrayList(); + } + + @Override + public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { + + ServletOutputStream os = response.getOutputStream(); + + os.println(); + os.println("/* Apache Tuscany scaDomain.js Header */"); + os.println(); + + writeJSONRPCJavaScript(os); + writeScaDomainCode(os, request.getServletPath()); + } + + /** + * Creates a JavaScript variable within the scaDomain script for each SCA service and + * initializes its value with the JSON-RPC client to invoke the serverside service. + */ + protected void writeScaDomainCode(ServletOutputStream out, String path) throws IOException { + out.println(); + out.println("/* Apache Tuscany scaDomain.js Footer */"); + out.println(); + out.println("function scaDomain() {}"); + + // remove the leading slash '/' character + path = path.substring(1); + + for (String serviceName : serviceNames) { + out.println(); + + // A slight hack to make the service function available with a variable named 'serviceName' + // to do that the JSONRpcClient is added to the scaDomain and then the service function is got from that + out.println("scaDomain." + serviceName + " = " + "new JSONRpcClient(\"" + serviceName + "\");"); + out.println(serviceName + " = scaDomain." + serviceName + ".Service;"); + } + + out.println(); + out.println("/** End of Apache Tuscany scaDomain.js */"); + out.println(); + } + + /** + * Reads the jsonrpc.js script from the classpath and adds its contents to the output stream. + */ + protected void writeJSONRPCJavaScript(ServletOutputStream os) throws IOException { + URL url = getClass().getResource("jsonrpc.js"); + InputStream is = url.openStream(); + int i; + while ((i = is.read()) != -1) { + os.write(i); + } + } + + public void addService(String serviceName) { + serviceNames.add(serviceName); + } + + public void removeService(String serviceName) { + serviceNames.remove(serviceName); + } + + public List getServiceNames() { + return serviceNames; + } + +} diff --git a/java/sca/contrib/modules/binding-jsonrpc-runtime/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.BindingProviderFactory b/java/sca/contrib/modules/binding-jsonrpc-runtime/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.BindingProviderFactory new file mode 100644 index 0000000000..4767358e7a --- /dev/null +++ b/java/sca/contrib/modules/binding-jsonrpc-runtime/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.BindingProviderFactory @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for the binding extension +org.apache.tuscany.sca.binding.jsonrpc.provider.JSONRPCBindingProviderFactory;model=org.apache.tuscany.sca.binding.jsonrpc.JSONRPCBinding diff --git a/java/sca/contrib/modules/binding-jsonrpc-runtime/src/main/resources/org/apache/tuscany/sca/binding/jsonrpc/provider/jsonrpc.js b/java/sca/contrib/modules/binding-jsonrpc-runtime/src/main/resources/org/apache/tuscany/sca/binding/jsonrpc/provider/jsonrpc.js new file mode 100644 index 0000000000..d837bab91c --- /dev/null +++ b/java/sca/contrib/modules/binding-jsonrpc-runtime/src/main/resources/org/apache/tuscany/sca/binding/jsonrpc/provider/jsonrpc.js @@ -0,0 +1,493 @@ +/* + * JSON-RPC JavaScript client + * + * $Id: jsonrpc.js,v 1.36.2.3 2006/03/08 15:09:37 mclark Exp $ + * + * Copyright (c) 2003-2004 Jan-Klaas Kollhof + * Copyright (c) 2005 Michael Clark, Metaparadigm Pte Ltd + * + * This code is based on Jan-Klaas' JavaScript o lait library (jsolait). + * + * 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. + * + */ + +/* + * Modifications for Apache Tuscany: + * - JSONRpcClient_createMethod changed so callback is last arg + */ + +/* escape a character */ + +escapeJSONChar = +function escapeJSONChar(c) +{ + if(c == "\"" || c == "\\") return "\\" + c; + else if (c == "\b") return "\\b"; + else if (c == "\f") return "\\f"; + else if (c == "\n") return "\\n"; + else if (c == "\r") return "\\r"; + else if (c == "\t") return "\\t"; + var hex = c.charCodeAt(0).toString(16); + if(hex.length == 1) return "\\u000" + hex; + else if(hex.length == 2) return "\\u00" + hex; + else if(hex.length == 3) return "\\u0" + hex; + else return "\\u" + hex; +}; + + +/* encode a string into JSON format */ + +escapeJSONString = +function escapeJSONString(s) +{ + /* The following should suffice but Safari's regex is b0rken + (doesn't support callback substitutions) + return "\"" + s.replace(/([^\u0020-\u007f]|[\\\"])/g, + escapeJSONChar) + "\""; + */ + + /* Rather inefficient way to do it */ + var parts = s.split(""); + for(var i=0; i < parts.length; i++) { + var c =parts[i]; + if(c == '"' || + c == '\\' || + c.charCodeAt(0) < 32 || + c.charCodeAt(0) >= 128) + parts[i] = escapeJSONChar(parts[i]); + } + return "\"" + parts.join("") + "\""; +}; + + +/* Marshall objects to JSON format */ + +toJSON = function toJSON(o) +{ + if(o == null) { + return "null"; + } else if(o.constructor == String) { + return escapeJSONString(o); + } else if(o.constructor == Number) { + return o.toString(); + } else if(o.constructor == Boolean) { + return o.toString(); + } else if(o.constructor == Date) { + return '{javaClass: "java.util.Date", time: ' + o.valueOf() +'}'; + } else if(o.constructor == Array) { + var v = []; + for(var i = 0; i < o.length; i++) v.push(toJSON(o[i])); + return "[" + v.join(", ") + "]"; + } else { + var v = []; + for(attr in o) { + if(o[attr] == null) v.push("\"" + attr + "\": null"); + else if(typeof o[attr] == "function"); /* skip */ + else v.push(escapeJSONString(attr) + ": " + toJSON(o[attr])); + } + return "{" + v.join(", ") + "}"; + } +}; + + +/* JSONRpcClient constructor */ + +JSONRpcClient = +function JSONRpcClient_ctor(serverURL, user, pass, objectID) +{ + this.serverURL = serverURL; + this.user = user; + this.pass = pass; + this.objectID = objectID; + + /* Add standard methods */ + if(this.objectID) { + this._addMethods(["listMethods"]); + var req = this._makeRequest("listMethods", []); + } else { + this._addMethods(["system.listMethods"]); + var req = this._makeRequest("system.listMethods", []); + } + var m = this._sendRequest(req); + this._addMethods(m); +}; + + +/* JSONRpcCLient.Exception */ + +JSONRpcClient.Exception = +function JSONRpcClient_Exception_ctor(code, message, javaStack) +{ + this.code = code; + var name; + if(javaStack) { + this.javaStack = javaStack; + var m = javaStack.match(/^([^:]*)/); + if(m) name = m[0]; + } + if(name) this.name = name; + else this.name = "JSONRpcClientException"; + this.message = message; +}; + +JSONRpcClient.Exception.CODE_REMOTE_EXCEPTION = 490; +JSONRpcClient.Exception.CODE_ERR_CLIENT = 550; +JSONRpcClient.Exception.CODE_ERR_PARSE = 590; +JSONRpcClient.Exception.CODE_ERR_NOMETHOD = 591; +JSONRpcClient.Exception.CODE_ERR_UNMARSHALL = 592; +JSONRpcClient.Exception.CODE_ERR_MARSHALL = 593; + +JSONRpcClient.Exception.prototype = new Error(); + +JSONRpcClient.Exception.prototype.toString = +function JSONRpcClient_Exception_toString(code, msg) +{ + return this.name + ": " + this.message; +}; + + +/* Default top level exception handler */ + +JSONRpcClient.default_ex_handler = +function JSONRpcClient_default_ex_handler(e) { alert(e); }; + + +/* Client settable variables */ + +JSONRpcClient.toplevel_ex_handler = JSONRpcClient.default_ex_handler; +JSONRpcClient.profile_async = false; +JSONRpcClient.max_req_active = 1; +JSONRpcClient.requestId = 1; + + +/* JSONRpcClient implementation */ + +JSONRpcClient.prototype._createMethod = +function JSONRpcClient_createMethod(methodName) +{ + var fn=function() + { + var args = []; + var callback = null; + for(var i=0;i 0) { + var res = JSONRpcClient.async_responses.shift(); + if(res.canceled) continue; + if(res.profile) res.profile.dispatch = new Date(); + try { + res.cb(res.result, res.ex, res.profile); + } catch(e) { + JSONRpcClient.toplevel_ex_handler(e); + } + } + + while(JSONRpcClient.async_requests.length > 0 && + JSONRpcClient.num_req_active < JSONRpcClient.max_req_active) { + var req = JSONRpcClient.async_requests.shift(); + if(req.canceled) continue; + req.client._sendRequest.call(req.client, req); + } +}; + +JSONRpcClient.kick_async = +function JSONRpcClient_kick_async() +{ + if(JSONRpcClient.async_timeout == null) + JSONRpcClient.async_timeout = + setTimeout(JSONRpcClient._async_handler, 0); +}; + +JSONRpcClient.cancelRequest = +function JSONRpcClient_cancelRequest(requestId) +{ + /* If it is in flight then mark it as canceled in the inflight map + and the XMLHttpRequest callback will discard the reply. */ + if(JSONRpcClient.async_inflight[requestId]) { + JSONRpcClient.async_inflight[requestId].canceled = true; + return true; + } + + /* If its not in flight yet then we can just mark it as canceled in + the the request queue and it will get discarded before being sent. */ + for(var i in JSONRpcClient.async_requests) { + if(JSONRpcClient.async_requests[i].requestId == requestId) { + JSONRpcClient.async_requests[i].canceled = true; + return true; + } + } + + /* It may have returned from the network and be waiting for its callback + to be dispatched, so mark it as canceled in the response queue + and the response will get discarded before calling the callback. */ + for(var i in JSONRpcClient.async_responses) { + if(JSONRpcClient.async_responses[i].requestId == requestId) { + JSONRpcClient.async_responses[i].canceled = true; + return true; + } + } + + return false; +}; + +JSONRpcClient.prototype._makeRequest = +function JSONRpcClient_makeRequest(methodName, args, cb) +{ + var req = {}; + req.client = this; + req.requestId = JSONRpcClient.requestId++; + + var obj = {}; + obj.id = req.requestId; + if (this.objectID) + obj.method = ".obj#" + this.objectID + "." + methodName; + else + obj.method = methodName; + obj.params = args; + + if (cb) req.cb = cb; + if (JSONRpcClient.profile_async) + req.profile = { "submit": new Date() }; + req.data = toJSON(obj); + + return req; +}; + +JSONRpcClient.prototype._sendRequest = +function JSONRpcClient_sendRequest(req) +{ + if(req.profile) req.profile.start = new Date(); + + /* Get free http object from the pool */ + var http = JSONRpcClient.poolGetHTTPRequest(); + JSONRpcClient.num_req_active++; + + /* Send the request */ + if (typeof(this.user) == "undefined") { + http.open("POST", this.serverURL, (req.cb != null)); + } else { + http.open("POST", this.serverURL, (req.cb != null), this.user, this.pass); + } + + /* setRequestHeader is missing in Opera 8 Beta */ + try { http.setRequestHeader("Content-type", "text/plain"); } catch(e) {} + + /* Construct call back if we have one */ + if(req.cb) { + var self = this; + http.onreadystatechange = function() { + if(http.readyState == 4) { + http.onreadystatechange = function () {}; + var res = { "cb": req.cb, "result": null, "ex": null}; + if (req.profile) { + res.profile = req.profile; + res.profile.end = new Date(); + } + try { res.result = self._handleResponse(http); } + catch(e) { res.ex = e; } + if(!JSONRpcClient.async_inflight[req.requestId].canceled) + JSONRpcClient.async_responses.push(res); + delete JSONRpcClient.async_inflight[req.requestId]; + JSONRpcClient.kick_async(); + } + }; + } else { + http.onreadystatechange = function() {}; + } + + JSONRpcClient.async_inflight[req.requestId] = req; + + try { + http.send(req.data); + } catch(e) { + JSONRpcClient.poolReturnHTTPRequest(http); + JSONRpcClient.num_req_active--; + throw new JSONRpcClient.Exception + (JSONRpcClient.Exception.CODE_ERR_CLIENT, "Connection failed"); + } + + if(!req.cb) return this._handleResponse(http); +}; + +JSONRpcClient.prototype._handleResponse = +function JSONRpcClient_handleResponse(http) +{ + /* Get the charset */ + if(!this.charset) { + this.charset = JSONRpcClient._getCharsetFromHeaders(http); + } + + /* Get request results */ + var status, statusText, data; + try { + status = http.status; + statusText = http.statusText; + data = http.responseText; + } catch(e) { + JSONRpcClient.poolReturnHTTPRequest(http); + JSONRpcClient.num_req_active--; + JSONRpcClient.kick_async(); + throw new JSONRpcClient.Exception + (JSONRpcClient.Exception.CODE_ERR_CLIENT, "Connection failed"); + } + + /* Return http object to the pool; */ + JSONRpcClient.poolReturnHTTPRequest(http); + JSONRpcClient.num_req_active--; + + /* Unmarshall the response */ + if(status != 200) { + throw new JSONRpcClient.Exception(status, statusText); + } + var obj; + try { + eval("obj = " + data); + } catch(e) { + throw new JSONRpcClient.Exception(550, "error parsing result"); + } + if(obj.error) + throw new JSONRpcClient.Exception(obj.error.code, obj.error.msg, + obj.error.trace); + var res = obj.result; + + /* Handle CallableProxy */ + if(res && res.objectID && res.JSONRPCType == "CallableReference") + return new JSONRpcClient(this.serverURL, this.user, + this.pass, res.objectID); + + return res; +}; + + +/* XMLHttpRequest wrapper code */ + +/* XMLHttpRequest pool globals */ +JSONRpcClient.http_spare = []; +JSONRpcClient.http_max_spare = 8; + +JSONRpcClient.poolGetHTTPRequest = +function JSONRpcClient_pool_getHTTPRequest() +{ + if(JSONRpcClient.http_spare.length > 0) { + return JSONRpcClient.http_spare.pop(); + } + return JSONRpcClient.getHTTPRequest(); +}; + +JSONRpcClient.poolReturnHTTPRequest = +function JSONRpcClient_poolReturnHTTPRequest(http) +{ + if(JSONRpcClient.http_spare.length >= JSONRpcClient.http_max_spare) + delete http; + else + JSONRpcClient.http_spare.push(http); +}; + +JSONRpcClient.msxmlNames = [ "MSXML2.XMLHTTP.5.0", + "MSXML2.XMLHTTP.4.0", + "MSXML2.XMLHTTP.3.0", + "MSXML2.XMLHTTP", + "Microsoft.XMLHTTP" ]; + +JSONRpcClient.getHTTPRequest = +function JSONRpcClient_getHTTPRequest() +{ + /* Mozilla XMLHttpRequest */ + try { + JSONRpcClient.httpObjectName = "XMLHttpRequest"; + return new XMLHttpRequest(); + } catch(e) {} + + /* Microsoft MSXML ActiveX */ + for (var i=0;i < JSONRpcClient.msxmlNames.length; i++) { + try { + JSONRpcClient.httpObjectName = JSONRpcClient.msxmlNames[i]; + return new ActiveXObject(JSONRpcClient.msxmlNames[i]); + } catch (e) {} + } + + /* None found */ + JSONRpcClient.httpObjectName = null; + throw new JSONRpcClient.Exception(0, "Can't create XMLHttpRequest object"); +}; + diff --git a/java/sca/contrib/modules/binding-jsonrpc-runtime/src/test/java/bean/TestBean.java b/java/sca/contrib/modules/binding-jsonrpc-runtime/src/test/java/bean/TestBean.java new file mode 100644 index 0000000000..4b159fb563 --- /dev/null +++ b/java/sca/contrib/modules/binding-jsonrpc-runtime/src/test/java/bean/TestBean.java @@ -0,0 +1,51 @@ +/* + * 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. + */ +package bean; + +public class TestBean { + private String testString; + private String[] testStringArray; + private int testInt; + + + public String getTestString() { + return testString; + } + + public void setTestString(String testString) { + this.testString = testString; + } + + public String[] getTestStringArray() { + return testStringArray; + } + + public void setStringArray(String[] stringArray) { + this.testStringArray = stringArray; + } + + public int getTestInt() { + return testInt; + } + + public void setTestInt(int testInt) { + this.testInt = testInt; + } + +} diff --git a/java/sca/contrib/modules/binding-jsonrpc-runtime/src/test/java/echo/Echo.java b/java/sca/contrib/modules/binding-jsonrpc-runtime/src/test/java/echo/Echo.java new file mode 100644 index 0000000000..c46e5698d1 --- /dev/null +++ b/java/sca/contrib/modules/binding-jsonrpc-runtime/src/test/java/echo/Echo.java @@ -0,0 +1,62 @@ +/* + * 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. + */ +package echo; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.oasisopen.sca.annotation.Remotable; + +import bean.TestBean; + +/** + * Interface of our sample JSONRPC service. + * + * @version $Rev$ $Date$ + */ +@Remotable +public interface Echo { + + String echo(String msg); + + void echoRuntimeException() throws RuntimeException; + + void echoBusinessException() throws EchoBusinessException; + + int echoInt(int param); + + boolean echoBoolean(boolean param); + + Map echoMap(HashMap map); + + TestBean echoBean(TestBean testBean); + + List echoList(ArrayList list); + + String [] echoArrayString(String[] stringArray); + + int [] echoArrayInt(int[] intArray); + + Set echoSet(HashSet set); + +} diff --git a/java/sca/contrib/modules/binding-jsonrpc-runtime/src/test/java/echo/EchoBusinessException.java b/java/sca/contrib/modules/binding-jsonrpc-runtime/src/test/java/echo/EchoBusinessException.java new file mode 100644 index 0000000000..bf8c7d2c8a --- /dev/null +++ b/java/sca/contrib/modules/binding-jsonrpc-runtime/src/test/java/echo/EchoBusinessException.java @@ -0,0 +1,29 @@ +/* + * 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. + */ +package echo; + +public class EchoBusinessException extends Exception { + private static final long serialVersionUID = 7234119326657905710L; + + public EchoBusinessException(String message) + { + super(message); + } + +} diff --git a/java/sca/contrib/modules/binding-jsonrpc-runtime/src/test/java/echo/EchoComponentImpl.java b/java/sca/contrib/modules/binding-jsonrpc-runtime/src/test/java/echo/EchoComponentImpl.java new file mode 100644 index 0000000000..3e7b848221 --- /dev/null +++ b/java/sca/contrib/modules/binding-jsonrpc-runtime/src/test/java/echo/EchoComponentImpl.java @@ -0,0 +1,98 @@ +/* + * 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. + */ +package echo; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import bean.TestBean; + +/** + * A simple client component that uses a reference with an JSONRPC binding. + * + * @version $Rev$ $Date$ + */ +public class EchoComponentImpl implements Echo { + + public String echo(String msg) { + System.out.println("Echo: "+ msg); + return "echo: " + msg; + } + + public void echoBusinessException() throws EchoBusinessException { + throw new EchoBusinessException("Business Exception"); + + } + + public void echoRuntimeException() throws RuntimeException { + throw new RuntimeException("Runtime Exception"); + } + + public int echoInt(int param) { + int value = param; + return value; + } + + public boolean echoBoolean(boolean param) { + boolean value = param; + return value; + } + + public Map echoMap(HashMap param) { + Map map = new HashMap(); + map = param; + return map; + } + + public TestBean echoBean(TestBean testBean1) { + TestBean testBean = new TestBean(); + testBean.setTestString(testBean1.getTestString()); + testBean.setTestInt(testBean1.getTestInt()); + return testBean; + } + + public List echoList(ArrayList param){ + List list = new ArrayList(); + for(Iterator itr = param.iterator();itr.hasNext();) + { + list.add(itr.next()); + } + return list; + } + + public String[] echoArrayString(String[] stringArray) { + return stringArray; + } + + public int[] echoArrayInt(int[] intArray) { + return intArray; + } + + public Set echoSet(HashSet param){ + Set set = new HashSet(); + set = param; + return set; + + } +} diff --git a/java/sca/contrib/modules/binding-jsonrpc-runtime/src/test/java/org/apache/tuscany/sca/binding/jsonrpc/JSONRPCDataTypeTestCase.java b/java/sca/contrib/modules/binding-jsonrpc-runtime/src/test/java/org/apache/tuscany/sca/binding/jsonrpc/JSONRPCDataTypeTestCase.java new file mode 100644 index 0000000000..47ce8f4433 --- /dev/null +++ b/java/sca/contrib/modules/binding-jsonrpc-runtime/src/test/java/org/apache/tuscany/sca/binding/jsonrpc/JSONRPCDataTypeTestCase.java @@ -0,0 +1,180 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jsonrpc; + +import java.io.ByteArrayInputStream; + +import junit.framework.Assert; + +import org.apache.tuscany.sca.node.Contribution; +import org.apache.tuscany.sca.node.ContributionLocationHelper; +import org.apache.tuscany.sca.node.Node; +import org.apache.tuscany.sca.node.NodeFactory; +import org.json.JSONObject; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.meterware.httpunit.PostMethodWebRequest; +import com.meterware.httpunit.WebConversation; +import com.meterware.httpunit.WebRequest; +import com.meterware.httpunit.WebResponse; + +/** + * @version $Rev$ $Date$ + */ +public class JSONRPCDataTypeTestCase { + + private static final String SERVICE_PATH = "/EchoService"; + private static final String SERVICE_URL = "http://localhost:8085/SCADomain" + SERVICE_PATH; + private Node node; + + @Before + public void setUp() throws Exception { + String contribution = ContributionLocationHelper.getContributionLocation(getClass()); + node = NodeFactory.newInstance().createNode("JSONRPCBinding.composite", new Contribution("test", contribution)); + node.start(); + } + + @After + public void tearDown() throws Exception { + node.stop(); + node.destroy(); + } + + @Test + public void testInt() throws Exception { + JSONObject jsonRequest = new JSONObject("{ \"method\": \"echoInt\", \"params\": [12345], \"id\": 4}"); + + WebConversation wc = new WebConversation(); + WebRequest request = new PostMethodWebRequest(SERVICE_URL, new ByteArrayInputStream(jsonRequest.toString().getBytes("UTF-8")), "application/json"); + WebResponse response = wc.getResource(request); + + Assert.assertEquals(200, response.getResponseCode()); + + JSONObject jsonResp = new JSONObject(response.getText()); + + Assert.assertEquals(12345, jsonResp.getInt("result")); + } + + @Test + public void testBoolean() throws Exception { + JSONObject jsonRequest = new JSONObject("{ \"method\": \"echoBoolean\", \"params\": [true], \"id\": 5}"); + + WebConversation wc = new WebConversation(); + WebRequest request = new PostMethodWebRequest(SERVICE_URL, new ByteArrayInputStream(jsonRequest.toString().getBytes("UTF-8")), "application/json"); + WebResponse response = wc.getResource(request); + + Assert.assertEquals(200, response.getResponseCode()); + + JSONObject jsonResp = new JSONObject(response.getText()); + + Assert.assertEquals(true, jsonResp.getBoolean("result")); + } + + @Test + public void testMap() throws Exception { + JSONObject jsonRequest = new JSONObject("{ \"method\": \"echoMap\", \"params\": [ {\"javaClass\": \"java.util.HashMap\", \"map\": { \"Binding\": \"JSON-RPC\"}}], \"id\": 6}"); + + WebConversation wc = new WebConversation(); + WebRequest request = new PostMethodWebRequest(SERVICE_URL, new ByteArrayInputStream(jsonRequest.toString().getBytes("UTF-8")), "application/json"); + WebResponse response = wc.getResource(request); + + Assert.assertEquals(200, response.getResponseCode()); + + JSONObject jsonResp = new JSONObject(response.getText()); + + Assert.assertEquals("JSON-RPC", jsonResp.getJSONObject("result").getJSONObject("map").getString("Binding")); + } + + @Test + public void testBean() throws Exception { + JSONObject jsonRequest = new JSONObject("{ \"method\": \"echoBean\", \"params\": [ {\"javaClass\": \"bean.TestBean\", \"testString\": \"JSON-RPC\", \"testInt\":1234}], \"id\": 7}"); + + WebConversation wc = new WebConversation(); + WebRequest request = new PostMethodWebRequest(SERVICE_URL, new ByteArrayInputStream(jsonRequest.toString().getBytes("UTF-8")), "application/json"); + WebResponse response = wc.getResource(request); + + Assert.assertEquals(200, response.getResponseCode()); + + JSONObject jsonResp = new JSONObject(response.getText()); + + Assert.assertEquals("JSON-RPC", jsonResp.getJSONObject("result").getString("testString")); + } + + @Test + public void testList() throws Exception { + JSONObject jsonRequest = new JSONObject("{ \"method\": \"echoList\", \"params\": [ {\"javaClass\": \"java.util.ArrayList\", \"list\": [0,1,2,3,4]}], \"id\": 8}"); + + WebConversation wc = new WebConversation(); + WebRequest request = new PostMethodWebRequest(SERVICE_URL, new ByteArrayInputStream(jsonRequest.toString().getBytes("UTF-8")), "application/json"); + WebResponse response = wc.getResource(request); + + Assert.assertEquals(200, response.getResponseCode()); + + JSONObject jsonResp = new JSONObject(response.getText()); + + Assert.assertEquals(0, jsonResp.getJSONObject("result").getJSONArray("list").get(0)); + } + + @Test + public void testArrayString() throws Exception { + JSONObject jsonRequest = new JSONObject("{\"params\":[[\"1\",\"2\"]],\"method\":\"echoArrayString\",\"id\":9}"); + + WebConversation wc = new WebConversation(); + WebRequest request = new PostMethodWebRequest(SERVICE_URL, new ByteArrayInputStream(jsonRequest.toString().getBytes("UTF-8")), "application/json"); + WebResponse response = wc.getResource(request); + + Assert.assertEquals(200, response.getResponseCode()); + + JSONObject jsonResp = new JSONObject(response.getText()); + + Assert.assertEquals(1, jsonResp.getJSONArray("result").getInt(0)); + } + + @Test + public void testArrayInt() throws Exception { + JSONObject jsonRequest = new JSONObject("{\"params\":[[1,2]],\"method\":\"echoArrayInt\",\"id\":10}"); + + WebConversation wc = new WebConversation(); + WebRequest request = new PostMethodWebRequest(SERVICE_URL, new ByteArrayInputStream(jsonRequest.toString().getBytes("UTF-8")), "application/json"); + WebResponse response = wc.getResource(request); + + Assert.assertEquals(200, response.getResponseCode()); + + JSONObject jsonResp = new JSONObject(response.getText()); + + Assert.assertEquals(1, jsonResp.getJSONArray("result").getInt(0)); + } + + @Test + public void testSet() throws Exception { + JSONObject jsonRequest = new JSONObject("{ \"method\": \"echoSet\", \"params\": [ {\"javaClass\": \"java.util.HashSet\", \"set\": {\"1\": \"red\", \"2\": \"blue\"}}],\"id\": 11}"); + + WebConversation wc = new WebConversation(); + WebRequest request = new PostMethodWebRequest(SERVICE_URL, new ByteArrayInputStream(jsonRequest.toString().getBytes("UTF-8")), "application/json"); + WebResponse response = wc.getResource(request); + + Assert.assertEquals(200, response.getResponseCode()); + + JSONObject jsonResp = new JSONObject(response.getText()); + + Assert.assertEquals("red", jsonResp.getJSONObject("result").getJSONObject("set").getString("red")); + } +} diff --git a/java/sca/contrib/modules/binding-jsonrpc-runtime/src/test/java/org/apache/tuscany/sca/binding/jsonrpc/JSONRPCExceptionTestCase.java b/java/sca/contrib/modules/binding-jsonrpc-runtime/src/test/java/org/apache/tuscany/sca/binding/jsonrpc/JSONRPCExceptionTestCase.java new file mode 100644 index 0000000000..0619831c06 --- /dev/null +++ b/java/sca/contrib/modules/binding-jsonrpc-runtime/src/test/java/org/apache/tuscany/sca/binding/jsonrpc/JSONRPCExceptionTestCase.java @@ -0,0 +1,92 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jsonrpc; + +import java.io.ByteArrayInputStream; + +import junit.framework.Assert; + +import org.apache.tuscany.sca.node.Contribution; +import org.apache.tuscany.sca.node.ContributionLocationHelper; +import org.apache.tuscany.sca.node.Node; +import org.apache.tuscany.sca.node.NodeFactory; +import org.json.JSONObject; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.meterware.httpunit.PostMethodWebRequest; +import com.meterware.httpunit.WebConversation; +import com.meterware.httpunit.WebRequest; +import com.meterware.httpunit.WebResponse; + +/** + * @version $Rev$ $Date$ + */ +public class JSONRPCExceptionTestCase{ + + private static final String SERVICE_PATH = "/EchoService"; + + private static final String SERVICE_URL = "http://localhost:8085/SCADomain" + SERVICE_PATH; + + private Node node; + + @Before + public void setUp() throws Exception { + String contribution = ContributionLocationHelper.getContributionLocation(getClass()); + node = NodeFactory.newInstance().createNode("JSONRPCBinding.composite", new Contribution("test", contribution)); + node.start(); + } + + @After + public void tearDown() throws Exception { + node.stop(); + node.destroy(); + } + + @Test + public void testRuntimeException() throws Exception{ + JSONObject jsonRequest = new JSONObject("{ \"method\": \"echoRuntimeException\", \"params\": [], \"id\": 2}"); + + WebConversation wc = new WebConversation(); + WebRequest request = new PostMethodWebRequest( SERVICE_URL, new ByteArrayInputStream(jsonRequest.toString().getBytes("UTF-8")),"application/json"); + WebResponse response = wc.getResource(request); + + Assert.assertEquals(200, response.getResponseCode()); + + JSONObject jsonErr = new JSONObject(response.getText()).getJSONObject("error"); + + Assert.assertEquals("Runtime Exception", jsonErr.getString("msg")); + } + + @Test + public void testBusinessException() throws Exception{ + JSONObject jsonRequest = new JSONObject("{ \"method\": \"echoBusinessException\", \"params\": [], \"id\": 3}"); + + WebConversation wc = new WebConversation(); + WebRequest request = new PostMethodWebRequest( SERVICE_URL, new ByteArrayInputStream(jsonRequest.toString().getBytes("UTF-8")),"application/json"); + WebResponse response = wc.getResource(request); + + Assert.assertEquals(200, response.getResponseCode()); + + JSONObject jsonErr = new JSONObject(response.getText()).getJSONObject("error"); + + Assert.assertEquals("Business Exception", jsonErr.getString("msg")); + } +} \ No newline at end of file diff --git a/java/sca/contrib/modules/binding-jsonrpc-runtime/src/test/java/org/apache/tuscany/sca/binding/jsonrpc/JSONRPCServiceTestCase.java b/java/sca/contrib/modules/binding-jsonrpc-runtime/src/test/java/org/apache/tuscany/sca/binding/jsonrpc/JSONRPCServiceTestCase.java new file mode 100644 index 0000000000..ed73766202 --- /dev/null +++ b/java/sca/contrib/modules/binding-jsonrpc-runtime/src/test/java/org/apache/tuscany/sca/binding/jsonrpc/JSONRPCServiceTestCase.java @@ -0,0 +1,76 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.jsonrpc; + +import java.io.ByteArrayInputStream; + +import junit.framework.Assert; + +import org.apache.tuscany.sca.node.Contribution; +import org.apache.tuscany.sca.node.ContributionLocationHelper; +import org.apache.tuscany.sca.node.Node; +import org.apache.tuscany.sca.node.NodeFactory; +import org.json.JSONObject; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.meterware.httpunit.PostMethodWebRequest; +import com.meterware.httpunit.WebConversation; +import com.meterware.httpunit.WebRequest; +import com.meterware.httpunit.WebResponse; + +/** + * @version $Rev$ $Date$ + */ +public class JSONRPCServiceTestCase{ + + private static final String SERVICE_PATH = "/EchoService"; + + private static final String SERVICE_URL = "http://localhost:8085/SCADomain" + SERVICE_PATH; + + private Node node; + + @Before + public void setUp() throws Exception { + String contribution = ContributionLocationHelper.getContributionLocation(getClass()); + node = NodeFactory.newInstance().createNode("JSONRPCBinding.composite", new Contribution("test", contribution)); + node.start(); + } + + @After + public void tearDown() throws Exception { + node.stop(); + node.destroy(); + } + + @Test + public void testJSONRPCBinding() throws Exception { + JSONObject jsonRequest = new JSONObject("{ \"method\": \"echo\", \"params\": [\"Hello JSON-RPC\"], \"id\": 1}"); + + WebConversation wc = new WebConversation(); + WebRequest request = new PostMethodWebRequest( SERVICE_URL, new ByteArrayInputStream(jsonRequest.toString().getBytes("UTF-8")),"application/json"); + WebResponse response = wc.getResource(request); + + Assert.assertEquals(200, response.getResponseCode()); + + JSONObject jsonResp = new JSONObject(response.getText()); + Assert.assertEquals("echo: Hello JSON-RPC", jsonResp.getString("result")); + } +} \ No newline at end of file diff --git a/java/sca/contrib/modules/binding-jsonrpc-runtime/src/test/resources/JSONRPCBinding.composite b/java/sca/contrib/modules/binding-jsonrpc-runtime/src/test/resources/JSONRPCBinding.composite new file mode 100644 index 0000000000..978fdcfa7f --- /dev/null +++ b/java/sca/contrib/modules/binding-jsonrpc-runtime/src/test/resources/JSONRPCBinding.composite @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + diff --git a/java/sca/contrib/modules/binding-jsonrpc/LICENSE b/java/sca/contrib/modules/binding-jsonrpc/LICENSE new file mode 100644 index 0000000000..8aa906c321 --- /dev/null +++ b/java/sca/contrib/modules/binding-jsonrpc/LICENSE @@ -0,0 +1,205 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + + diff --git a/java/sca/contrib/modules/binding-jsonrpc/META-INF/MANIFEST.MF b/java/sca/contrib/modules/binding-jsonrpc/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..f1d73db1fb --- /dev/null +++ b/java/sca/contrib/modules/binding-jsonrpc/META-INF/MANIFEST.MF @@ -0,0 +1,20 @@ +Manifest-Version: 1.0 +Export-Package: org.apache.tuscany.sca.binding.jsonrpc;uses:="org.apac + he.tuscany.sca.assembly,org.apache.tuscany.sca.policy";version="2.0.0" +Private-Package: org.apache.tuscany.sca.binding.jsonrpc.impl;version=" + 1.4" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA JSON-RPC Binding Model +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397309921 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA JSON-RPC Binding Model +Import-Package: org.apache.tuscany.sca.assembly;version="2.0.0",org.apac + he.tuscany.sca.assembly.xml;version="2.0.0",org.apache.tuscany.sca.bind + ing.jsonrpc;version="2.0.0",org.apache.tuscany.sca.policy;version="2.0.0" +Bundle-SymbolicName: org.apache.tuscany.sca.binding.jsonrpc +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/binding-jsonrpc/NOTICE b/java/sca/contrib/modules/binding-jsonrpc/NOTICE new file mode 100644 index 0000000000..25bb89c9b2 --- /dev/null +++ b/java/sca/contrib/modules/binding-jsonrpc/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/binding-jsonrpc/pom.xml b/java/sca/contrib/modules/binding-jsonrpc/pom.xml new file mode 100644 index 0000000000..f3f41200a3 --- /dev/null +++ b/java/sca/contrib/modules/binding-jsonrpc/pom.xml @@ -0,0 +1,59 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + + tuscany-binding-jsonrpc + Apache Tuscany SCA JSON-RPC Binding Model + + + + org.apache.tuscany.sca + tuscany-assembly + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-policy + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-interface-java + 2.0-SNAPSHOT + + + + junit + junit + 4.5 + test + + + + diff --git a/java/sca/contrib/modules/binding-jsonrpc/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/JSONRPCBinding.java b/java/sca/contrib/modules/binding-jsonrpc/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/JSONRPCBinding.java new file mode 100644 index 0000000000..ce86365980 --- /dev/null +++ b/java/sca/contrib/modules/binding-jsonrpc/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/JSONRPCBinding.java @@ -0,0 +1,32 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.jsonrpc; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.policy.PolicySetAttachPoint; + +/** + * A model for the JSONRPC binding. + * + * @version $Rev$ $Date$ + */ +public interface JSONRPCBinding extends Binding, PolicySetAttachPoint { + +} diff --git a/java/sca/contrib/modules/binding-jsonrpc/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/JSONRPCBindingFactory.java b/java/sca/contrib/modules/binding-jsonrpc/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/JSONRPCBindingFactory.java new file mode 100644 index 0000000000..707a9d7103 --- /dev/null +++ b/java/sca/contrib/modules/binding-jsonrpc/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/JSONRPCBindingFactory.java @@ -0,0 +1,35 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.jsonrpc; + + +/** + * Factory for the JSON RPC binding model. + * + * @version $Rev$ $Date$ +*/ +public interface JSONRPCBindingFactory { + + /** + * Creates a new JSON RPC Binding + * @return a new JSON RPC Binding + */ + JSONRPCBinding createJSONRPCBinding(); +} diff --git a/java/sca/contrib/modules/binding-jsonrpc/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/impl/JSONRPCBindingFactoryImpl.java b/java/sca/contrib/modules/binding-jsonrpc/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/impl/JSONRPCBindingFactoryImpl.java new file mode 100644 index 0000000000..625457a668 --- /dev/null +++ b/java/sca/contrib/modules/binding-jsonrpc/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/impl/JSONRPCBindingFactoryImpl.java @@ -0,0 +1,38 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.jsonrpc.impl; + +import org.apache.tuscany.sca.binding.jsonrpc.JSONRPCBinding; +import org.apache.tuscany.sca.binding.jsonrpc.JSONRPCBindingFactory; + + +/** + * Factory for the JSON RPC binding model. + * + * @version $Rev$ $Date$ +*/ +public class JSONRPCBindingFactoryImpl implements JSONRPCBindingFactory { + + public JSONRPCBinding createJSONRPCBinding() { + return new JSONRPCBindingImpl(); + } + + +} diff --git a/java/sca/contrib/modules/binding-jsonrpc/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/impl/JSONRPCBindingImpl.java b/java/sca/contrib/modules/binding-jsonrpc/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/impl/JSONRPCBindingImpl.java new file mode 100644 index 0000000000..1ee3631a98 --- /dev/null +++ b/java/sca/contrib/modules/binding-jsonrpc/src/main/java/org/apache/tuscany/sca/binding/jsonrpc/impl/JSONRPCBindingImpl.java @@ -0,0 +1,105 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.jsonrpc.impl; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.tuscany.sca.policy.Intent; +import org.apache.tuscany.sca.policy.IntentAttachPointType; +import org.apache.tuscany.sca.policy.PolicySet; + +import org.apache.tuscany.sca.binding.jsonrpc.JSONRPCBinding; + +/** + * A model for the JSONRPC binding. + * + * @version $Rev$ $Date$ + */ +public class JSONRPCBindingImpl implements JSONRPCBinding { + private String name; + private String uri; + + + private List requiredIntents = new ArrayList(); + private List policySets = new ArrayList(); + private IntentAttachPointType intentAttachPointType; + private List applicablePolicySets = new ArrayList(); + + public String getName() { + return name; + } + + public String getURI() { + return uri; + } + + public void setURI(String uri) { + this.uri = uri; + } + + public void setName(String name) { + this.name = name; + } + + public boolean isUnresolved() { + // The binding is always resolved + return false; + } + + public void setUnresolved(boolean unresolved) { + // The binding is always resolved + } + + //Policy related getters/setters + + public List getPolicySets() { + return policySets; + } + + public List getRequiredIntents() { + return requiredIntents; + } + + public IntentAttachPointType getType() { + return intentAttachPointType; + } + + public void setType(IntentAttachPointType intentAttachPointType) { + this.intentAttachPointType = intentAttachPointType; + } + + public void setPolicySets(List policySets) { + this.policySets = policySets; + } + + public void setRequiredIntents(List intents) { + this.requiredIntents = intents; + } + + public List getApplicablePolicySets() { + return applicablePolicySets; + } + + @Override + public Object clone() throws CloneNotSupportedException { + return super.clone(); + } +} diff --git a/java/sca/contrib/modules/binding-jsonrpc/src/main/resources/META-INF/services/org.apache.tuscany.sca.binding.jsonrpc.JSONRPCBindingFactory b/java/sca/contrib/modules/binding-jsonrpc/src/main/resources/META-INF/services/org.apache.tuscany.sca.binding.jsonrpc.JSONRPCBindingFactory new file mode 100644 index 0000000000..8b9662997d --- /dev/null +++ b/java/sca/contrib/modules/binding-jsonrpc/src/main/resources/META-INF/services/org.apache.tuscany.sca.binding.jsonrpc.JSONRPCBindingFactory @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for model factory +org.apache.tuscany.sca.binding.jsonrpc.impl.JSONRPCBindingFactoryImpl diff --git a/java/sca/contrib/modules/binding-jsonrpc/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor b/java/sca/contrib/modules/binding-jsonrpc/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor new file mode 100644 index 0000000000..0f39251068 --- /dev/null +++ b/java/sca/contrib/modules/binding-jsonrpc/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for the artifact processor extension +org.apache.tuscany.sca.assembly.xml.DefaultBeanModelProcessor;qname=http://tuscany.apache.org/xmlns/sca/1.0#binding.jsonrpc,model=org.apache.tuscany.sca.binding.jsonrpc.JSONRPCBinding,factory=org.apache.tuscany.sca.binding.jsonrpc.JSONRPCBindingFactory diff --git a/java/sca/contrib/modules/binding-rss-rome/LICENSE b/java/sca/contrib/modules/binding-rss-rome/LICENSE new file mode 100644 index 0000000000..6e529a25c4 --- /dev/null +++ b/java/sca/contrib/modules/binding-rss-rome/LICENSE @@ -0,0 +1,205 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + + diff --git a/java/sca/contrib/modules/binding-rss-rome/META-INF/MANIFEST.MF b/java/sca/contrib/modules/binding-rss-rome/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..95f62ad91d --- /dev/null +++ b/java/sca/contrib/modules/binding-rss-rome/META-INF/MANIFEST.MF @@ -0,0 +1,39 @@ +Manifest-Version: 1.0 +Private-Package: org.apache.tuscany.sca.binding.rss.collection;version + ="1.4",org.apache.tuscany.sca.binding.rss.provider;version="2.0.0" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA RSS Feed Binding Extension +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397329562 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA RSS Feed Binding Extension +Import-Package: com.sun.syndication.feed.atom, + com.sun.syndication.feed.synd, + com.sun.syndication.io, + javax.servlet, + javax.servlet.http, + javax.xml.namespace, + org.apache.commons.codec.binary, + org.apache.tuscany.sca.assembly;version="2.0.0", + org.apache.tuscany.sca.binding.rss;version="2.0.0", + org.apache.tuscany.sca.binding.rss.collection;resolution:=optional, + org.apache.tuscany.sca.core;version="2.0.0", + org.apache.tuscany.sca.data.collection;version="2.0.0", + org.apache.tuscany.sca.databinding;version="2.0.0", + org.apache.tuscany.sca.databinding.impl;version="2.0.0", + org.apache.tuscany.sca.host.http;version="2.0.0", + org.apache.tuscany.sca.interfacedef;version="2.0.0", + org.apache.tuscany.sca.interfacedef.impl;version="2.0.0", + org.apache.tuscany.sca.interfacedef.util;version="2.0.0", + org.apache.tuscany.sca.invocation;version="2.0.0", + org.apache.tuscany.sca.policy;version="2.0.0", + org.apache.tuscany.sca.provider;version="2.0.0", + org.apache.tuscany.sca.runtime;version="2.0.0", + org.jdom;version="1.0.0", + org.oasisopen.sca.annotation;version="2.0.0" +Bundle-SymbolicName: org.apache.tuscany.sca.binding.rss.rome +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/binding-rss-rome/NOTICE b/java/sca/contrib/modules/binding-rss-rome/NOTICE new file mode 100644 index 0000000000..51042eab05 --- /dev/null +++ b/java/sca/contrib/modules/binding-rss-rome/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/binding-rss-rome/pom.xml b/java/sca/contrib/modules/binding-rss-rome/pom.xml new file mode 100644 index 0000000000..f46851dbec --- /dev/null +++ b/java/sca/contrib/modules/binding-rss-rome/pom.xml @@ -0,0 +1,151 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + + tuscany-binding-rss-rome + Apache Tuscany SCA RSS Feed Binding Extension + + + + org.apache.tuscany.sca + tuscany-assembly + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-binding-rss + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-interface-java + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-data-api + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-core-spi + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-databinding + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-host-http + 2.0-SNAPSHOT + + + + commons-httpclient + commons-httpclient + 3.1 + + + + rome + rome + 0.9 + + + + javax.servlet + servlet-api + 2.5 + + + + org.apache.tuscany.sca + tuscany-host-jetty + 2.0-SNAPSHOT + test + + + + org.apache.tuscany.sca + tuscany-implementation-java-runtime + 2.0-SNAPSHOT + test + + + + org.apache.tuscany.sca + tuscany-node-impl + 2.0-SNAPSHOT + test + + + + junit + junit + 4.5 + test + + + + commons-codec + commons-codec + 1.3 + + + commons-codec + commons-codec + + + + + + commons-logging + commons-logging + 1.1.1 + + + javax.servlet + servlet-api + + + avalon-framework + avalon-framework + + + + + + + diff --git a/java/sca/contrib/modules/binding-rss-rome/src/main/java/org/apache/tuscany/sca/binding/rss/collection/Collection.java b/java/sca/contrib/modules/binding-rss-rome/src/main/java/org/apache/tuscany/sca/binding/rss/collection/Collection.java new file mode 100644 index 0000000000..1124348158 --- /dev/null +++ b/java/sca/contrib/modules/binding-rss-rome/src/main/java/org/apache/tuscany/sca/binding/rss/collection/Collection.java @@ -0,0 +1,49 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.rss.collection; + +import org.oasisopen.sca.annotation.Remotable; + +import com.sun.syndication.feed.synd.SyndFeed; + + +/** + * Provides access to a collection of resources using RSS. + * + * @version $Rev$ $Date$ + */ +@Remotable +public interface Collection { + + /** + * Get an RSS feed for a collection of resources. + * + * @return the RSS feed + */ + SyndFeed getFeed(); + + /** + * Get an RSS feed for a collection of resources resulting from a query. + * + * @param queryString the query string + * @return the RSS feed + */ + SyndFeed query(String queryString); + +} diff --git a/java/sca/contrib/modules/binding-rss-rome/src/main/java/org/apache/tuscany/sca/binding/rss/collection/MediaCollection.java b/java/sca/contrib/modules/binding-rss-rome/src/main/java/org/apache/tuscany/sca/binding/rss/collection/MediaCollection.java new file mode 100644 index 0000000000..a2b83465da --- /dev/null +++ b/java/sca/contrib/modules/binding-rss-rome/src/main/java/org/apache/tuscany/sca/binding/rss/collection/MediaCollection.java @@ -0,0 +1,55 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.rss.collection; + +import java.io.InputStream; + +import org.oasisopen.sca.annotation.Remotable; + +import com.sun.syndication.feed.atom.Entry; + +/** + * Provides access to a collection of resources using Atom. + * + * @version $Rev$ $Date$ + */ +@Remotable +public interface MediaCollection extends Collection { + + /** + * Creates a new media entry + * + * @param title + * @param slug + * @param contentType + * @param media + */ + Entry postMedia(String title, String slug, String contentType, InputStream media); + + /** + * Update a media entry. + * + * @param id + * @param contentType + * @param media + * @return + */ + void putMedia(String id, String contentType, InputStream media) throws NotFoundException; + +} diff --git a/java/sca/contrib/modules/binding-rss-rome/src/main/java/org/apache/tuscany/sca/binding/rss/collection/NotFoundException.java b/java/sca/contrib/modules/binding-rss-rome/src/main/java/org/apache/tuscany/sca/binding/rss/collection/NotFoundException.java new file mode 100644 index 0000000000..0912878938 --- /dev/null +++ b/java/sca/contrib/modules/binding-rss-rome/src/main/java/org/apache/tuscany/sca/binding/rss/collection/NotFoundException.java @@ -0,0 +1,45 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.rss.collection; + +/** + * Indicates that a resource could not be found. + * + * @version $Rev$ $Date$ + */ +public class NotFoundException extends Exception { + private static final long serialVersionUID = -5046027674128627383L; + + public NotFoundException() { + } + + public NotFoundException(String message) { + super(message); + } + + public NotFoundException(Throwable cause) { + super(cause); + } + + public NotFoundException(String message, Throwable cause) { + super(message, cause); + } + +} diff --git a/java/sca/contrib/modules/binding-rss-rome/src/main/java/org/apache/tuscany/sca/binding/rss/provider/RSSBindingInvoker.java b/java/sca/contrib/modules/binding-rss-rome/src/main/java/org/apache/tuscany/sca/binding/rss/provider/RSSBindingInvoker.java new file mode 100644 index 0000000000..e3a177198c --- /dev/null +++ b/java/sca/contrib/modules/binding-rss-rome/src/main/java/org/apache/tuscany/sca/binding/rss/provider/RSSBindingInvoker.java @@ -0,0 +1,76 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.rss.provider; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.logging.Logger; + +import org.apache.tuscany.sca.invocation.DataExchangeSemantics; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; + +import com.sun.syndication.feed.synd.SyndFeed; +import com.sun.syndication.io.FeedException; +import com.sun.syndication.io.SyndFeedInput; +import com.sun.syndication.io.XmlReader; + +/** + * Invoker for the RSS binding. + * + * @version $Rev$ $Date$ + */ +class RSSBindingInvoker implements Invoker , DataExchangeSemantics { + private static final Logger logger = Logger.getLogger(RSSBindingInvoker.class.getName()); + + private String uri; + + RSSBindingInvoker(String uri, String feedType) { + this.uri = uri; + } + + public Message invoke(Message msg) { + try { + logger.fine("invoke " + uri); + + // Read an RSS feed into a Synd feed + SyndFeedInput input = new SyndFeedInput(); + SyndFeed feed = input.build(new XmlReader(new URL(uri))); + + //FIXME Support conversion to data-api entries + + msg.setBody(feed); + + } catch (MalformedURLException e) { + msg.setFaultBody(e); + } catch (IllegalArgumentException e) { + msg.setFaultBody(e); + } catch (FeedException e) { + msg.setFaultBody(e); + } catch (IOException e) { + msg.setFaultBody(e); + } + return msg; + } + + public boolean allowsPassByReference() { + return true; + } +} diff --git a/java/sca/contrib/modules/binding-rss-rome/src/main/java/org/apache/tuscany/sca/binding/rss/provider/RSSBindingListenerServlet.java b/java/sca/contrib/modules/binding-rss-rome/src/main/java/org/apache/tuscany/sca/binding/rss/provider/RSSBindingListenerServlet.java new file mode 100644 index 0000000000..7eb5aeb3df --- /dev/null +++ b/java/sca/contrib/modules/binding-rss-rome/src/main/java/org/apache/tuscany/sca/binding/rss/provider/RSSBindingListenerServlet.java @@ -0,0 +1,394 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.rss.provider; + +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.UnsupportedEncodingException; +import java.io.Writer; +import java.net.URLDecoder; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.StringTokenizer; +import java.util.logging.Logger; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.xml.namespace.QName; + +import org.apache.commons.codec.binary.Base64; +import org.apache.tuscany.sca.data.collection.Item; +import org.apache.tuscany.sca.databinding.Mediator; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.interfacedef.impl.DataTypeImpl; +import org.apache.tuscany.sca.interfacedef.util.XMLType; +import org.apache.tuscany.sca.invocation.InvocationChain; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.invocation.MessageFactory; +import org.apache.tuscany.sca.runtime.RuntimeWire; + +import com.sun.syndication.feed.synd.SyndContent; +import com.sun.syndication.feed.synd.SyndContentImpl; +import com.sun.syndication.feed.synd.SyndEntry; +import com.sun.syndication.feed.synd.SyndEntryImpl; +import com.sun.syndication.feed.synd.SyndFeed; +import com.sun.syndication.feed.synd.SyndFeedImpl; +import com.sun.syndication.feed.synd.SyndLink; +import com.sun.syndication.feed.synd.SyndLinkImpl; +import com.sun.syndication.io.FeedException; +import com.sun.syndication.io.SyndFeedOutput; + +/** + * An RSS binding listener, implemented as a Servlet and + * registered in a Servlet host provided by the SCA hosting runtime. + * + * @version $Rev$ $Date$ + */ +class RSSBindingListenerServlet extends HttpServlet { + private static final Logger logger = Logger.getLogger(RSSBindingListenerServlet.class.getName()); + private static final long serialVersionUID = 1L; + + private RuntimeWire wire; + private Invoker getFeedInvoker; + private Invoker getAllInvoker; + private Invoker queryInvoker; + private MessageFactory messageFactory; + private Mediator mediator; + private DataType itemClassType; + private DataType itemXMLType; + private boolean supportsFeedEntries; + + /** + * Constructs a new binding listener. + * + * @param wire + * @param messageFactory + */ + RSSBindingListenerServlet(RuntimeWire wire, MessageFactory messageFactory, Mediator mediator) { + this.wire = wire; + this.messageFactory = messageFactory; + this.mediator = mediator; + + // Get the invokers for the supported operations + Operation getOperation = null; + for (InvocationChain invocationChain : this.wire.getInvocationChains()) { + invocationChain.setAllowsPassByReference(true); + Operation operation = invocationChain.getTargetOperation(); + String operationName = operation.getName(); + if (operationName.equals("getFeed")) { + getFeedInvoker = invocationChain.getHeadInvoker(); + } else if (operationName.equals("getAll")) { + getAllInvoker = invocationChain.getHeadInvoker(); + } else if (operationName.equals("query")) { + queryInvoker = invocationChain.getHeadInvoker(); + } else if (operationName.equals("get")) { + getOperation = operation; + } + } + + // Determine the collection item type + itemXMLType = new DataTypeImpl>(String.class.getName(), String.class, String.class); + Class itemClass = getOperation.getOutputType().getPhysical(); + if (itemClass == SyndEntry.class) { + supportsFeedEntries = true; + } + DataType outputType = getOperation.getOutputType(); + QName qname = outputType.getLogical().getElementName(); + qname = new QName(qname.getNamespaceURI(), itemClass.getSimpleName()); + itemClassType = new DataTypeImpl("java:complexType", itemClass, new XMLType(qname, null)); + + } + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + // No authentication required for a get request + + // Get the request path + String path = URLDecoder.decode(request.getRequestURI().substring(request.getServletPath().length()), "UTF-8"); + + logger.fine("get " + request.getRequestURI()); + + // Handle an RSS request + if (path == null || path.length() == 0 || path.equals("/")) { + + // Return an RSS feed containing the entries in the collection + SyndFeed feed = null; + if (supportsFeedEntries) { + + // The service implementation supports feed entries, invoke its getFeed operation + Message requestMessage = messageFactory.createMessage(); + Message responseMessage = getFeedInvoker.invoke(requestMessage); + if (responseMessage.isFault()) { + throw new ServletException((Throwable)responseMessage.getBody()); + } + feed = (SyndFeed)responseMessage.getBody(); + + } else { + + // The service implementation does not support feed entries, invoke its + // getAll operation to get the data item collection. then create feed entries + // from the data items + Message requestMessage = messageFactory.createMessage(); + Message responseMessage; + if (request.getQueryString() != null) { + requestMessage.setBody(new Object[] {request.getQueryString()}); + responseMessage = queryInvoker.invoke(requestMessage); + } else { + responseMessage = getAllInvoker.invoke(requestMessage); + } + if (responseMessage.isFault()) { + throw new ServletException((Throwable)responseMessage.getBody()); + } + org.apache.tuscany.sca.data.collection.Entry[] collection = + (org.apache.tuscany.sca.data.collection.Entry[])responseMessage.getBody(); + if (collection != null) { + // Create the feed + feed = new SyndFeedImpl(); + feed.setTitle("Feed"); + + for (org.apache.tuscany.sca.data.collection.Entry entry: collection) { + SyndEntry feedEntry = createFeedEntry(entry); + feed.getEntries().add(feedEntry); + } + } + } + + // Convert to an RSS feed + if (feed != null) { + response.setContentType("application/rss+xml; charset=utf-8"); + feed.setFeedType("rss_2.0"); + feed.setLink(path); + SyndFeedOutput syndOutput = new SyndFeedOutput(); + try { + syndOutput.output(feed, getWriter(response)); + } catch (FeedException e) { + throw new ServletException(e); + } + } else { + response.sendError(HttpServletResponse.SC_NOT_FOUND); + } + } else { + response.sendError(HttpServletResponse.SC_NOT_FOUND); + } + + } + + /** + * Create an Atom entry from a data collection entry. + * @param entry + * @return + */ + private SyndEntry createFeedEntry(org.apache.tuscany.sca.data.collection.Entry entry) { + Object key = entry.getKey(); + Object data = entry.getData(); + if (data instanceof Item) { + Item item = (Item)data; + + SyndEntry feedEntry = new SyndEntryImpl(); + feedEntry.setUri(key.toString()); + feedEntry.setTitle(item.getTitle()); + + String value = item.getContents(); + if (value != null) { + SyndContent content = new SyndContentImpl(); + content.setType("text/xml"); + content.setValue(value); + List contents = new ArrayList(); + contents.add(content); + feedEntry.setContents(contents); + } + + String href = item.getLink(); + if (href == null) { + href = key.toString(); + } + SyndLink link = new SyndLinkImpl(); + link.setRel("edit"); + link.setHref(href); + feedEntry.getLinks().add(link); + link = new SyndLinkImpl(); + link.setRel("alternate"); + link.setHref(href); + feedEntry.getLinks().add(link); + + Date date = item.getDate(); + if (date == null) { + date = new Date(); + } + feedEntry.setPublishedDate(date); + return feedEntry; + + } else if (data != null) { + SyndEntry feedEntry = new SyndEntryImpl(); + feedEntry.setUri(key.toString()); + feedEntry.setTitle("item"); + + // Convert the item to XML + String value = mediator.mediate(data, itemClassType, itemXMLType, null).toString(); + + SyndContent content = new SyndContentImpl(); + content.setType("text/xml"); + content.setValue(value); + List contents = new ArrayList(); + contents.add(content); + feedEntry.setContents(contents); + + SyndLink link = new SyndLinkImpl(); + link.setRel("edit"); + link.setHref(key.toString()); + feedEntry.getLinks().add(link); + link = new SyndLinkImpl(); + link.setRel("alternate"); + link.setHref(key.toString()); + feedEntry.getLinks().add(link); + + feedEntry.setPublishedDate(new Date()); + return feedEntry; + } else { + return null; + } + } + + /** + * Create a data collection entry from an RSS entry. + * @param feedEntry + * @return + */ + private org.apache.tuscany.sca.data.collection.Entry createEntry(SyndEntry feedEntry) { + if (feedEntry != null) { + if (itemClassType.getPhysical() == Item.class) { + String key = feedEntry.getUri(); + + Item item = new Item(); + item.setTitle(feedEntry.getTitle()); + + List contents = feedEntry.getContents(); + if (!contents.isEmpty()) { + SyndContent content = (SyndContent)contents.get(0); + String value = content.getValue(); + item.setContents(value); + } + + for (Object l : feedEntry.getLinks()) { + SyndLink link = (SyndLink)l; + if (link.getRel() == null || "edit".equals(link.getRel())) { + String href = link.getHref(); + if (href.startsWith("null/")) { + href = href.substring(5); + } + item.setLink(href); + break; + } + } + + item.setDate(feedEntry.getPublishedDate()); + + return new org.apache.tuscany.sca.data.collection.Entry(key, item); + + } else { + String key = feedEntry.getUri(); + + // Create the item from XML + List contents = feedEntry.getContents(); + if (contents.isEmpty()) { + return null; + } + SyndContent content = (SyndContent)contents.get(0); + String value = content.getValue(); + Object data = mediator.mediate(value, itemXMLType, itemClassType, null); + + return new org.apache.tuscany.sca.data.collection.Entry(key, data); + } + } else { + return null; + } + } + + + private Writer getWriter(HttpServletResponse response) throws UnsupportedEncodingException, IOException { + Writer writer = new OutputStreamWriter(response.getOutputStream(), "UTF-8"); + return writer; + } + + /** + * Process the authorization header + * + * @param request + * @return + * @throws ServletException + */ + private String processAuthorizationHeader(HttpServletRequest request) throws ServletException { + try { + String authorization = request.getHeader("Authorization"); + if (authorization != null) { + StringTokenizer tokens = new StringTokenizer(authorization); + if (tokens.hasMoreTokens()) { + String basic = tokens.nextToken(); + if (basic.equalsIgnoreCase("Basic")) { + String credentials = tokens.nextToken(); + String userAndPassword = new String(Base64.decodeBase64(credentials.getBytes())); + int colon = userAndPassword.indexOf(":"); + if (colon != -1) { + String user = userAndPassword.substring(0, colon); + String password = userAndPassword.substring(colon + 1); + + // Authenticate the User. + if (authenticate(user, password)) { + return user; + } + } + } + } + } + } catch (Exception e) { + throw new ServletException(e); + } + return null; + } + + /** + * Authenticate a user. + * + * @param user + * @param password + * @return + */ + private boolean authenticate(String user, String password) { + + // TODO Handle this using SCA security policies + //FIXME Why are we using endsWith instead of equals here?? + return ("admin".endsWith(user) && "admin".equals(password)); + } + + /** + * Reject an unauthorized request. + * + * @param response + */ + private void unauthorized(HttpServletResponse response) throws IOException { + response.setHeader("WWW-Authenticate", "BASIC realm=\"Tuscany\""); + response.sendError(HttpServletResponse.SC_UNAUTHORIZED); + } +} diff --git a/java/sca/contrib/modules/binding-rss-rome/src/main/java/org/apache/tuscany/sca/binding/rss/provider/RSSBindingProviderFactory.java b/java/sca/contrib/modules/binding-rss-rome/src/main/java/org/apache/tuscany/sca/binding/rss/provider/RSSBindingProviderFactory.java new file mode 100644 index 0000000000..216d8f3abe --- /dev/null +++ b/java/sca/contrib/modules/binding-rss-rome/src/main/java/org/apache/tuscany/sca/binding/rss/provider/RSSBindingProviderFactory.java @@ -0,0 +1,74 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.rss.provider; + +import org.apache.tuscany.sca.binding.rss.RSSBinding; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.core.FactoryExtensionPoint; +import org.apache.tuscany.sca.databinding.DataBindingExtensionPoint; +import org.apache.tuscany.sca.databinding.Mediator; +import org.apache.tuscany.sca.databinding.TransformerExtensionPoint; +import org.apache.tuscany.sca.databinding.impl.MediatorImpl; +import org.apache.tuscany.sca.host.http.ServletHost; +import org.apache.tuscany.sca.host.http.ServletHostExtensionPoint; +import org.apache.tuscany.sca.invocation.MessageFactory; +import org.apache.tuscany.sca.provider.BindingProviderFactory; +import org.apache.tuscany.sca.provider.ReferenceBindingProvider; +import org.apache.tuscany.sca.provider.ServiceBindingProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; + +/** + * Implementation of the RSS binding provider factory. + * + * @version $Rev$ $Date$ + */ +public class RSSBindingProviderFactory implements BindingProviderFactory { + + private MessageFactory messageFactory; + private Mediator mediator; + private ServletHost servletHost; + + public RSSBindingProviderFactory(ExtensionPointRegistry extensionPoints) { + ServletHostExtensionPoint servletHosts = extensionPoints.getExtensionPoint(ServletHostExtensionPoint.class); + this.servletHost = servletHosts.getServletHosts().get(0); + FactoryExtensionPoint modelFactories = extensionPoints.getExtensionPoint(FactoryExtensionPoint.class); + this.messageFactory = modelFactories.getFactory(MessageFactory.class); + this.mediator = new MediatorImpl(extensionPoints.getExtensionPoint(DataBindingExtensionPoint.class), + extensionPoints.getExtensionPoint(TransformerExtensionPoint.class)); + } + + public ReferenceBindingProvider createReferenceBindingProvider(RuntimeComponent component, + RuntimeComponentReference reference, + RSSBinding binding) { + return new RSSReferenceBindingProvider(component, reference, binding); + } + + public ServiceBindingProvider createServiceBindingProvider(RuntimeComponent component, + RuntimeComponentService service, + RSSBinding binding) { + return new RSSServiceBindingProvider(component, service, binding, servletHost, messageFactory, mediator); + } + + public Class getModelType() { + return RSSBinding.class; + } +} diff --git a/java/sca/contrib/modules/binding-rss-rome/src/main/java/org/apache/tuscany/sca/binding/rss/provider/RSSReferenceBindingProvider.java b/java/sca/contrib/modules/binding-rss-rome/src/main/java/org/apache/tuscany/sca/binding/rss/provider/RSSReferenceBindingProvider.java new file mode 100644 index 0000000000..8a30e9d3fb --- /dev/null +++ b/java/sca/contrib/modules/binding-rss-rome/src/main/java/org/apache/tuscany/sca/binding/rss/provider/RSSReferenceBindingProvider.java @@ -0,0 +1,65 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.rss.provider; + +import org.apache.tuscany.sca.binding.rss.RSSBinding; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.provider.ReferenceBindingProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; + +/** + * Implementation of the RSS binding provider. + * + * @version $Rev$ $Date$ + */ +class RSSReferenceBindingProvider implements ReferenceBindingProvider { + + private RuntimeComponentReference reference; + private RSSBinding binding; + + RSSReferenceBindingProvider(RuntimeComponent component, + RuntimeComponentReference reference, + RSSBinding binding) { + this.reference = reference; + this.binding = binding; + } + + public Invoker createInvoker(Operation operation) { + return new RSSBindingInvoker(binding.getURI(), "rss_2.0"); + } + + public boolean supportsOneWayInvocation() { + return false; + } + + public InterfaceContract getBindingInterfaceContract() { + return reference.getInterfaceContract(); + } + + public void start() { + } + + public void stop() { + } + +} diff --git a/java/sca/contrib/modules/binding-rss-rome/src/main/java/org/apache/tuscany/sca/binding/rss/provider/RSSServiceBindingProvider.java b/java/sca/contrib/modules/binding-rss-rome/src/main/java/org/apache/tuscany/sca/binding/rss/provider/RSSServiceBindingProvider.java new file mode 100644 index 0000000000..4e5429ac83 --- /dev/null +++ b/java/sca/contrib/modules/binding-rss-rome/src/main/java/org/apache/tuscany/sca/binding/rss/provider/RSSServiceBindingProvider.java @@ -0,0 +1,85 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.rss.provider; + +import org.apache.tuscany.sca.binding.rss.RSSBinding; +import org.apache.tuscany.sca.databinding.Mediator; +import org.apache.tuscany.sca.host.http.ServletHost; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.invocation.MessageFactory; +import org.apache.tuscany.sca.provider.ServiceBindingProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; +import org.apache.tuscany.sca.runtime.RuntimeWire; + +/** + * Implementation of the RSS binding provider. + * + * @version $Rev$ $Date$ + */ +class RSSServiceBindingProvider implements ServiceBindingProvider { + + private RuntimeComponentService service; + private RSSBinding binding; + private ServletHost servletHost; + private MessageFactory messageFactory; + private String servletMapping; + private Mediator mediator; + + RSSServiceBindingProvider(RuntimeComponent component, + RuntimeComponentService service, + RSSBinding binding, + ServletHost servletHost, + MessageFactory messageFactory, + Mediator mediator) { + this.service = service; + this.binding = binding; + this.servletHost = servletHost; + this.messageFactory = messageFactory; + this.mediator = mediator; + } + + public InterfaceContract getBindingInterfaceContract() { + return service.getInterfaceContract(); + } + + public boolean supportsOneWayInvocation() { + return false; + } + + public void start() { + RuntimeComponentService componentService = (RuntimeComponentService)service; + RuntimeWire wire = componentService.getRuntimeWire(binding); + + RSSBindingListenerServlet servlet = + new RSSBindingListenerServlet(wire, messageFactory, mediator); + + servletMapping = binding.getURI(); + servletHost.addServletMapping(servletMapping, servlet); + + // Save the actual binding URI in the binding + binding.setURI(servletHost.getURLMapping(binding.getURI()).toString()); + } + + public void stop() { + servletHost.removeServletMapping(servletMapping); + } + +} diff --git a/java/sca/contrib/modules/binding-rss-rome/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.BindingProviderFactory b/java/sca/contrib/modules/binding-rss-rome/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.BindingProviderFactory new file mode 100644 index 0000000000..e60dc2855a --- /dev/null +++ b/java/sca/contrib/modules/binding-rss-rome/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.BindingProviderFactory @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for the binding extension +org.apache.tuscany.sca.binding.rss.provider.RSSBindingProviderFactory;model=org.apache.tuscany.sca.binding.rss.RSSBinding diff --git a/java/sca/contrib/modules/binding-rss-rome/src/test/java/org/apache/tuscany/sca/binding/rss/Consumer.java b/java/sca/contrib/modules/binding-rss-rome/src/test/java/org/apache/tuscany/sca/binding/rss/Consumer.java new file mode 100644 index 0000000000..489631ae3b --- /dev/null +++ b/java/sca/contrib/modules/binding-rss-rome/src/test/java/org/apache/tuscany/sca/binding/rss/Consumer.java @@ -0,0 +1,41 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.rss; + +import org.apache.tuscany.sca.node.Contribution; +import org.apache.tuscany.sca.node.ContributionLocationHelper; +import org.apache.tuscany.sca.node.Node; +import org.apache.tuscany.sca.node.NodeFactory; + +public class Consumer { + + public static void main(String[] args) throws Exception { + + String contribution = ContributionLocationHelper.getContributionLocation(Consumer.class); + Node node = NodeFactory.newInstance().createNode("org/apache/tuscany/sca/binding/feed/Consumer.composite", new Contribution("test", contribution)); + node.start(); + + CustomerClient testService = node.getService(CustomerClient.class, "CustomerClient"); + testService.testCustomerCollection(); + + node.stop(); + node.destroy(); + } +} diff --git a/java/sca/contrib/modules/binding-rss-rome/src/test/java/org/apache/tuscany/sca/binding/rss/CustomerClient.java b/java/sca/contrib/modules/binding-rss-rome/src/test/java/org/apache/tuscany/sca/binding/rss/CustomerClient.java new file mode 100644 index 0000000000..af87155f45 --- /dev/null +++ b/java/sca/contrib/modules/binding-rss-rome/src/test/java/org/apache/tuscany/sca/binding/rss/CustomerClient.java @@ -0,0 +1,25 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.rss; + +public interface CustomerClient { + + void testCustomerCollection() throws Exception; +} diff --git a/java/sca/contrib/modules/binding-rss-rome/src/test/java/org/apache/tuscany/sca/binding/rss/CustomerClientImpl.java b/java/sca/contrib/modules/binding-rss-rome/src/test/java/org/apache/tuscany/sca/binding/rss/CustomerClientImpl.java new file mode 100644 index 0000000000..a80f721136 --- /dev/null +++ b/java/sca/contrib/modules/binding-rss-rome/src/test/java/org/apache/tuscany/sca/binding/rss/CustomerClientImpl.java @@ -0,0 +1,45 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.rss; + +import org.apache.tuscany.sca.binding.rss.collection.Collection; +import org.oasisopen.sca.annotation.Reference; + +import com.sun.syndication.feed.synd.SyndEntry; +import com.sun.syndication.feed.synd.SyndFeed; + + +public class CustomerClientImpl implements CustomerClient { + + @Reference + public Collection resourceCollection; + + public void testCustomerCollection() throws Exception { + + System.out.println(">>> get collection"); + SyndFeed feed = resourceCollection.getFeed(); + System.out.println("<<< get collection"); + for (Object o : feed.getEntries()) { + SyndEntry e = (SyndEntry)o; + System.out.println("id = " + e.getUri() + " entry = " + e.getTitle()); + } + } + +} diff --git a/java/sca/contrib/modules/binding-rss-rome/src/test/java/org/apache/tuscany/sca/binding/rss/CustomerCollectionImpl.java b/java/sca/contrib/modules/binding-rss-rome/src/test/java/org/apache/tuscany/sca/binding/rss/CustomerCollectionImpl.java new file mode 100644 index 0000000000..505a9cdee3 --- /dev/null +++ b/java/sca/contrib/modules/binding-rss-rome/src/test/java/org/apache/tuscany/sca/binding/rss/CustomerCollectionImpl.java @@ -0,0 +1,103 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.rss; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import org.apache.tuscany.sca.binding.rss.collection.Collection; +import org.oasisopen.sca.annotation.Scope; + +import com.sun.syndication.feed.atom.Content; +import com.sun.syndication.feed.synd.SyndContent; +import com.sun.syndication.feed.synd.SyndContentImpl; +import com.sun.syndication.feed.synd.SyndEntry; +import com.sun.syndication.feed.synd.SyndEntryImpl; +import com.sun.syndication.feed.synd.SyndFeed; +import com.sun.syndication.feed.synd.SyndFeedImpl; +import com.sun.syndication.feed.synd.SyndLink; +import com.sun.syndication.feed.synd.SyndLinkImpl; + +@Scope("COMPOSITE") +public class CustomerCollectionImpl implements Collection { + + private Map entries = new HashMap(); + + public CustomerCollectionImpl() { + + for (int i = 0; i < 4; i++) { + String id = "urn:uuid:customer-" + UUID.randomUUID().toString(); + + SyndEntry entry = new SyndEntryImpl(); + entry.setTitle("customer " + "Jane Doe_" + String.valueOf(i)); + entry.setUri(id); + + SyndContent content = new SyndContentImpl(); + content.setValue("Jane Doe_" + String.valueOf(i)); + content.setType(Content.TEXT); + entry.setContents(Collections.singletonList(content)); + + List links = new ArrayList(); + SyndLink link = new SyndLinkImpl(); + link.setRel("edit"); + link.setHref("" + id); + links.add(link); + entry.setLinks(links); + + links = new ArrayList(); + link = new SyndLinkImpl(); + link.setRel("alternate"); + link.setHref("" + id); + links.add(link); + entry.setLinks(links); + + entry.setPublishedDate(new Date()); + + entries.put(id, entry); + System.out.println(">>> id=" + id); + } + } + + public SyndFeed getFeed() { + System.out.println(">>> CustomerCollectionImpl.getFeed"); + + SyndFeed feed = new SyndFeedImpl(); + feed.setTitle("customers"); + feed.setDescription("This is a sample feed"); + feed.getEntries().addAll(entries.values()); + return feed; + } + + public SyndFeed query(String queryString) { + System.out.println(">>> CustomerCollectionImpl.query"); + + SyndFeed feed = new SyndFeedImpl(); + feed.setTitle("customers"); + feed.setDescription("This is a sample feed"); + feed.getEntries().addAll(entries.values()); + return feed; + } + +} diff --git a/java/sca/contrib/modules/binding-rss-rome/src/test/java/org/apache/tuscany/sca/binding/rss/Provider.java b/java/sca/contrib/modules/binding-rss-rome/src/test/java/org/apache/tuscany/sca/binding/rss/Provider.java new file mode 100644 index 0000000000..42d64ef957 --- /dev/null +++ b/java/sca/contrib/modules/binding-rss-rome/src/test/java/org/apache/tuscany/sca/binding/rss/Provider.java @@ -0,0 +1,47 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.rss; + +import java.io.IOException; + +import org.apache.tuscany.sca.node.Contribution; +import org.apache.tuscany.sca.node.ContributionLocationHelper; +import org.apache.tuscany.sca.node.Node; +import org.apache.tuscany.sca.node.NodeFactory; + +public class Provider { + + public static void main(String[] args) { + + String contribution = ContributionLocationHelper.getContributionLocation(Consumer.class); + Node node = NodeFactory.newInstance().createNode("org/apache/tuscany/sca/binding/feed/Provider.composite", new Contribution("test", contribution)); + node.start(); + System.out.println("Provider.composite ready..."); + + try { + System.in.read(); + } catch (IOException e) { + e.printStackTrace(); + } + + node.stop(); + node.destroy(); + } +} diff --git a/java/sca/contrib/modules/binding-rss-rome/src/test/resources/org/apache/tuscany/sca/binding/feed/Consumer.composite b/java/sca/contrib/modules/binding-rss-rome/src/test/resources/org/apache/tuscany/sca/binding/feed/Consumer.composite new file mode 100644 index 0000000000..43cd5e00b9 --- /dev/null +++ b/java/sca/contrib/modules/binding-rss-rome/src/test/resources/org/apache/tuscany/sca/binding/feed/Consumer.composite @@ -0,0 +1,32 @@ + + + + + + + + + + + + diff --git a/java/sca/contrib/modules/binding-rss-rome/src/test/resources/org/apache/tuscany/sca/binding/feed/Provider.composite b/java/sca/contrib/modules/binding-rss-rome/src/test/resources/org/apache/tuscany/sca/binding/feed/Provider.composite new file mode 100644 index 0000000000..5ffcb50eb8 --- /dev/null +++ b/java/sca/contrib/modules/binding-rss-rome/src/test/resources/org/apache/tuscany/sca/binding/feed/Provider.composite @@ -0,0 +1,33 @@ + + + + + + + + + + + + + diff --git a/java/sca/contrib/modules/binding-rss/LICENSE b/java/sca/contrib/modules/binding-rss/LICENSE new file mode 100644 index 0000000000..6e529a25c4 --- /dev/null +++ b/java/sca/contrib/modules/binding-rss/LICENSE @@ -0,0 +1,205 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + + diff --git a/java/sca/contrib/modules/binding-rss/META-INF/MANIFEST.MF b/java/sca/contrib/modules/binding-rss/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..51294d796d --- /dev/null +++ b/java/sca/contrib/modules/binding-rss/META-INF/MANIFEST.MF @@ -0,0 +1,19 @@ +Manifest-Version: 1.0 +Export-Package: org.apache.tuscany.sca.binding.rss;uses:="org.apache.t + uscany.sca.assembly";version="2.0.0" +Private-Package: org.apache.tuscany.sca.binding.rss.impl;version="2.0.0" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA RSS Feed Binding Extension +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397326765 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA RSS Feed Binding Extension +Import-Package: org.apache.tuscany.sca.assembly;version="2.0.0",org.apac + he.tuscany.sca.binding.rss;version="2.0.0",org.apache.tuscany.sca.polic + y;version="2.0.0" +Bundle-SymbolicName: org.apache.tuscany.sca.binding.rss +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/binding-rss/NOTICE b/java/sca/contrib/modules/binding-rss/NOTICE new file mode 100644 index 0000000000..51042eab05 --- /dev/null +++ b/java/sca/contrib/modules/binding-rss/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/binding-rss/pom.xml b/java/sca/contrib/modules/binding-rss/pom.xml new file mode 100644 index 0000000000..0b1bf698ec --- /dev/null +++ b/java/sca/contrib/modules/binding-rss/pom.xml @@ -0,0 +1,79 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + + tuscany-binding-rss + Apache Tuscany SCA RSS Feed Binding Extension + + + + org.apache.tuscany.sca + tuscany-assembly + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-interface-java + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-data-api + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-core-spi + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-implementation-java-runtime + 2.0-SNAPSHOT + test + + + + org.apache.tuscany.sca + tuscany-node-impl + 2.0-SNAPSHOT + test + + + + junit + junit + 4.5 + test + + + + diff --git a/java/sca/contrib/modules/binding-rss/src/main/java/org/apache/tuscany/sca/binding/rss/RSSBinding.java b/java/sca/contrib/modules/binding-rss/src/main/java/org/apache/tuscany/sca/binding/rss/RSSBinding.java new file mode 100644 index 0000000000..2b4989264c --- /dev/null +++ b/java/sca/contrib/modules/binding-rss/src/main/java/org/apache/tuscany/sca/binding/rss/RSSBinding.java @@ -0,0 +1,28 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.rss; + +import org.apache.tuscany.sca.assembly.Binding; + +/** + * RSS Feed binding model. + */ +public interface RSSBinding extends Binding { +} diff --git a/java/sca/contrib/modules/binding-rss/src/main/java/org/apache/tuscany/sca/binding/rss/RSSBindingFactory.java b/java/sca/contrib/modules/binding-rss/src/main/java/org/apache/tuscany/sca/binding/rss/RSSBindingFactory.java new file mode 100644 index 0000000000..3e691e636e --- /dev/null +++ b/java/sca/contrib/modules/binding-rss/src/main/java/org/apache/tuscany/sca/binding/rss/RSSBindingFactory.java @@ -0,0 +1,35 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.rss; + +/** + * Factory for the RSS binding + * + * @version $Rev$ $Date$ + */ +public interface RSSBindingFactory { + + /** + * Creates a new RSS binding. + * @return the new RSS binding + */ + RSSBinding createRSSBinding(); + +} diff --git a/java/sca/contrib/modules/binding-rss/src/main/java/org/apache/tuscany/sca/binding/rss/impl/RSSBindingFactoryImpl.java b/java/sca/contrib/modules/binding-rss/src/main/java/org/apache/tuscany/sca/binding/rss/impl/RSSBindingFactoryImpl.java new file mode 100644 index 0000000000..a4e6a8283d --- /dev/null +++ b/java/sca/contrib/modules/binding-rss/src/main/java/org/apache/tuscany/sca/binding/rss/impl/RSSBindingFactoryImpl.java @@ -0,0 +1,36 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.rss.impl; + +import org.apache.tuscany.sca.binding.rss.RSSBinding; +import org.apache.tuscany.sca.binding.rss.RSSBindingFactory; + +/** + * Factory for the RSS binding model. + * + * @version $Rev$ $Date$ + */ +public class RSSBindingFactoryImpl implements RSSBindingFactory { + + public RSSBinding createRSSBinding() { + return new RSSBindingImpl(); + } + +} diff --git a/java/sca/contrib/modules/binding-rss/src/main/java/org/apache/tuscany/sca/binding/rss/impl/RSSBindingImpl.java b/java/sca/contrib/modules/binding-rss/src/main/java/org/apache/tuscany/sca/binding/rss/impl/RSSBindingImpl.java new file mode 100644 index 0000000000..6158752e7c --- /dev/null +++ b/java/sca/contrib/modules/binding-rss/src/main/java/org/apache/tuscany/sca/binding/rss/impl/RSSBindingImpl.java @@ -0,0 +1,99 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.rss.impl; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.tuscany.sca.binding.rss.RSSBinding; +import org.apache.tuscany.sca.policy.Intent; +import org.apache.tuscany.sca.policy.IntentAttachPointType; +import org.apache.tuscany.sca.policy.PolicySet; +import org.apache.tuscany.sca.policy.PolicySetAttachPoint; + +/** + * Implementation of the RSS Feed binding model. + */ +class RSSBindingImpl implements RSSBinding, PolicySetAttachPoint { + + private String name; + private String uri; + private List requiredIntents = new ArrayList(); + private List policySets = new ArrayList(); + private IntentAttachPointType intentAttachPointType; + private List applicablePolicySets = new ArrayList(); + + public List getApplicablePolicySets() { + return applicablePolicySets; + } + + public String getName() { + return name; + } + + public String getURI() { + return uri; + } + + public void setName(String name) { + this.name = name; + } + + public void setURI(String uri) { + this.uri = uri; + } + + public boolean isUnresolved() { + return false; + } + + public void setUnresolved(boolean unresolved) { + // The binding is always resolved + } + + public List getPolicySets() { + return policySets; + } + + public List getRequiredIntents() { + return requiredIntents; + } + + public IntentAttachPointType getType() { + return intentAttachPointType; + } + + public void setType(IntentAttachPointType intentAttachPointType) { + this.intentAttachPointType = intentAttachPointType; + } + + public void setPolicySets(List policySets) { + this.policySets = policySets; + } + + public void setRequiredIntents(List intents) { + this.requiredIntents = intents; + } + + @Override + public Object clone() throws CloneNotSupportedException { + return super.clone(); + } +} diff --git a/java/sca/contrib/modules/binding-rss/src/main/resources/META-INF/services/org.apache.tuscany.sca.binding.rss.RSSBindingFactory b/java/sca/contrib/modules/binding-rss/src/main/resources/META-INF/services/org.apache.tuscany.sca.binding.rss.RSSBindingFactory new file mode 100644 index 0000000000..73c47a3f41 --- /dev/null +++ b/java/sca/contrib/modules/binding-rss/src/main/resources/META-INF/services/org.apache.tuscany.sca.binding.rss.RSSBindingFactory @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for the model factory +org.apache.tuscany.sca.binding.rss.impl.RSSBindingFactoryImpl \ No newline at end of file diff --git a/java/sca/contrib/modules/binding-rss/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor b/java/sca/contrib/modules/binding-rss/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor new file mode 100644 index 0000000000..2d0597ff01 --- /dev/null +++ b/java/sca/contrib/modules/binding-rss/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for the artifact processor extension +org.apache.tuscany.sca.assembly.xml.DefaultBeanModelProcessor;qname=http://tuscany.apache.org/xmlns/sca/1.0#binding.rss,model=org.apache.tuscany.sca.binding.rss.RSSBinding,factory=org.apache.tuscany.sca.binding.rss.RSSBindingFactory diff --git a/java/sca/contrib/modules/binding-sca-axis2/LICENSE b/java/sca/contrib/modules/binding-sca-axis2/LICENSE new file mode 100644 index 0000000000..6e529a25c4 --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/LICENSE @@ -0,0 +1,205 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + + diff --git a/java/sca/contrib/modules/binding-sca-axis2/META-INF/MANIFEST.MF b/java/sca/contrib/modules/binding-sca-axis2/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..b9357df32d --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/META-INF/MANIFEST.MF @@ -0,0 +1,35 @@ +Manifest-Version: 1.0 +Private-Package: org.apache.tuscany.sca.binding.sca.axis2.impl;version + ="1.4" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA Axis2-based Default Binding Extension +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397360421 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA Axis2-based Default Binding Ext + ension +Import-Package: org.apache.axiom.om, + org.apache.tuscany.sca.assembly;version="2.0.0", + org.apache.tuscany.sca.binding.sca;version="2.0.0", + org.apache.tuscany.sca.binding.ws;version="2.0.0", + org.apache.tuscany.sca.binding.ws.axis2;version="2.0.0", + org.apache.tuscany.sca.binding.ws.wsdlgen;version="2.0.0", + org.apache.tuscany.sca.core;version="2.0.0", + org.apache.tuscany.sca.core.assembly;version="2.0.0", + org.apache.tuscany.sca.databinding;version="2.0.0", + org.apache.tuscany.sca.endpointresolver;version="2.0.0";resolution:=optional, + org.apache.tuscany.sca.host.http;version="2.0.0", + org.apache.tuscany.sca.interfacedef;version="2.0.0", + org.apache.tuscany.sca.invocation;version="2.0.0", + org.apache.tuscany.sca.monitor;version="2.0.0", + org.apache.tuscany.sca.policy.util;version="2.0.0", + org.apache.tuscany.sca.provider;version="2.0.0", + org.apache.tuscany.sca.runtime;version="2.0.0", + org.oasisopen.sca;version="2.0.0", + org.oasisopen.sca.annotation;version="2.0.0";resolution:=optional +Bundle-SymbolicName: org.apache.tuscany.sca.binding.sca.axis2 +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/binding-sca-axis2/NOTICE b/java/sca/contrib/modules/binding-sca-axis2/NOTICE new file mode 100644 index 0000000000..51042eab05 --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/binding-sca-axis2/pom.xml b/java/sca/contrib/modules/binding-sca-axis2/pom.xml new file mode 100644 index 0000000000..eb02b3abdf --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/pom.xml @@ -0,0 +1,83 @@ + + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + + tuscany-binding-sca-axis2 + Apache Tuscany SCA Axis2-based Default Binding Extension + + + + + org.apache.tuscany.sca + tuscany-binding-sca + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-binding-ws-axis2 + 2.0-SNAPSHOT + + + + javax.servlet + servlet-api + 2.5 + + + + org.apache.tuscany.sca + tuscany-host-jetty + 2.0-SNAPSHOT + test + + + + org.apache.tuscany.sca + tuscany-node-impl + 2.0-SNAPSHOT + test + + + + org.apache.tuscany.sca + tuscany-implementation-java-runtime + 2.0-SNAPSHOT + test + + + + org.apache.tuscany.sca + tuscany-endpoint + 2.0-SNAPSHOT + test + + + + + diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/main/java/org/apache/tuscany/sca/binding/sca/axis2/impl/Axis2SCABindingInvoker.java b/java/sca/contrib/modules/binding-sca-axis2/src/main/java/org/apache/tuscany/sca/binding/sca/axis2/impl/Axis2SCABindingInvoker.java new file mode 100644 index 0000000000..88a4b63637 --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/main/java/org/apache/tuscany/sca/binding/sca/axis2/impl/Axis2SCABindingInvoker.java @@ -0,0 +1,100 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.sca.axis2.impl; + +import java.util.logging.Logger; + +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.runtime.EndpointReference; +import org.oasisopen.sca.ServiceUnavailableException; + + +/** + * A wrapper for the Axis2BindingInvoker that ensures that the URL of the target + * service is correct by looking it up in the service registry if it is not provided + * + * @version $Rev: 563772 $ $Date: 2007-08-08 07:50:49 +0100 (Wed, 08 Aug 2007) $ + */ +public class Axis2SCABindingInvoker implements Interceptor { + + private static final Logger logger = Logger.getLogger(Axis2SCABindingInvoker.class.getName()); + + private Invoker axis2Invoker; + private Axis2SCAReferenceBindingProvider provider; + + public Axis2SCABindingInvoker(Axis2SCAReferenceBindingProvider provider, Invoker axis2Invoker) { + this.axis2Invoker = axis2Invoker; + this.provider = provider; + } + + public void setNext(Invoker next) { + } + + public Invoker getNext() { + return null; + } + + /** + * Fix up the URL for the message. The "to" EndPoint comes from the wire + * target and needs to be replaced with the endpoint from the registry. + * The default URL for an Endpoint URI where there is no + * target component or service information, as in the case of a + * wire crossing a node boundary, is "/" + */ + public Message invoke(Message msg) { + + // make sure that the epr of the target service is set in the TO + // field of the message + EndpointReference to = msg.getTo(); + + // check to see if we either don't have an endpoint set or if the URI + // is dynamic or the target service is marked as unresolved + if ((to == null) || (to.getURI().equals("/") || (to.getContract() == null) || (to.getContract().isUnresolved()))) { + + EndpointReference eprTo = provider.getServiceEndpoint(); + + if ( (eprTo == null) || (eprTo.getURI() == null)) { + throw new ServiceUnavailableException("Endpoint for service: " + provider.getSCABinding().getURI() + + " can't be found for component: " + + provider.getComponent().getName() + + " reference: " + + provider.getComponentReference().getName()); + } + msg.setTo(eprTo); + } + + // make sure that the epr of the callback service (if there is one) is set + // in the callbackReference field of the message. + EndpointReference callbackEPR = msg.getFrom().getReferenceParameters().getCallbackReference(); + + if ((callbackEPR == null) || (callbackEPR.getURI().equals("/"))) { + + callbackEPR = provider.getCallbackEndpoint(); + + if (callbackEPR != null) { + msg.getFrom().getReferenceParameters().setCallbackReference(callbackEPR); + } + } + + // do the axis2 stuff + return axis2Invoker.invoke(msg); + } +} diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/main/java/org/apache/tuscany/sca/binding/sca/axis2/impl/Axis2SCABindingProviderFactory.java b/java/sca/contrib/modules/binding-sca-axis2/src/main/java/org/apache/tuscany/sca/binding/sca/axis2/impl/Axis2SCABindingProviderFactory.java new file mode 100644 index 0000000000..b105696b5d --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/main/java/org/apache/tuscany/sca/binding/sca/axis2/impl/Axis2SCABindingProviderFactory.java @@ -0,0 +1,67 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.sca.axis2.impl; + +import java.util.List; + +import org.apache.tuscany.sca.binding.sca.DistributedSCABinding; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.policy.util.PolicyHandlerDefinitionsLoader; +import org.apache.tuscany.sca.policy.util.PolicyHandlerTuple; +import org.apache.tuscany.sca.provider.BindingProviderFactory; +import org.apache.tuscany.sca.provider.ReferenceBindingProvider; +import org.apache.tuscany.sca.provider.ServiceBindingProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; + +/** + * The factory for the Axis2 based implementation of the distributed sca binding + * + * @version $Rev: 563772 $ $Date: 2007-08-08 07:50:49 +0100 (Wed, 08 Aug 2007) $ + */ +public class Axis2SCABindingProviderFactory implements BindingProviderFactory { + + private ExtensionPointRegistry extensionPoints; + private List policyHandlerClassnames = null; + + public Axis2SCABindingProviderFactory(ExtensionPointRegistry extensionPoints) { + this.extensionPoints = extensionPoints; + policyHandlerClassnames = PolicyHandlerDefinitionsLoader.loadPolicyHandlerClassnames(); + } + + public ReferenceBindingProvider createReferenceBindingProvider(RuntimeComponent component, + RuntimeComponentReference reference, + DistributedSCABinding binding) { + return new Axis2SCAReferenceBindingProvider(component, reference, binding, + extensionPoints, policyHandlerClassnames); + } + + public ServiceBindingProvider createServiceBindingProvider(RuntimeComponent component, + RuntimeComponentService service, + DistributedSCABinding binding) { + return new Axis2SCAServiceBindingProvider(component, service, binding, + extensionPoints, policyHandlerClassnames); + } + + public Class getModelType() { + return DistributedSCABinding.class; + } +} diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/main/java/org/apache/tuscany/sca/binding/sca/axis2/impl/Axis2SCAReferenceBindingProvider.java b/java/sca/contrib/modules/binding-sca-axis2/src/main/java/org/apache/tuscany/sca/binding/sca/axis2/impl/Axis2SCAReferenceBindingProvider.java new file mode 100644 index 0000000000..59e0aa6494 --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/main/java/org/apache/tuscany/sca/binding/sca/axis2/impl/Axis2SCAReferenceBindingProvider.java @@ -0,0 +1,184 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.sca.axis2.impl; + +import java.net.URI; +import java.util.List; +import java.util.logging.Logger; + +import org.apache.axiom.om.OMElement; +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.assembly.SCABinding; +import org.apache.tuscany.sca.binding.sca.DistributedSCABinding; +import org.apache.tuscany.sca.binding.ws.WebServiceBinding; +import org.apache.tuscany.sca.binding.ws.WebServiceBindingFactory; +import org.apache.tuscany.sca.binding.ws.axis2.Axis2ReferenceBindingProvider; +import org.apache.tuscany.sca.binding.ws.wsdlgen.BindingWSDLGenerator; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.core.FactoryExtensionPoint; +import org.apache.tuscany.sca.core.assembly.EndpointReferenceImpl; +import org.apache.tuscany.sca.databinding.DataBindingExtensionPoint; +import org.apache.tuscany.sca.host.http.ServletHost; +import org.apache.tuscany.sca.host.http.ServletHostExtensionPoint; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.policy.util.PolicyHandlerTuple; +import org.apache.tuscany.sca.provider.ReferenceBindingProvider; +import org.apache.tuscany.sca.runtime.EndpointReference; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; + +/** + * The reference binding provider for the remote sca binding implementation. Relies on the + * binding-ws-axis implementation for sending messages to remote services to this provider + * just uses the ws-axis provider. + * + * @version $Rev: 563772 $ $Date: 2007-08-08 07:50:49 +0100 (Wed, 08 Aug 2007) $ + */ +public class Axis2SCAReferenceBindingProvider implements ReferenceBindingProvider { + + private static final Logger logger = Logger.getLogger(Axis2SCAReferenceBindingProvider.class.getName()); + + private RuntimeComponent component; + private RuntimeComponentReference reference; + private SCABinding binding; + private Axis2ReferenceBindingProvider axisReferenceBindingProvider; + private WebServiceBinding wsBinding; + + private EndpointReference serviceEPR = null; + private EndpointReference callbackEPR = null; + + public Axis2SCAReferenceBindingProvider(RuntimeComponent component, + RuntimeComponentReference reference, + DistributedSCABinding binding, + ExtensionPointRegistry extensionPoints, + List policyHandlerClassnames) { + + ServletHostExtensionPoint servletHosts = extensionPoints.getExtensionPoint(ServletHostExtensionPoint.class); + ServletHost servletHost = servletHosts.getServletHosts().get(0); + FactoryExtensionPoint modelFactories = extensionPoints.getExtensionPoint(FactoryExtensionPoint.class); + DataBindingExtensionPoint dataBindings = extensionPoints.getExtensionPoint(DataBindingExtensionPoint.class); + + this.component = component; + this.reference = reference; + this.binding = binding.getSCABinding(); + wsBinding = modelFactories.getFactory(WebServiceBindingFactory.class).createWebServiceBinding(); + wsBinding.setName(this.binding.getName()); + + // Turn the java interface contract into a WSDL interface contract + BindingWSDLGenerator.generateWSDL(component, reference, wsBinding, extensionPoints, null); + + // Set to use the Axiom data binding + InterfaceContract contract = wsBinding.getBindingInterfaceContract(); + contract.getInterface().resetDataBinding(OMElement.class.getName()); + + axisReferenceBindingProvider = new Axis2ReferenceBindingProvider(component, + reference, + wsBinding, + modelFactories, + policyHandlerClassnames, + dataBindings); + } + + public InterfaceContract getBindingInterfaceContract() { + return wsBinding.getBindingInterfaceContract(); + } + + public boolean supportsOneWayInvocation() { + return false; + } + + public Invoker createInvoker(Operation operation) { + return new Axis2SCABindingInvoker(this, axisReferenceBindingProvider.createInvoker(operation)); + } + + /** + * Uses the distributed domain service discovery feature to locate remote + * service endpoints + * + * @return An EPR for the target service that this reference refers to + */ + public EndpointReference getServiceEndpoint(){ + + if (serviceEPR == null){ + String endpointURL = null; + + if (binding.getURI() != null) { + // check if the binding URI is already resolved if it is use is if not + try { + URI uri = new URI(binding.getURI()); + if (uri.isAbsolute()) { + endpointURL = binding.getURI(); + } + } catch(Exception ex) { + // do nothing + } + } + + serviceEPR = new EndpointReferenceImpl(endpointURL); + } + + return serviceEPR; + } + + + /** + * Retrieves the URI of the callback service (that this reference has created) + * returns null if there is no callback service for the sca binding + * + * @return the callback endpoint + */ + public EndpointReference getCallbackEndpoint(){ + if (callbackEPR == null) { + if (reference.getCallbackService() != null) { + for (Binding callbackBinding : reference.getCallbackService().getBindings()) { + if (callbackBinding instanceof SCABinding) { + callbackEPR = new EndpointReferenceImpl(reference.getName() + "/" + callbackBinding.getName()); + continue; + } + } + } + } + return callbackEPR; + } + + + public SCABinding getSCABinding () { + return binding; + } + + public RuntimeComponent getComponent () { + return component; + } + + public RuntimeComponentReference getComponentReference () { + return reference; + } + + public void start() { + axisReferenceBindingProvider.start(); + } + + public void stop() { + axisReferenceBindingProvider.stop(); + } + +} diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/main/java/org/apache/tuscany/sca/binding/sca/axis2/impl/Axis2SCAServiceBindingProvider.java b/java/sca/contrib/modules/binding-sca-axis2/src/main/java/org/apache/tuscany/sca/binding/sca/axis2/impl/Axis2SCAServiceBindingProvider.java new file mode 100644 index 0000000000..f1aaa9188a --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/main/java/org/apache/tuscany/sca/binding/sca/axis2/impl/Axis2SCAServiceBindingProvider.java @@ -0,0 +1,122 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.sca.axis2.impl; + +import java.util.List; +import java.util.logging.Logger; + +import org.apache.axiom.om.OMElement; +import org.apache.tuscany.sca.assembly.SCABinding; +import org.apache.tuscany.sca.binding.sca.DistributedSCABinding; +import org.apache.tuscany.sca.binding.ws.WebServiceBinding; +import org.apache.tuscany.sca.binding.ws.WebServiceBindingFactory; +import org.apache.tuscany.sca.binding.ws.axis2.Axis2ServiceProvider; +import org.apache.tuscany.sca.binding.ws.wsdlgen.BindingWSDLGenerator; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.core.FactoryExtensionPoint; +import org.apache.tuscany.sca.databinding.DataBindingExtensionPoint; +import org.apache.tuscany.sca.host.http.ServletHost; +import org.apache.tuscany.sca.host.http.ServletHostExtensionPoint; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.invocation.MessageFactory; +import org.apache.tuscany.sca.policy.util.PolicyHandlerTuple; +import org.apache.tuscany.sca.provider.ServiceBindingProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; + +/** + * The service binding provider for the remote sca binding implementation. Relies on the + * binding-ws-axis implementation for providing a remote message endpoint for this service + * + * @version $Rev: 563772 $ $Date: 2007-08-08 07:50:49 +0100 (Wed, 08 Aug 2007) $ + */ +public class Axis2SCAServiceBindingProvider implements ServiceBindingProvider { + + private static final Logger logger = Logger.getLogger(Axis2SCAServiceBindingProvider.class.getName()); + + private SCABinding binding; + private Axis2ServiceProvider axisProvider; + private WebServiceBinding wsBinding; + + private boolean started = false; + + + public Axis2SCAServiceBindingProvider(RuntimeComponent component, + RuntimeComponentService service, + DistributedSCABinding binding, + ExtensionPointRegistry extensionPoints, + List policyHandlerClassnames) { + + ServletHostExtensionPoint servletHosts = extensionPoints.getExtensionPoint(ServletHostExtensionPoint.class); + ServletHost servletHost = servletHosts.getServletHosts().get(0); + FactoryExtensionPoint modelFactories = extensionPoints.getExtensionPoint(FactoryExtensionPoint.class); + MessageFactory messageFactory = modelFactories.getFactory(MessageFactory.class); + DataBindingExtensionPoint dataBindings = extensionPoints.getExtensionPoint(DataBindingExtensionPoint.class); + + this.binding = binding.getSCABinding(); + wsBinding = modelFactories.getFactory(WebServiceBindingFactory.class).createWebServiceBinding(); + wsBinding.setName(this.binding.getName()); + wsBinding.setURI(this.binding.getURI()); + + // Turn the java interface contract into a WSDL interface contract + BindingWSDLGenerator.generateWSDL(component, service, wsBinding, extensionPoints, null); + + // Set to use the Axiom data binding + InterfaceContract contract = wsBinding.getBindingInterfaceContract(); + contract.getInterface().resetDataBinding(OMElement.class.getName()); + + axisProvider = new Axis2SCAServiceProvider(component, + service, + this.binding, + wsBinding, + servletHost, + messageFactory, + policyHandlerClassnames); + } + + public InterfaceContract getBindingInterfaceContract() { + return wsBinding.getBindingInterfaceContract(); + } + + public boolean supportsOneWayInvocation() { + return false; + } + + public void start() { + if (started) { + return; + } else { + started = true; + } + + axisProvider.start(); + } + + public void stop() { + if (!started) { + return; + } else { + started = false; + } + + axisProvider.stop(); + } + +} diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/main/java/org/apache/tuscany/sca/binding/sca/axis2/impl/Axis2SCAServiceProvider.java b/java/sca/contrib/modules/binding-sca-axis2/src/main/java/org/apache/tuscany/sca/binding/sca/axis2/impl/Axis2SCAServiceProvider.java new file mode 100644 index 0000000000..cf13d821f7 --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/main/java/org/apache/tuscany/sca/binding/sca/axis2/impl/Axis2SCAServiceProvider.java @@ -0,0 +1,84 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.sca.axis2.impl; + +import java.util.List; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.assembly.SCABinding; +import org.apache.tuscany.sca.binding.ws.WebServiceBinding; +import org.apache.tuscany.sca.binding.ws.axis2.Axis2ServiceProvider; +import org.apache.tuscany.sca.host.http.ServletHost; +import org.apache.tuscany.sca.invocation.MessageFactory; +import org.apache.tuscany.sca.policy.util.PolicyHandlerTuple; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; + +/** + * A specialization of the Axis2BindingProvider that just switches in the SCABinding model + * element when it is required. The SCABinding is required as the service binding provider + * finds the service wire based in the binding + * + * @version $Rev: 563772 $ $Date: 2007-08-08 07:50:49 +0100 (Wed, 08 Aug 2007) $ + */ +public class Axis2SCAServiceProvider extends Axis2ServiceProvider { + + private SCABinding binding; + + /** + * Switch in the fake ws binding + * + * @param component + * @param service + * @param binding + * @param wsBinding + * @param servletHost + * @param messageFactory + */ + public Axis2SCAServiceProvider(RuntimeComponent component, + RuntimeComponentService service, + SCABinding binding, + WebServiceBinding wsBinding, + ServletHost servletHost, + MessageFactory messageFactory, + List policyHandlerClassnames) { + + super(component, + service, + wsBinding, + servletHost, + messageFactory, + policyHandlerClassnames); + + this.binding = binding; + } + + /** + * Return the sca binding as wires will be registered against this rather + * than against the wsBinding that the Axis2SCAServiceProvider is + * expecting + * + * @return the binding + */ + @Override + protected Binding getBinding(){ + return binding; + } +} diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.BindingProviderFactory b/java/sca/contrib/modules/binding-sca-axis2/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.BindingProviderFactory new file mode 100644 index 0000000000..1b369cde06 --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.BindingProviderFactory @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for the binding extension +org.apache.tuscany.sca.binding.sca.axis2.impl.Axis2SCABindingProviderFactory;model=org.apache.tuscany.sca.binding.sca.DistributedSCABinding diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/AsynchTestCase.java b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/AsynchTestCase.java new file mode 100644 index 0000000000..0ae3c68f99 --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/AsynchTestCase.java @@ -0,0 +1,80 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.sca.axis2; + + +import junit.framework.Assert; + +import org.apache.tuscany.sca.binding.sca.axis2.helloworld.HelloWorldClient; +import org.apache.tuscany.sca.binding.sca.axis2.helloworld.impl.HelloWorldClientCallbackOnewayRemoteImpl; +import org.apache.tuscany.sca.node.Contribution; +import org.apache.tuscany.sca.node.Node; +import org.apache.tuscany.sca.node.NodeFactory; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +public class AsynchTestCase { + + public static Node nodeG; + public static Node nodeH; + + @BeforeClass + public static void init() throws Exception { + System.out.println("Setting up nodes"); + + try { + // create and start domains + NodeFactory nodeFactory = NodeFactory.newInstance(); + ClassLoader cl = AsynchTestCase.class.getClassLoader(); + nodeG = nodeFactory.createNode("HelloWorld.composite", new Contribution("http://calculator", cl.getResource("nodeG").toString())); + nodeH = nodeFactory.createNode("HelloWorld.composite", new Contribution("http://calculator", cl.getResource("nodeH").toString())); + + nodeG.start(); + nodeH.start(); + + } catch (Exception ex) { + System.err.println("Exception when creating domain " + ex.getMessage()); + ex.printStackTrace(System.err); + throw ex; + } + } + + @AfterClass + public static void destroy() throws Exception { + nodeG.stop(); + nodeG.destroy(); + nodeH.stop(); + nodeG.destroy(); + } + + @Test + public void testHelloWorldAsynch() throws Exception { + HelloWorldClient helloWorldClientB; + helloWorldClientB = nodeG.getService(HelloWorldClient.class, "AHelloWorldClientCallbackRemote"); + helloWorldClientB.getGreetings("fred"); + System.out.println("Sleeping ..."); + Thread.sleep(2000); + System.out.println("... Done"); + Assert.assertEquals("callback fred", HelloWorldClientCallbackOnewayRemoteImpl.result ); + + } + + +} diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/BindingScaEndpointResolverFactoryImpl.java b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/BindingScaEndpointResolverFactoryImpl.java new file mode 100644 index 0000000000..b345e563e3 --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/BindingScaEndpointResolverFactoryImpl.java @@ -0,0 +1,50 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.sca.axis2; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.assembly.Endpoint; +import org.apache.tuscany.sca.assembly.SCABinding; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.endpointresolver.EndpointResolver; +import org.apache.tuscany.sca.endpointresolver.EndpointResolverFactory; + +/** + * The factory for creating endpoint Binding providers + * + * @version $Rev$ $Date$ + */ +public class BindingScaEndpointResolverFactoryImpl implements EndpointResolverFactory { + + private ExtensionPointRegistry extensionPoints; + + public BindingScaEndpointResolverFactoryImpl(ExtensionPointRegistry extensionPoints) { + this.extensionPoints = extensionPoints; + } + + public EndpointResolver createEndpointResolver(Endpoint endpoint, Binding binding) { + + return new BindingScaEndpointResolverImpl(extensionPoints, endpoint, binding); + } + + public Class getModelType() { + return SCABinding.class; + } +} diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/BindingScaEndpointResolverImpl.java b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/BindingScaEndpointResolverImpl.java new file mode 100644 index 0000000000..472e85116e --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/BindingScaEndpointResolverImpl.java @@ -0,0 +1,69 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.sca.axis2; + + +import java.util.logging.Logger; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.assembly.Endpoint; +import org.apache.tuscany.sca.assembly.SCABinding; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.endpointresolver.EndpointResolver; + +/** + * The endpoint resolver allows unresolved endpoints to be plumbed into + * the runtime start and message send processing as a hook to late resolution + * of target services + * + * @version $Rev$ $Date$ + */ +public class BindingScaEndpointResolverImpl implements EndpointResolver { + + private final static Logger logger = Logger.getLogger(BindingScaEndpointResolverImpl.class.getName()); + + private Endpoint endpoint; + private SCABinding binding; + + public BindingScaEndpointResolverImpl(ExtensionPointRegistry extensionPoints, + Endpoint endpoint, + Binding binding) { + this.endpoint = endpoint; + this.binding = (SCABinding)binding; + } + + public void start(){ + // do nothing + } + + public void resolve() { + if (endpoint.isUnresolved()){ + // pretend to resolve the endpoint. In this test case to what we know + // it should be + logger.info("Fixing up endpoint soure binding"); + endpoint.setSourceBinding(endpoint.getCandidateBindings().get(0)); + endpoint.getSourceBinding().setURI("http://localhost:8085/BHelloWorldServiceRemote"); + } + } + + public void stop(){ + // do nothing + } +} diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/CallbackTestCase.java b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/CallbackTestCase.java new file mode 100644 index 0000000000..5a68b6c3d9 --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/CallbackTestCase.java @@ -0,0 +1,84 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.sca.axis2; + +import junit.framework.Assert; + +import org.apache.tuscany.sca.binding.sca.axis2.helloworld.HelloWorldClient; +import org.apache.tuscany.sca.node.Contribution; +import org.apache.tuscany.sca.node.Node; +import org.apache.tuscany.sca.node.NodeFactory; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +public class CallbackTestCase { + + public static Node nodeE; + public static Node nodeF; + + @BeforeClass + public static void init() throws Exception { + System.out.println("Setting up nodes"); + + try { + // create and start domains + NodeFactory nodeFactory = NodeFactory.newInstance(); + ClassLoader cl = AsynchTestCase.class.getClassLoader(); + nodeE = nodeFactory.createNode("HelloWorld.composite", new Contribution("http://calculator", cl.getResource("nodeE").toString())); + nodeF = nodeFactory.createNode("HelloWorld.composite", new Contribution("http://calculator", cl.getResource("nodeF").toString())); + + nodeE.start(); + nodeF.start(); + + } catch (Exception ex) { + System.err.println("Exception when creating domain " + ex.getMessage()); + ex.printStackTrace(System.err); + throw ex; + } + } + + @AfterClass + public static void destroy() throws Exception { + nodeE.stop(); + nodeE.destroy(); + nodeF.stop(); + nodeF.destroy(); + } + + //@Test + public void testKeepServerRunning() throws Exception { + System.out.println("press enter to continue"); + System.in.read(); + } + + @Test + public void testHelloWorldCallbackLocal() throws Exception { + HelloWorldClient helloWorldClientB; + helloWorldClientB = nodeF.getService(HelloWorldClient.class, "BHelloWorldClientCallbackLocal"); + Assert.assertEquals("Hello callback fred", helloWorldClientB.getGreetings("fred")); + } + + @Test + public void testHelloWorldCallbackRemote() throws Exception { + HelloWorldClient helloWorldClientA; + helloWorldClientA = nodeE.getService(HelloWorldClient.class, "AHelloWorldClientCallbackRemote"); + Assert.assertEquals("Hello callback fred", helloWorldClientA.getGreetings("fred")); + } +} diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/PromotionTestCase.java b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/PromotionTestCase.java new file mode 100644 index 0000000000..3f48f1d465 --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/PromotionTestCase.java @@ -0,0 +1,73 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.sca.axis2; + +import junit.framework.Assert; + +import org.apache.tuscany.sca.binding.sca.axis2.helloworld.HelloWorldClient; +import org.apache.tuscany.sca.node.Contribution; +import org.apache.tuscany.sca.node.Node; +import org.apache.tuscany.sca.node.NodeFactory; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +public class PromotionTestCase { + + public static Node nodeC; + public static Node nodeD; + + @BeforeClass + public static void init() throws Exception { + System.out.println("Setting up nodes"); + + try { + // create and start domains + NodeFactory nodeFactory = NodeFactory.newInstance(); + ClassLoader cl = AsynchTestCase.class.getClassLoader(); + nodeC = nodeFactory.createNode("HelloWorld.composite", new Contribution("http://calculator", cl.getResource("nodeC").toString())); + nodeD = nodeFactory.createNode("HelloWorld.composite", new Contribution("http://calculator", cl.getResource("nodeD").toString())); + + nodeC.start(); + nodeD.start(); + + } catch (Exception ex) { + System.err.println("Exception when creating domain " + ex.getMessage()); + ex.printStackTrace(System.err); + throw ex; + } + } + + @AfterClass + public static void destroy() throws Exception { + nodeC.stop(); + nodeC.destroy(); + nodeD.stop(); + nodeD.destroy(); + } + + @Test + public void testHelloWorldPromotion() throws Exception { + HelloWorldClient helloWorldClientA; + helloWorldClientA = nodeC.getService(HelloWorldClient.class, "AHelloWorldClientRemotePromotion"); + Assert.assertEquals(helloWorldClientA.getGreetings("fred"), "Hello fred"); + + } + +} diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/SimpleTestCase.java b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/SimpleTestCase.java new file mode 100644 index 0000000000..7196118775 --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/SimpleTestCase.java @@ -0,0 +1,112 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.binding.sca.axis2; + +import junit.framework.Assert; + +import org.apache.tuscany.sca.binding.sca.axis2.helloworld.HelloWorldClient; +import org.apache.tuscany.sca.node.Contribution; +import org.apache.tuscany.sca.node.Node; +import org.apache.tuscany.sca.node.NodeFactory; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.oasisopen.sca.ServiceUnavailableException; + +public class SimpleTestCase { + + public static Node nodeA; + public static Node nodeB; + + @BeforeClass + public static void init() throws Exception { + System.out.println("Setting up nodes"); + + try { + // create and start domains + NodeFactory nodeFactory = NodeFactory.newInstance(); + ClassLoader cl = AsynchTestCase.class.getClassLoader(); + nodeA = nodeFactory.createNode("HelloWorld.composite", new Contribution("http://calculator", cl.getResource("nodeA").toString())); + nodeB = nodeFactory.createNode("HelloWorld.composite", new Contribution("http://calculator", cl.getResource("nodeB").toString())); + + nodeA.start(); + nodeB.start(); + + } catch (Exception ex) { + System.err.println("Exception when creating domain " + ex.getMessage()); + ex.printStackTrace(System.err); + throw ex; + } + } + + @AfterClass + public static void destroy() throws Exception { + nodeA.stop(); + nodeA.destroy(); + nodeB.stop(); + nodeB.destroy(); + } + + @Test + public void testHelloWorldLocal() throws Exception { + HelloWorldClient helloWorldClientA = nodeA.getService(HelloWorldClient.class, "AHelloWorldClientLocal"); + Assert.assertEquals(helloWorldClientA.getGreetings("fred"), "Hello fred"); + + } + + @Test + public void testHelloWorldRemote() throws Exception { + + HelloWorldClient helloWorldClientA; + helloWorldClientA = nodeA.getService(HelloWorldClient.class, "AHelloWorldClientRemote"); + + try { + helloWorldClientA.getGreetings("fred"); + } catch (ServiceUnavailableException ex){ + Assert.fail(); + } + } + + @Test + public void testHelloWorldLocalAndRemote() throws Exception { + HelloWorldClient helloWorldClientA = nodeA.getService(HelloWorldClient.class, "AHelloWorldClientLocalAndRemote"); + HelloWorldClient helloWorldClientB = nodeB.getService(HelloWorldClient.class, "BHelloWorldClientLocalAndRemote"); + Assert.assertEquals(helloWorldClientA.getGreetings("fred"), "Hello fred"); + Assert.assertEquals(helloWorldClientB.getGreetings("fred"), "Hello fred"); + } + + @Test + public void testHelloWorldMultipleServices() throws Exception { + HelloWorldClient helloWorldClientA = nodeA.getService(HelloWorldClient.class, "AHelloWorldClientMultipleServices"); + HelloWorldClient helloWorldClientA2 = nodeA.getService(HelloWorldClient.class, "AHelloWorldClientMultipleServices2"); + HelloWorldClient helloWorldClientB = nodeB.getService(HelloWorldClient.class, "BHelloWorldClientMultipleServices"); + Assert.assertEquals(helloWorldClientA.getGreetings("fred"), "Hello fred"); + Assert.assertEquals(helloWorldClientA2.getGreetings("fred"), "Hello fred"); + Assert.assertEquals(helloWorldClientB.getGreetings("fred"), "Hello fred"); + } + + @Test + public void testHelloWorldMultipleBindings() throws Exception { + HelloWorldClient helloWorldClientA; + helloWorldClientA = nodeA.getService(HelloWorldClient.class, "AHelloWorldClientMultipleBindings"); + Assert.assertEquals(helloWorldClientA.getGreetings("fred"), "Hello fred"); + + } + +} diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/HelloWorldCallbackRemote.java b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/HelloWorldCallbackRemote.java new file mode 100644 index 0000000000..0de092052f --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/HelloWorldCallbackRemote.java @@ -0,0 +1,29 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.sca.axis2.helloworld; + +import org.oasisopen.sca.annotation.Remotable; + +@Remotable +public interface HelloWorldCallbackRemote { + + String getGreetingsCallbackRemote(String s); + +} diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/HelloWorldClient.java b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/HelloWorldClient.java new file mode 100644 index 0000000000..e4d36ac78b --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/HelloWorldClient.java @@ -0,0 +1,27 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.sca.axis2.helloworld; + + +public interface HelloWorldClient { + + String getGreetings(String s); + +} diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/HelloWorldServiceCallbackOnewayRemote.java b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/HelloWorldServiceCallbackOnewayRemote.java new file mode 100644 index 0000000000..5b2f73f9e2 --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/HelloWorldServiceCallbackOnewayRemote.java @@ -0,0 +1,33 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.sca.axis2.helloworld; + +import org.oasisopen.sca.annotation.Callback; +import org.oasisopen.sca.annotation.OneWay; +import org.oasisopen.sca.annotation.Remotable; + +@Remotable +@Callback(HelloWorldCallbackRemote.class) +public interface HelloWorldServiceCallbackOnewayRemote { + + @OneWay + void getGreetingsRemote(String s); + +} diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/HelloWorldServiceCallbackRemote.java b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/HelloWorldServiceCallbackRemote.java new file mode 100644 index 0000000000..f4c4354a39 --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/HelloWorldServiceCallbackRemote.java @@ -0,0 +1,31 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.sca.axis2.helloworld; + +import org.oasisopen.sca.annotation.Callback; +import org.oasisopen.sca.annotation.Remotable; + +@Remotable +@Callback(HelloWorldCallbackRemote.class) +public interface HelloWorldServiceCallbackRemote { + + String getGreetingsRemote(String s); + +} diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/HelloWorldServiceLocal.java b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/HelloWorldServiceLocal.java new file mode 100644 index 0000000000..7b8e00eb2a --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/HelloWorldServiceLocal.java @@ -0,0 +1,27 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.sca.axis2.helloworld; + + +public interface HelloWorldServiceLocal { + + String getGreetingsLocal(String s); + +} diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/HelloWorldServiceRemote.java b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/HelloWorldServiceRemote.java new file mode 100644 index 0000000000..2cec5893a9 --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/HelloWorldServiceRemote.java @@ -0,0 +1,29 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.sca.axis2.helloworld; + +import org.oasisopen.sca.annotation.Remotable; + +@Remotable +public interface HelloWorldServiceRemote { + + String getGreetingsRemote(String s); + +} diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/HelloWorldServiceRemote2.java b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/HelloWorldServiceRemote2.java new file mode 100644 index 0000000000..f4029e0ad5 --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/HelloWorldServiceRemote2.java @@ -0,0 +1,29 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.sca.axis2.helloworld; + +import org.oasisopen.sca.annotation.Remotable; + +@Remotable +public interface HelloWorldServiceRemote2 { + + String getGreetingsRemote2(String s); + +} diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/impl/HelloWorldClientCallbackOnewayRemoteImpl.java b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/impl/HelloWorldClientCallbackOnewayRemoteImpl.java new file mode 100644 index 0000000000..00fe836512 --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/impl/HelloWorldClientCallbackOnewayRemoteImpl.java @@ -0,0 +1,43 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.sca.axis2.helloworld.impl; + +import org.apache.tuscany.sca.binding.sca.axis2.helloworld.HelloWorldClient; +import org.apache.tuscany.sca.binding.sca.axis2.helloworld.HelloWorldServiceCallbackOnewayRemote; +import org.oasisopen.sca.annotation.Reference; + +public class HelloWorldClientCallbackOnewayRemoteImpl implements HelloWorldClient { + + public static String result; + + @Reference + public HelloWorldServiceCallbackOnewayRemote helloWorldService; + + public String getGreetings(String s) { + helloWorldService.getGreetingsRemote(s); + return null; + } + + public String getGreetingsCallbackRemote(String s) { + result = "callback " + s; + return result; + } + +} diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/impl/HelloWorldClientCallbackRemoteImpl.java b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/impl/HelloWorldClientCallbackRemoteImpl.java new file mode 100644 index 0000000000..df9a09c5fb --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/impl/HelloWorldClientCallbackRemoteImpl.java @@ -0,0 +1,42 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.sca.axis2.helloworld.impl; + +import org.apache.tuscany.sca.binding.sca.axis2.helloworld.HelloWorldClient; +import org.apache.tuscany.sca.binding.sca.axis2.helloworld.HelloWorldServiceCallbackRemote; +import org.oasisopen.sca.annotation.Reference; + +public class HelloWorldClientCallbackRemoteImpl implements HelloWorldClient { + + public static String result; + + @Reference + public HelloWorldServiceCallbackRemote helloWorldService; + + public String getGreetings(String s) { + return helloWorldService.getGreetingsRemote(s); + } + + public String getGreetingsCallbackRemote(String s) { + result = "callback " + s; + return result; + } + +} diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/impl/HelloWorldClientLocalImpl.java b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/impl/HelloWorldClientLocalImpl.java new file mode 100644 index 0000000000..dcefef52e7 --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/impl/HelloWorldClientLocalImpl.java @@ -0,0 +1,35 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.sca.axis2.helloworld.impl; + +import org.apache.tuscany.sca.binding.sca.axis2.helloworld.HelloWorldClient; +import org.apache.tuscany.sca.binding.sca.axis2.helloworld.HelloWorldServiceLocal; +import org.oasisopen.sca.annotation.Reference; + +public class HelloWorldClientLocalImpl implements HelloWorldClient { + + @Reference + public HelloWorldServiceLocal helloWorldService; + + public String getGreetings(String s) { + return helloWorldService.getGreetingsLocal(s); + } + +} diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/impl/HelloWorldClientRemote2Impl.java b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/impl/HelloWorldClientRemote2Impl.java new file mode 100644 index 0000000000..628434108e --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/impl/HelloWorldClientRemote2Impl.java @@ -0,0 +1,35 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.sca.axis2.helloworld.impl; + +import org.apache.tuscany.sca.binding.sca.axis2.helloworld.HelloWorldClient; +import org.apache.tuscany.sca.binding.sca.axis2.helloworld.HelloWorldServiceRemote2; +import org.oasisopen.sca.annotation.Reference; + +public class HelloWorldClientRemote2Impl implements HelloWorldClient { + + @Reference + public HelloWorldServiceRemote2 helloWorldService; + + public String getGreetings(String s) { + return helloWorldService.getGreetingsRemote2(s); + } + +} diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/impl/HelloWorldClientRemoteImpl.java b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/impl/HelloWorldClientRemoteImpl.java new file mode 100644 index 0000000000..0dbb58272c --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/impl/HelloWorldClientRemoteImpl.java @@ -0,0 +1,35 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.sca.axis2.helloworld.impl; + +import org.apache.tuscany.sca.binding.sca.axis2.helloworld.HelloWorldClient; +import org.apache.tuscany.sca.binding.sca.axis2.helloworld.HelloWorldServiceRemote; +import org.oasisopen.sca.annotation.Reference; + +public class HelloWorldClientRemoteImpl implements HelloWorldClient { + + @Reference + public HelloWorldServiceRemote helloWorldService; + + public String getGreetings(String s) { + return helloWorldService.getGreetingsRemote(s); + } + +} diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/impl/HelloWorldServiceCallbackOnewayRemoteImpl.java b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/impl/HelloWorldServiceCallbackOnewayRemoteImpl.java new file mode 100644 index 0000000000..2d2fe0146d --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/impl/HelloWorldServiceCallbackOnewayRemoteImpl.java @@ -0,0 +1,36 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.sca.axis2.helloworld.impl; + +import org.apache.tuscany.sca.binding.sca.axis2.helloworld.HelloWorldCallbackRemote; +import org.apache.tuscany.sca.binding.sca.axis2.helloworld.HelloWorldServiceCallbackOnewayRemote; +import org.oasisopen.sca.annotation.Callback; + + +public class HelloWorldServiceCallbackOnewayRemoteImpl implements HelloWorldServiceCallbackOnewayRemote { + + @Callback + protected HelloWorldCallbackRemote theCallback; + + public void getGreetingsRemote(String s) { + theCallback.getGreetingsCallbackRemote(s); + } + +} diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/impl/HelloWorldServiceCallbackRemoteImpl.java b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/impl/HelloWorldServiceCallbackRemoteImpl.java new file mode 100644 index 0000000000..219525e62d --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/impl/HelloWorldServiceCallbackRemoteImpl.java @@ -0,0 +1,35 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.sca.axis2.helloworld.impl; + +import org.apache.tuscany.sca.binding.sca.axis2.helloworld.HelloWorldCallbackRemote; +import org.apache.tuscany.sca.binding.sca.axis2.helloworld.HelloWorldServiceCallbackRemote; +import org.oasisopen.sca.annotation.Callback; + +public class HelloWorldServiceCallbackRemoteImpl implements HelloWorldServiceCallbackRemote { + + @Callback + protected HelloWorldCallbackRemote theCallback; + + public String getGreetingsRemote(String s) { + return "Hello " + theCallback.getGreetingsCallbackRemote(s); + } + +} diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/impl/HelloWorldServiceLocalImpl.java b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/impl/HelloWorldServiceLocalImpl.java new file mode 100644 index 0000000000..20dd97b74a --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/impl/HelloWorldServiceLocalImpl.java @@ -0,0 +1,30 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.sca.axis2.helloworld.impl; + +import org.apache.tuscany.sca.binding.sca.axis2.helloworld.HelloWorldServiceLocal; + +public class HelloWorldServiceLocalImpl implements HelloWorldServiceLocal { + + public String getGreetingsLocal(String s) { + return "Hello " + s; + } + +} diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/impl/HelloWorldServiceMultipleServicesImpl.java b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/impl/HelloWorldServiceMultipleServicesImpl.java new file mode 100644 index 0000000000..b34d809958 --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/impl/HelloWorldServiceMultipleServicesImpl.java @@ -0,0 +1,41 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.sca.axis2.helloworld.impl; + +import org.apache.tuscany.sca.binding.sca.axis2.helloworld.HelloWorldServiceLocal; +import org.apache.tuscany.sca.binding.sca.axis2.helloworld.HelloWorldServiceRemote; +import org.apache.tuscany.sca.binding.sca.axis2.helloworld.HelloWorldServiceRemote2; +import org.oasisopen.sca.annotation.Service; + +@Service(interfaces={HelloWorldServiceRemote.class, HelloWorldServiceRemote2.class, HelloWorldServiceLocal.class} ) +public class HelloWorldServiceMultipleServicesImpl implements HelloWorldServiceLocal, HelloWorldServiceRemote, HelloWorldServiceRemote2 { + + public String getGreetingsLocal(String s) { + return "Hello " + s; + } + + public String getGreetingsRemote(String s) { + return "Hello " + s; + } + + public String getGreetingsRemote2(String s) { + return "Hello " + s; + } +} diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/impl/HelloWorldServiceRemoteImpl.java b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/impl/HelloWorldServiceRemoteImpl.java new file mode 100644 index 0000000000..b25aebd9df --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/test/java/org/apache/tuscany/sca/binding/sca/axis2/helloworld/impl/HelloWorldServiceRemoteImpl.java @@ -0,0 +1,30 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.sca.axis2.helloworld.impl; + +import org.apache.tuscany.sca.binding.sca.axis2.helloworld.HelloWorldServiceRemote; + +public class HelloWorldServiceRemoteImpl implements HelloWorldServiceRemote { + + public String getGreetingsRemote(String s) { + return "Hello " + s; + } + +} diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/META-INF/services/org.apache.tuscany.sca.endpointresolver.EndpointResolverFactory b/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/META-INF/services/org.apache.tuscany.sca.endpointresolver.EndpointResolverFactory new file mode 100644 index 0000000000..5e4fd566c3 --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/META-INF/services/org.apache.tuscany.sca.endpointresolver.EndpointResolverFactory @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for the binding extension +org.apache.tuscany.sca.binding.sca.axis2.BindingScaEndpointResolverFactoryImpl;model=org.apache.tuscany.sca.assembly.SCABinding diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeA/HelloWorld.composite b/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeA/HelloWorld.composite new file mode 100644 index 0000000000..093258051e --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeA/HelloWorld.composite @@ -0,0 +1,75 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeA/META-INF/sca-contribution.xml b/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeA/META-INF/sca-contribution.xml new file mode 100644 index 0000000000..d6b9e82250 --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeA/META-INF/sca-contribution.xml @@ -0,0 +1,24 @@ + + + + + \ No newline at end of file diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeB/HelloWorld.composite b/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeB/HelloWorld.composite new file mode 100644 index 0000000000..8cf7230ed5 --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeB/HelloWorld.composite @@ -0,0 +1,84 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeB/META-INF/sca-contribution.xml b/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeB/META-INF/sca-contribution.xml new file mode 100644 index 0000000000..d6b9e82250 --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeB/META-INF/sca-contribution.xml @@ -0,0 +1,24 @@ + + + + + \ No newline at end of file diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeC/HelloWorld.composite b/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeC/HelloWorld.composite new file mode 100644 index 0000000000..066727f76d --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeC/HelloWorld.composite @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeC/HelloWorldComponent.composite b/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeC/HelloWorldComponent.composite new file mode 100644 index 0000000000..485e0815d2 --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeC/HelloWorldComponent.composite @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeC/META-INF/sca-contribution.xml b/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeC/META-INF/sca-contribution.xml new file mode 100644 index 0000000000..d6b9e82250 --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeC/META-INF/sca-contribution.xml @@ -0,0 +1,24 @@ + + + + + \ No newline at end of file diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeD/HelloWorld.composite b/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeD/HelloWorld.composite new file mode 100644 index 0000000000..a5a4f04cb5 --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeD/HelloWorld.composite @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeD/HelloWorldComponent.composite b/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeD/HelloWorldComponent.composite new file mode 100644 index 0000000000..bf30bdf42d --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeD/HelloWorldComponent.composite @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeD/META-INF/sca-contribution.xml b/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeD/META-INF/sca-contribution.xml new file mode 100644 index 0000000000..d6b9e82250 --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeD/META-INF/sca-contribution.xml @@ -0,0 +1,24 @@ + + + + + \ No newline at end of file diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeE/HelloWorld.composite b/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeE/HelloWorld.composite new file mode 100644 index 0000000000..b519793290 --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeE/HelloWorld.composite @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeE/META-INF/sca-contribution.xml b/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeE/META-INF/sca-contribution.xml new file mode 100644 index 0000000000..d6b9e82250 --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeE/META-INF/sca-contribution.xml @@ -0,0 +1,24 @@ + + + + + \ No newline at end of file diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeF/HelloWorld.composite b/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeF/HelloWorld.composite new file mode 100644 index 0000000000..20a6c54e6e --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeF/HelloWorld.composite @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeF/META-INF/sca-contribution.xml b/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeF/META-INF/sca-contribution.xml new file mode 100644 index 0000000000..d6b9e82250 --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeF/META-INF/sca-contribution.xml @@ -0,0 +1,24 @@ + + + + + \ No newline at end of file diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeG/HelloWorld.composite b/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeG/HelloWorld.composite new file mode 100644 index 0000000000..a76008d0c5 --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeG/HelloWorld.composite @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeG/META-INF/sca-contribution.xml b/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeG/META-INF/sca-contribution.xml new file mode 100644 index 0000000000..d6b9e82250 --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeG/META-INF/sca-contribution.xml @@ -0,0 +1,24 @@ + + + + + \ No newline at end of file diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeH/HelloWorld.composite b/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeH/HelloWorld.composite new file mode 100644 index 0000000000..0c22af22ab --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeH/HelloWorld.composite @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + diff --git a/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeH/META-INF/sca-contribution.xml b/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeH/META-INF/sca-contribution.xml new file mode 100644 index 0000000000..d6b9e82250 --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-axis2/src/test/resources/nodeH/META-INF/sca-contribution.xml @@ -0,0 +1,24 @@ + + + + + \ No newline at end of file diff --git a/java/sca/contrib/modules/binding-sca-corba/LICENSE b/java/sca/contrib/modules/binding-sca-corba/LICENSE new file mode 100644 index 0000000000..6e529a25c4 --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-corba/LICENSE @@ -0,0 +1,205 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + + diff --git a/java/sca/contrib/modules/binding-sca-corba/META-INF/MANIFEST.MF b/java/sca/contrib/modules/binding-sca-corba/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..ede93bb946 --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-corba/META-INF/MANIFEST.MF @@ -0,0 +1,39 @@ +Manifest-Version: 1.0 +Private-Package: org.apache.tuscany.sca.binding.sca.corba.impl;version + ="1.4" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA CORBA-based Default Binding Extension +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397364015 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA CORBA-based Default Binding Ext + ension +Import-Package: javax.xml.namespace;version="1.0", + javax.xml.stream, + org.apache.axiom.om, + org.apache.axiom.om.impl.builder, + org.apache.tuscany.sca.assembly;version="2.0.0", + org.apache.tuscany.sca.binding.corba.provider.exceptions;version="2.0.0", + org.apache.tuscany.sca.binding.corba.provider.reference;version="2.0.0", + org.apache.tuscany.sca.binding.corba.provider.service;version="2.0.0", + org.apache.tuscany.sca.binding.corba.provider.types;version="2.0.0", + org.apache.tuscany.sca.binding.sca;version="2.0.0", + org.apache.tuscany.sca.binding.ws;version="2.0.0", + org.apache.tuscany.sca.binding.ws.wsdlgen;version="2.0.0", + org.apache.tuscany.sca.core;version="2.0.0", + org.apache.tuscany.sca.host.corba;version="2.0.0", + org.apache.tuscany.sca.interfacedef;version="2.0.0", + org.apache.tuscany.sca.interfacedef.util;version="2.0.0", + org.apache.tuscany.sca.invocation;version="2.0.0", + org.apache.tuscany.sca.monitor;version="2.0.0", + org.apache.tuscany.sca.policy;version="2.0.0", + org.apache.tuscany.sca.provider;version="2.0.0", + org.apache.tuscany.sca.runtime;version="2.0.0", + org.omg.CORBA, + org.oasisopen.sca;version="2.0.0" +Bundle-SymbolicName: org.apache.tuscany.sca.binding.sca.corba +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/binding-sca-corba/NOTICE b/java/sca/contrib/modules/binding-sca-corba/NOTICE new file mode 100644 index 0000000000..51042eab05 --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-corba/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/binding-sca-corba/pom.xml b/java/sca/contrib/modules/binding-sca-corba/pom.xml new file mode 100644 index 0000000000..c7ae956137 --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-corba/pom.xml @@ -0,0 +1,88 @@ + + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + + tuscany-binding-sca-corba + + Apache Tuscany SCA CORBA-based Default Binding Extension + + + + + + org.apache.tuscany.sca + tuscany-binding-sca + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-binding-corba + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-binding-corba-runtime + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-host-corba + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-host-corba-jse + 2.0-SNAPSHOT + test + + + + org.apache.tuscany.sca + tuscany-interface-wsdl + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-databinding-axiom + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-binding-ws-wsdlgen + 2.0-SNAPSHOT + + + + + diff --git a/java/sca/contrib/modules/binding-sca-corba/src/main/java/org/apache/tuscany/sca/binding/sca/corba/impl/CorbaSCABindingProviderFactory.java b/java/sca/contrib/modules/binding-sca-corba/src/main/java/org/apache/tuscany/sca/binding/sca/corba/impl/CorbaSCABindingProviderFactory.java new file mode 100644 index 0000000000..2eee714de6 --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-corba/src/main/java/org/apache/tuscany/sca/binding/sca/corba/impl/CorbaSCABindingProviderFactory.java @@ -0,0 +1,64 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.sca.corba.impl; + +import org.apache.tuscany.sca.binding.sca.DistributedSCABinding; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.host.corba.CorbaHost; +import org.apache.tuscany.sca.host.corba.CorbaHostExtensionPoint; +import org.apache.tuscany.sca.host.corba.ExtensibleCorbaHost; +import org.apache.tuscany.sca.provider.BindingProviderFactory; +import org.apache.tuscany.sca.provider.ReferenceBindingProvider; +import org.apache.tuscany.sca.provider.ServiceBindingProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; + +/** + * Binding provider factory for SCA default binding over CORBA binding + */ +public class CorbaSCABindingProviderFactory implements BindingProviderFactory { + + private CorbaHostExtensionPoint chep; + private CorbaHost host; + private ExtensionPointRegistry extensions; + + public CorbaSCABindingProviderFactory(ExtensionPointRegistry extensions) { + this.extensions = extensions; + chep = extensions.getExtensionPoint(CorbaHostExtensionPoint.class); + host = new ExtensibleCorbaHost(chep); + } + + public ReferenceBindingProvider createReferenceBindingProvider(RuntimeComponent component, + RuntimeComponentReference reference, + DistributedSCABinding binding) { + return new CorbaSCAReferenceBindingProvider(binding.getSCABinding(), host, component, reference, extensions); + } + + public ServiceBindingProvider createServiceBindingProvider(RuntimeComponent component, + RuntimeComponentService service, + DistributedSCABinding binding) { + return new CorbaSCAServiceBindingProvider(binding.getSCABinding(), host, component, service, extensions); + } + + public Class getModelType() { + return DistributedSCABinding.class; + } +} diff --git a/java/sca/contrib/modules/binding-sca-corba/src/main/java/org/apache/tuscany/sca/binding/sca/corba/impl/CorbaSCAInvocationProxy.java b/java/sca/contrib/modules/binding-sca-corba/src/main/java/org/apache/tuscany/sca/binding/sca/corba/impl/CorbaSCAInvocationProxy.java new file mode 100644 index 0000000000..257be80807 --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-corba/src/main/java/org/apache/tuscany/sca/binding/sca/corba/impl/CorbaSCAInvocationProxy.java @@ -0,0 +1,111 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.sca.corba.impl; + +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; + +import javax.xml.stream.XMLStreamException; + +import org.apache.axiom.om.OMElement; +import org.apache.tuscany.sca.binding.corba.provider.exceptions.RequestConfigurationException; +import org.apache.tuscany.sca.binding.corba.provider.service.InvocationException; +import org.apache.tuscany.sca.binding.corba.provider.service.InvocationProxy; +import org.apache.tuscany.sca.binding.corba.provider.service.OperationTypes; +import org.apache.tuscany.sca.binding.corba.provider.types.TypeTree; +import org.apache.tuscany.sca.binding.corba.provider.types.TypeTreeCreator; +import org.apache.tuscany.sca.interfacedef.Interface; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.interfacedef.util.FaultException; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.invocation.MessageFactory; +import org.apache.tuscany.sca.runtime.RuntimeWire; + +/** + * Invocation proxy for SCA default binding over CORBA binding + */ +public class CorbaSCAInvocationProxy implements InvocationProxy { + + private static final Logger logger = Logger.getLogger(CorbaSCAInvocationProxy.class.getName()); + private RuntimeWire wire; + private Interface componentInterface; + private OperationTypes types = new OperationTypes(); + private MessageFactory messageFactory; + + public CorbaSCAInvocationProxy(RuntimeWire wire, Interface componentInterface, MessageFactory messageFactory) { + this.wire = wire; + this.componentInterface = componentInterface; + this.messageFactory = messageFactory; + try { + List inputType = new ArrayList(); + inputType.add(TypeTreeCreator.createTypeTree(String.class, null)); + types.setInputType(inputType); + types.setOutputType(TypeTreeCreator.createTypeTree(String.class, null)); + } catch (RequestConfigurationException e) { + // ignore - string type should not cause this exception + } + } + + public Object invoke(String operationName, List arguments) throws InvocationException { + try { + OMElement omContent = CorbaSCAInvoker.stringToOM((String)arguments.get(0)); + String componentOperationName = omContent.getQName().getLocalPart(); + Operation componentOperation = null; + for (Operation operation : componentInterface.getOperations()) { + if (operation.getName().equals(componentOperationName)) { + componentOperation = operation; + break; + } + } + if (componentOperation != null) { + Message msg = messageFactory.createMessage(); + msg.setOperation(componentOperation); + Object[] args = new Object[1]; + args[0] = omContent; + msg.setBody(args); + OMElement omResult = (OMElement)wire.invoke(componentOperation, msg); + return omResult.toStringWithConsume(); + } + } catch (XMLStreamException e) { + logger.log(Level.WARNING, "XMLStreamException during handling invocation target exception", e); + } catch (InvocationTargetException e) { + OMElement omException = (OMElement)((FaultException)e.getCause()).getFaultInfo(); + try { + WrappedSCAException wrappedException = new WrappedSCAException(omException.toStringWithConsume()); + InvocationException exception = new InvocationException(wrappedException); + throw exception; + } catch (XMLStreamException xmle) { + logger.log(Level.WARNING, "XMLStreamException during handling invocation target exception", xmle); + } + + } + + return null; + } + + public OperationTypes getOperationTypes(String operationName) { + // ignoring operationName - only one operation for this proxy is allowed + return types; + } + +} diff --git a/java/sca/contrib/modules/binding-sca-corba/src/main/java/org/apache/tuscany/sca/binding/sca/corba/impl/CorbaSCAInvoker.java b/java/sca/contrib/modules/binding-sca-corba/src/main/java/org/apache/tuscany/sca/binding/sca/corba/impl/CorbaSCAInvoker.java new file mode 100644 index 0000000000..1cb532a46b --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-corba/src/main/java/org/apache/tuscany/sca/binding/sca/corba/impl/CorbaSCAInvoker.java @@ -0,0 +1,97 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.sca.corba.impl; + +import java.io.ByteArrayInputStream; +import java.lang.reflect.Method; +import java.util.Map; + +import javax.xml.stream.XMLStreamException; + +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.impl.builder.StAXOMBuilder; +import org.apache.tuscany.sca.binding.corba.provider.exceptions.RequestConfigurationException; +import org.apache.tuscany.sca.binding.corba.provider.reference.DynaCorbaRequest; +import org.apache.tuscany.sca.binding.corba.provider.reference.DynaCorbaResponse; +import org.apache.tuscany.sca.interfacedef.util.FaultException; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; +import org.omg.CORBA.Object; +import org.oasisopen.sca.ServiceRuntimeException; + +public class CorbaSCAInvoker implements Invoker { + + private Object remoteObject; + private Class referenceClass; + + public CorbaSCAInvoker(Object remoteObject, + Class referenceClass, + Map operationsMap, + boolean scaBindingRules) { + this.remoteObject = remoteObject; + this.referenceClass = referenceClass; + } + + /** + * @see org.apache.tuscany.sca.invocation.Invoker#invoke(org.apache.tuscany.sca.invocation.Message) + */ + public Message invoke(Message msg) { + try { + DynaCorbaRequest request = new DynaCorbaRequest(remoteObject, "scaService"); + request.setReferenceClass(referenceClass); + request.setOutputType(String.class); + request.addExceptionType(WrappedSCAException.class); + java.lang.Object[] args = msg.getBody(); + OMElement omElement = (OMElement)args[0]; + String arg = omElement.toStringWithConsume(); + request.addArgument(arg); + DynaCorbaResponse response = request.invoke(); + OMElement responseOM = stringToOM((String)response.getContent()); + msg.setBody(responseOM); + } catch (WrappedSCAException e) { + try { + OMElement exceptionOM = stringToOM(e.getFault()); + FaultException f = new FaultException(e.getMessage(), exceptionOM, e); + f.setFaultName(exceptionOM.getQName()); + msg.setFaultBody(f); + } catch (XMLStreamException e1) { + } + } catch (RequestConfigurationException e) { + throw new ServiceRuntimeException(e); + } catch (Exception e) { + msg.setFaultBody(e); + } + return msg; + } + + /** + * This will help you to create an OMElement from an xml fragment which you have as a string. + * + * @param xmlFragment - the well-formed xml fragment + * @return The OMElement created out of the string xml fragment. + * @throws XMLStreamException + */ + static OMElement stringToOM(String xmlFragment) throws XMLStreamException { + if (xmlFragment != null) { + return new StAXOMBuilder(new ByteArrayInputStream(xmlFragment.getBytes())).getDocumentElement(); + } + return null; + } +} diff --git a/java/sca/contrib/modules/binding-sca-corba/src/main/java/org/apache/tuscany/sca/binding/sca/corba/impl/CorbaSCAReferenceBindingProvider.java b/java/sca/contrib/modules/binding-sca-corba/src/main/java/org/apache/tuscany/sca/binding/sca/corba/impl/CorbaSCAReferenceBindingProvider.java new file mode 100644 index 0000000000..c578f8bdf4 --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-corba/src/main/java/org/apache/tuscany/sca/binding/sca/corba/impl/CorbaSCAReferenceBindingProvider.java @@ -0,0 +1,95 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.sca.corba.impl; + +import java.util.logging.Logger; + +import org.apache.axiom.om.OMElement; +import org.apache.tuscany.sca.assembly.SCABinding; +import org.apache.tuscany.sca.binding.ws.WebServiceBinding; +import org.apache.tuscany.sca.binding.ws.WebServiceBindingFactory; +import org.apache.tuscany.sca.binding.ws.wsdlgen.BindingWSDLGenerator; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.host.corba.CorbaHost; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.provider.ReferenceBindingProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.omg.CORBA.Object; + +/** + * Reference binding provider for SCA default binding over CORBA binding + */ +public class CorbaSCAReferenceBindingProvider implements ReferenceBindingProvider { + + private static final Logger logger = Logger.getLogger(CorbaSCAReferenceBindingProvider.class.getName()); + + private SCABinding binding; + private CorbaHost host; + private Object remoteObject; + private Class referenceClass; + private InterfaceContract wsdlInterfaceContract; + + public CorbaSCAReferenceBindingProvider(SCABinding binding, + CorbaHost host, + RuntimeComponent component, + RuntimeComponentReference reference, + ExtensionPointRegistry extensions) { + this.binding = binding; + this.host = host; + + WebServiceBindingFactory wsFactory = extensions.getExtensionPoint(WebServiceBindingFactory.class); + WebServiceBinding wsBinding = wsFactory.createWebServiceBinding(); + BindingWSDLGenerator.generateWSDL(component, reference, wsBinding, extensions, null); + wsdlInterfaceContract = wsBinding.getBindingInterfaceContract(); + wsdlInterfaceContract.getInterface().resetDataBinding(OMElement.class.getName()); + } + + public InterfaceContract getBindingInterfaceContract() { + return wsdlInterfaceContract; + } + + public boolean supportsOneWayInvocation() { + return false; + } + + public Invoker createInvoker(Operation operation) { + try { + if (remoteObject == null) { + remoteObject = host.lookup(binding.getURI()); + } + return new CorbaSCAInvoker(remoteObject, referenceClass, null, true); + } catch (Exception e) { + logger.warning(e.getMessage()); + } + return null; + } + + public void start() { + + } + + public void stop() { + + } + +} diff --git a/java/sca/contrib/modules/binding-sca-corba/src/main/java/org/apache/tuscany/sca/binding/sca/corba/impl/CorbaSCAServiceBindingProvider.java b/java/sca/contrib/modules/binding-sca-corba/src/main/java/org/apache/tuscany/sca/binding/sca/corba/impl/CorbaSCAServiceBindingProvider.java new file mode 100644 index 0000000000..e8a76050e2 --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-corba/src/main/java/org/apache/tuscany/sca/binding/sca/corba/impl/CorbaSCAServiceBindingProvider.java @@ -0,0 +1,97 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.sca.corba.impl; + +import org.apache.axiom.om.OMElement; +import org.apache.tuscany.sca.assembly.SCABinding; +import org.apache.tuscany.sca.binding.corba.provider.service.DynaCorbaServant; +import org.apache.tuscany.sca.binding.corba.provider.service.InvocationProxy; +import org.apache.tuscany.sca.binding.ws.WebServiceBinding; +import org.apache.tuscany.sca.binding.ws.WebServiceBindingFactory; +import org.apache.tuscany.sca.binding.ws.wsdlgen.BindingWSDLGenerator; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.host.corba.CorbaHost; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.invocation.MessageFactory; +import org.apache.tuscany.sca.provider.ServiceBindingProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; +import org.oasisopen.sca.ServiceRuntimeException; + +/** + * Service binding provider for SCA default binding over CORBA binding + */ +public class CorbaSCAServiceBindingProvider implements ServiceBindingProvider { + + private SCABinding binding; + private CorbaHost host; + private RuntimeComponentService service; + private DynaCorbaServant servant; + private MessageFactory messageFactory; + private InterfaceContract wsdlInterfaceContract; + + public CorbaSCAServiceBindingProvider(SCABinding binding, + CorbaHost host, + RuntimeComponent component, + RuntimeComponentService service, + ExtensionPointRegistry extensions) { + this.binding = binding; + this.host = host; + this.service = service; + + messageFactory = extensions.getExtensionPoint(MessageFactory.class); + + WebServiceBindingFactory wsFactory = extensions.getExtensionPoint(WebServiceBindingFactory.class); + WebServiceBinding wsBinding = wsFactory.createWebServiceBinding(); + BindingWSDLGenerator.generateWSDL(component, service, wsBinding, extensions, null); + wsdlInterfaceContract = wsBinding.getBindingInterfaceContract(); + wsdlInterfaceContract.getInterface().resetDataBinding(OMElement.class.getName()); + } + + public InterfaceContract getBindingInterfaceContract() { + return wsdlInterfaceContract; + } + + public boolean supportsOneWayInvocation() { + return false; + } + + public void start() { + try { + InvocationProxy proxy = + new CorbaSCAInvocationProxy(service.getRuntimeWire(binding), service.getInterfaceContract() + .getInterface(), messageFactory); + servant = new DynaCorbaServant(proxy, "IDL:org/apache/tuscany/sca/binding/sca/corba/Service:1.0"); + host.registerServant(binding.getURI(), servant); + } catch (Exception e) { + throw new ServiceRuntimeException(e); + } + } + + public void stop() { + try { + host.unregisterServant(binding.getURI()); + } catch (Exception e) { + throw new ServiceRuntimeException(e); + } + + } + +} diff --git a/java/sca/contrib/modules/binding-sca-corba/src/main/java/org/apache/tuscany/sca/binding/sca/corba/impl/WrappedSCAException.java b/java/sca/contrib/modules/binding-sca-corba/src/main/java/org/apache/tuscany/sca/binding/sca/corba/impl/WrappedSCAException.java new file mode 100644 index 0000000000..128d5ef159 --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-corba/src/main/java/org/apache/tuscany/sca/binding/sca/corba/impl/WrappedSCAException.java @@ -0,0 +1,56 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.binding.sca.corba.impl; + +/** + * Exception holder for SCA default binding over CORBA. Holds fault message in + * XML + */ +public class WrappedSCAException extends Exception { + + private static final long serialVersionUID = 1L; + public String fault; + + /** + * Creates exception holder with null fault message. This no argument + * constructor is needed by CORBA binding. + */ + public WrappedSCAException() { + + } + + /** + * Creates exception holder with fault message + * + * @param fault XML fault message + */ + public WrappedSCAException(String fault) { + this.fault = fault; + } + + public String getFault() { + return fault; + } + + public void setFault(String fault) { + this.fault = fault; + } + +} diff --git a/java/sca/contrib/modules/binding-sca-corba/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.BindingProviderFactory b/java/sca/contrib/modules/binding-sca-corba/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.BindingProviderFactory new file mode 100644 index 0000000000..e07a7cbb95 --- /dev/null +++ b/java/sca/contrib/modules/binding-sca-corba/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.BindingProviderFactory @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for the binding extension +org.apache.tuscany.sca.binding.sca.corba.impl.CorbaSCABindingProviderFactory;model=org.apache.tuscany.sca.binding.sca.DistributedSCABinding diff --git a/java/sca/contrib/modules/common-xml/META-INF/MANIFEST.MF b/java/sca/contrib/modules/common-xml/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..ad4d6bd487 --- /dev/null +++ b/java/sca/contrib/modules/common-xml/META-INF/MANIFEST.MF @@ -0,0 +1,29 @@ +Manifest-Version: 1.0 +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA Common XML +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397108125 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA Core SPI +Import-Package: javax.xml.namespace, + javax.xml.xpath, + javax.xml.datatype, + javax.xml.parsers, + javax.xml.stream, + javax.xml.stream.util, + javax.xml.transform, + javax.xml.transform.dom, + javax.xml.transform.sax, + javax.xml.transform.stream, + org.w3c.dom, + org.xml.sax, + org.xml.sax.ext, + org.xml.sax.helpers, + org.apache.tuscany.sca.core;version="2.0.0", + org.apache.tuscany.sca.extensibility;version="2.0.0" +Bundle-SymbolicName: org.apache.tuscany.sca.common.xml +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/common-xml/pom.xml b/java/sca/contrib/modules/common-xml/pom.xml new file mode 100644 index 0000000000..4b7a6df1d0 --- /dev/null +++ b/java/sca/contrib/modules/common-xml/pom.xml @@ -0,0 +1,66 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + tuscany-common-xml + Apache Tuscany SCA Common XML + + + + org.apache.tuscany.sca + tuscany-extensibility + 2.0-SNAPSHOT + + + + org.apache.geronimo.specs + geronimo-stax-api_1.0_spec + 1.0.1 + + + + org.codehaus.woodstox + wstx-asl + 3.2.4 + test + + + stax + stax-api + + + + + + xmlunit + xmlunit + 1.2 + test + + + + + diff --git a/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/SimpleTypeMapper.java b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/SimpleTypeMapper.java new file mode 100644 index 0000000000..8bdb8ae2df --- /dev/null +++ b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/SimpleTypeMapper.java @@ -0,0 +1,210 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.common.xml; + +import java.util.HashMap; +import java.util.Map; + +import javax.xml.namespace.QName; + +/** + * Simple type mapper that maps from XSD types to Java Classes and Java Classes to XSD types. + * + * @version $Rev$ $Date$ + */ +public class SimpleTypeMapper extends XSDDataTypeConverter { + + public static final Map, String> JAVA2XML = new HashMap, String>(); + + public static final String URI_2001_SCHEMA_XSD = "http://www.w3.org/2001/XMLSchema"; + + public static final Map> XML2JAVA = new HashMap>(); + + public static final QName XSD_ANY = new QName(URI_2001_SCHEMA_XSD, "any"); + + public static final QName XSD_ANYSIMPLETYPE = new QName(URI_2001_SCHEMA_XSD, "anySimpleType"); + + public static final QName XSD_ANYTYPE = new QName(URI_2001_SCHEMA_XSD, "anyType"); + + public static final QName XSD_ANYURI = new QName(URI_2001_SCHEMA_XSD, "anyURI"); + + public static final QName XSD_BASE64 = new QName(URI_2001_SCHEMA_XSD, "base64Binary"); + + public static final QName XSD_BOOLEAN = new QName(URI_2001_SCHEMA_XSD, "boolean"); + + public static final QName XSD_BYTE = new QName(URI_2001_SCHEMA_XSD, "byte"); + + public static final QName XSD_DATE = new QName(URI_2001_SCHEMA_XSD, "date"); + + public static final QName XSD_DATETIME = new QName(URI_2001_SCHEMA_XSD, "dateTime"); + + public static final QName XSD_DAY = new QName(URI_2001_SCHEMA_XSD, "gDay"); + + public static final QName XSD_DECIMAL = new QName(URI_2001_SCHEMA_XSD, "decimal"); + + public static final QName XSD_DOUBLE = new QName(URI_2001_SCHEMA_XSD, "double"); + + public static final QName XSD_DURATION = new QName(URI_2001_SCHEMA_XSD, "duration"); + + public static final QName XSD_ENTITIES = new QName(URI_2001_SCHEMA_XSD, "ENTITIES"); + + public static final QName XSD_ENTITY = new QName(URI_2001_SCHEMA_XSD, "ENTITY"); + + public static final QName XSD_FLOAT = new QName(URI_2001_SCHEMA_XSD, "float"); + + public static final QName XSD_HEXBIN = new QName(URI_2001_SCHEMA_XSD, "hexBinary"); + + public static final QName XSD_IDREF = new QName(URI_2001_SCHEMA_XSD, "IDREF"); + + public static final QName XSD_IDREFS = new QName(URI_2001_SCHEMA_XSD, "IDREFS"); + + public static final QName XSD_INT = new QName(URI_2001_SCHEMA_XSD, "int"); + + public static final QName XSD_INTEGER = new QName(URI_2001_SCHEMA_XSD, "integer"); + + public static final QName XSD_LONG = new QName(URI_2001_SCHEMA_XSD, "long"); + + public static final QName XSD_MONTH = new QName(URI_2001_SCHEMA_XSD, "gMonth"); + + public static final QName XSD_MONTHDAY = new QName(URI_2001_SCHEMA_XSD, "gMonthDay"); + + public static final QName XSD_NAME = new QName(URI_2001_SCHEMA_XSD, "Name"); + + public static final QName XSD_NCNAME = new QName(URI_2001_SCHEMA_XSD, "NCName"); + + public static final QName XSD_NEGATIVEINTEGER = new QName(URI_2001_SCHEMA_XSD, "negativeInteger"); + + public static final QName XSD_NMTOKEN = new QName(URI_2001_SCHEMA_XSD, "NMTOKEN"); + + public static final QName XSD_NMTOKENS = new QName(URI_2001_SCHEMA_XSD, "NMTOKENS"); + + public static final QName XSD_NONNEGATIVEINTEGER = new QName(URI_2001_SCHEMA_XSD, "nonNegativeInteger"); + + public static final QName XSD_NONPOSITIVEINTEGER = new QName(URI_2001_SCHEMA_XSD, "nonPositiveInteger"); + + public static final QName XSD_NORMALIZEDSTRING = new QName(URI_2001_SCHEMA_XSD, "normalizedString"); + + public static final QName XSD_NOTATION = new QName(URI_2001_SCHEMA_XSD, "NOTATION"); + + public static final QName XSD_POSITIVEINTEGER = new QName(URI_2001_SCHEMA_XSD, "positiveInteger"); + + public static final QName XSD_QNAME = new QName(URI_2001_SCHEMA_XSD, "QName"); + + public static final QName XSD_SHORT = new QName(URI_2001_SCHEMA_XSD, "short"); + + public static final QName XSD_STRING = new QName(URI_2001_SCHEMA_XSD, "string"); + + public static final QName XSD_TIME = new QName(URI_2001_SCHEMA_XSD, "time"); + + public static final QName XSD_TOKEN = new QName(URI_2001_SCHEMA_XSD, "token"); + + public static final QName XSD_UNSIGNEDBYTE = new QName(URI_2001_SCHEMA_XSD, "unsignedByte"); + + public static final QName XSD_UNSIGNEDINT = new QName(URI_2001_SCHEMA_XSD, "unsignedInt"); + + public static final QName XSD_UNSIGNEDLONG = new QName(URI_2001_SCHEMA_XSD, "unsignedLong"); + + public static final QName XSD_UNSIGNEDSHORT = new QName(URI_2001_SCHEMA_XSD, "unsignedShort"); + + public static final QName XSD_YEAR = new QName(URI_2001_SCHEMA_XSD, "gYear"); + + public static final QName XSD_YEARMONTH = new QName(URI_2001_SCHEMA_XSD, "gYearMonth"); + + static { + JAVA2XML.put(boolean.class, "boolean"); + JAVA2XML.put(byte.class, "byte"); + JAVA2XML.put(short.class, "short"); + JAVA2XML.put(int.class, "int"); + JAVA2XML.put(long.class, "long"); + JAVA2XML.put(float.class, "float"); + JAVA2XML.put(double.class, "double"); + JAVA2XML.put(Boolean.class, "boolean"); + JAVA2XML.put(Byte.class, "byte"); + JAVA2XML.put(Short.class, "short"); + JAVA2XML.put(Integer.class, "int"); + JAVA2XML.put(Long.class, "long"); + JAVA2XML.put(Float.class, "float"); + JAVA2XML.put(Double.class, "double"); + JAVA2XML.put(java.lang.String.class, "string"); + JAVA2XML.put(java.math.BigInteger.class, "integer"); + JAVA2XML.put(java.math.BigDecimal.class, "decimal"); + JAVA2XML.put(java.util.Calendar.class, "dateTime"); + JAVA2XML.put(java.util.Date.class, "dateTime"); + JAVA2XML.put(javax.xml.namespace.QName.class, "QName"); + JAVA2XML.put(java.net.URI.class, "string"); + JAVA2XML.put(javax.xml.datatype.XMLGregorianCalendar.class, "anySimpleType"); + JAVA2XML.put(javax.xml.datatype.Duration.class, "duration"); + JAVA2XML.put(java.lang.Object.class, "anyType"); + JAVA2XML.put(java.awt.Image.class, "base64Binary"); + JAVA2XML.put(byte[].class, "base64Binary"); + // java2XSD.put(javax.activation.DataHandler.class, "base64Binary"); + JAVA2XML.put(javax.xml.transform.Source.class, "base64Binary"); + JAVA2XML.put(java.util.UUID.class, "string"); + } + + static { + XML2JAVA.put(new QName(URI_2001_SCHEMA_XSD, "string"), java.lang.String.class); + XML2JAVA.put(new QName(URI_2001_SCHEMA_XSD, "integer"), java.math.BigInteger.class); + XML2JAVA.put(new QName(URI_2001_SCHEMA_XSD, "int"), int.class); + XML2JAVA.put(new QName(URI_2001_SCHEMA_XSD, "long"), long.class); + XML2JAVA.put(new QName(URI_2001_SCHEMA_XSD, "short"), short.class); + XML2JAVA.put(new QName(URI_2001_SCHEMA_XSD, "decimal"), java.math.BigDecimal.class); + XML2JAVA.put(new QName(URI_2001_SCHEMA_XSD, "float"), float.class); + XML2JAVA.put(new QName(URI_2001_SCHEMA_XSD, "double"), double.class); + XML2JAVA.put(new QName(URI_2001_SCHEMA_XSD, "boolean"), boolean.class); + XML2JAVA.put(new QName(URI_2001_SCHEMA_XSD, "byte"), byte.class); + XML2JAVA.put(new QName(URI_2001_SCHEMA_XSD, "QName"), javax.xml.namespace.QName.class); + XML2JAVA.put(new QName(URI_2001_SCHEMA_XSD, "dateTime"), javax.xml.datatype.XMLGregorianCalendar.class); + XML2JAVA.put(new QName(URI_2001_SCHEMA_XSD, "base64Binary"), byte[].class); + XML2JAVA.put(new QName(URI_2001_SCHEMA_XSD, "hexBinary"), byte[].class); + XML2JAVA.put(new QName(URI_2001_SCHEMA_XSD, "unsignedInt"), long.class); + XML2JAVA.put(new QName(URI_2001_SCHEMA_XSD, "unsignedShort"), int.class); + XML2JAVA.put(new QName(URI_2001_SCHEMA_XSD, "unsignedByte"), short.class); + XML2JAVA.put(new QName(URI_2001_SCHEMA_XSD, "time"), javax.xml.datatype.XMLGregorianCalendar.class); + XML2JAVA.put(new QName(URI_2001_SCHEMA_XSD, "date"), javax.xml.datatype.XMLGregorianCalendar.class); + XML2JAVA.put(new QName(URI_2001_SCHEMA_XSD, "gDay"), javax.xml.datatype.XMLGregorianCalendar.class); + XML2JAVA.put(new QName(URI_2001_SCHEMA_XSD, "gMonth"), javax.xml.datatype.XMLGregorianCalendar.class); + XML2JAVA.put(new QName(URI_2001_SCHEMA_XSD, "gYear"), javax.xml.datatype.XMLGregorianCalendar.class); + XML2JAVA.put(new QName(URI_2001_SCHEMA_XSD, "gYearMonth"), javax.xml.datatype.XMLGregorianCalendar.class); + XML2JAVA.put(new QName(URI_2001_SCHEMA_XSD, "gMonthDay"), javax.xml.datatype.XMLGregorianCalendar.class); + XML2JAVA.put(new QName(URI_2001_SCHEMA_XSD, "anySimpleType"), java.lang.Object.class); // For elements + // XML2JAVA.put(new QName(URI_2001_SCHEMA_XSD, "anySimpleType"), java.lang.String.class); // For + // attributes + XML2JAVA.put(new QName(URI_2001_SCHEMA_XSD, "duration"), javax.xml.datatype.Duration.class); + XML2JAVA.put(new QName(URI_2001_SCHEMA_XSD, "NOTATION"), javax.xml.namespace.QName.class); + } + + public SimpleTypeMapper() { + super(); + } + + public static Class getJavaType(QName xmlType) { + if (xmlType != null && URI_2001_SCHEMA_XSD.equals(xmlType.getNamespaceURI())) { + return XML2JAVA.get(xmlType.getLocalPart()); + } else { + return null; + } + } + + public static QName getXMLType(Class javaType) { + return new QName(URI_2001_SCHEMA_XSD, JAVA2XML.get(javaType)); + } + +} diff --git a/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/XSDDataTypeConverter.java b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/XSDDataTypeConverter.java new file mode 100644 index 0000000000..895e4e476c --- /dev/null +++ b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/XSDDataTypeConverter.java @@ -0,0 +1,945 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.common.xml; + +import java.io.IOException; +import java.io.OutputStream; +import java.io.Writer; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.text.FieldPosition; +import java.text.Format; +import java.text.ParsePosition; +import java.util.Calendar; +import java.util.TimeZone; + +import javax.xml.XMLConstants; +import javax.xml.datatype.DatatypeConfigurationException; +import javax.xml.datatype.DatatypeFactory; +import javax.xml.datatype.Duration; +import javax.xml.namespace.NamespaceContext; +import javax.xml.namespace.QName; + +/** + * Utility class for XSD data type conversions + * + * @version $Rev$ $Date$ + */ +public class XSDDataTypeConverter { + public static final class Base64Binary { + private static final char[] S_BASE64CHAR = + {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', + 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', + 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', + '5', '6', '7', '8', '9', '+', '/'}; + + private static final char S_BASE64PAD = '='; + + private static final byte[] S_DECODETABLE = new byte[128]; + + static { + for (int i = 0; i < S_DECODETABLE.length; i++) { + S_DECODETABLE[i] = Byte.MAX_VALUE; // 127 + } + for (int i = 0; i < S_BASE64CHAR.length; i++) { + // 0 to 63 + S_DECODETABLE[S_BASE64CHAR[i]] = (byte) i; + } + } + + private Base64Binary() { + } + + /** + * + */ + public static byte[] decode(char[] data, int off, int len) { + char[] ibuf = new char[4]; + int ibufcount = 0; + byte[] obuf = new byte[len / 4 * 3 + 3]; + int obufcount = 0; + for (int i = off; i < off + len; i++) { + char ch = data[i]; + if (ch == S_BASE64PAD || ch < S_DECODETABLE.length && S_DECODETABLE[ch] != Byte.MAX_VALUE) { + ibuf[ibufcount++] = ch; + if (ibufcount == ibuf.length) { + ibufcount = 0; + obufcount += decode0(ibuf, obuf, obufcount); + } + } + } + if (obufcount == obuf.length) { + return obuf; + } + byte[] ret = new byte[obufcount]; + System.arraycopy(obuf, 0, ret, 0, obufcount); + return ret; + } + + /** + * + */ + public static void decode(char[] data, int off, int len, OutputStream ostream) throws IOException { + char[] ibuf = new char[4]; + int ibufcount = 0; + byte[] obuf = new byte[3]; + for (int i = off; i < off + len; i++) { + char ch = data[i]; + if (ch == S_BASE64PAD || ch < S_DECODETABLE.length && S_DECODETABLE[ch] != Byte.MAX_VALUE) { + ibuf[ibufcount++] = ch; + if (ibufcount == ibuf.length) { + ibufcount = 0; + int obufcount = decode0(ibuf, obuf, 0); + ostream.write(obuf, 0, obufcount); + } + } + } + } + + /** + * + */ + public static byte[] decode(String data) { + char[] ibuf = new char[4]; + int ibufcount = 0; + byte[] obuf = new byte[data.length() / 4 * 3 + 3]; + int obufcount = 0; + for (int i = 0; i < data.length(); i++) { + char ch = data.charAt(i); + if (ch == S_BASE64PAD || ch < S_DECODETABLE.length && S_DECODETABLE[ch] != Byte.MAX_VALUE) { + ibuf[ibufcount++] = ch; + if (ibufcount == ibuf.length) { + ibufcount = 0; + obufcount += decode0(ibuf, obuf, obufcount); + } + } + } + if (obufcount == obuf.length) { + return obuf; + } + byte[] ret = new byte[obufcount]; + System.arraycopy(obuf, 0, ret, 0, obufcount); + return ret; + } + + /** + * + */ + public static void decode(String data, OutputStream ostream) throws IOException { + char[] ibuf = new char[4]; + int ibufcount = 0; + byte[] obuf = new byte[3]; + for (int i = 0; i < data.length(); i++) { + char ch = data.charAt(i); + if (ch == S_BASE64PAD || ch < S_DECODETABLE.length && S_DECODETABLE[ch] != Byte.MAX_VALUE) { + ibuf[ibufcount++] = ch; + if (ibufcount == ibuf.length) { + ibufcount = 0; + int obufcount = decode0(ibuf, obuf, 0); + ostream.write(obuf, 0, obufcount); + } + } + } + } + + private static int decode0(char[] ibuf, byte[] obuf, int index) { + int wp = index; + int outlen = 3; + if (ibuf[3] == S_BASE64PAD) { + outlen = 2; + } + if (ibuf[2] == S_BASE64PAD) { + outlen = 1; + } + int b0 = S_DECODETABLE[ibuf[0]]; + int b1 = S_DECODETABLE[ibuf[1]]; + int b2 = S_DECODETABLE[ibuf[2]]; + int b3 = S_DECODETABLE[ibuf[3]]; + switch (outlen) { + case 1: + obuf[wp] = (byte) (b0 << 2 & 0xfc | b1 >> 4 & 0x3); + return 1; + case 2: + obuf[wp++] = (byte) (b0 << 2 & 0xfc | b1 >> 4 & 0x3); + obuf[wp] = (byte) (b1 << 4 & 0xf0 | b2 >> 2 & 0xf); + return 2; + case 3: + obuf[wp++] = (byte) (b0 << 2 & 0xfc | b1 >> 4 & 0x3); + obuf[wp++] = (byte) (b1 << 4 & 0xf0 | b2 >> 2 & 0xf); + obuf[wp] = (byte) (b2 << 6 & 0xc0 | b3 & 0x3f); + return 3; + default: + throw new IllegalArgumentException("The character sequence is not base64 encoded."); + } + } + + /** + * Returns base64 representation of specified byte array. + */ + public static String encode(byte[] data) { + return encode(data, 0, data.length); + } + + /** + * Returns base64 representation of specified byte array. + */ + public static String encode(byte[] data, int off, int len) { + if (len <= 0) { + return ""; + } + char[] out = new char[len / 3 * 4 + 4]; + int rindex = off; + int windex = 0; + int rest = len - off; + while (rest >= 3) { + int i = + ((data[rindex] & 0xff) << 16) + ((data[rindex + 1] & 0xff) << 8) + + (data[rindex + 2] & 0xff); + out[windex++] = S_BASE64CHAR[i >> 18]; + out[windex++] = S_BASE64CHAR[(i >> 12) & 0x3f]; + out[windex++] = S_BASE64CHAR[(i >> 6) & 0x3f]; + out[windex++] = S_BASE64CHAR[i & 0x3f]; + rindex += 3; + rest -= 3; + } + if (rest == 1) { + int i = data[rindex] & 0xff; + out[windex++] = S_BASE64CHAR[i >> 2]; + out[windex++] = S_BASE64CHAR[(i << 4) & 0x3f]; + out[windex++] = S_BASE64PAD; + out[windex++] = S_BASE64PAD; + } else if (rest == 2) { + int i = ((data[rindex] & 0xff) << 8) + (data[rindex + 1] & 0xff); + out[windex++] = S_BASE64CHAR[i >> 10]; + out[windex++] = S_BASE64CHAR[(i >> 4) & 0x3f]; + out[windex++] = S_BASE64CHAR[(i << 2) & 0x3f]; + out[windex++] = S_BASE64PAD; + } + return new String(out, 0, windex); + } + + /** + * Outputs base64 representation of the specified byte array to a byte stream. + */ + public static void encode(byte[] data, int off, int len, OutputStream ostream) throws IOException { + if (len <= 0) { + return; + } + byte[] out = new byte[4]; + int rindex = off; + int rest = len - off; + while (rest >= 3) { + int i = + ((data[rindex] & 0xff) << 16) + ((data[rindex + 1] & 0xff) << 8) + + (data[rindex + 2] & 0xff); + out[0] = (byte) S_BASE64CHAR[i >> 18]; + out[1] = (byte) S_BASE64CHAR[(i >> 12) & 0x3f]; + out[2] = (byte) S_BASE64CHAR[(i >> 6) & 0x3f]; + out[3] = (byte) S_BASE64CHAR[i & 0x3f]; + ostream.write(out, 0, 4); + rindex += 3; + rest -= 3; + } + if (rest == 1) { + int i = data[rindex] & 0xff; + out[0] = (byte) S_BASE64CHAR[i >> 2]; + out[1] = (byte) S_BASE64CHAR[(i << 4) & 0x3f]; + out[2] = (byte) S_BASE64PAD; + out[3] = (byte) S_BASE64PAD; + ostream.write(out, 0, 4); + } else if (rest == 2) { + int i = ((data[rindex] & 0xff) << 8) + (data[rindex + 1] & 0xff); + out[0] = (byte) S_BASE64CHAR[i >> 10]; + out[1] = (byte) S_BASE64CHAR[(i >> 4) & 0x3f]; + out[2] = (byte) S_BASE64CHAR[(i << 2) & 0x3f]; + out[3] = (byte) S_BASE64PAD; + ostream.write(out, 0, 4); + } + } + + /** + * Outputs base64 representation of the specified byte array to a character stream. + */ + public static void encode(byte[] data, int off, int len, Writer writer) throws IOException { + if (len <= 0) { + return; + } + char[] out = new char[4]; + int rindex = off; + int rest = len - off; + int output = 0; + while (rest >= 3) { + int i = + ((data[rindex] & 0xff) << 16) + ((data[rindex + 1] & 0xff) << 8) + + (data[rindex + 2] & 0xff); + out[0] = S_BASE64CHAR[i >> 18]; + out[1] = S_BASE64CHAR[(i >> 12) & 0x3f]; + out[2] = S_BASE64CHAR[(i >> 6) & 0x3f]; + out[3] = S_BASE64CHAR[i & 0x3f]; + writer.write(out, 0, 4); + rindex += 3; + rest -= 3; + output += 4; + if (output % 76 == 0) { + writer.write("\n"); + } + } + if (rest == 1) { + int i = data[rindex] & 0xff; + out[0] = S_BASE64CHAR[i >> 2]; + out[1] = S_BASE64CHAR[(i << 4) & 0x3f]; + out[2] = S_BASE64PAD; + out[3] = S_BASE64PAD; + writer.write(out, 0, 4); + } else if (rest == 2) { + int i = ((data[rindex] & 0xff) << 8) + (data[rindex + 1] & 0xff); + out[0] = S_BASE64CHAR[i >> 10]; + out[1] = S_BASE64CHAR[(i >> 4) & 0x3f]; + out[2] = S_BASE64CHAR[(i << 2) & 0x3f]; + out[3] = S_BASE64PAD; + writer.write(out, 0, 4); + } + } + } + + /** + *

+ * Utility class for xs:hexbinary.

+ */ + public static final class HexBinary { + private HexBinary() { + } + + /** + * Converts the string pValue into an array of hex bytes. + */ + public static byte[] decode(String pValue) { + if ((pValue.length() % 2) != 0) { + throw new IllegalArgumentException("A HexBinary string must have even length."); + } + byte[] result = new byte[pValue.length() / 2]; + int j = 0; + int i = 0; + while (i < pValue.length()) { + byte b; + char c = pValue.charAt(i++); + char d = pValue.charAt(i++); + if (c >= '0' && c <= '9') { + b = (byte) ((c - '0') << 4); + } else if (c >= 'A' && c <= 'F') { + b = (byte) ((c - 'A' + 10) << 4); + } else if (c >= 'a' && c <= 'f') { + b = (byte) ((c - 'a' + 10) << 4); + } else { + throw new IllegalArgumentException("Invalid hex digit: " + c); + } + if (d >= '0' && d <= '9') { + b += (byte) (d - '0'); + } else if (d >= 'A' && d <= 'F') { + b += (byte) (d - 'A' + 10); + } else if (d >= 'a' && d <= 'f') { + b += (byte) (d - 'a' + 10); + } else { + throw new IllegalArgumentException("Invalid hex digit: " + d); + } + result[j++] = b; + } + return result; + } + + /** + * Converts the byte array pHexBinary into a string. + */ + public static String encode(byte[] pHexBinary) { + StringBuffer result = new StringBuffer(); + for (int i = 0; i < pHexBinary.length; i++) { + byte b = pHexBinary[i]; + byte c = (byte) ((b & 0xf0) >> 4); + if (c <= 9) { + result.append((char) ('0' + c)); + } else { + result.append((char) ('A' + c - 10)); + } + c = (byte) (b & 0x0f); + if (c <= 9) { + result.append((char) ('0' + c)); + } else { + result.append((char) ('A' + c - 10)); + } + } + return result.toString(); + } + + /** + * Creates a clone of the given byte array. + */ + public static byte[] getClone(byte[] pHexBinary) { + byte[] result = new byte[pHexBinary.length]; + System.arraycopy(pHexBinary, 0, result, 0, pHexBinary.length); + return result; + } + } + + public class XSDDateFormat extends XSDDateTimeFormat { + private static final long serialVersionUID = -1629412916827246627L; + + /** + * Creates a new instance. + */ + public XSDDateFormat() { + super(true, false); + } + } + + /** + *

+ * An instance of {@link java.text.Format}, which may be used to parse and format xs:dateTime values. + *

+ */ + public static class XSDDateTimeFormat extends Format { + private static final long serialVersionUID = -1148332471737068969L; + + final boolean parseDate; + + final boolean parseTime; + + /** + * Creates a new instance. + */ + public XSDDateTimeFormat() { + this(true, true); + } + + XSDDateTimeFormat(boolean pParseDate, boolean pParseTime) { + parseDate = pParseDate; + parseTime = pParseTime; + } + + private void append(StringBuffer pBuffer, int pNum, int pMinLen) { + String s = Integer.toString(pNum); + for (int i = s.length(); i < pMinLen; i++) { + pBuffer.append('0'); + } + pBuffer.append(s); + } + + @Override + public StringBuffer format(Object pCalendar, StringBuffer pBuffer, FieldPosition pPos) { + assert pCalendar != null : "The Calendar argument must not be null."; + assert pBuffer != null : "The StringBuffer argument must not be null."; + assert pPos != null : "The FieldPosition argument must not be null."; + + Calendar cal = (Calendar) pCalendar; + if (parseDate) { + int year = cal.get(Calendar.YEAR); + if (year < 0) { + pBuffer.append('-'); + year = -year; + } + append(pBuffer, year, 4); + pBuffer.append('-'); + append(pBuffer, cal.get(Calendar.MONTH) + 1, 2); + pBuffer.append('-'); + append(pBuffer, cal.get(Calendar.DAY_OF_MONTH), 2); + if (parseTime) { + pBuffer.append('T'); + } + } + if (parseTime) { + append(pBuffer, cal.get(Calendar.HOUR_OF_DAY), 2); + pBuffer.append(':'); + append(pBuffer, cal.get(Calendar.MINUTE), 2); + pBuffer.append(':'); + append(pBuffer, cal.get(Calendar.SECOND), 2); + int millis = cal.get(Calendar.MILLISECOND); + if (millis > 0) { + pBuffer.append('.'); + append(pBuffer, millis, 3); + } + } + TimeZone tz = cal.getTimeZone(); + // JDK 1.4: int offset = tz.getOffset(cal.getTimeInMillis()); + int offset = cal.get(Calendar.ZONE_OFFSET); + if (tz.inDaylightTime(cal.getTime())) { + offset += cal.get(Calendar.DST_OFFSET); + } + if (offset == 0) { + pBuffer.append('Z'); + } else { + if (offset < 0) { + pBuffer.append('-'); + offset = -offset; + } else { + pBuffer.append('+'); + } + int minutes = offset / (60 * 1000); + int hours = minutes / 60; + minutes -= hours * 60; + append(pBuffer, hours, 2); + pBuffer.append(':'); + append(pBuffer, minutes, 2); + } + return pBuffer; + } + + private int parseInt(String pString, int offset, StringBuffer pDigits) { + int length = pString.length(); + int pOffset = offset; + pDigits.setLength(0); + while (pOffset < length) { + char c = pString.charAt(pOffset); + if (Character.isDigit(c)) { + pDigits.append(c); + ++pOffset; + } else { + break; + } + } + return pOffset; + } + + @Override + public Object parseObject(String pString, ParsePosition pParsePosition) { + assert pString != null : "The String argument must not be null."; + assert pParsePosition != null : "The ParsePosition argument must not be null."; + int offset = pParsePosition.getIndex(); + int length = pString.length(); + + boolean isMinus = false; + StringBuffer digits = new StringBuffer(); + int year = 0; + int month = 0; + int mday = 0; + if (parseDate) { + // Sign + if (offset < length) { + char c = pString.charAt(offset); + if (c == '+') { + ++offset; + } else if (c == '-') { + ++offset; + isMinus = true; + } + } + + offset = parseInt(pString, offset, digits); + if (digits.length() < 4) { + pParsePosition.setErrorIndex(offset); + return null; + } + year = Integer.parseInt(digits.toString()); + + if (offset < length && pString.charAt(offset) == '-') { + ++offset; + } else { + pParsePosition.setErrorIndex(offset); + return null; + } + + offset = parseInt(pString, offset, digits); + if (digits.length() != 2) { + pParsePosition.setErrorIndex(offset); + return null; + } + month = Integer.parseInt(digits.toString()); + + if (offset < length && pString.charAt(offset) == '-') { + ++offset; + } else { + pParsePosition.setErrorIndex(offset); + return null; + } + + offset = parseInt(pString, offset, digits); + if (digits.length() != 2) { + pParsePosition.setErrorIndex(offset); + return null; + } + mday = Integer.parseInt(digits.toString()); + + if (parseTime) { + if (offset < length && pString.charAt(offset) == 'T') { + ++offset; + } else { + pParsePosition.setErrorIndex(offset); + return null; + } + } + } else { + year = month = mday = 0; + } + + int hour = 0; + int minute = 0; + int second = 0; + int millis = 0; + if (parseTime) { + offset = parseInt(pString, offset, digits); + if (digits.length() != 2) { + pParsePosition.setErrorIndex(offset); + return null; + } + hour = Integer.parseInt(digits.toString()); + + if (offset < length && pString.charAt(offset) == ':') { + ++offset; + } else { + pParsePosition.setErrorIndex(offset); + return null; + } + + offset = parseInt(pString, offset, digits); + if (digits.length() != 2) { + pParsePosition.setErrorIndex(offset); + return null; + } + minute = Integer.parseInt(digits.toString()); + + if (offset < length && pString.charAt(offset) == ':') { + ++offset; + } else { + pParsePosition.setErrorIndex(offset); + return null; + } + + offset = parseInt(pString, offset, digits); + if (digits.length() != 2) { + pParsePosition.setErrorIndex(offset); + return null; + } + second = Integer.parseInt(digits.toString()); + + if (offset < length && pString.charAt(offset) == '.') { + ++offset; + offset = parseInt(pString, offset, digits); + if (digits.length() > 0) { + millis = Integer.parseInt(digits.toString()); + } else { + millis = 0; + } + } else { + millis = 0; + } + } else { + hour = minute = second = millis = 0; + } + + digits.setLength(0); + digits.append("GMT"); + if (offset < length) { + char c = pString.charAt(offset); + if (c == 'Z') { + // Ignore UTC, it is the default + ++offset; + } else if (c == '+' || c == '-') { + digits.append(c); + ++offset; + for (int i = 0; i < 5; i++) { + if (offset >= length) { + pParsePosition.setErrorIndex(offset); + return null; + } + c = pString.charAt(offset); + if ((i != 2 && Character.isDigit(c)) || (i == 2 && c == ':')) { + digits.append(c); + } else { + pParsePosition.setErrorIndex(offset); + return null; + } + ++offset; + } + } + } + + Calendar cal = Calendar.getInstance(TimeZone.getTimeZone(digits.toString())); + cal.set(isMinus ? -year : year, parseDate ? month - 1 : month, mday, hour, minute, second); + cal.set(Calendar.MILLISECOND, millis); + pParsePosition.setIndex(offset); + return cal; + } + } + + public static class XSDTimeFormat extends XSDDateTimeFormat { + private static final long serialVersionUID = 1346506860724640517L; + + /** + * Creates a new instance. + */ + public XSDTimeFormat() { + super(false, true); + } + } + + private static final long MAX_UNSIGNED_INT = (((long) Integer.MAX_VALUE) * 2) + 1; + + private static final int MAX_UNSIGNED_SHORT = Short.MAX_VALUE * 2 + 1; + + public String parseAnySimpleType(String value) { + return value; + } + + public byte[] parseBase64Binary(String value) { + return Base64Binary.decode(value); + } + + public boolean parseBoolean(String value) { + return Boolean.valueOf(value).booleanValue(); + } + + public byte parseByte(String value) { + return Byte.parseByte(value); + } + + public Calendar parseDate(String value) { + XSDDateFormat format = new XSDDateFormat(); + ParsePosition pos = new ParsePosition(0); + Calendar cal = (Calendar) format.parseObject(value, pos); + if (cal == null) { + throw new IllegalArgumentException("Failed to parse date " + value + " at:" + + value.substring(pos.getErrorIndex())); + } + return cal; + } + + public Calendar parseDateTime(String value) { + XSDDateTimeFormat format = new XSDDateTimeFormat(); + ParsePosition pos = new ParsePosition(0); + Calendar cal = (Calendar) format.parseObject(value, pos); + if (cal == null) { + throw new IllegalArgumentException("Failed to parse dateTime " + value + " at:" + + value.substring(pos.getErrorIndex())); + } + return cal; + } + + public BigDecimal parseDecimal(String value) { + return new BigDecimal(value); + } + + public double parseDouble(String value) { + if ("INF".equals(value)) { + return Double.POSITIVE_INFINITY; + } else if ("-INF".equals(value)) { + return Double.NEGATIVE_INFINITY; + } else if ("NaN".equals(value)) { + return Double.NaN; + } else { + return Double.parseDouble(value); + } + } + + public Duration parseDuration(String pDuration) { + try { + return DatatypeFactory.newInstance().newDuration(pDuration); + } catch (DatatypeConfigurationException e) { + throw new IllegalArgumentException(e); + } + } + + public float parseFloat(String value) { + if ("INF".equals(value)) { + return Float.POSITIVE_INFINITY; + } else if ("-INF".equals(value)) { + return Float.NEGATIVE_INFINITY; + } else if ("NaN".equals(value)) { + return Float.NaN; + } else { + return Float.parseFloat(value); + } + } + + public byte[] parseHexBinary(String value) { + return HexBinary.decode(value); + } + + public int parseInt(String value) { + return Integer.parseInt(value); + } + + public BigInteger parseInteger(String value) { + return new BigInteger(value); + } + + public long parseLong(String value) { + return Long.parseLong(value); + } + + public QName parseQName(String value, NamespaceContext context) { + int offset = value.indexOf(':'); + String uri; + String localName; + switch (offset) { + case -1: + localName = value; + uri = context.getNamespaceURI(""); + if (uri == null) { + // Should not happen, indicates an error in the + // NamespaceContext + // implementation + throw new IllegalArgumentException("The default prefix is not bound."); + } + break; + case 0: + throw new IllegalArgumentException("Default prefix must be indicated by not using a colon: " + + value); + default: + String prefix = value.substring(0, offset); + localName = value.substring(offset + 1); + uri = context.getNamespaceURI(prefix); + if (uri == null) { + throw new IllegalArgumentException("The prefix " + prefix + " is not bound."); + } + } + return new QName(uri, localName); + } + + public short parseShort(String value) { + return Short.parseShort(value); + } + + public String parseString(String value) { + return value; + } + + public Calendar parseTime(String value) { + XSDTimeFormat format = new XSDTimeFormat(); + ParsePosition pos = new ParsePosition(0); + Calendar cal = (Calendar) format.parseObject(value, pos); + if (cal == null) { + throw new IllegalArgumentException("Failed to parse time " + value + " at:" + + value.substring(pos.getErrorIndex())); + } + return cal; + } + + public long parseUnsignedInt(String value) { + long l = Long.parseLong(value); + if (l < 0) { + throw new IllegalArgumentException("Failed to parse UnsignedInt " + value + + ": result is negative"); + } + if (l > MAX_UNSIGNED_INT) { + throw new IllegalArgumentException("Failed to parse UnsignedInt " + value + + ": result exceeds maximum value " + MAX_UNSIGNED_INT); + } + return l; + } + + public int parseUnsignedShort(String value) { + int i = Integer.parseInt(value); + if (i < 0) { + throw new IllegalArgumentException("Failed to parse UnsignedShort " + value + + ": result is negative"); + } + if (i > MAX_UNSIGNED_SHORT) { + throw new IllegalArgumentException("Failed to parse UnsignedShort " + value + + ": result exceeds maximum value " + MAX_UNSIGNED_SHORT); + } + return i; + } + + public String printAnySimpleType(String value) { + return value; + } + + public String printBase64Binary(byte[] value) { + return Base64Binary.encode(value); + } + + public String printBoolean(boolean value) { + return (value ? Boolean.TRUE : Boolean.FALSE).toString(); + } + + public String printByte(byte value) { + return Byte.toString(value); + } + + public String printDate(Calendar value) { + return new XSDDateFormat().format(value); + } + + public String printDateTime(Calendar value) { + return new XSDDateTimeFormat().format(value); + } + + public String printDecimal(BigDecimal value) { + return value.toString(); + } + + public String printDouble(double value) { + return Double.toString(value); + } + + public String printDuration(Duration pDuration) { + return pDuration.toString(); + } + + public String printFloat(float value) { + return Float.toString(value); + } + + public String printHexBinary(byte[] value) { + return HexBinary.encode(value); + } + + public String printInt(int value) { + return Integer.toString(value); + } + + public String printInteger(BigInteger value) { + return value.toString(); + } + + public String printLong(long value) { + return Long.toString(value); + } + + public String printQName(QName value, NamespaceContext context) { + String prefix = context.getPrefix(value.getNamespaceURI()); + if (prefix == null) { + throw new IllegalArgumentException("The namespace URI " + value.getNamespaceURI() + + " is not bound."); + } else if (XMLConstants.DEFAULT_NS_PREFIX.equals(prefix)) { + return value.getLocalPart(); + } else { + return prefix + ":" + value.getLocalPart(); + } + } + + public String printShort(short value) { + return Short.toString(value); + } + + public String printString(String value) { + return value; + } + + public String printTime(Calendar value) { + return new XSDTimeFormat().format(value); + } + + public String printUnsignedInt(long value) { + return Long.toString(value); + } + + public String printUnsignedShort(int value) { + return Integer.toString(value); + } +} diff --git a/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/dom/DOMHelper.java b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/dom/DOMHelper.java new file mode 100644 index 0000000000..db2ce906e1 --- /dev/null +++ b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/dom/DOMHelper.java @@ -0,0 +1,115 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.common.xml.dom; + +import javax.xml.namespace.QName; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; + +/** + * Helper for DOM + * + * @version $Rev$ $Date$ + */ +public final class DOMHelper { + private static DocumentBuilderFactory FACTORY; + + private DOMHelper() { + } + + public static Document newDocument() throws ParserConfigurationException { + return newDocumentBuilder().newDocument(); + } + + public static DocumentBuilder newDocumentBuilder() throws ParserConfigurationException { + init(); + return FACTORY.newDocumentBuilder(); + } + + /** + * + */ + private static synchronized void init() { + if (FACTORY == null) { + FACTORY = DocumentBuilderFactory.newInstance(); + FACTORY.setNamespaceAware(true); + } + } + + public static QName getQName(Node node) { + String ns = node.getNamespaceURI(); + if (ns == null) { + ns = ""; + } + // node.getLocalName() will return null if it is created using DOM Level + // 1 method + // such as createElement() + return new QName(ns, node.getNodeName()); + } + + public static Element createElement(Document document, QName name) { + String prefix = name.getPrefix(); + String qname = + (prefix != null && prefix.length() > 0) ? prefix + ":" + name.getLocalPart() : name.getLocalPart(); + return document.createElementNS(name.getNamespaceURI(), qname); + } + + /** + * Wrap an element as a DOM document + * @param node + * @return + */ + public static Document promote(Node node) { + if (node instanceof Document) { + return (Document)node; + } + Element element = (Element)node; + Document doc = element.getOwnerDocument(); + if (doc.getDocumentElement() == element) { + return doc; + } + doc = (Document)element.getOwnerDocument().cloneNode(false); + Element schema = (Element)doc.importNode(element, true); + doc.appendChild(schema); + Node parent = element.getParentNode(); + while (parent instanceof Element) { + Element root = (Element)parent; + NamedNodeMap nodeMap = root.getAttributes(); + for (int i = 0; i < nodeMap.getLength(); i++) { + Attr attr = (Attr)nodeMap.item(i); + String name = attr.getName(); + if ("xmlns".equals(name) || name.startsWith("xmlns:")) { + if (schema.getAttributeNode(name) == null) { + schema.setAttributeNodeNS((Attr)doc.importNode(attr, true)); + } + } + } + parent = parent.getParentNode(); + } + return doc; + } + +} diff --git a/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/dom/SAX2DOMAdapter.java b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/dom/SAX2DOMAdapter.java new file mode 100644 index 0000000000..6b721583aa --- /dev/null +++ b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/dom/SAX2DOMAdapter.java @@ -0,0 +1,245 @@ +/* + * Copyright 2001-2004 The Apache Software Foundation. + * + * 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.apache.tuscany.sca.common.xml.dom; + +import java.util.ArrayList; +import java.util.List; +import java.util.Stack; + +import javax.xml.parsers.ParserConfigurationException; + +import org.w3c.dom.Comment; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.ProcessingInstruction; +import org.w3c.dom.Text; +import org.xml.sax.Attributes; +import org.xml.sax.ContentHandler; +import org.xml.sax.Locator; +import org.xml.sax.SAXException; +import org.xml.sax.ext.LexicalHandler; + +/** + * SAX2DOM adapter + * + * @version $Rev$ $Date$ + */ +public class SAX2DOMAdapter implements ContentHandler, LexicalHandler { + public static final String EMPTYSTRING = ""; + public static final String XML_PREFIX = "xml"; + public static final String XMLNS_PREFIX = "xmlns"; + public static final String XMLNS_STRING = "xmlns:"; + public static final String XMLNS_URI = "http://www.w3.org/2000/xmlns/"; + + private Node root; + + private Document document; + + private Node nextSibling; + + private Stack nodeStk = new Stack(); + + private List namespaceDecls; + + private Node lastSibling; + + public SAX2DOMAdapter() throws ParserConfigurationException { + this.document = DOMHelper.newDocument(); + this.root = document; + } + + public SAX2DOMAdapter(Node root, Node nextSibling) throws ParserConfigurationException { + this.root = root; + if (root instanceof Document) { + this.document = (Document)root; + } else if (root != null) { + this.document = root.getOwnerDocument(); + } else { + this.document = DOMHelper.newDocument(); + this.root = document; + } + + this.nextSibling = nextSibling; + } + + public SAX2DOMAdapter(Node root) throws ParserConfigurationException { + this(root, null); + } + + public Node getDOM() { + return root; + } + + public void characters(char[] ch, int start, int length) { + final Node last = nodeStk.peek(); + + // No text nodes can be children of root (DOM006 exception) + if (last != document) { + final String text = new String(ch, start, length); + if (lastSibling != null && lastSibling.getNodeType() == Node.TEXT_NODE) { + ((Text)lastSibling).appendData(text); + } else if (last == root && nextSibling != null) { + lastSibling = last.insertBefore(document.createTextNode(text), nextSibling); + } else { + lastSibling = last.appendChild(document.createTextNode(text)); + } + + } + } + + public void startDocument() { + nodeStk.push(root); + } + + public void endDocument() { + nodeStk.pop(); + } + + public void startElement(String namespace, String localName, String qName, Attributes attrs) { + final Element tmp = document.createElementNS(namespace, qName); + + // Add namespace declarations first + if (namespaceDecls != null) { + final int nDecls = namespaceDecls.size(); + for (int i = 0; i < nDecls; i++) { + final String prefix = namespaceDecls.get(i++); + + if (prefix == null || prefix.equals(EMPTYSTRING)) { + tmp.setAttributeNS(XMLNS_URI, XMLNS_PREFIX, namespaceDecls.get(i)); + } else { + tmp.setAttributeNS(XMLNS_URI, XMLNS_STRING + prefix, namespaceDecls.get(i)); + } + } + namespaceDecls.clear(); + } + + // Add attributes to element + final int nattrs = attrs.getLength(); + for (int i = 0; i < nattrs; i++) { + if (attrs.getLocalName(i) == null) { + tmp.setAttribute(attrs.getQName(i), attrs.getValue(i)); + } else { + tmp.setAttributeNS(attrs.getURI(i), attrs.getQName(i), attrs.getValue(i)); + } + } + + // Append this new node onto current stack node + Node last = nodeStk.peek(); + + // If the SAX2DOM is created with a non-null next sibling node, + // insert the result nodes before the next sibling under the root. + if (last == root && nextSibling != null) { + last.insertBefore(tmp, nextSibling); + } else { + last.appendChild(tmp); + } + + // Push this node onto stack + nodeStk.push(tmp); + lastSibling = null; + } + + public void endElement(String namespace, String localName, String qName) { + nodeStk.pop(); + lastSibling = null; + } + + public void startPrefixMapping(String prefix, String uri) { + if (namespaceDecls == null) { + namespaceDecls = new ArrayList(2); + } + namespaceDecls.add(prefix); + namespaceDecls.add(uri); + } + + public void endPrefixMapping(String prefix) { + // do nothing + } + + /** + * This class is only used internally so this method should never be called. + */ + public void ignorableWhitespace(char[] ch, int start, int length) { + } + + /** + * adds processing instruction node to DOM. + */ + public void processingInstruction(String target, String data) { + final Node last = nodeStk.peek(); + ProcessingInstruction pi = document.createProcessingInstruction(target, data); + if (pi != null) { + if (last == root && nextSibling != null) { + last.insertBefore(pi, nextSibling); + } else { + last.appendChild(pi); + } + + lastSibling = pi; + } + } + + /** + * This class is only used internally so this method should never be called. + */ + public void setDocumentLocator(Locator locator) { + } + + /** + * This class is only used internally so this method should never be called. + */ + public void skippedEntity(String name) { + } + + /** + * Lexical Handler method to create comment node in DOM tree. + */ + public void comment(char[] ch, int start, int length) { + final Node last = nodeStk.peek(); + Comment comment = document.createComment(new String(ch, start, length)); + if (comment != null) { + if (last == root && nextSibling != null) { + last.insertBefore(comment, nextSibling); + } else { + last.appendChild(comment); + } + + lastSibling = comment; + } + } + + // Lexical Handler methods- not implemented + public void startCDATA() { + } + + public void endCDATA() { + } + + public void startEntity(java.lang.String name) { + } + + public void endDTD() { + } + + public void endEntity(String name) { + } + + public void startDTD(String name, String publicId, String systemId) throws SAXException { + } + +} diff --git a/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/DOMXMLStreamReader.java b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/DOMXMLStreamReader.java new file mode 100644 index 0000000000..4a5d4aaa6a --- /dev/null +++ b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/DOMXMLStreamReader.java @@ -0,0 +1,36 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.common.xml.stax; + +import org.w3c.dom.Node; + +public class DOMXMLStreamReader extends XmlTreeStreamReaderImpl { + + public DOMXMLStreamReader(Node node) { + super(new DOMXmlNodeImpl(node)); + switch (node.getNodeType()) { + case Node.DOCUMENT_NODE: + break; + case Node.ELEMENT_NODE: + break; + default: + throw new IllegalArgumentException("Illegal node type: " + node); + } + } +} diff --git a/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/DOMXmlNodeImpl.java b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/DOMXmlNodeImpl.java new file mode 100644 index 0000000000..83ff31000d --- /dev/null +++ b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/DOMXmlNodeImpl.java @@ -0,0 +1,156 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.common.xml.stax; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import javax.xml.namespace.QName; + +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +/** + * @version $Rev$ $Date$ + */ +public class DOMXmlNodeImpl implements XmlNode { + private Node node; + private Map namespaces; + private Type type; + + /** + * @param element + */ + public DOMXmlNodeImpl(Node element) { + super(); + if (element.getNodeType() == Node.DOCUMENT_NODE) { + this.node = ((Document)element).getDocumentElement(); + } else { + this.node = element; + } + switch (node.getNodeType()) { + case Node.CDATA_SECTION_NODE: + this.type = Type.CHARACTERS; + break; + case Node.ELEMENT_NODE: + this.type = Type.ELEMENT; + break; + case Node.TEXT_NODE: + this.type = Type.CHARACTERS; + break; + } + } + + /** + * @see org.apache.tuscany.sca.common.xml.stax.databinding.xml.XmlNode#attributes() + */ + public List attributes() { + if (type != Type.ELEMENT) { + return null; + } + NamedNodeMap attrs = node.getAttributes(); + List xmlAttrs = new ArrayList(); + for (int i = 0; i < attrs.getLength(); i++) { + Attr attr = (Attr)attrs.item(i); + if (!attr.getName().equals("xmlns") && !attr.getName().startsWith("xmlns:")) { + xmlAttrs.add(new SimpleXmlNodeImpl(getQName(attr), attr.getValue(), XmlNode.Type.ATTRIBUTE)); + } + } + return xmlAttrs; + } + + /** + * @see org.apache.tuscany.sca.common.xml.stax.databinding.xml.XmlNode#children() + */ + public Iterator children() { + if (type != Type.ELEMENT) { + return null; + } + NodeList nodes = node.getChildNodes(); + List xmlNodes = new ArrayList(); + for (int i = 0; i < nodes.getLength(); i++) { + Node child = (Node)nodes.item(i); + int nodeType = child.getNodeType(); + if (nodeType == Node.ELEMENT_NODE || nodeType == Node.TEXT_NODE || nodeType == Node.CDATA_SECTION_NODE) { + xmlNodes.add(new DOMXmlNodeImpl(child)); + } + } + return xmlNodes.iterator(); + } + + /** + * @see org.apache.tuscany.sca.common.xml.stax.databinding.xml.XmlNode#getName() + */ + public QName getName() { + return getQName(node); + } + + private static QName getQName(Node node) { + int type = node.getNodeType(); + if (type == Node.ELEMENT_NODE || type == Node.ATTRIBUTE_NODE) { + String ns = node.getNamespaceURI(); + String prefix = node.getPrefix(); + String localName = node.getLocalName(); + return new QName(ns == null ? "" : ns, localName, prefix == null ? "" : prefix); + } + return null; + } + + /** + * @see org.apache.tuscany.sca.common.xml.stax.databinding.xml.XmlNode#getValue() + */ + public String getValue() { + return node.getNodeValue(); + } + + /** + * @see org.apache.tuscany.sca.common.xml.stax.databinding.xml.XmlNode#namespaces() + */ + public Map namespaces() { + if (type != Type.ELEMENT) { + return null; + } + if (namespaces == null) { + namespaces = new HashMap(); + NamedNodeMap attrs = node.getAttributes(); + for (int i = 0; i < attrs.getLength(); i++) { + Attr attr = (Attr)attrs.item(i); + if ("xmlns".equals(attr.getPrefix())) { + namespaces.put(attr.getLocalName(), attr.getValue()); + } + if ("xmlns".equals(attr.getName())) { + namespaces.put("", attr.getValue()); + } + } + } + return namespaces; + } + + public Type getType() { + return type; + } + +} diff --git a/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/DelegatingNamespaceContext.java b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/DelegatingNamespaceContext.java new file mode 100644 index 0000000000..21a857491b --- /dev/null +++ b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/DelegatingNamespaceContext.java @@ -0,0 +1,310 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.common.xml.stax; + +import java.util.ArrayList; +import java.util.EmptyStackException; +import java.util.Iterator; +import java.util.List; + +import javax.xml.namespace.NamespaceContext; + +public class DelegatingNamespaceContext implements NamespaceContext { + private static int count; + + private class WrappingIterator implements Iterator { + + private Iterator containedIterator; + + public WrappingIterator(Iterator containedIterator) { + this.containedIterator = containedIterator; + } + + public Iterator getContainedIterator() { + return containedIterator; + } + + public boolean hasNext() { + return containedIterator.hasNext(); + } + + public Object next() { + return containedIterator.next(); + } + + /** + * As per the contract on the API of Namespace context the returned iterator should be immutable + */ + public void remove() { + throw new UnsupportedOperationException(); + } + + public void setContainedIterator(Iterator containedIterator) { + this.containedIterator = containedIterator; + } + } + + private NamespaceContext parentNsContext; + + private FastStack prefixStack = new FastStack(); + + // Keep two ArrayLists for the prefixes and namespaces. They should be in + // sync + // since the index of the entry will be used to relate them + // use the minimum initial capacity to let things handle memory better + + private FastStack uriStack = new FastStack(); + + /** + * Generates a unique namespace prefix that is not in the scope of the NamespaceContext + * + * @return string + */ + public String generateUniquePrefix() { + String prefix = "p" + count++; + // null should be returned if the prefix is not bound! + while (getNamespaceURI(prefix) != null) { + prefix = "p" + count++; + } + + return prefix; + } + + public String getNamespaceURI(String prefix) { + // do the corrections as per the Javadoc + int index = prefixStack.search(prefix); + if (index != -1) { + return uriStack.get(index); + } + if (parentNsContext != null) { + return parentNsContext.getPrefix(prefix); + } + return null; + } + + public NamespaceContext getParentNsContext() { + return parentNsContext; + } + + public String getPrefix(String uri) { + // do the corrections as per the Javadoc + int index = uriStack.search(uri); + if (index != -1) { + return prefixStack.get(index); + } + + if (parentNsContext != null) { + return parentNsContext.getPrefix(uri); + } + return null; + } + + public Iterator getPrefixes(String uri) { + // create an ArrayList that contains the relevant prefixes + String[] uris = uriStack.toArray(new String[uriStack.size()]); + List tempList = new ArrayList(); + for (int i = uris.length - 1; i >= 0; i--) { + if (uris[i].equals(uri)) { + tempList.add(prefixStack.get(i)); + // we assume that array conversion preserves the order + } + } + // by now all the relevant prefixes are collected + // make a new iterator and provide a wrapper iterator to + // obey the contract on the API + return new WrappingIterator(tempList.iterator()); + } + + /** + * Pop a namespace + */ + public void popNamespace() { + prefixStack.pop(); + uriStack.pop(); + } + + /** + * Register a namespace in this context + * + * @param prefix + * @param uri + */ + public void pushNamespace(String prefix, String uri) { + prefixStack.push(prefix); + uriStack.push(uri); + + } + + public void setParentNsContext(NamespaceContext parentNsContext) { + this.parentNsContext = parentNsContext; + } + + /** + * An implementation of the {@link java.util.Stack} API that is based on an ArrayList instead of a + * Vector, so it is not synchronized to protect against multi-threaded access. The implementation is + * therefore operates faster in environments where you do not need to worry about multiple thread contention. + *

+ * The removal order of an ArrayStack is based on insertion order: The most recently added element is + * removed first. The iteration order is not the same as the removal order. The iterator returns elements + * from the bottom up, whereas the {@link #remove()} method removes them from the top down. + *

+ * Unlike Stack, ArrayStack accepts null entries. + */ + public static class FastStack extends ArrayList { + + /** Ensure Serialization compatibility */ + private static final long serialVersionUID = 2130079159931574599L; + + /** + * Constructs a new empty ArrayStack. The initial size is controlled by ArrayList + * and is currently 10. + */ + public FastStack() { + super(); + } + + /** + * Constructs a new empty ArrayStack with an initial size. + * + * @param initialSize the initial size to use + * @throws IllegalArgumentException if the specified initial size is negative + */ + public FastStack(int initialSize) { + super(initialSize); + } + + /** + * Return true if this stack is currently empty. + *

+ * This method exists for compatibility with java.util.Stack. New users of this class should use + * isEmpty instead. + * + * @return true if the stack is currently empty + */ + public boolean empty() { + return isEmpty(); + } + + /** + * Returns the top item off of this stack without removing it. + * + * @return the top item on the stack + * @throws EmptyStackException if the stack is empty + */ + public T peek() throws EmptyStackException { + int n = size(); + if (n <= 0) { + throw new EmptyStackException(); + } else { + return get(n - 1); + } + } + + /** + * Returns the n'th item down (zero-relative) from the top of this stack without removing it. + * + * @param n the number of items down to go + * @return the n'th item on the stack, zero relative + * @throws EmptyStackException if there are not enough items on the stack to satisfy this request + */ + public T peek(int n) throws EmptyStackException { + int m = (size() - n) - 1; + if (m < 0) { + throw new EmptyStackException(); + } else { + return get(m); + } + } + + /** + * Pops the top item off of this stack and return it. + * + * @return the top item on the stack + * @throws EmptyStackException if the stack is empty + */ + public T pop() throws EmptyStackException { + int n = size(); + if (n <= 0) { + throw new EmptyStackException(); + } else { + return remove(n - 1); + } + } + + /** + * Pushes a new item onto the top of this stack. The pushed item is also returned. This is equivalent to calling + * add. + * + * @param item the item to be added + * @return the item just pushed + */ + public Object push(T item) { + add(item); + return item; + } + + /** + * Returns the top-most index for the object in the stack + * + * @param object the object to be searched for + * @return top-most index, or -1 if not found + */ + public int search(T object) { + int i = size() - 1; // Current index + while (i >= 0) { + T current = get(i); + if ((object == null && current == null) || (object != null && object.equals(current))) { + return i; + } + i--; + } + return -1; + } + + /** + * Returns the element on the top of the stack. + * + * @return the element on the top of the stack + * @throws EmptyStackException if the stack is empty + */ + public T get() { + int size = size(); + if (size == 0) { + throw new EmptyStackException(); + } + return get(size - 1); + } + + /** + * Removes the element on the top of the stack. + * + * @return the removed element + * @throws EmptyStackException if the stack is empty + */ + public T remove() { + int size = size(); + if (size == 0) { + throw new EmptyStackException(); + } + return remove(size - 1); + } + + } + +} diff --git a/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/NameValueArrayStreamReader.java b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/NameValueArrayStreamReader.java new file mode 100644 index 0000000000..5942f23d20 --- /dev/null +++ b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/NameValueArrayStreamReader.java @@ -0,0 +1,404 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.common.xml.stax; + +import javax.xml.namespace.NamespaceContext; +import javax.xml.namespace.QName; +import javax.xml.stream.Location; +import javax.xml.stream.XMLStreamException; + + +public class NameValueArrayStreamReader implements XMLFragmentStreamReader { + + private static final int START_ELEMENT_STATE = 0; + private static final int TEXT_STATE = 1; + private static final int END_ELEMENT_STATE = 2; + private static final int FINAL_END_ELEMENT_STATE = 3; + private static final int START_ELEMENT_STATE_WITH_NULL = 4; + + private DelegatingNamespaceContext namespaceContext = new DelegatingNamespaceContext(); + // the index of the array + private int arrayIndex; + + private QName name; + private String[] values; + + // start element is the default state + private int state = START_ELEMENT_STATE; + + public NameValueArrayStreamReader(QName name, String[] values) { + this.name = name; + this.values = values; + } + + public void setParentNamespaceContext(NamespaceContext nsContext) { + this.namespaceContext.setParentNsContext(nsContext); + } + + public void init() { + // TODO what if the QName namespace has not been declared + } + + public Object getProperty(String string) throws IllegalArgumentException { + return null; + } + + /** + * @throws XMLStreamException + */ + public int next() throws XMLStreamException { + switch (state) { + case START_ELEMENT_STATE: + if (values.length > 0) { + state = TEXT_STATE; + return CHARACTERS; + } else { + state = FINAL_END_ELEMENT_STATE; + return END_ELEMENT; + } + + case START_ELEMENT_STATE_WITH_NULL: + if (arrayIndex == (values.length - 1)) { + state = FINAL_END_ELEMENT_STATE; + } else { + state = END_ELEMENT_STATE; + } + return END_ELEMENT; + case FINAL_END_ELEMENT_STATE: + // oops, not supposed to happen! + throw new XMLStreamException("end already reached!"); + case END_ELEMENT_STATE: + // we've to have more values since this is not the + // last value + // increment the counter + arrayIndex++; + if (values[arrayIndex] == null) { + state = START_ELEMENT_STATE_WITH_NULL; + } else { + state = START_ELEMENT_STATE; + } + return START_ELEMENT; + case TEXT_STATE: + if (arrayIndex == (values.length - 1)) { + state = FINAL_END_ELEMENT_STATE; + return END_ELEMENT; + } else { + state = END_ELEMENT_STATE; + return END_ELEMENT; + } + + default: + throw new XMLStreamException("unknown event type!"); + } + } + + public void require(int i, String string, String string1) throws XMLStreamException { + // nothing done here + } + + public String getElementText() throws XMLStreamException { + return null; // not implemented + } + + public int nextTag() throws XMLStreamException { + return 0; // not implemented + } + + public String getAttributeValue(String string, String string1) { + if (state == TEXT_STATE) { + // TODO something + return null; + } else { + return null; + } + + } + + public int getAttributeCount() { + if (state == START_ELEMENT_STATE_WITH_NULL) { + return 1; + } + if (state == START_ELEMENT_STATE) { + return 0; + } else { + throw new IllegalStateException(); + } + + } + + public QName getAttributeName(int i) { + if (state == START_ELEMENT_STATE_WITH_NULL && i == 0) { + return NIL_QNAME; + } + if (state == START_ELEMENT_STATE) { + return null; + } else { + throw new IllegalStateException(); + } + } + + public String getAttributeNamespace(int i) { + if (state == START_ELEMENT_STATE_WITH_NULL && i == 0) { + return NIL_QNAME.getNamespaceURI(); + } + if (state == START_ELEMENT_STATE) { + return null; + } else { + throw new IllegalStateException(); + } + } + + public String getAttributeLocalName(int i) { + if (state == START_ELEMENT_STATE_WITH_NULL && i == 0) { + return NIL_QNAME.getLocalPart(); + } + if (state == START_ELEMENT_STATE) { + return null; + } else { + throw new IllegalStateException(); + } + } + + public String getAttributePrefix(int i) { + if (state == START_ELEMENT_STATE_WITH_NULL && i == 0) { + return NIL_QNAME.getPrefix(); + } + if (state == START_ELEMENT_STATE) { + return null; + } else { + throw new IllegalStateException(); + } + } + + public String getAttributeType(int i) { + return null; // not implemented + } + + public String getAttributeValue(int i) { + if (state == START_ELEMENT_STATE_WITH_NULL && i == 0) { + return NIL_VALUE_TRUE; + } + if (state == START_ELEMENT_STATE) { + return null; + } else { + throw new IllegalStateException(); + } + } + + public boolean isAttributeSpecified(int i) { + return false; // not supported + } + + public int getNamespaceCount() { + if (state == START_ELEMENT_STATE_WITH_NULL && isXsiNamespacePresent()) { + return 1; + } else { + return 0; + } + + } + + public String getNamespacePrefix(int i) { + if (state == START_ELEMENT_STATE_WITH_NULL && isXsiNamespacePresent() && i == 0) { + return NIL_QNAME.getPrefix(); + } else { + return null; + } + } + + public String getNamespaceURI(int i) { + if (state == START_ELEMENT_STATE_WITH_NULL && isXsiNamespacePresent() && i == 0) { + return NIL_QNAME.getNamespaceURI(); + } else { + return null; + } + } + + public NamespaceContext getNamespaceContext() { + return this.namespaceContext; + } + + public boolean isDone() { + return state == FINAL_END_ELEMENT_STATE; + } + + public int getEventType() { + switch (state) { + case START_ELEMENT_STATE: + return START_ELEMENT; + case END_ELEMENT_STATE: + return END_ELEMENT; + case TEXT_STATE: + return CHARACTERS; + case FINAL_END_ELEMENT_STATE: + return END_ELEMENT; + default: + throw new UnsupportedOperationException(); + // we've no idea what this is!!!!! + } + + } + + public String getText() { + if (state == TEXT_STATE) { + return values[arrayIndex]; + } else { + throw new IllegalStateException(); + } + } + + public char[] getTextCharacters() { + if (state == TEXT_STATE) { + return values[arrayIndex].toCharArray(); + } else { + throw new IllegalStateException(); + } + } + + public int getTextCharacters(int i, char[] chars, int i1, int i2) throws XMLStreamException { + // not implemented + throw new UnsupportedOperationException(); + } + + public int getTextStart() { + if (state == TEXT_STATE) { + return 0; + } else { + throw new IllegalStateException(); + } + } + + public int getTextLength() { + if (state == TEXT_STATE) { + return values[arrayIndex].length(); + } else { + throw new IllegalStateException(); + } + + } + + public String getEncoding() { + return null; + } + + public boolean hasText() { + return state == TEXT_STATE; + } + + public Location getLocation() { + return null; // not supported + } + + public QName getName() { + if (state != TEXT_STATE) { + return name; + } else { + return null; + } + } + + public String getLocalName() { + if (state != TEXT_STATE) { + return name.getLocalPart(); + } else { + return null; + } + } + + public boolean hasName() { + return state != TEXT_STATE; + + } + + public String getNamespaceURI() { + if (state != TEXT_STATE) { + return name.getNamespaceURI(); + } else { + return null; + } + + } + + public String getPrefix() { + if (state != TEXT_STATE) { + return name.getPrefix(); + } else { + return null; + } + } + + public String getVersion() { + return null; // TODO 1.0 ? + } + + public boolean isStandalone() { + return false; + } + + public boolean standaloneSet() { + return false; + } + + public String getCharacterEncodingScheme() { + return null; + } + + public String getPITarget() { + return null; + } + + public String getPIData() { + return null; + } + + public boolean hasNext() throws XMLStreamException { + return state != FINAL_END_ELEMENT_STATE; + } + + public void close() throws XMLStreamException { + // Do nothing - we've nothing to free here + } + + public String getNamespaceURI(String prefix) { + return namespaceContext.getNamespaceURI(prefix); + } + + public boolean isStartElement() { + return state == START_ELEMENT_STATE; + } + + public boolean isEndElement() { + return state == END_ELEMENT_STATE; + } + + public boolean isCharacters() { + return state == TEXT_STATE; + } + + public boolean isWhiteSpace() { + return false; // no whitespaces here + } + + /** + * Test whether the xsi namespace is present + */ + private boolean isXsiNamespacePresent() { + return namespaceContext.getNamespaceURI(NIL_QNAME.getPrefix()) != null; + } +} diff --git a/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/NameValuePairStreamReader.java b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/NameValuePairStreamReader.java new file mode 100644 index 0000000000..b4b655d541 --- /dev/null +++ b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/NameValuePairStreamReader.java @@ -0,0 +1,348 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.common.xml.stax; + +import javax.xml.namespace.NamespaceContext; +import javax.xml.namespace.QName; +import javax.xml.stream.Location; +import javax.xml.stream.XMLStreamException; + + + +public class NameValuePairStreamReader implements XMLFragmentStreamReader { + + private static final int START_ELEMENT_STATE = 0; + private static final int TEXT_STATE = 1; + private static final int END_ELEMENT_STATE = 2; + + private DelegatingNamespaceContext namespaceContext = new DelegatingNamespaceContext(); + + private QName name; + private String value; + + private int state = START_ELEMENT_STATE; + // initiate at the start element state + + // keeps track whether the namespace is declared + // false by default + private boolean nsDeclared; + + public NameValuePairStreamReader(QName name, String value) { + this.name = name; + this.value = value; + } + + public Object getProperty(String key) throws IllegalArgumentException { + return null; + } + + public int next() throws XMLStreamException { + // no need to handle null here. it should have been handled + // already + switch (state) { + case START_ELEMENT_STATE: + state = TEXT_STATE; + return CHARACTERS; + case END_ELEMENT_STATE: + // oops, not supposed to happen! + throw new XMLStreamException("end already reached!"); + case TEXT_STATE: + state = END_ELEMENT_STATE; + return END_ELEMENT; + default: + throw new XMLStreamException("unknown event type!"); + } + } + + public void require(int i, String string, String string1) throws XMLStreamException { + // not implemented + } + + public String getElementText() throws XMLStreamException { + if (state == START_ELEMENT) { + // move to the end state and return the value + state = END_ELEMENT_STATE; + return value; + } else { + throw new XMLStreamException(); + } + + } + + public int nextTag() throws XMLStreamException { + return 0; // TODO + } + + public boolean hasNext() throws XMLStreamException { + return state != END_ELEMENT_STATE; + } + + public void close() throws XMLStreamException { + // Do nothing - we've nothing to free here + } + + public String getNamespaceURI(String prefix) { + return namespaceContext.getNamespaceURI(prefix); + } + + public boolean isStartElement() { + return state == START_ELEMENT_STATE; + } + + public boolean isEndElement() { + return state == END_ELEMENT_STATE; + } + + public boolean isCharacters() { + return state == TEXT_STATE; + } + + public boolean isWhiteSpace() { + return false; // no whitespaces here + } + + public String getAttributeValue(String string, String string1) { + return null; + } + + public int getAttributeCount() { + return 0; + } + + public QName getAttributeName(int i) { + return null; + } + + public String getAttributeNamespace(int i) { + return null; + } + + public String getAttributeLocalName(int i) { + return null; + } + + public String getAttributePrefix(int i) { + return null; + } + + public String getAttributeType(int i) { + return null; + } + + public String getAttributeValue(int i) { + return null; + } + + public boolean isAttributeSpecified(int i) { + return false; // no attributes here + } + + public int getNamespaceCount() { + return nsDeclared ? 1 : 0; + } + + public String getNamespacePrefix(int i) { + return (nsDeclared && i == 0) ? name.getPrefix() : null; + } + + public String getNamespaceURI(int i) { + return (nsDeclared && i == 0) ? name.getNamespaceURI() : null; + } + + public NamespaceContext getNamespaceContext() { + return this.namespaceContext; + } + + public int getEventType() { + switch (state) { + case START_ELEMENT_STATE: + return START_ELEMENT; + case END_ELEMENT_STATE: + return END_ELEMENT; + case TEXT_STATE: + return CHARACTERS; + default: + throw new UnsupportedOperationException(); + // we've no idea what this is!!!!! + } + + } + + public String getText() { + if (state == TEXT_STATE) { + return value; + } else { + throw new IllegalStateException(); + } + } + + public char[] getTextCharacters() { + if (state == TEXT_STATE) { + return value.toCharArray(); + } else { + throw new IllegalStateException(); + } + } + + public int getTextCharacters(int i, char[] chars, int i1, int i2) throws XMLStreamException { + // not implemented + throw new UnsupportedOperationException(); + } + + public int getTextStart() { + if (state == TEXT_STATE) { + return 0; + } else { + throw new IllegalStateException(); + } + } + + public int getTextLength() { + if (state == TEXT_STATE) { + return value.length(); + } else { + throw new IllegalStateException(); + } + + } + + public String getEncoding() { + return null; + } + + public boolean hasText() { + return state == TEXT_STATE; + } + + public Location getLocation() { + return new Location() { + public int getLineNumber() { + return 0; + } + + public int getColumnNumber() { + return 0; + } + + public int getCharacterOffset() { + return 0; + } + + public String getPublicId() { + return null; + } + + public String getSystemId() { + return null; + } + }; + } + + public QName getName() { + if (state != TEXT_STATE) { + return name; + } else { + return null; + } + } + + public String getLocalName() { + if (state != TEXT_STATE) { + return name.getLocalPart(); + } else { + return null; + } + } + + public boolean hasName() { + return state != TEXT_STATE; + + } + + public String getNamespaceURI() { + if (state != TEXT_STATE) { + return name.getNamespaceURI(); + } else { + return null; + } + + } + + public String getPrefix() { + if (state != TEXT_STATE) { + return name.getPrefix(); + } else { + return null; + } + } + + public String getVersion() { + return null; // TODO 1.0 ? + } + + public boolean isStandalone() { + return false; + } + + public boolean standaloneSet() { + return false; + } + + public String getCharacterEncodingScheme() { + return null; + } + + public String getPITarget() { + return null; + } + + public String getPIData() { + return null; + } + + public boolean isDone() { + return state == END_ELEMENT_STATE; + } + + public void setParentNamespaceContext(NamespaceContext nsContext) { + this.namespaceContext.setParentNsContext(nsContext); + } + + public void init() { + // just add the current elements namespace and prefix to the this + // elements nscontext + addToNsMap(name.getPrefix(), name.getNamespaceURI()); + + } + + /** + * @param prefix + * @param uri + */ + private void addToNsMap(String prefix, String uri) { + // TODO - need to fix this up to cater for cases where + // namespaces are having no prefixes + if (!uri.equals(namespaceContext.getNamespaceURI(prefix))) { + // this namespace is not there. Need to declare it + namespaceContext.pushNamespace(prefix, uri); + nsDeclared = true; + } + } + +} diff --git a/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/NamedProperty.java b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/NamedProperty.java new file mode 100644 index 0000000000..2ddcd4baa5 --- /dev/null +++ b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/NamedProperty.java @@ -0,0 +1,59 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.common.xml.stax; + +import java.util.Map; + +import javax.xml.namespace.QName; + +/** + * A named property + * + * @version $Rev$ $Date$ + */ +public class NamedProperty implements Map.Entry { + private QName key; + + private Object value; + + public NamedProperty(QName key, Object value) { + this.key = key; + this.value = value; + } + + public NamedProperty(String key, Object value) { + this.key = new QName(key); + this.value = value; + } + + public QName getKey() { + return key; + } + + public Object getValue() { + return value; + } + + public Object setValue(Object value) { + Object v = this.value; + this.value = value; + return v; + } +} diff --git a/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/NilElementStreamReader.java b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/NilElementStreamReader.java new file mode 100644 index 0000000000..fc78807cdb --- /dev/null +++ b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/NilElementStreamReader.java @@ -0,0 +1,279 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.common.xml.stax; + +import javax.xml.namespace.NamespaceContext; +import javax.xml.namespace.QName; +import javax.xml.stream.Location; +import javax.xml.stream.XMLStreamException; + +public class NilElementStreamReader implements XMLFragmentStreamReader { + + private static final int END_ELEMENT_STATE = 2; + + private static final int START_ELEMENT_STATE = 1; + private int currentState = START_ELEMENT; + + private QName elementQName; + + public NilElementStreamReader(QName elementQName) { + this.elementQName = elementQName; + } + + public void setParentNamespaceContext(NamespaceContext nsContext) { + // NOOP + } + + public void close() throws XMLStreamException { + // do nothing + } + + public int getAttributeCount() { + return 1; + } + + public String getAttributeLocalName(int i) { + return (i == 0) ? NIL_QNAME.getLocalPart() : null; + } + + public QName getAttributeName(int i) { + return (i == 0) ? NIL_QNAME : null; + } + + public String getAttributeNamespace(int i) { + return (i == 0) ? NIL_QNAME.getNamespaceURI() : null; + } + + public String getAttributePrefix(int i) { + return (i == 0) ? NIL_QNAME.getPrefix() : null; + } + + public String getAttributeType(int i) { + throw new UnsupportedOperationException(); + } + + public String getAttributeValue(int i) { + return (i == 0) ? NIL_VALUE_TRUE : null; + } + + public String getAttributeValue(String string, String string1) { + if (string == null && NIL_QNAME.getLocalPart().equals(string1)) { + return NIL_VALUE_TRUE; + } + return null; + } + + public String getCharacterEncodingScheme() { + throw new UnsupportedOperationException(); + } + + public String getElementText() throws XMLStreamException { + return null; + } + + public String getEncoding() { + return null; + } + + public int getEventType() { + int returnEvent = START_DOCUMENT; + switch (currentState) { + case START_ELEMENT_STATE: + returnEvent = START_ELEMENT; + break; + case END_ELEMENT_STATE: + returnEvent = END_ELEMENT; + break; + } + return returnEvent; + } + + public String getLocalName() { + return elementQName.getLocalPart(); + } + + public Location getLocation() { + return new Location() { + public int getCharacterOffset() { + return 0; + } + + public int getColumnNumber() { + return 0; + } + + public int getLineNumber() { + return 0; + } + + public String getPublicId() { + return null; + } + + public String getSystemId() { + return null; + } + }; + } + + public QName getName() { + return elementQName; + } + + public NamespaceContext getNamespaceContext() { + throw new UnsupportedOperationException(); + } + + public int getNamespaceCount() { + return 0; + } + + public String getNamespacePrefix(int i) { + return null; + } + + public String getNamespaceURI() { + return elementQName.getNamespaceURI(); + } + + public String getNamespaceURI(int i) { + return null; + } + + public String getNamespaceURI(String string) { + if (elementQName.getPrefix() != null && elementQName.getPrefix().equals(string)) { + return elementQName.getNamespaceURI(); + } else { + return null; + } + } + + public String getPIData() { + throw new UnsupportedOperationException(); + } + + public String getPITarget() { + throw new UnsupportedOperationException(); + } + + public String getPrefix() { + return elementQName.getPrefix(); + } + + public Object getProperty(String key) throws IllegalArgumentException { + // since optimization is a global property + // we've to implement it everywhere + return null; + } + + public String getText() { + return null; + } + + public char[] getTextCharacters() { + return new char[0]; + } + + public int getTextCharacters(int i, char[] chars, int i1, int i2) throws XMLStreamException { + return 0; + } + + public int getTextLength() { + return 0; + } + + public int getTextStart() { + return 0; + } + + public String getVersion() { + throw new UnsupportedOperationException(); + } + + public boolean hasName() { + return true; + } + + public boolean hasNext() throws XMLStreamException { + return currentState != END_ELEMENT_STATE; + + } + + public boolean hasText() { + return false; + } + + public void init() { + // NOOP + } + + public boolean isAttributeSpecified(int i) { + return i == 0; + } + + public boolean isCharacters() { + return false; + } + + public boolean isDone() { + return currentState == END_ELEMENT_STATE; + } + + public boolean isEndElement() { + return currentState == END_ELEMENT_STATE; + } + + public boolean isStandalone() { + throw new UnsupportedOperationException(); + } + + public boolean isStartElement() { + return currentState == START_ELEMENT_STATE; + } + + public boolean isWhiteSpace() { + return false; + } + + public int next() throws XMLStreamException { + int returnEvent = START_DOCUMENT; + switch (currentState) { + case START_ELEMENT_STATE: + currentState = END_ELEMENT_STATE; + returnEvent = END_ELEMENT; + break; + case END_ELEMENT_STATE: + throw new XMLStreamException("parser completed!"); + + } + return returnEvent; + } + + public int nextTag() throws XMLStreamException { + throw new UnsupportedOperationException(); + } + + public void require(int i, String string, String string1) throws XMLStreamException { + // nothing + } + + public boolean standaloneSet() { + throw new UnsupportedOperationException(); + } +} diff --git a/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/SimpleXmlNodeImpl.java b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/SimpleXmlNodeImpl.java new file mode 100644 index 0000000000..a28705cff2 --- /dev/null +++ b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/SimpleXmlNodeImpl.java @@ -0,0 +1,112 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.common.xml.stax; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import javax.xml.namespace.QName; + +/** + * @version $Rev$ $Date$ + */ +public class SimpleXmlNodeImpl implements XmlNode { + private static final String XSI_PREFIX = "xsi"; + private static final String XSI_NS = "http://www.w3.org/2001/XMLSchema-instance"; + private static final QName XSI_NIL = new QName(XSI_NS, "nil", XSI_PREFIX); + private static final Map NS_MAP = new HashMap(); + static { + NS_MAP.put(XSI_PREFIX, XSI_NS); + } + + protected Type type; + protected QName name; + protected Object value; + + public SimpleXmlNodeImpl(QName name, Object value) { + this(name, value, name != null ? Type.ELEMENT : Type.CHARACTERS); + } + + public SimpleXmlNodeImpl(QName name, Object value, Type type) { + super(); + this.type = type; + this.name = name; + this.value = value; + } + + /** + * @see org.apache.tuscany.sca.common.xml.stax.databinding.xml.XmlNode#attributes() + */ + public List attributes() { + if (type == Type.ELEMENT && value == null) { + // Nil element + XmlNode attr = new SimpleXmlNodeImpl(XSI_NIL, "true"); + return Arrays.asList(attr); + } + return null; + } + + /** + * @see org.apache.tuscany.sca.common.xml.stax.databinding.xml.XmlNode#children() + */ + public Iterator children() { + if (type == Type.ELEMENT && value != null) { + // Nil element + XmlNode node = new SimpleXmlNodeImpl(null, value); + return Arrays.asList(node).iterator(); + } + return null; + } + + /** + * @see org.apache.tuscany.sca.common.xml.stax.databinding.xml.XmlNode#getName() + */ + public QName getName() { + return name; + } + + /** + * @see org.apache.tuscany.sca.common.xml.stax.databinding.xml.XmlNode#getValue() + */ + public String getValue() { + return value == null ? null : String.valueOf(value); + } + + /** + * @see org.apache.tuscany.sca.common.xml.stax.databinding.xml.XmlNode#namespaces() + */ + public Map namespaces() { + if (type == Type.ELEMENT && value == null) { + return NS_MAP; + } + return null; + } + + public Type getType() { + return type; + } + + public void setType(Type type) { + this.type = type; + } +} diff --git a/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/StAX2SAXAdapter.java b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/StAX2SAXAdapter.java new file mode 100644 index 0000000000..12550781d3 --- /dev/null +++ b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/StAX2SAXAdapter.java @@ -0,0 +1,256 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.common.xml.stax; + +import javax.xml.namespace.QName; +import javax.xml.stream.Location; +import javax.xml.stream.XMLStreamConstants; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import org.xml.sax.Attributes; +import org.xml.sax.ContentHandler; +import org.xml.sax.Locator; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +/** + * Adapter that converts from StAX to SAX event streams. Currently the following + * SAX events are not generated: + *

    + *
  • ignorableWhitespace
  • + *
  • skippedEntity
  • + *
      + * Also the following StAX events are not mapped: + *
        + *
      • CDATA
      • + *
      • COMMENT
      • + *
      • DTD
      • + *
      • ENTITY_DECLARATION
      • + *
      • ENTITY_REFERENCE
      • + *
      • NOTATION_DECLARATION
      • + *
      • SPACE
      • + *
      + * StAX ATTRIBUTE events are ignored but the equivalent attributes (derived from + * the START_ELEMENT event) are supplied in the SAX startElement event's + * Attributes parameter. If the adaptor is configured to pass namespace prefixes + * then namespace information will also be included in the Attributes; StAX + * NAMESPACE events are ignored.

      Another issue is namespace processing. If + * the reader is positioned at a sub-node, we cannot capture all the in-scope + * namespace bindings. Therefore we cannot re-create a proper SAX event stream + * from a StAX parser.

      For example

      <a:root xmlns:a="foo" + * xmlns:b="bar"><b:sub>a:foo</b:sub></a:root>

      And if + * you are handed a parser at <b:sub>, then your SAX events should look + * like:

      <b:sub xmlns:a="foo" xmlns:b="bar">a:foo</b:sub>

      + * not:

      <b:sub>a:foo</b:sub>

      Proposal: we change the + * receiver of SAX events (SDOXMLResourceImpl) so that it uses NamespaceContext + * to resolve prefix (as opposed to record start/endPrefixMappings and use it + * for resolution.) + * + * @version $Rev$ $Date$ + */ +public class StAX2SAXAdapter { + private final boolean namespacePrefixes; + + /** + * Construct a new StAX to SAX adapter that will convert a StAX event stream + * into a SAX event stream. + * + * @param namespacePrefixes whether xmlns attributes should be included in + * startElement events; + */ + public StAX2SAXAdapter(boolean namespacePrefixes) { + this.namespacePrefixes = namespacePrefixes; + } + + /** + * Pull events from the StAX stream and dispatch to the SAX ContentHandler. + * The StAX stream would typically be located on a START_DOCUMENT or + * START_ELEMENT event and when this method returns it will be located on + * the associated END_DOCUMENT or END_ELEMENT event. Behaviour with other + * start events is undefined. + * + * @param reader StAX event source to read + * @param handler SAX ContentHandler for processing events + * @throws XMLStreamException if there was a problem reading the stream + * @throws SAXException passed through from the ContentHandler + */ + public void parse(XMLStreamReader reader, ContentHandler handler) throws XMLStreamException, SAXException { + handler.setDocumentLocator(new LocatorAdaptor(reader.getLocation())); + + // remembers the nest level of elements to know when we are done + int level = 0; + int event = reader.getEventType(); + while (true) { + switch (event) { + case XMLStreamConstants.START_DOCUMENT: + level++; + handler.startDocument(); + break; + case XMLStreamConstants.START_ELEMENT: + level++; + handleStartElement(reader, handler); + break; + case XMLStreamConstants.PROCESSING_INSTRUCTION: + handler.processingInstruction(reader.getPITarget(), reader.getPIData()); + break; + case XMLStreamConstants.CHARACTERS: + handler.characters(reader.getTextCharacters(), reader.getTextStart(), reader + .getTextLength()); + break; + case XMLStreamConstants.END_ELEMENT: + handleEndElement(reader, handler); + level--; + if (level == 0) { + return; + } + break; + case XMLStreamConstants.END_DOCUMENT: + handler.endDocument(); + return; + /* + * uncomment to handle all events rather than just mapped + * ones // StAX events that are not mapped to SAX case + * XMLStreamConstants.COMMENT: case + * XMLStreamConstants.SPACE: case + * XMLStreamConstants.ENTITY_REFERENCE: case + * XMLStreamConstants.DTD: case XMLStreamConstants.CDATA: + * case XMLStreamConstants.NOTATION_DECLARATION: case + * XMLStreamConstants.ENTITY_DECLARATION: break; // StAX + * events handled in START_ELEMENT case + * XMLStreamConstants.ATTRIBUTE: case + * XMLStreamConstants.NAMESPACE: break; default: throw new + * AssertionError("Unknown StAX event: " + event); + */ + } + event = reader.next(); + } + } + + private void handleStartElement(XMLStreamReader reader, ContentHandler handler) throws SAXException { + // send startPrefixMapping events immediately before startElement event + int nsCount = reader.getNamespaceCount(); + for (int i = 0; i < nsCount; i++) { + String prefix = reader.getNamespacePrefix(i); + if (prefix == null) { // true for default namespace + prefix = ""; + } + handler.startPrefixMapping(prefix, reader.getNamespaceURI(i)); + } + + // fire startElement + QName qname = reader.getName(); + String prefix = qname.getPrefix(); + String rawname; + if (prefix == null || prefix.length() == 0) { + rawname = qname.getLocalPart(); + } else { + rawname = prefix + ':' + qname.getLocalPart(); + } + Attributes attrs = getAttributes(reader); + handler.startElement(qname.getNamespaceURI(), qname.getLocalPart(), rawname, attrs); + } + + private static void handleEndElement(XMLStreamReader reader, ContentHandler handler) throws SAXException { + // fire endElement + QName qname = reader.getName(); + handler.endElement(qname.getNamespaceURI(), qname.getLocalPart(), qname.toString()); + + // send endPrefixMapping events immediately after endElement event + // we send them in the opposite order to that returned but this is not + // actually required by SAX + int nsCount = reader.getNamespaceCount(); + for (int i = nsCount - 1; i >= 0; i--) { + String prefix = reader.getNamespacePrefix(i); + if (prefix == null) { // true for default namespace + prefix = ""; + } + handler.endPrefixMapping(prefix); + } + } + + /** + * Get the attributes associated with the current START_ELEMENT event. + * + * @return the StAX attributes converted to org.xml.sax.Attributes + */ + private Attributes getAttributes(XMLStreamReader reader) { + assert reader.getEventType() == XMLStreamConstants.START_ELEMENT; + + AttributesImpl attrs = new AttributesImpl(); + + // add namespace declarations if required + if (namespacePrefixes) { + for (int i = 0; i < reader.getNamespaceCount(); i++) { + String prefix = reader.getNamespacePrefix(i); + String uri = reader.getNamespaceURI(i); + attrs.addAttribute(null, prefix, "xmlns:" + prefix, "CDATA", uri); + } + } + + // Regular attributes + for (int i = 0; i < reader.getAttributeCount(); i++) { + String uri = reader.getAttributeNamespace(i); + if (uri == null) { + uri = ""; + } + String localName = reader.getAttributeLocalName(i); + String prefix = reader.getAttributePrefix(i); + String qname; + if (prefix == null || prefix.length() == 0) { + qname = localName; + } else { + qname = prefix + ':' + localName; + } + String type = reader.getAttributeType(i); + String value = reader.getAttributeValue(i); + + attrs.addAttribute(uri, localName, qname, type, value); + } + + return attrs; + } + + /** + * Adaptor for mapping Locator information. + */ + private static final class LocatorAdaptor implements Locator { + private final Location location; + + private LocatorAdaptor(Location location) { + this.location = location; + } + + public int getColumnNumber() { + return location == null ? 0 : location.getColumnNumber(); + } + + public int getLineNumber() { + return location == null ? 0 : location.getLineNumber(); + } + + public String getPublicId() { + return location == null ? "" : location.getPublicId(); + } + + public String getSystemId() { + return location == null ? "" : location.getSystemId(); + } + } +} diff --git a/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/StAXHelper.java b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/StAXHelper.java new file mode 100644 index 0000000000..444d6ccabf --- /dev/null +++ b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/StAXHelper.java @@ -0,0 +1,87 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.common.xml.stax; + +import java.io.InputStream; +import java.io.OutputStream; +import java.io.Reader; +import java.io.StringReader; +import java.io.StringWriter; +import java.io.Writer; + +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLOutputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; +import javax.xml.transform.Source; + + + +public final class StAXHelper { + private static final XMLInputFactory INPUT_FACTORY = XMLInputFactory.newInstance(); + private static final XMLOutputFactory OUTPUT_FACTORY = XMLOutputFactory.newInstance(); + + private StAXHelper() { + } + + public static XMLStreamReader createXMLStreamReader(InputStream inputStream) throws XMLStreamException { + return INPUT_FACTORY.createXMLStreamReader(inputStream); + } + + public static XMLStreamReader createXMLStreamReader(Reader reader) throws XMLStreamException { + return INPUT_FACTORY.createXMLStreamReader(reader); + } + + public static XMLStreamReader createXMLStreamReader(Source source) throws XMLStreamException { + return INPUT_FACTORY.createXMLStreamReader(source); + } + + public static XMLStreamReader createXMLStreamReader(String string) throws XMLStreamException { + StringReader reader = new StringReader(string); + return createXMLStreamReader(reader); + } + + public static String save(XMLStreamReader reader) throws XMLStreamException { + StringWriter writer = new StringWriter(); + save(reader, writer); + return writer.toString(); + } + + public static void save(XMLStreamReader reader, OutputStream outputStream) throws XMLStreamException { + XMLStreamSerializer serializer = new XMLStreamSerializer(); + XMLStreamWriter streamWriter = OUTPUT_FACTORY.createXMLStreamWriter(outputStream); + serializer.serialize(reader, streamWriter); + streamWriter.flush(); + } + + public static void save(XMLStreamReader reader, Writer writer) throws XMLStreamException { + XMLStreamSerializer serializer = new XMLStreamSerializer(); + XMLStreamWriter streamWriter = OUTPUT_FACTORY.createXMLStreamWriter(writer); + serializer.serialize(reader, streamWriter); + streamWriter.flush(); + } + + public static void save(XMLStreamReader reader, XMLStreamWriter writer) throws XMLStreamException { + XMLStreamSerializer serializer = new XMLStreamSerializer(); + serializer.serialize(reader, writer); + writer.flush(); + } + +} diff --git a/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/WrappingXMLStreamReader.java b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/WrappingXMLStreamReader.java new file mode 100644 index 0000000000..a237bb457e --- /dev/null +++ b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/WrappingXMLStreamReader.java @@ -0,0 +1,100 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.common.xml.stax; + +import javax.xml.namespace.NamespaceContext; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.util.StreamReaderDelegate; + +public class WrappingXMLStreamReader extends StreamReaderDelegate implements XMLFragmentStreamReader { + + private boolean done; + private int level; + + public WrappingXMLStreamReader(XMLStreamReader realReader) throws XMLStreamException { + super(realReader); + if (realReader == null) { + throw new UnsupportedOperationException("Reader cannot be null"); + } + + if (realReader instanceof XMLFragmentStreamReader) { + ((XMLFragmentStreamReader)realReader).init(); + } + + if (realReader.getEventType() == START_DOCUMENT) { + // Position to the 1st element + realReader.nextTag(); + } + if (realReader.getEventType() != START_ELEMENT) { + throw new IllegalStateException("The reader is not positioned at START_DOCUMENT or START_ELEMENT"); + } + this.done = false; + this.level = 1; + } + + @Override + public boolean hasNext() throws XMLStreamException { + return !done && super.hasNext(); + } + + @Override + public int next() throws XMLStreamException { + if (!hasNext()) { + throw new IllegalStateException("No more events"); + } + int event = super.next(); + if (!super.hasNext()) { + done = true; + } + if (event == START_ELEMENT) { + level++; + } else if (event == END_ELEMENT) { + level--; + if (level == 0) { + done = true; + } + } + return event; + } + + @Override + public int nextTag() throws XMLStreamException { + int event = 0; + while (true) { + event = next(); + if (event == START_ELEMENT || event == END_ELEMENT) { + return event; + } + } + } + + public void setParentNamespaceContext(NamespaceContext nsContext) { + // nothing to do here + } + + public void init() { + // Nothing to do here + } + + public boolean isDone() { + return done; + } + +} diff --git a/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/XMLDocumentStreamReader.java b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/XMLDocumentStreamReader.java new file mode 100644 index 0000000000..8ee9ea2242 --- /dev/null +++ b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/XMLDocumentStreamReader.java @@ -0,0 +1,482 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.common.xml.stax; + +import java.util.NoSuchElementException; + +import javax.xml.namespace.NamespaceContext; +import javax.xml.namespace.QName; +import javax.xml.stream.Location; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +/** + * This class is derived from Apache Axis2 class + * org.apache.axis2.util.StreamWrapper. It's used wrap a XMLStreamReader to + * create a XMLStreamReader representing a document and it will produce + * START_DOCUMENT, END_DOCUMENT events. + * + * @version $Rev$ $Date$ + */ +public class XMLDocumentStreamReader implements XMLStreamReader { + private static final int STATE_COMPLETE_AT_NEXT = 2; // The wrapper + // will produce + // END_DOCUMENT + + private static final int STATE_COMPLETED = 3; // Done + + private static final int STATE_INIT = 0; // The wrapper will produce + // START_DOCUMENT + + private static final int STATE_SWITCHED = 1; // The real reader will + // produce events + + private XMLStreamReader realReader; + private boolean fragment; + private int level = 1; + + private int state = STATE_INIT; + + public XMLDocumentStreamReader(XMLStreamReader realReader) { + if (realReader == null) { + throw new UnsupportedOperationException("Reader cannot be null"); + } + + this.realReader = realReader; + + if (realReader instanceof XMLFragmentStreamReader) { + ((XMLFragmentStreamReader)realReader).init(); + } + + // If the real reader is positioned at START_DOCUMENT, always use + // the real reader + if (realReader.getEventType() == START_DOCUMENT) { + fragment = false; + state = STATE_SWITCHED; + } + } + + public void close() throws XMLStreamException { + realReader.close(); + } + + public int getAttributeCount() { + if (isDelegating()) { + return realReader.getAttributeCount(); + } else { + throw new IllegalStateException(); + } + } + + public String getAttributeLocalName(int i) { + if (isDelegating()) { + return realReader.getAttributeLocalName(i); + } else { + throw new IllegalStateException(); + } + } + + public QName getAttributeName(int i) { + if (isDelegating()) { + return realReader.getAttributeName(i); + } else { + throw new IllegalStateException(); + } + } + + public String getAttributeNamespace(int i) { + if (isDelegating()) { + return realReader.getAttributeNamespace(i); + } else { + throw new IllegalStateException(); + } + } + + public String getAttributePrefix(int i) { + if (isDelegating()) { + return realReader.getAttributePrefix(i); + } else { + throw new IllegalStateException(); + } + } + + public String getAttributeType(int i) { + if (isDelegating()) { + return realReader.getAttributeType(i); + } else { + throw new IllegalStateException(); + } + } + + public String getAttributeValue(int i) { + if (isDelegating()) { + return realReader.getAttributeValue(i); + } else { + throw new IllegalStateException(); + } + } + + public String getAttributeValue(String s, String s1) { + if (isDelegating()) { + return realReader.getAttributeValue(s, s1); + } else { + throw new IllegalStateException(); + } + } + + public String getCharacterEncodingScheme() { + return realReader.getCharacterEncodingScheme(); + } + + public String getElementText() throws XMLStreamException { + if (isDelegating()) { + return realReader.getElementText(); + } else { + throw new XMLStreamException(); + } + } + + public String getEncoding() { + return realReader.getEncoding(); + } + + public int getEventType() { + int event = -1; + switch (state) { + case STATE_SWITCHED: + case STATE_COMPLETE_AT_NEXT: + event = realReader.getEventType(); + break; + case STATE_INIT: + event = START_DOCUMENT; + break; + case STATE_COMPLETED: + event = END_DOCUMENT; + break; + } + return event; + } + + public String getLocalName() { + if (isDelegating()) { + return realReader.getLocalName(); + } else { + throw new IllegalStateException(); + } + } + + public Location getLocation() { + if (isDelegating()) { + return realReader.getLocation(); + } else { + return null; + } + } + + public QName getName() { + if (isDelegating()) { + return realReader.getName(); + } else { + throw new IllegalStateException(); + } + } + + public NamespaceContext getNamespaceContext() { + return realReader.getNamespaceContext(); + } + + public int getNamespaceCount() { + if (isDelegating()) { + return realReader.getNamespaceCount(); + } else { + throw new IllegalStateException(); + } + } + + public String getNamespacePrefix(int i) { + if (isDelegating()) { + return realReader.getNamespacePrefix(i); + } else { + throw new IllegalStateException(); + } + } + + public String getNamespaceURI() { + if (isDelegating()) { + return realReader.getNamespaceURI(); + } else { + throw new IllegalStateException(); + } + } + + public String getNamespaceURI(int i) { + if (isDelegating()) { + return realReader.getNamespaceURI(i); + } else { + throw new IllegalStateException(); + } + } + + public String getNamespaceURI(String s) { + if (isDelegating()) { + return realReader.getNamespaceURI(s); + } else { + throw new IllegalStateException(); + } + } + + public String getPIData() { + if (isDelegating()) { + return realReader.getPIData(); + } else { + throw new IllegalStateException(); + } + } + + public String getPITarget() { + if (isDelegating()) { + return realReader.getPITarget(); + } else { + throw new IllegalStateException(); + } + } + + public String getPrefix() { + if (isDelegating()) { + return realReader.getPrefix(); + } else { + throw new IllegalStateException(); + } + } + + public Object getProperty(String s) throws IllegalArgumentException { + if (isDelegating()) { + return realReader.getProperty(s); + } else { + throw new IllegalArgumentException(); + } + } + + public String getText() { + if (isDelegating()) { + return realReader.getText(); + } else { + throw new IllegalStateException(); + } + } + + public char[] getTextCharacters() { + if (isDelegating()) { + return realReader.getTextCharacters(); + } else { + throw new IllegalStateException(); + } + } + + public int getTextCharacters(int i, char[] chars, int i1, int i2) throws XMLStreamException { + if (isDelegating()) { + return realReader.getTextCharacters(i, chars, i1, i2); + } else { + throw new IllegalStateException(); + } + } + + public int getTextLength() { + if (isDelegating()) { + return realReader.getTextLength(); + } else { + throw new IllegalStateException(); + } + } + + public int getTextStart() { + if (isDelegating()) { + return realReader.getTextStart(); + } else { + throw new IllegalStateException(); + } + } + + public String getVersion() { + if (isDelegating()) { + return realReader.getVersion(); + } else { + return null; + } + } + + public boolean hasName() { + if (isDelegating()) { + return realReader.hasName(); + } else { + return false; + } + } + + public boolean hasNext() throws XMLStreamException { + if (state == STATE_COMPLETE_AT_NEXT) { + return true; + } else if (state == STATE_COMPLETED) { + return false; + } else if (state == STATE_SWITCHED) { + return realReader.hasNext(); + } else { + return true; + } + } + + public boolean hasText() { + if (isDelegating()) { + return realReader.hasText(); + } else { + return false; + } + } + + public boolean isAttributeSpecified(int i) { + if (isDelegating()) { + return realReader.isAttributeSpecified(i); + } else { + return false; + } + } + + public boolean isCharacters() { + if (isDelegating()) { + return realReader.isCharacters(); + } else { + return false; + } + } + + private boolean isDelegating() { + return state == STATE_SWITCHED || state == STATE_COMPLETE_AT_NEXT; + } + + public boolean isEndElement() { + if (isDelegating()) { + return realReader.isEndElement(); + } else { + return false; + } + } + + public boolean isStandalone() { + if (isDelegating()) { + return realReader.isStandalone(); + } else { + return false; + } + } + + public boolean isStartElement() { + if (isDelegating()) { + return realReader.isStartElement(); + } else { + return false; + } + } + + public boolean isWhiteSpace() { + if (isDelegating()) { + return realReader.isWhiteSpace(); + } else { + return false; + } + } + + public int next() throws XMLStreamException { + int returnEvent; + + switch (state) { + case STATE_SWITCHED: + returnEvent = realReader.next(); + if (returnEvent == END_DOCUMENT) { + state = STATE_COMPLETED; + } else if (!realReader.hasNext()) { + state = STATE_COMPLETE_AT_NEXT; + } + if (fragment && returnEvent == END_ELEMENT) { + level--; + if (level == 0) { + // We are now at the end of the top-level element in the fragment + state = STATE_COMPLETE_AT_NEXT; + } + } + if (fragment && returnEvent == START_ELEMENT) { + level++; + } + break; + case STATE_INIT: + state = STATE_SWITCHED; + returnEvent = realReader.getEventType(); + if (returnEvent == START_ELEMENT) { + // The real reader is positioned at the top-level element in the fragment + level = 0; + fragment = true; + } + break; + case STATE_COMPLETE_AT_NEXT: + state = STATE_COMPLETED; + returnEvent = END_DOCUMENT; + break; + case STATE_COMPLETED: + // oops - no way we can go beyond this + throw new NoSuchElementException("End of stream has reached."); + default: + throw new UnsupportedOperationException(); + } + + return returnEvent; + } + + public int nextTag() throws XMLStreamException { + if (isDelegating()) { + int returnEvent = realReader.nextTag(); + if (fragment && returnEvent == END_ELEMENT) { + level--; + if (level == 0) { + // We are now at the end of the top-level element in the fragment + state = STATE_COMPLETE_AT_NEXT; + } + } + if (fragment && returnEvent == START_ELEMENT) { + level++; + } + return returnEvent; + } else { + throw new XMLStreamException(); + } + } + + public void require(int i, String s, String s1) throws XMLStreamException { + if (isDelegating()) { + realReader.require(i, s, s1); + } + } + + public boolean standaloneSet() { + if (isDelegating()) { + return realReader.standaloneSet(); + } else { + return false; + } + } +} diff --git a/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/XMLFragmentStreamReader.java b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/XMLFragmentStreamReader.java new file mode 100644 index 0000000000..defe3595be --- /dev/null +++ b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/XMLFragmentStreamReader.java @@ -0,0 +1,53 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.common.xml.stax; + +import javax.xml.namespace.NamespaceContext; +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamReader; + +public interface XMLFragmentStreamReader extends XMLStreamReader { + QName NIL_QNAME = new QName("http://www.w3.org/2001/XMLSchema-instance", "nil", "xsi"); + String NIL_VALUE_TRUE = "true"; + + /** + * this will help to handle Text within the current element. user should + * pass the element text to the property list as this ELEMENT_TEXT as the + * key. This key deliberately has a space in it so that it is not a valid + * XML name + */ + String ELEMENT_TEXT = "Element Text"; + + /** + * Extra method to query the state of the pullparser + */ + boolean isDone(); + + /** + * add the parent namespace context to this parser + */ + void setParentNamespaceContext(NamespaceContext nsContext); + + /** + * Initiate the parser - this will do whatever the needed tasks to initiate + * the parser and must be called before attempting any specific parsing + * using this parser + */ + void init(); +} diff --git a/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/XMLFragmentStreamReaderImpl.java b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/XMLFragmentStreamReaderImpl.java new file mode 100644 index 0000000000..2e42ac868f --- /dev/null +++ b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/XMLFragmentStreamReaderImpl.java @@ -0,0 +1,858 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.common.xml.stax; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import javax.xml.namespace.NamespaceContext; +import javax.xml.namespace.QName; +import javax.xml.stream.Location; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + + +/** + * This is the new implementation of the XMLFramentStreamReader. The approach + * here is simple When the pull parser needs to generate events for a particular + * name-value(s) pair it always hands over (delegates) the task to another pull + * parser which knows how to deal with it The common types of name value pairs + * we'll come across are + *

        + *
      • String name/QName name - String value + *
      • String name/QName name - String[] value + *
      • QName name/String name - XMLStreamReader value + *
      • QName name/String name - XMLStreamable value + *
      • QName name/String name - Java bean + *
      • QName name/String name - Datahandler + * + *
      + *

      As for the attributes, these are the possible combinations in the array + *

        + *
      • String name/QName name - String value + *
      + * Note that certain array methods have been deliberately removed to avoid + * complications. The generated code will take the trouble to lay the elements + * of the array in the correct order

      Hence there will be a parser impl + * that knows how to handle these types, and this parent parser will always + * delegate these tasks to the child pullparasers in effect this is one huge + * state machine that has only a few states and delegates things down to the + * child parsers whenever possible

      + * + * @version $Rev$ $Date$ + */ +public class XMLFragmentStreamReaderImpl implements XMLFragmentStreamReader { + + private static final int DELEGATED_STATE = 2; + private static final int END_ELEMENT_STATE = 1; + // states for this pullparser - it can only have four states + private static final int START_ELEMENT_STATE = 0; + private static final int TEXT_STATE = 3; + + protected NamedProperty[] attributes; + + // reference to the child reader + protected XMLFragmentStreamReader childReader; + // current property index + // initialized at zero + protected int index; + protected Map declaredNamespaceMap = new HashMap(); + protected QName elementQName; + + // we always create a new namespace context + protected DelegatingNamespaceContext namespaceContext = new DelegatingNamespaceContext(); + + protected NamedProperty[] elements; + + // integer field that keeps the state of this + // parser. + protected int state = START_ELEMENT_STATE; + + /* + * we need to pass in a namespace context since when delegated, we've no + * idea of the current namespace context. So it needs to be passed on here! + */ + public XMLFragmentStreamReaderImpl(QName elementQName, NamedProperty[] elements, NamedProperty[] attributes) { + // validate the lengths, since both the arrays are supposed + // to have + this.elements = elements == null ? new NamedProperty[0] : elements; + this.elementQName = elementQName; + this.attributes = attributes == null ? new NamedProperty[0] : attributes; + } + + protected XMLFragmentStreamReaderImpl(QName elementQName) { + this.elementQName = elementQName; + } + + /** + * add the namespace context + */ + + public void setParentNamespaceContext(NamespaceContext nsContext) { + // register the namespace context passed in to this + this.namespaceContext.setParentNsContext(nsContext); + + } + + protected NamedProperty[] getElements() { + return elements; + } + + protected NamedProperty[] getAttributes() { + return attributes; + } + + protected QName[] getNamespaces() { + return new QName[0]; + } + + /** + * @param prefix + * @param uri + */ + protected void addToNsMap(String prefix, String uri) { + if (!uri.equals(namespaceContext.getNamespaceURI(prefix))) { + namespaceContext.pushNamespace(prefix, uri); + declaredNamespaceMap.put(prefix, uri); + } + } + + public void close() throws XMLStreamException { + // do nothing here - we have no resources to free + } + + public int getAttributeCount() { + return (state == DELEGATED_STATE) ? childReader.getAttributeCount() : (state == START_ELEMENT_STATE + ? getAttributes().length : 0); + } + + public String getAttributeLocalName(int i) { + if (state == DELEGATED_STATE) { + return childReader.getAttributeLocalName(i); + } else if (state == START_ELEMENT_STATE) { + QName name = getAttributeName(i); + if (name == null) { + return null; + } else { + return name.getLocalPart(); + } + } else { + throw new IllegalStateException(); + } + } + + /** + * @param i + */ + public QName getAttributeName(int i) { + if (state == DELEGATED_STATE) { + return childReader.getAttributeName(i); + } else if (state == START_ELEMENT_STATE) { + if ((i >= (getAttributes().length)) || i < 0) { // out of range + return null; + } else { + // get the attribute pointer + QName attribPointer = getAttributes()[i].getKey(); + // case one - attrib name is null + // this should be the pointer to the OMAttribute then + if (attribPointer == null) { + throw new UnsupportedOperationException(); + } else if (attribPointer instanceof QName) { + return attribPointer; + } else { + return null; + } + } + } else { + throw new IllegalStateException(); // as per the API contract + } + + } + + public String getAttributeNamespace(int i) { + if (state == DELEGATED_STATE) { + return childReader.getAttributeNamespace(i); + } else if (state == START_ELEMENT_STATE) { + QName name = getAttributeName(i); + if (name == null) { + return null; + } else { + return name.getNamespaceURI(); + } + } else { + throw new IllegalStateException(); + } + } + + public String getAttributePrefix(int i) { + if (state == DELEGATED_STATE) { + return childReader.getAttributePrefix(i); + } else if (state == START_ELEMENT_STATE) { + QName name = getAttributeName(i); + if (name == null) { + return null; + } else { + return name.getPrefix(); + } + } else { + throw new IllegalStateException(); + } + } + + public String getAttributeType(int i) { + return null; // not supported + } + + public String getAttributeValue(int i) { + if (state == DELEGATED_STATE) { + return childReader.getAttributeValue(i); + } else if (state == START_ELEMENT_STATE) { + if ((i >= (getAttributes().length)) || i < 0) { // out of range + return null; + } else { + // get the attribute pointer + QName attribPointer = getAttributes()[i].getKey(); + Object omAttribObj = getAttributes()[i].getValue(); + // case one - attrib name is null + // this should be the pointer to the OMAttribute then + if (attribPointer == null) { + throw new UnsupportedOperationException(); + } else if (attribPointer instanceof QName) { + return (String)omAttribObj; + } else { + return null; + } + } + } else { + throw new IllegalStateException(); + } + + } + + public String getAttributeValue(String nsUri, String localName) { + + int attribCount = getAttributeCount(); + String returnValue = null; + QName attribQualifiedName; + for (int i = 0; i < attribCount; i++) { + attribQualifiedName = getAttributeName(i); + if (nsUri == null) { + if (localName.equals(attribQualifiedName.getLocalPart())) { + returnValue = getAttributeValue(i); + break; + } + } else { + if (localName.equals(attribQualifiedName.getLocalPart()) && nsUri.equals(attribQualifiedName + .getNamespaceURI())) { + returnValue = getAttributeValue(i); + break; + } + } + + } + + return returnValue; + } + + public String getCharacterEncodingScheme() { + return null; // TODO - should we return something for this ? + } + + /** + * TODO implement the right contract for this + * + * @throws XMLStreamException + */ + public String getElementText() throws XMLStreamException { + if (state == DELEGATED_STATE) { + return childReader.getElementText(); + } else { + return null; + } + + } + + // ///////////////////////////////////////////////////////////////////////// + // / attribute handling + // ///////////////////////////////////////////////////////////////////////// + + public String getEncoding() { + if (state == DELEGATED_STATE) { + return childReader.getEncoding(); + } else { + // we've no idea what the encoding is going to be in this case + // perhaps we ought to return some constant here, which the user + // might + // have access to change! + return null; + } + } + + public int getEventType() { + if (state == START_ELEMENT_STATE) { + return START_ELEMENT; + } else if (state == END_ELEMENT_STATE) { + return END_ELEMENT; + } else if (state == TEXT_STATE) { + return CHARACTERS; + } else { // this is the delegated state + return childReader.getEventType(); + } + } + + public String getLocalName() { + if (state == DELEGATED_STATE) { + return childReader.getLocalName(); + } else if (state != TEXT_STATE) { + return elementQName.getLocalPart(); + } else { + throw new IllegalStateException(); + } + } + + /** + */ + public Location getLocation() { + // return a default location + return new Location() { + public int getCharacterOffset() { + return 0; + } + + public int getColumnNumber() { + return 0; + } + + public int getLineNumber() { + return 0; + } + + public String getPublicId() { + return null; + } + + public String getSystemId() { + return null; + } + }; + } + + public QName getName() { + if (state == DELEGATED_STATE) { + return childReader.getName(); + } else if (state != TEXT_STATE) { + return elementQName; + } else { + throw new IllegalStateException(); + } + + } + + public NamespaceContext getNamespaceContext() { + if (state == DELEGATED_STATE) { + return childReader.getNamespaceContext(); + } else { + return namespaceContext; + } + + } + + public int getNamespaceCount() { + if (state == DELEGATED_STATE) { + return childReader.getNamespaceCount(); + } else { + return declaredNamespaceMap.size(); + } + } + + /** + * @param i + */ + public String getNamespacePrefix(int i) { + if (state == DELEGATED_STATE) { + return childReader.getNamespacePrefix(i); + } else if (state != TEXT_STATE) { + // order the prefixes + String[] prefixes = makePrefixArray(); + if ((i >= prefixes.length) || (i < 0)) { + return null; + } else { + return prefixes[i]; + } + + } else { + throw new IllegalStateException(); + } + + } + + public String getNamespaceURI() { + if (state == DELEGATED_STATE) { + return childReader.getNamespaceURI(); + } else if (state == TEXT_STATE) { + return null; + } else { + return elementQName.getNamespaceURI(); + } + } + + // ///////////////////////////////////////////////////////////////////////// + // //////////// end of attribute handling + // ///////////////////////////////////////////////////////////////////////// + + // ////////////////////////////////////////////////////////////////////////// + // //////////// namespace handling + // ////////////////////////////////////////////////////////////////////////// + + public String getNamespaceURI(int i) { + if (state == DELEGATED_STATE) { + return childReader.getNamespaceURI(i); + } else if (state != TEXT_STATE) { + String namespacePrefix = getNamespacePrefix(i); + return namespacePrefix == null ? null : (String)declaredNamespaceMap.get(namespacePrefix); + } else { + throw new IllegalStateException(); + } + + } + + public String getNamespaceURI(String prefix) { + return namespaceContext.getNamespaceURI(prefix); + } + + public String getPIData() { + throw new UnsupportedOperationException("Yet to be implemented !!"); + } + + public String getPITarget() { + throw new UnsupportedOperationException("Yet to be implemented !!"); + } + + public String getPrefix() { + if (state == DELEGATED_STATE) { + return childReader.getPrefix(); + } else if (state == TEXT_STATE) { + return null; + } else { + String prefix = elementQName.getPrefix(); + return "".equals(prefix) ? null : prefix; + } + } + + // ///////////////////////////////////////////////////////////////////////// + // /////// end of namespace handling + // ///////////////////////////////////////////////////////////////////////// + + /** + * @param key + * @throws IllegalArgumentException + */ + public Object getProperty(String key) throws IllegalArgumentException { + if (state == START_ELEMENT_STATE || state == END_ELEMENT_STATE) { + return null; + } else if (state == TEXT_STATE) { + return null; + } else if (state == DELEGATED_STATE) { + return childReader.getProperty(key); + } else { + return null; + } + + } + + public String getText() { + if (state == DELEGATED_STATE) { + return childReader.getText(); + } else if (state == TEXT_STATE) { + return (String)getElements()[index - 1].getValue(); + } else { + throw new IllegalStateException(); + } + } + + public char[] getTextCharacters() { + if (state == DELEGATED_STATE) { + return childReader.getTextCharacters(); + } else if (state == TEXT_STATE) { + return getElements()[index - 1].getValue() == null ? new char[0] : ((String)getElements()[index - 1] + .getValue()).toCharArray(); + } else { + throw new IllegalStateException(); + } + } + + private int copy(int sourceStart, char[] target, int targetStart, int length) { + char[] source = getTextCharacters(); + if (sourceStart > source.length) { + throw new IndexOutOfBoundsException("source start > source length"); + } + int sourceLen = source.length - sourceStart; + if (length > sourceLen) { + length = sourceLen; + } + System.arraycopy(source, sourceStart, target, targetStart, length); + return sourceLen; + } + + public int getTextCharacters(int i, char[] chars, int i1, int i2) throws XMLStreamException { + if (state == DELEGATED_STATE) { + return childReader.getTextCharacters(i, chars, i1, i2); + } else if (state == TEXT_STATE) { + return copy(i, chars, i1, i2); + } else { + throw new IllegalStateException(); + } + } + + public int getTextLength() { + if (state == DELEGATED_STATE) { + return childReader.getTextLength(); + } else if (state == TEXT_STATE) { + return getTextCharacters().length; + } else { + throw new IllegalStateException(); + } + } + + public int getTextStart() { + if (state == DELEGATED_STATE) { + return childReader.getTextStart(); + } else if (state == TEXT_STATE) { + return 0; // assume text always starts at 0 + } else { + throw new IllegalStateException(); + } + } + + public String getVersion() { + return null; + } + + public boolean hasName() { + // since this parser always has a name, the hasName + // has to return true if we are still navigating this element + // if not we should ask the child reader for it. + if (state == DELEGATED_STATE) { + return childReader.hasName(); + } else { + return state != TEXT_STATE; + } + } + + /** + * @throws XMLStreamException + */ + public boolean hasNext() throws XMLStreamException { + if (state == DELEGATED_STATE) { + if (childReader.isDone()) { + // the child reader is done. We shouldn't be getting the + // hasNext result from the child pullparser then + return true; + } else { + return childReader.hasNext(); + } + } else { + return state == START_ELEMENT_STATE || state == TEXT_STATE; + + } + } + + /** + * check the validity of this implementation + */ + public boolean hasText() { + if (state == DELEGATED_STATE) { + return childReader.hasText(); + } else { + return state == TEXT_STATE; + } + + } + + /** + * we need to split out the calling to the populate namespaces separately + * since this needs to be done *after* setting the parent namespace context. + * We cannot assume it will happen at construction! + */ + public void init() { + // here we have an extra issue to attend to. we need to look at the + // prefixes and URIs (the combination) and populate a HashMap of + // namespaces. The HashMap of namespaces will be used to serve the + // namespace context + + populateNamespaceContext(); + } + + public boolean isAttributeSpecified(int i) { + return false; // not supported + } + + public boolean isCharacters() { + if (state == START_ELEMENT_STATE || state == END_ELEMENT_STATE) { + return false; + } + return childReader.isCharacters(); + } + + /** + * are we done ? + */ + public boolean isDone() { + return state == END_ELEMENT_STATE; + } + + public boolean isEndElement() { + if (state == START_ELEMENT_STATE) { + return false; + } else if (state == END_ELEMENT_STATE) { + return true; + } + return childReader.isEndElement(); + } + + public boolean isStandalone() { + return true; + } + + public boolean isStartElement() { + if (state == START_ELEMENT_STATE) { + return true; + } else if (state == END_ELEMENT_STATE) { + return false; + } + return childReader.isStartElement(); + } + + public boolean isWhiteSpace() { + if (state == START_ELEMENT_STATE || state == END_ELEMENT_STATE) { + return false; + } + return childReader.isWhiteSpace(); + } + + /** + * Get the prefix list from the HashTable and take that into an array + */ + private String[] makePrefixArray() { + String[] prefixes = declaredNamespaceMap.keySet().toArray(new String[declaredNamespaceMap.size()]); + Arrays.sort(prefixes); + return prefixes; + } + + /** + * By far this should be the most important method in this class this method + * changes the state of the parser + */ + public int next() throws XMLStreamException { + int returnEvent = -1; // invalid state is the default state + switch (state) { + case START_ELEMENT_STATE: + // current element is start element. We should be looking at the + // property list and making a pullparser for the property value + if (getElements() == null || getElements().length == 0) { + // no properties - move to the end element state + // straight away + state = END_ELEMENT_STATE; + returnEvent = END_ELEMENT; + } else { + // there are properties. now we should delegate this task to + // a + // child reader depending on the property type + returnEvent = processProperties(); + + } + break; + case END_ELEMENT_STATE: + // we've reached the end element already. If the user tries to + // push + // further ahead then it is an exception + throw new XMLStreamException("Trying to go beyond the end of the pullparser"); + + case DELEGATED_STATE: + if (childReader.isDone()) { + // we've reached the end! + if (index > (getElements().length - 1)) { + state = END_ELEMENT_STATE; + returnEvent = END_ELEMENT; + } else { + returnEvent = processProperties(); + } + } else { + returnEvent = childReader.next(); + } + break; + + case TEXT_STATE: + // if there are any more event we should be delegating to + // processProperties. if not we just return an end element + if (index > (getElements().length - 1)) { + state = END_ELEMENT_STATE; + returnEvent = END_ELEMENT; + } else { + returnEvent = processProperties(); + } + break; + } + return returnEvent; + } + + // ///////////////////////////////////////////////////////////////////////// + // / Other utility methods + // //////////////////////////////////////////////////////////////////////// + + /** + * TODO implement this + * + * @throws XMLStreamException + */ + public int nextTag() throws XMLStreamException { + return 0; + } + + /** + * Populates a namespace context + */ + private void populateNamespaceContext() { + + // first add the current element namespace to the namespace context + // declare it if not found + addToNsMap(elementQName.getPrefix(), elementQName.getNamespaceURI()); + + for (QName n : getNamespaces()) { + addToNsMap(n.getPrefix(), n.getNamespaceURI()); + } + + // traverse through the attributes and populate the namespace context + // the attrib list can be of many combinations + // the valid combinations are + // String - String + // QName - QName + // null - OMAttribute + + for (int i = 0; i < getAttributes().length; i++) { // jump in two + QName attrQName = getAttributes()[i].getKey(); + if (!"".equals(attrQName.getNamespaceURI())) { + addToNsMap(attrQName.getPrefix(), attrQName.getNamespaceURI()); + } + } + } + + /** + * A convenient method to reuse the properties + * + * @return event to be thrown + * @throws XMLStreamException + */ + private int processProperties() throws XMLStreamException { + // move to the next property depending on the current property + // index + QName propertyQName = getElements()[index].getKey(); + boolean textFound = false; + if (propertyQName == null) { + throw new XMLStreamException("property key cannot be null!"); + } else if (ELEMENT_TEXT.equals(propertyQName.getLocalPart())) { + // propPointer being a String has a special case + // that is it can be a the special constant ELEMENT_TEXT that + // says this text event + textFound = true; + } + + // OK! we got the key. Now look at the value + Object propertyValue = getElements()[index].getValue(); + // cater for the special case now + if (textFound) { + // no delegation here - make the parser null and immediately + // return with the event characters + childReader = null; + state = TEXT_STATE; + ++index; + return CHARACTERS; + } else if (propertyValue == null) { + // if the value is null we delegate the work to a nullable + // parser + childReader = new NilElementStreamReader(propertyQName); + childReader.setParentNamespaceContext(this.namespaceContext); + childReader.init(); + } else if (propertyValue instanceof String) { + // strings are handled by the NameValuePairStreamReader + childReader = new NameValuePairStreamReader(propertyQName, (String)propertyValue); + childReader.setParentNamespaceContext(this.namespaceContext); + childReader.init(); + } else if (propertyValue instanceof String[]) { + // string[] are handled by the NameValueArrayStreamReader + // if the array is empty - skip it + if (((String[])propertyValue).length == 0) { + // advance the index + ++index; + return processProperties(); + } else { + childReader = new NameValueArrayStreamReader(propertyQName, (String[])propertyValue); + childReader.setParentNamespaceContext(this.namespaceContext); + childReader.init(); + } + + } else if (propertyValue instanceof XMLStreamable) { + // ADBbean has it's own method to get a reader + XMLStreamReader reader = ((XMLStreamable)propertyValue).getXMLStreamReader(propertyQName); + // we know for sure that this is an ADB XMLStreamreader. + // However we need to make sure that it is compatible + if (reader instanceof XMLFragmentStreamReader) { + childReader = (XMLFragmentStreamReader)reader; + childReader.setParentNamespaceContext(this.namespaceContext); + childReader.init(); + } else { + // wrap it to make compatible + childReader = new WrappingXMLStreamReader(reader); + } + } else if (propertyValue instanceof XMLStreamReader) { + XMLStreamReader reader = (XMLStreamReader)propertyValue; + if (reader instanceof XMLFragmentStreamReader) { + childReader = (XMLFragmentStreamReader)reader; + childReader.setParentNamespaceContext(this.namespaceContext); + childReader.init(); + } else { + // wrap it to make compatible + childReader = new WrappingXMLStreamReader(reader); + } + + } else { + // all special possibilities has been tried! Let's treat + // the thing as a bean and try generating events from it + throw new UnsupportedOperationException("Property type is not supported"); + // we cannot register the namespace context here + } + + // set the state here + state = DELEGATED_STATE; + // we are done with the delegation + // increment the property index + ++index; + return childReader.getEventType(); + } + + public void require(int i, String string, String string1) throws XMLStreamException { + throw new UnsupportedOperationException(); + } + + public boolean standaloneSet() { + return true; + } + +} diff --git a/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/XMLStreamSerializer.java b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/XMLStreamSerializer.java new file mode 100644 index 0000000000..2a86611fcb --- /dev/null +++ b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/XMLStreamSerializer.java @@ -0,0 +1,287 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.common.xml.stax; + +import javax.xml.namespace.NamespaceContext; +import javax.xml.stream.XMLStreamConstants; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; + +/** + * The XMLStreamSerializer pulls events from the XMLStreamReader and dumps into the XMLStreamWriter + * + * @version $Rev$ $Date$ + */ +public class XMLStreamSerializer implements XMLStreamConstants { + public static final String NAMESPACE_PREFIX = "ns"; + private static int namespaceSuffix; + + /* + * The behavior of the Serializer is such that it returns when it encounters the starting element for the second + * time. The depth variable tracks the depth of the Serializer and tells it when to return. Note that it is assumed + * that this Serialization starts on an Element. + */ + + /** + * Field depth + */ + private int depth; + + /** + * Generates a unique namespace prefix that is not in the scope of the NamespaceContext + * + * @param nsCtxt + * @return string + */ + private String generateUniquePrefix(NamespaceContext nsCtxt) { + String prefix = NAMESPACE_PREFIX + namespaceSuffix++; + // null should be returned if the prefix is not bound! + while (nsCtxt.getNamespaceURI(prefix) != null) { + prefix = NAMESPACE_PREFIX + namespaceSuffix++; + } + + return prefix; + } + + /** + * Method serialize. + * + * @param node + * @param writer + * @throws XMLStreamException + */ + public void serialize(XMLStreamReader node, XMLStreamWriter writer) throws XMLStreamException { + serializeNode(node, writer); + } + + /** + * @param reader + * @param writer + * @throws XMLStreamException + */ + protected void serializeAttributes(XMLStreamReader reader, XMLStreamWriter writer) throws XMLStreamException { + int count = reader.getAttributeCount(); + String prefix; + String namespaceName; + String writerPrefix; + for (int i = 0; i < count; i++) { + prefix = reader.getAttributePrefix(i); + namespaceName = reader.getAttributeNamespace(i); + /* + * Due to parser implementations returning null as the namespace URI (for the empty namespace) we need to + * make sure that we deal with a namespace name that is not null. The best way to work around this issue is + * to set the namespace URI to "" if it is null + */ + if (namespaceName == null) { + namespaceName = ""; + } + + writerPrefix = writer.getPrefix(namespaceName); + + if (!"".equals(namespaceName)) { + // prefix has already being declared but this particular + // attrib has a + // no prefix attached. So use the prefix provided by the + // writer + if (writerPrefix != null && (prefix == null || prefix.equals(""))) { + writer.writeAttribute(writerPrefix, namespaceName, reader.getAttributeLocalName(i), reader + .getAttributeValue(i)); + + // writer prefix is available but different from the + // current + // prefix of the attrib. We should be declaring the new + // prefix + // as a namespace declaration + } else if (prefix != null && !"".equals(prefix) && !prefix.equals(writerPrefix)) { + writer.writeNamespace(prefix, namespaceName); + writer.writeAttribute(prefix, namespaceName, reader.getAttributeLocalName(i), reader + .getAttributeValue(i)); + + // prefix is null (or empty), but the namespace name is + // valid! it has not + // being written previously also. So we need to generate + // a prefix + // here + } else if (prefix == null || prefix.equals("")) { + prefix = generateUniquePrefix(writer.getNamespaceContext()); + writer.writeNamespace(prefix, namespaceName); + writer.writeAttribute(prefix, namespaceName, reader.getAttributeLocalName(i), reader + .getAttributeValue(i)); + } else { + writer.writeAttribute(prefix, namespaceName, reader.getAttributeLocalName(i), reader + .getAttributeValue(i)); + } + } else { + // empty namespace is equal to no namespace! + writer.writeAttribute(reader.getAttributeLocalName(i), reader.getAttributeValue(i)); + } + + } + } + + /** + * Method serializeCData. + * + * @param reader + * @param writer + * @throws XMLStreamException + */ + protected void serializeCData(XMLStreamReader reader, XMLStreamWriter writer) throws XMLStreamException { + writer.writeCData(reader.getText()); + } + + /** + * Method serializeComment. + * + * @param reader + * @param writer + * @throws XMLStreamException + */ + protected void serializeComment(XMLStreamReader reader, XMLStreamWriter writer) throws XMLStreamException { + writer.writeComment(reader.getText()); + } + + /** + * @param reader + * @param writer + * @throws XMLStreamException + */ + protected void serializeElement(XMLStreamReader reader, XMLStreamWriter writer) throws XMLStreamException { + String prefix = reader.getPrefix(); + String nameSpaceName = reader.getNamespaceURI(); + if (nameSpaceName != null) { + String writerPrefix = writer.getPrefix(nameSpaceName); + if (writerPrefix != null) { + writer.writeStartElement(nameSpaceName, reader.getLocalName()); + } else { + if (prefix != null) { + writer.writeStartElement(prefix, reader.getLocalName(), nameSpaceName); + writer.writeNamespace(prefix, nameSpaceName); + // writer.setPrefix(prefix, nameSpaceName); + } else { + // [rfeng] We need to set default NS 1st before calling writeStateElement + writer.setDefaultNamespace(nameSpaceName); + writer.writeStartElement(nameSpaceName, reader.getLocalName()); + writer.writeDefaultNamespace(nameSpaceName); + } + } + } else { + writer.writeStartElement(reader.getLocalName()); + } + + // add the namespaces + int count = reader.getNamespaceCount(); + String namespacePrefix; + for (int i = 0; i < count; i++) { + namespacePrefix = reader.getNamespacePrefix(i); + // [rfeng] The following is commented out to allow to default ns + // if (namespacePrefix != null && namespacePrefix.length() == 0) { + // continue; + // } + + serializeNamespace(namespacePrefix, reader.getNamespaceURI(i), writer); + } + + // add attributes + serializeAttributes(reader, writer); + + } + + /** + * Method serializeEndElement. + * + * @param writer + * @throws XMLStreamException + */ + protected void serializeEndElement(XMLStreamWriter writer) throws XMLStreamException { + writer.writeEndElement(); + } + + /** + * Method serializeNamespace. + * + * @param prefix + * @param uri + * @param writer + * @throws XMLStreamException + */ + private void serializeNamespace(String prefix, String uri, XMLStreamWriter writer) throws XMLStreamException { + String prefix1 = writer.getPrefix(uri); + if (prefix1 == null) { + writer.writeNamespace(prefix, uri); + // writer.setPrefix(prefix, uri); + } + } + + /** + * Method serializeNode. + * + * @param reader + * @param writer + * @throws XMLStreamException + */ + protected void serializeNode(XMLStreamReader reader, XMLStreamWriter writer) throws XMLStreamException { + while (true) { + int event = reader.getEventType(); + if (event == START_ELEMENT) { + serializeElement(reader, writer); + depth++; + } else if (event == ATTRIBUTE) { + serializeAttributes(reader, writer); + } else if (event == CHARACTERS) { + serializeText(reader, writer); + } else if (event == COMMENT) { + serializeComment(reader, writer); + } else if (event == CDATA) { + serializeCData(reader, writer); + } else if (event == END_ELEMENT) { + serializeEndElement(writer); + depth--; + } else if (event == START_DOCUMENT) { + depth++; // if a start document is found then increment + writer.writeStartDocument(); + // the depth + } else if (event == END_DOCUMENT) { + if (depth != 0) { + depth--; // for the end document - reduce the depth + } + writer.writeEndDocument(); + } + if (depth == 0) { + break; + } + if (reader.hasNext()) { + reader.next(); + } else { + break; + } + } + } + + /** + * @param reader + * @param writer + * @throws XMLStreamException + */ + protected void serializeText(XMLStreamReader reader, XMLStreamWriter writer) throws XMLStreamException { + writer.writeCharacters(reader.getText()); + } +} diff --git a/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/XMLStreamable.java b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/XMLStreamable.java new file mode 100644 index 0000000000..b4b1a24f9d --- /dev/null +++ b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/XMLStreamable.java @@ -0,0 +1,37 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.common.xml.stax; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamReader; + +/** + * An interface represents data that can be read using StAX streaming + * + * @version $Rev$ $Date$ + */ +public interface XMLStreamable { + /** + * Get the XMLStreamReader for StAX processing + * + * @param rootElementName the name of the element to be generated + * @return Returns a pull parser. + */ + XMLStreamReader getXMLStreamReader(QName rootElementName); +} diff --git a/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/XmlNode.java b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/XmlNode.java new file mode 100644 index 0000000000..75a820a620 --- /dev/null +++ b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/XmlNode.java @@ -0,0 +1,69 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.common.xml.stax; + +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import javax.xml.namespace.QName; + +/** + * @version $Rev$ $Date$ + */ +public interface XmlNode { + enum Type {ELEMENT, ATTRIBUTE, CHARACTERS, READER}; + /** + * Returns the children of the receiver as an Iterator. + */ + Iterator children(); + + /** + * Returns the attributes of the element as an List. Namespace declarations + * should be excluded. + * + * @return + */ + List attributes(); + + /** + * Returns a map of prefix to namespace URI + * @return + */ + Map namespaces(); + + /** + * Return the QName of the element. If it's for a text node, the name is null. + * @return + */ + QName getName(); + + /** + * Return the text value of the leaf element + * @return + */ + T getValue(); + + /** + * Return the type of the XML node + * @return + */ + Type getType(); +} diff --git a/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/XmlNodeIterator.java b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/XmlNodeIterator.java new file mode 100644 index 0000000000..080f9c21e0 --- /dev/null +++ b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/XmlNodeIterator.java @@ -0,0 +1,355 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.common.xml.stax; + +import java.util.ArrayList; +import java.util.EmptyStackException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import javax.xml.namespace.NamespaceContext; + +/** + * @version $Rev$ $Date$ + */ +public class XmlNodeIterator implements Iterator { + public static final int START = 0; + public static final int END = 1; + + protected FastStack stack; + protected int state; + protected NamespaceContextImpl nsContext; + + public XmlNodeIterator(XmlNode rootNode) { + super(); + List v = new ArrayList(1); + v.add(rootNode); + stack = new FastStack(); + Iterator i = v.iterator(); + stack.push(new ElementHolder(null, i)); + this.state = START; + this.nsContext = new NamespaceContextImpl(null); + } + + public boolean hasNext() { + return !(stack.empty() || (state == END && stack.peek().parent == null)); + } + + public XmlNode next() { + this.state = START; + ElementHolder element = stack.peek(); + Iterator it = element.children; + if (it == null || (!it.hasNext())) { + // End of the children, return END event of parent + stack.pop(); + this.state = END; + this.nsContext = (NamespaceContextImpl)nsContext.getParent(); + return element.parent; + } + XmlNode node = it.next(); + stack.push(new ElementHolder(node, node.children())); + this.nsContext = new NamespaceContextImpl(this.nsContext); + populateNamespaces(node); + return node; + } + + public void remove() { + throw new UnsupportedOperationException(); + } + + public int getState() { + return state; + } + + public NamespaceContext getNamespaceContext() { + return nsContext; + } + + private void populateNamespaces(XmlNode element) { + if (element.getName() != null) { + if (element.namespaces() != null) { + for (Map.Entry e : element.namespaces().entrySet()) { + nsContext.register(e.getKey(), e.getValue()); + } + } + } + } + + private static class ElementHolder { + private XmlNode parent; + private Iterator children; + + public ElementHolder(XmlNode parent, Iterator children) { + this.parent = parent; + this.children = children; + } + } + + private static class NamespaceContextImpl implements NamespaceContext { + private NamespaceContext parent; + private Map map = new HashMap(); + + /** + * @param parent + */ + public NamespaceContextImpl(NamespaceContext parent) { + super(); + this.parent = parent; + if (parent == null) { + map.put("xml", "http://www.w3.org/XML/1998/namespace"); + map.put("xmlns", "http://www.w3.org/2000/xmlns/"); + } + } + + public String getNamespaceURI(String prefix) { + if (prefix == null) { + throw new IllegalArgumentException("Prefix is null"); + } + + String ns = (String)map.get(prefix); + if (ns != null) { + return ns; + } + if (parent != null) { + return parent.getNamespaceURI(prefix); + } + return null; + } + + public String getPrefix(String nsURI) { + if (nsURI == null) + throw new IllegalArgumentException("Namespace is null"); + for (Iterator> i = map.entrySet().iterator(); i.hasNext();) { + Map.Entry entry = i.next(); + if (entry.getValue().equals(nsURI)) { + return entry.getKey(); + } + } + if (parent != null) { + return parent.getPrefix(nsURI); + } + return null; + } + + public Iterator getPrefixes(String nsURI) { + List prefixList = new ArrayList(); + for (Iterator> i = map.entrySet().iterator(); i.hasNext();) { + Map.Entry entry = i.next(); + if (entry.getValue().equals(nsURI)) { + prefixList.add(entry.getKey()); + } + } + final Iterator currentIterator = prefixList.iterator(); + final Iterator parentIterator = parent != null ? null : parent.getPrefixes(nsURI); + return new Iterator() { + + public boolean hasNext() { + return currentIterator.hasNext() || (parentIterator != null && parentIterator.hasNext()); + } + + public Object next() { + if (!hasNext()) { + throw new IllegalStateException("End of iterator has reached"); + } + return currentIterator.hasNext() ? currentIterator.next() : parentIterator.next(); + } + + public void remove() { + throw new UnsupportedOperationException(); + } + + }; + + } + + public void register(String prefix, String ns) { + map.put(prefix, ns); + } + + public NamespaceContext getParent() { + return parent; + } + + @Override + public String toString() { + StringBuffer sb = new StringBuffer(map.toString()); + if (parent != null) { + sb.append("\nParent: "); + sb.append(parent); + } + return sb.toString(); + } + } + + /** + * An implementation of the {@link java.util.Stack} API that is based on an ArrayList instead of a + * Vector, so it is not synchronized to protect against multi-threaded access. The implementation is + * therefore operates faster in environments where you do not need to worry about multiple thread contention. + *

      + * The removal order of an ArrayStack is based on insertion order: The most recently added element is + * removed first. The iteration order is not the same as the removal order. The iterator returns elements + * from the bottom up, whereas the {@link #remove()} method removes them from the top down. + *

      + * Unlike Stack, ArrayStack accepts null entries. + */ + public static class FastStack extends ArrayList { + + /** Ensure Serialization compatibility */ + private static final long serialVersionUID = 2130079159931574599L; + + /** + * Constructs a new empty ArrayStack. The initial size is controlled by ArrayList + * and is currently 10. + */ + public FastStack() { + super(); + } + + /** + * Constructs a new empty ArrayStack with an initial size. + * + * @param initialSize the initial size to use + * @throws IllegalArgumentException if the specified initial size is negative + */ + public FastStack(int initialSize) { + super(initialSize); + } + + /** + * Return true if this stack is currently empty. + *

      + * This method exists for compatibility with java.util.Stack. New users of this class should use + * isEmpty instead. + * + * @return true if the stack is currently empty + */ + public boolean empty() { + return isEmpty(); + } + + /** + * Returns the top item off of this stack without removing it. + * + * @return the top item on the stack + * @throws EmptyStackException if the stack is empty + */ + public T peek() throws EmptyStackException { + int n = size(); + if (n <= 0) { + throw new EmptyStackException(); + } else { + return get(n - 1); + } + } + + /** + * Returns the n'th item down (zero-relative) from the top of this stack without removing it. + * + * @param n the number of items down to go + * @return the n'th item on the stack, zero relative + * @throws EmptyStackException if there are not enough items on the stack to satisfy this request + */ + public T peek(int n) throws EmptyStackException { + int m = (size() - n) - 1; + if (m < 0) { + throw new EmptyStackException(); + } else { + return get(m); + } + } + + /** + * Pops the top item off of this stack and return it. + * + * @return the top item on the stack + * @throws EmptyStackException if the stack is empty + */ + public T pop() throws EmptyStackException { + int n = size(); + if (n <= 0) { + throw new EmptyStackException(); + } else { + return remove(n - 1); + } + } + + /** + * Pushes a new item onto the top of this stack. The pushed item is also returned. This is equivalent to calling + * add. + * + * @param item the item to be added + * @return the item just pushed + */ + public Object push(T item) { + add(item); + return item; + } + + /** + * Returns the top-most index for the object in the stack + * + * @param object the object to be searched for + * @return top-most index, or -1 if not found + */ + public int search(T object) { + int i = size() - 1; // Current index + while (i >= 0) { + T current = get(i); + if ((object == null && current == null) || (object != null && object.equals(current))) { + return i; + } + i--; + } + return -1; + } + + /** + * Returns the element on the top of the stack. + * + * @return the element on the top of the stack + * @throws EmptyStackException if the stack is empty + */ + public T get() { + int size = size(); + if (size == 0) { + throw new EmptyStackException(); + } + return get(size - 1); + } + + /** + * Removes the element on the top of the stack. + * + * @return the removed element + * @throws EmptyStackException if the stack is empty + */ + public T remove() { + int size = size(); + if (size == 0) { + throw new EmptyStackException(); + } + return remove(size - 1); + } + + } + +} diff --git a/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/XmlTreeStreamReaderImpl.java b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/XmlTreeStreamReaderImpl.java new file mode 100644 index 0000000000..93295b3d43 --- /dev/null +++ b/java/sca/contrib/modules/common-xml/src/main/java/org/apache/tuscany/sca/common/xml/stax/XmlTreeStreamReaderImpl.java @@ -0,0 +1,531 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.common.xml.stax; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import javax.xml.namespace.NamespaceContext; +import javax.xml.namespace.QName; +import javax.xml.stream.Location; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +/** + * + * @version $Rev$ $Date$ + */ +public class XmlTreeStreamReaderImpl implements XMLStreamReader { + + protected int state; + protected XmlNodeIterator iterator; + protected XmlNode current; + + protected XMLStreamReader reader; + + /* + * we need to pass in a namespace context since when delegated, we've no + * idea of the current namespace context. So it needs to be passed on here! + */ + public XmlTreeStreamReaderImpl(XmlNode root) { + this.iterator = new XmlNodeIterator(root); + this.current = null; + this.state = START_DOCUMENT; + this.reader = null; + } + + public void close() throws XMLStreamException { + if (reader != null) { + reader.close(); + } + } + + private void checkElementState() { + if (getEventType() != START_ELEMENT && getEventType() != END_ELEMENT) { + throw new IllegalStateException(); + } + } + + private List getAttributes() { + if (current != null && current.attributes() != null) { + return current.attributes(); + } else { + return Collections.emptyList(); + } + } + + public int getAttributeCount() { + checkElementState(); + if (reader != null) { + return reader.getAttributeCount(); + } + return getAttributes().size(); + } + + public String getAttributeLocalName(int i) { + checkElementState(); + if (reader != null) { + return reader.getAttributeLocalName(i); + } + return getAttributes().get(i).getName().getLocalPart(); + } + + /** + * @param i + */ + public QName getAttributeName(int i) { + checkElementState(); + if (reader != null) { + return reader.getAttributeName(i); + } + return getAttributes().get(i).getName(); + } + + public String getAttributeNamespace(int i) { + checkElementState(); + if (reader != null) { + return reader.getAttributeNamespace(i); + } + return getAttributes().get(i).getName().getNamespaceURI(); + } + + public String getAttributePrefix(int i) { + checkElementState(); + if (reader != null) { + return reader.getAttributePrefix(i); + } + return getAttributes().get(i).getName().getPrefix(); + } + + public String getAttributeType(int i) { + if (reader != null) { + return reader.getAttributeType(i); + } + return null; // not supported + } + + public String getAttributeValue(int i) { + checkElementState(); + if (reader != null) { + return reader.getAttributeValue(i); + } + return getAttributes().get(i).getValue(); + } + + public String getAttributeValue(String nsUri, String localName) { + checkElementState(); + if (reader != null) { + return reader.getAttributeValue(nsUri, localName); + } + int count = getAttributeCount(); + String value = null; + QName attrQName; + for (int i = 0; i < count; i++) { + attrQName = getAttributeName(i); + if (nsUri == null) { + if (localName.equals(attrQName.getLocalPart())) { + value = getAttributeValue(i); + break; + } + } else { + if (localName.equals(attrQName.getLocalPart()) && nsUri.equals(attrQName.getNamespaceURI())) { + value = getAttributeValue(i); + break; + } + } + + } + + return value; + } + + public String getCharacterEncodingScheme() { + if (reader != null) { + return reader.getCharacterEncodingScheme(); + } + return "UTF-8"; + } + + public String getElementText() throws XMLStreamException { + checkElementState(); + if (reader != null) { + return reader.getElementText(); + } + return current.getValue(); + } + + public String getEncoding() { + if (reader != null) { + return reader.getEncoding(); + } + return "UTF-8"; + } + + public int getEventType() { + return state; + } + + public String getLocalName() { + checkElementState(); + if (reader != null) { + return reader.getLocalName(); + } + return current.getName().getLocalPart(); + } + + /** + */ + public Location getLocation() { + if (reader != null) { + return reader.getLocation(); + } + // return a default location + return new Location() { + public int getCharacterOffset() { + return 0; + } + + public int getColumnNumber() { + return 0; + } + + public int getLineNumber() { + return 0; + } + + public String getPublicId() { + return null; + } + + public String getSystemId() { + return null; + } + }; + } + + public QName getName() { + checkElementState(); + if (reader != null) { + return reader.getName(); + } + return current.getName(); + } + + public NamespaceContext getNamespaceContext() { + if (reader != null) { + return reader.getNamespaceContext(); + } + return iterator.getNamespaceContext(); + } + + private Map getNamespaces() { + if (current != null && current.namespaces() != null) { + return current.namespaces(); + } else { + return Collections.emptyMap(); + } + } + + public int getNamespaceCount() { + checkElementState(); + if (reader != null) { + return reader.getNamespaceCount(); + } + return getNamespaces().size(); + } + + /** + * @param i + */ + public String getNamespacePrefix(int i) { + checkElementState(); + if (reader != null) { + return reader.getNamespacePrefix(i); + } + return new ArrayList>(getNamespaces().entrySet()).get(i).getKey(); + } + + public String getNamespaceURI() { + checkElementState(); + if (reader != null) { + return reader.getNamespaceURI(); + } + return current.getName().getNamespaceURI(); + } + + public String getNamespaceURI(int i) { + checkElementState(); + if (reader != null) { + return reader.getNamespaceURI(i); + } + return new ArrayList>(getNamespaces().entrySet()).get(i).getValue(); + } + + public String getNamespaceURI(String prefix) { + if (reader != null) { + return reader.getNamespaceURI(prefix); + } + return getNamespaceContext().getNamespaceURI(prefix); + } + + public String getPIData() { + if (reader != null) { + return reader.getPIData(); + } + throw new UnsupportedOperationException("Yet to be implemented !!"); + } + + public String getPITarget() { + if (reader != null) { + return reader.getPITarget(); + } + throw new UnsupportedOperationException("Yet to be implemented !!"); + } + + public String getPrefix() { + if (reader != null) { + return reader.getPrefix(); + } + if (state == START_ELEMENT || state == END_ELEMENT) { + String prefix = current.getName().getPrefix(); + return "".equals(prefix) ? null : prefix; + } else if (state == START_DOCUMENT) { + return null; + } else { + throw new IllegalStateException("State==" + state); + } + } + + /** + * @param key + * @throws IllegalArgumentException + */ + public Object getProperty(String key) throws IllegalArgumentException { + if (reader != null) { + return reader.getProperty(key); + } + return null; + } + + public String getText() { + if (reader != null) { + return reader.getText(); + } + return current.getValue(); + } + + public char[] getTextCharacters() { + if (reader != null) { + return reader.getTextCharacters(); + } + String value = current.getValue(); + return value == null ? new char[0] : value.toCharArray(); + } + + private int copy(int sourceStart, char[] target, int targetStart, int length) { + char[] source = getTextCharacters(); + if (sourceStart > source.length) { + throw new IndexOutOfBoundsException("source start > source length"); + } + int sourceLen = source.length - sourceStart; + if (length > sourceLen) { + length = sourceLen; + } + System.arraycopy(source, sourceStart, target, targetStart, length); + return sourceLen; + } + + public int getTextCharacters(int i, char[] chars, int i1, int i2) throws XMLStreamException { + if (reader != null) { + return reader.getTextCharacters(i, chars, i1, i2); + } + return copy(i, chars, i1, i2); + } + + public int getTextLength() { + if (reader != null) { + return reader.getTextLength(); + } + return getTextCharacters().length; + } + + public int getTextStart() { + if (reader != null) { + return reader.getTextStart(); + } + return 0; + } + + public String getVersion() { + return "1.0"; + } + + public boolean hasName() { + if (reader != null) { + return reader.hasName(); + } + return current.getName() != null; + } + + /** + * @throws XMLStreamException + */ + public boolean hasNext() throws XMLStreamException { + return iterator.hasNext() || state != END_DOCUMENT || (reader != null && reader.hasNext()); + } + + public boolean hasText() { + if (reader != null) { + return reader.hasText(); + } + return current.getType() == XmlNode.Type.CHARACTERS; + } + + public boolean isAttributeSpecified(int i) { + if (reader != null) { + return reader.isAttributeSpecified(i); + } + return false; // not supported + } + + public boolean isCharacters() { + if (reader != null) { + return reader.isCharacters(); + } + return current.getType() == XmlNode.Type.CHARACTERS; + } + + public boolean isEndElement() { + if (reader != null) { + return reader.isEndElement(); + } + return getEventType() == END_ELEMENT; + } + + public boolean isStandalone() { + return true; + } + + public boolean isStartElement() { + if (reader != null) { + return reader.isStartElement(); + } + return getEventType() == START_ELEMENT; + } + + public boolean isWhiteSpace() { + if (reader != null) { + return reader.isWhiteSpace(); + } + return false; + } + + /** + * By far this should be the most important method in this class this method + * changes the state of the parser + */ + public int next() throws XMLStreamException { + if (!hasNext()) { + throw new IllegalStateException("No more events"); + } + if (reader != null) { + if (!reader.hasNext()) { + this.reader = null; + } else { + // Go to the delegation mode + state = reader.next(); + return state; + } + } + if (!iterator.hasNext()) { + state = END_DOCUMENT; + current = null; + return state; + } + current = iterator.next(); + XmlNode.Type type = current.getType(); + + int itState = iterator.getState(); + if (itState == XmlNodeIterator.END) { + if (type == XmlNode.Type.ELEMENT) { + state = END_ELEMENT; + } else { + // Ignore the pop + state = next(); + } + } + if (itState == XmlNodeIterator.START) { + if (type == XmlNode.Type.ELEMENT) { + state = START_ELEMENT; + } else if (type == XmlNode.Type.CHARACTERS) { + state = CHARACTERS; + } else if (type == XmlNode.Type.READER) { + XMLStreamReader value = current.getValue(); + this.reader = new WrappingXMLStreamReader(value); + state = reader.getEventType(); + return state; + } + } + return state; + } + + /** + * TODO implement this + * + * @throws XMLStreamException + */ + public int nextTag() throws XMLStreamException { + while (true) { + int event = next(); + if (event == START_ELEMENT || event == END_ELEMENT) { + return event; + } + } + } + + public void require(int i, String ns, String localPart) throws XMLStreamException { + if (reader != null) { + reader.require(i, ns, localPart); + return; + } + int event = getEventType(); + if (event != i) { + throw new IllegalStateException("Event type is " + event + " (!=" + i + ")"); + } + QName name = getName(); + String ns1 = name.getNamespaceURI(); + String localName1 = name.getLocalPart(); + + if (ns != null && !ns.equals(ns1)) { + throw new IllegalStateException("Namespace URI is " + ns1 + " (!=" + ns + ")"); + } + + if (localPart != null && !localPart.equals(localName1)) { + throw new IllegalStateException("Local name is " + localName1 + " (!=" + localPart + ")"); + } + + } + + public boolean standaloneSet() { + return true; + } + +} diff --git a/java/sca/contrib/modules/common-xml/src/test/java/org/apache/tuscany/sca/common/xml/stax/StAXHelperTestCase.java b/java/sca/contrib/modules/common-xml/src/test/java/org/apache/tuscany/sca/common/xml/stax/StAXHelperTestCase.java new file mode 100644 index 0000000000..220febe656 --- /dev/null +++ b/java/sca/contrib/modules/common-xml/src/test/java/org/apache/tuscany/sca/common/xml/stax/StAXHelperTestCase.java @@ -0,0 +1,49 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.common.xml.stax; + +import static org.junit.Assert.assertNotNull; + +import javax.xml.stream.XMLStreamReader; + +import org.custommonkey.xmlunit.XMLAssert; +import org.junit.Test; + +/** + * Test Case for StAXHelper + * + * @version $Rev$ $Date$ + */ +public class StAXHelperTestCase { + private static final String XML = + "" + + "" + + ""; + + @Test + public void testHelper() throws Exception { + XMLStreamReader reader = StAXHelper.createXMLStreamReader(XML); + String xml = StAXHelper.save(reader); + XMLAssert.assertXMLEqual(XML, xml); + reader = StAXHelper.createXMLStreamReader(xml); + assertNotNull(reader); + } + +} diff --git a/java/sca/contrib/modules/common-xml/src/test/java/org/apache/tuscany/sca/common/xml/stax/XmlTreeStreamReaderTestCase.java b/java/sca/contrib/modules/common-xml/src/test/java/org/apache/tuscany/sca/common/xml/stax/XmlTreeStreamReaderTestCase.java new file mode 100644 index 0000000000..4063314f3e --- /dev/null +++ b/java/sca/contrib/modules/common-xml/src/test/java/org/apache/tuscany/sca/common/xml/stax/XmlTreeStreamReaderTestCase.java @@ -0,0 +1,204 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.common.xml.stax; + +import java.io.StringReader; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLOutputFactory; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; + +import org.custommonkey.xmlunit.XMLAssert; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * @version $Rev$ $Date$ + */ +public class XmlTreeStreamReaderTestCase { + private static final String IPO_XML = + "" + "" + + " " + + " Helen Zoe" + + " 47 Eden Street" + + " Cambridge" + + " CB1 1JR" + + " " + + " " + + " Robert Smith" + + " 8 Oak Avenue" + + " Old Town" + + " PA" + + " 95819" + + " " + + " " + + " " + + " Lapis necklace" + + " 1" + + " 99.95" + + " Want this for the holidays" + + " 1999-12-05" + + " " + + " " + + ""; + + private static final String XML_RESULT = + "" + "" + + "MyText" + + "" + + " " + + " " + + "Helen Zoe 47 Eden Street " + + "Cambridge CB1 1JR " + + " Robert Smith " + + "8 Oak Avenue Old Town PA " + + "95819 " + + "Lapis necklace 1 " + + "99.95 Want this for the holidays " + + "1999-12-05 "; + private XmlNodeImpl root; + + @Before + public void setUp() throws Exception { + root = new XmlNodeImpl(); + root.name = new QName("http://ns", "e1", "p1"); + + XmlNodeImpl e11 = new XmlNodeImpl(); + e11.name = new QName("http://ns1", "e11", "p2"); + + XmlNodeImpl e12 = new XmlNodeImpl(); + e12.name = new QName("http://ns", "e12"); + + root.children.add(e11); + root.children.add(e12); + + XmlNodeImpl e121 = new XmlNodeImpl(); + e121.name = new QName("http://ns", "e121"); + e12.children.add(e121); + + XmlNodeImpl e111 = new XmlNodeImpl(); + e111.value = "MyText"; + e11.children.add(e111); + + XmlNodeImpl e13 = new XmlNodeImpl(); + e13.value = XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(IPO_XML)); + root.children.add(e13); + + } + + @Test + public void testIterator() { + List elements = new ArrayList(); + XmlNodeIterator i = new XmlNodeIterator(root); + for (; i.hasNext();) { + XmlNode e = i.next(); + elements.add(e.getName()); + } + // System.out.println(elements); + QName[] names = + {new QName("http://ns", "e1"), new QName("http://ns1", "e11"), null, null, new QName("http://ns1", "e11"), + new QName("http://ns", "e12"), new QName("http://ns", "e121"), new QName("http://ns", "e121"), + new QName("http://ns", "e12"), null, null, new QName("http://ns", "e1")}; + Assert.assertEquals(Arrays.asList(names), elements); + } + + @Test + public void testReader() throws Exception { + XmlTreeStreamReaderImpl reader = new XmlTreeStreamReaderImpl(root); + XMLStreamSerializer serializer = new XMLStreamSerializer(); + StringWriter sw = new StringWriter(); + XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(sw); + serializer.serialize(reader, writer); + String xml = sw.toString(); + XMLAssert.assertXMLEqual(XML_RESULT, xml); + } + + private static class XmlNodeImpl implements XmlNode { + private List children = new ArrayList(); + private List attrs = new ArrayList(); + private Map namespaces = new HashMap(); + private QName name; + private Object value = "123"; + + /** + * @see org.apache.tuscany.sca.databinding.xml.XmlNode#attributes() + */ + public List attributes() { + return attrs; + } + + /** + * @see org.apache.tuscany.sca.databinding.xml.XmlNode#children() + */ + public Iterator children() { + return children.iterator(); + } + + /** + * @see org.apache.tuscany.sca.databinding.xml.XmlNode#getName() + */ + public QName getName() { + return name; + } + + /** + * @see org.apache.tuscany.sca.databinding.xml.XmlNode#getValue() + */ + public T getValue() { + return (T)value; + } + + /** + * @see org.apache.tuscany.sca.databinding.xml.XmlNode#namespaces() + */ + public Map namespaces() { + return namespaces; + } + + @Override + public String toString() { + return String.valueOf(name); + } + + public Type getType() { + if (value instanceof XMLStreamReader) { + return Type.READER; + } + return name == null ? Type.CHARACTERS : Type.ELEMENT; + } + + } +} diff --git a/java/sca/contrib/modules/compact-base/META-INF/MANIFEST.MF b/java/sca/contrib/modules/compact-base/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..f6590e5bb6 --- /dev/null +++ b/java/sca/contrib/modules/compact-base/META-INF/MANIFEST.MF @@ -0,0 +1,15 @@ +Manifest-Version: 1.0 +Built-By: ant +Build-Jdk: 1.5.0_15 +Bundle-Description: Apache Tuscany SCA Compact Base Jar +Bundle-SymbolicName: org.apache.tuscany.sca.compact.base +Bundle-Version: 2.0-SNAPSHOT +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Export-Package: org.apache.tuscany.sca* +Extension-Name: tuscany-compact-base +Main-Class: org.apache.tuscany.sca.node.DynamicNodeMain +Implementation-Title: Apache Tuscany SCA Compact Base Jar +Class-Path: activemq-all-5.1.0.jar geronimo-commonj_1.1_spec-1.0.jar j + axb-api-2.1.jar jaxb-impl-2.1.3.jar jaxws-api-2.1.jar jsr181-api-1.0- + MR1.jar stax-api-1.0.1.jar stax-api-1.0-2.jar wstx-asl-3.2.1.jar + diff --git a/java/sca/contrib/modules/compact-base/pom.xml b/java/sca/contrib/modules/compact-base/pom.xml new file mode 100644 index 0000000000..628bf299a9 --- /dev/null +++ b/java/sca/contrib/modules/compact-base/pom.xml @@ -0,0 +1,527 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + + tuscany-compact-base + Apache Tuscany SCA Compact Base Jar + + + true + ${pom.version} + + + + + ${pom.groupId} + tuscany-assembly + ${pom.version} + + + ${pom.groupId} + tuscany-assembly-xml + ${pom.version} + + + ${pom.groupId} + tuscany-assembly-xsd + ${pom.version} + + + ${pom.groupId} + tuscany-binding-sca + ${pom.version} + + + ${pom.groupId} + tuscany-binding-sca-xml + ${pom.version} + + + ${pom.groupId} + tuscany-contribution + ${pom.version} + + + ${pom.groupId} + tuscany-contribution-java + ${pom.version} + + + ${pom.groupId} + tuscany-contribution-namespace + ${pom.version} + + + ${pom.groupId} + tuscany-contribution-xml + ${pom.version} + + + ${pom.groupId} + tuscany-core + ${pom.version} + + + ${pom.groupId} + tuscany-core-databinding + ${pom.version} + + + ${pom.groupId} + tuscany-core-spi + ${pom.version} + + + ${pom.groupId} + tuscany-databinding + ${pom.version} + + + ${pom.groupId} + tuscany-databinding-jaxb + ${pom.version} + + + ${pom.groupId} + tuscany-definitions + ${pom.version} + + + ${pom.groupId} + tuscany-definitions-xml + ${pom.version} + + + ${pom.groupId} + tuscany-endpoint + ${pom.version} + + + ${pom.groupId} + tuscany-extensibility + ${pom.version} + + + ${pom.groupId} + tuscany-host-http + ${pom.version} + + + ${pom.groupId} + tuscany-host-webapp + ${pom.version} + + + ${pom.groupId} + tuscany-implementation-java + ${pom.version} + + + ${pom.groupId} + tuscany-implementation-java-xml + ${pom.version} + + + ${pom.groupId} + tuscany-implementation-java-runtime + ${pom.version} + + + ${pom.groupId} + tuscany-implementation-node + ${pom.version} + + + ${pom.groupId} + tuscany-interface + ${pom.version} + + + ${pom.groupId} + tuscany-interface-java + ${pom.version} + + + ${pom.groupId} + tuscany-interface-java-jaxws + ${pom.version} + + + ${pom.groupId} + tuscany-interface-java-xml + ${pom.version} + + + ${pom.groupId} + tuscany-monitor + ${pom.version} + + + ${pom.groupId} + tuscany-node-api + ${pom.version} + + + ${pom.groupId} + tuscany-node-impl + ${pom.version} + + + ${pom.groupId} + tuscany-policy + ${pom.version} + + + ${pom.groupId} + tuscany-policy-xml + ${pom.version} + + + ${pom.groupId} + tuscany-sca-api + ${pom.version} + + + ${pom.groupId} + tuscany-workspace + ${pom.version} + + + ${pom.groupId} + tuscany-workspace-impl + ${pom.version} + + + ${pom.groupId} + tuscany-workspace-xml + ${pom.version} + + + + + + cglib + cglib-nodep + 2.1_3 + + + + asm + asm-all + 3.1 + + + + + + + + + + + + + src/main/resources + + **/* + + + + + + + + org.apache.maven.plugins + maven-shade-plugin + + + + package + + shade + + + org.apache.tuscany.sca + false + ${createSourcesJar} + false + true + + + org.apache.tuscany.sca:tuscany-interface-java-jaxws + + com/example/** + + + + org.apache.tuscany.sca:tuscany-databinding-jaxb + + com/example/** + + + + org.apache.tuscany.sca:tuscany-databinding-sdo + + com/example/** + + + + ${project.groupId}:${project.artifactId} + + + org/** + + + + + + + META-INF/services/org.apache.tuscany.sca.assembly.AssemblyFactory + + + META-INF/services/org.apache.tuscany.sca.assembly.SCABindingFactory + + + META-INF/services/org.apache.tuscany.sca.binding.feed.AtomBindingFactory + + + META-INF/services/org.apache.tuscany.sca.binding.feed.RSSBindingFactory + + + META-INF/services/org.apache.tuscany.sca.binding.atom.AtomBindingFactory + + + META-INF/services/org.apache.tuscany.sca.binding.rss.RSSBindingFactory + + + META-INF/services/org.apache.tuscany.sca.binding.http.HTTPResourceBindingFactory + + + META-INF/services/org.apache.tuscany.sca.contribution.ContributionFactory + + + META-INF/services/org.apache.tuscany.sca.contribution.java.JavaImportExportFactory + + + META-INF/services/org.apache.tuscany.sca.contribution.ModelFactoryExtensionPoint + + + META-INF/services/org.apache.tuscany.sca.contribution.namespace.NamespaceImportExportFactory + + + META-INF/services/org.apache.tuscany.sca.contribution.processor.ContributionPostProcessorExtensionPoint + + + META-INF/services/org.apache.tuscany.sca.contribution.processor.PackageProcessor + + + META-INF/services/org.apache.tuscany.sca.contribution.processor.PackageProcessorExtensionPoint + + + META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor + + + META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessorExtensionPoint + + + META-INF/services/org.apache.tuscany.sca.contribution.processor.URLArtifactProcessor + + + META-INF/services/org.apache.tuscany.sca.contribution.processor.URLArtifactProcessorExtensionPoint + + + META-INF/services/org.apache.tuscany.sca.contribution.resolver.ModelResolver + + + META-INF/services/org.apache.tuscany.sca.contribution.resolver.ModelResolverExtensionPoint + + + META-INF/services/org.apache.tuscany.sca.contribution.service.ContributionListener + + + META-INF/services/org.apache.tuscany.sca.contribution.service.ContributionListenerExtensionPoint + + + META-INF/services/org.apache.tuscany.sca.core.ModuleActivator + + + META-INF/services/org.apache.tuscany.sca.databinding.DataBinding + + + META-INF/services/org.apache.tuscany.sca.databinding.DataBindingExtensionPoint + + + META-INF/services/org.apache.tuscany.sca.databinding.PullTransformer + + + META-INF/services/org.apache.tuscany.sca.databinding.PushTransformer + + + META-INF/services/org.apache.tuscany.sca.databinding.TransformerExtensionPoint + + + META-INF/services/org.apache.tuscany.sca.extension.helper.BindingActivator + + + META-INF/services/org.apache.tuscany.sca.extension.helper.ImplementationActivator + + + META-INF/services/org.apache.tuscany.sca.host.http.ServletHostExtensionPoint + + + META-INF/services/org.apache.tuscany.sca.host.rmi.RMIHostExtensionPoint + + + META-INF/services/org.apache.tuscany.sca.implementation.java.JavaImplementationFactory + + + META-INF/services/org.apache.tuscany.sca.implementation.resource.ResourceImplementationFactory + + + META-INF/services/org.apache.tuscany.sca.interfacedef.java.introspect.JavaInterfaceVisitor + + + META-INF/services/org.apache.tuscany.sca.interfacedef.java.JavaInterfaceFactory + + + META-INF/services/org.apache.tuscany.sca.interfacedef.wsdl.WSDLFactory + + + META-INF/services/org.apache.tuscany.sca.provider.BindingProviderFactory + + + META-INF/services/org.apache.tuscany.sca.provider.ImplementationProviderFactory + + + META-INF/services/org.apache.tuscany.sca.provider.ProviderFactoryExtensionPoint + + + META-INF/services/org.apache.tuscany.sca.runtime.RuntimeWireProcessorExtensionPoint + + + META-INF/services/org.apache.tuscany.sca.spi.ImplementationActivator + + + META-INF/services/org.apache.tuscany.sca.work.WorkScheduler + + + META-INF/services/org.apache.tuscany.sca.policy.util.PolicyHandler + + + META-INF/services/org.apache.tuscany.sca.provider.PolicyProviderFactory + + + META-INF/services/org.apache.tuscany.sca.provider.SCADefinitionsProvider + + + + + + + + + + + + diff --git a/java/sca/contrib/modules/contribution-osgi/LICENSE b/java/sca/contrib/modules/contribution-osgi/LICENSE new file mode 100644 index 0000000000..8aa906c321 --- /dev/null +++ b/java/sca/contrib/modules/contribution-osgi/LICENSE @@ -0,0 +1,205 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + + diff --git a/java/sca/contrib/modules/contribution-osgi/NOTICE b/java/sca/contrib/modules/contribution-osgi/NOTICE new file mode 100644 index 0000000000..25bb89c9b2 --- /dev/null +++ b/java/sca/contrib/modules/contribution-osgi/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/contribution-osgi/pom.xml b/java/sca/contrib/modules/contribution-osgi/pom.xml new file mode 100644 index 0000000000..71c90ca4ef --- /dev/null +++ b/java/sca/contrib/modules/contribution-osgi/pom.xml @@ -0,0 +1,78 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + tuscany-contribution-osgi + Apache Tuscany SCA Contribution Service OSGi + + + + org.apache.tuscany.sca + tuscany-contribution + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-osgi-runtime + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-contribution-java + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-core-spi + 2.0-SNAPSHOT + + + + org.apache.felix + org.apache.felix.main + 1.0.4 + + + + + + org.codehaus.woodstox + wstx-asl + 3.2.4 + runtime + + + stax + stax-api + + + + + + diff --git a/java/sca/contrib/modules/contribution-osgi/src/main/java/org/apache/tuscany/sca/contribution/osgi/BundleReference.java b/java/sca/contrib/modules/contribution-osgi/src/main/java/org/apache/tuscany/sca/contribution/osgi/BundleReference.java new file mode 100644 index 0000000000..0bbb8b707a --- /dev/null +++ b/java/sca/contrib/modules/contribution-osgi/src/main/java/org/apache/tuscany/sca/contribution/osgi/BundleReference.java @@ -0,0 +1,161 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.contribution.osgi; + + +/** + * A weak reference to a class, which should be used to register classes + * with an ArtifactResolver and resolve these classes later. + * + * @version $Rev$ $Date$ + */ +public class BundleReference { + + /** + * The bundle. + */ + private Object bundle; + + /** + * The bundle name. + */ + private String bundleName; + + /** + * The bundle version. + */ + private String bundleVersion; + + /** + * The bundle name and version. + */ + private String bundleUniqueName; + + /** + * The bundle relative path. + */ + private String bundleRelativePath; + + /** + * Constructs a new BundleReference. + * + * @param bundle The bundle reference + * @param bundleName The bundle name + * @param bundleVersion The bundle version + * @param bundleRelativePath The relative path for the bundle + */ + public BundleReference(Object bundle, String bundleName, String bundleVersion, String bundleRelativePath) { + this.bundle = bundle; + this.bundleName = bundleName; + this.bundleVersion = bundleVersion; + this.bundleRelativePath = bundleRelativePath; + this.bundleUniqueName = bundleName + "(" + (bundleVersion == null?"0.0.0":bundleVersion) + ")"; + } + + /** + * Constructs a new BundleReference. + * + * @param bundleName The bundle name + * @param bundleVersion The bundle version + */ + public BundleReference(String bundleName, String bundleVersion) { + this.bundleName = bundleName; + this.bundleVersion = bundleVersion; + this.bundleUniqueName = bundleName + "(" + (bundleVersion == null?"0.0.0":bundleVersion) + ")"; + } + + /** + * Get the referenced bundle. + * + * @return The referenced bundle + */ + public Object getBundle() { + return bundle; + } + + /** + * Get the referenced bundle name. + * + * @return The bundle name + */ + public String getBundleName() { + return bundleName; + } + + /** + * Get the referenced bundle version. + * + * @return The bundle version + */ + public String getBundleVersion() { + return bundleVersion; + } + + /** + * Get the referenced bundle name and version. + * + * @return The bundle name + */ + public String getBundleUniqueName() { + return bundleUniqueName; + } + + /** + * Get the relative location of the bundle inside its contribution. + * + * @return The bundle path + */ + public String getBundleRelativePath() { + return bundleRelativePath; + } + + + + /** + * Returns true if the bundle reference is unresolved. + * + * @return Whether or not the bundle has been resolved + */ + public boolean isUnresolved() { + return bundle == null; + } + + @Override + public int hashCode() { + return bundleUniqueName.hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (obj == this) { + return true; + } else { + if (obj instanceof BundleReference) { + BundleReference ref = (BundleReference)obj; + return bundleName.equals(ref.bundleName) && + (bundleVersion == null || ref.bundleVersion == null || + bundleVersion.equals(ref.bundleVersion)); + } else { + return false; + } + } + } + +} diff --git a/java/sca/contrib/modules/contribution-osgi/src/main/java/org/apache/tuscany/sca/contribution/osgi/impl/OSGiBundleContributionProcessor.java b/java/sca/contrib/modules/contribution-osgi/src/main/java/org/apache/tuscany/sca/contribution/osgi/impl/OSGiBundleContributionProcessor.java new file mode 100644 index 0000000000..5033d7eefc --- /dev/null +++ b/java/sca/contrib/modules/contribution-osgi/src/main/java/org/apache/tuscany/sca/contribution/osgi/impl/OSGiBundleContributionProcessor.java @@ -0,0 +1,161 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.contribution.osgi.impl; + +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URL; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.jar.JarEntry; +import java.util.jar.JarInputStream; + +import org.apache.tuscany.sca.contribution.PackageType; +import org.apache.tuscany.sca.contribution.processor.PackageProcessor; +import org.apache.tuscany.sca.contribution.service.ContributionException; +import org.apache.tuscany.sca.osgi.runtime.OSGiRuntime; +import org.osgi.framework.Bundle; + +/** + * Bundle Contribution package processor. + * + * @version $Rev$ $Date$ + */ +public class OSGiBundleContributionProcessor implements PackageProcessor { + + public OSGiBundleContributionProcessor() { + } + + public String getPackageType() { + return PackageType.BUNDLE; + } + + public URL getArtifactURL(URL sourceURL, URI artifact) throws MalformedURLException { + Bundle bundle = null; + try { + bundle = OSGiRuntime.findInstalledBundle(sourceURL); + if (bundle != null) { + URL url = bundle.getResource(artifact.getPath()); + if (url == null) + System.out.println("Could not load resource " + artifact); + return url; + } + } catch (Exception e) { + } + return null; + } + + public List getJarArtifacts(URL packageSourceURL, InputStream inputStream) throws ContributionException, + IOException { + if (packageSourceURL == null) { + throw new IllegalArgumentException("Invalid null package source URL."); + } + + if (inputStream == null) { + throw new IllegalArgumentException("Invalid null source inputstream."); + } + + // Assume the root is a jar file + JarInputStream jar = new JarInputStream(inputStream); + try { + Set names = new HashSet(); + while (true) { + JarEntry entry = jar.getNextJarEntry(); + if (entry == null) { + // EOF + break; + } + + // FIXME: Maybe we should externalize the filter as a property + String name = entry.getName(); + if (!name.startsWith(".") && !entry.isDirectory()) { + + // Trim trailing / + if (name.endsWith("/")) { + name = name.substring(0, name.length() - 1); + } + + // Add the entry name + if (!names.contains(name) && name.length() > 0) { + names.add(name); + + } + } + } + + // Return list of URIs + List artifacts = new ArrayList(); + for (String name: names) { + artifacts.add(URI.create(name)); + } + return artifacts; + + } finally { + jar.close(); + } +} + + public List getArtifacts(URL packageSourceURL, InputStream inputStream) throws ContributionException, + IOException { + + Bundle bundle = null; + try { + bundle = OSGiRuntime.findInstalledBundle(packageSourceURL); + } catch (Exception e) { + } + + if (bundle == null) { + throw new IllegalArgumentException("Could not find OSGi bundle " + packageSourceURL); + } + + if (packageSourceURL == null) { + throw new IllegalArgumentException("Invalid null package source URL."); + } + + List artifacts = new ArrayList(); + + try { + Enumeration entries = bundle.findEntries("/", "*", true); + while (entries.hasMoreElements()) { + URL entry = (URL)entries.nextElement(); + String entryName = entry.getPath(); + if (entryName.startsWith("/")) + entryName = entryName.substring(1); + artifacts.add(new URI(entryName)); + + if (entryName.endsWith(".jar")) { + + URL jarResource = bundle.getResource(entryName); + artifacts.addAll(getJarArtifacts(jarResource, jarResource.openStream())); + } + + } + } catch (Exception e) { + throw new RuntimeException(e); + } + + return artifacts; + } +} diff --git a/java/sca/contrib/modules/contribution-osgi/src/main/java/org/apache/tuscany/sca/contribution/osgi/impl/OSGiBundleProcessor.java b/java/sca/contrib/modules/contribution-osgi/src/main/java/org/apache/tuscany/sca/contribution/osgi/impl/OSGiBundleProcessor.java new file mode 100644 index 0000000000..b3c2302f60 --- /dev/null +++ b/java/sca/contrib/modules/contribution-osgi/src/main/java/org/apache/tuscany/sca/contribution/osgi/impl/OSGiBundleProcessor.java @@ -0,0 +1,141 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.contribution.osgi.impl; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.List; +import java.util.jar.Attributes; +import java.util.jar.JarInputStream; +import java.util.jar.Manifest; + +import org.apache.tuscany.sca.contribution.Artifact; +import org.apache.tuscany.sca.contribution.Contribution; +import org.apache.tuscany.sca.contribution.osgi.BundleReference; +import org.apache.tuscany.sca.osgi.runtime.OSGiRuntime; + +/** + * OSGi bundle processor + * + * @version $Rev$ $Date$ + */ +public class OSGiBundleProcessor { + + private boolean initializedOSGi; + private OSGiRuntime osgiRuntime; + + public OSGiBundleProcessor() { + } + + public Object installContributionBundle(Contribution contribution) { + + JarInputStream jar = null; + Object bundle = null; + + try { + + URL contribURL = new URL(contribution.getLocation()); + jar = new JarInputStream(contribURL.openStream()); + + Manifest manifest = jar.getManifest(); + if (manifest != null && manifest.getMainAttributes() + .containsKey(new Attributes.Name("Bundle-SymbolicName"))) { + + initialize(); + if (osgiRuntime != null) + bundle = osgiRuntime.installBundle(contribURL.toString(), null); + } + } catch (Exception e) { + // If OSGi cannot process the jar, treat the bundle as a plain jar file. + } finally { + + try { + if (jar != null) + jar.close(); + } catch (IOException e) { + } + } + + return bundle; + } + + public BundleReference installNestedBundle(Contribution contribution, + String bundleSymbolicName, + String bundleVersion) { + + BundleReference bundleReference = null; + + initialize(); + if (osgiRuntime == null) + return null; + + List artifacts = contribution.getArtifacts(); + for (Artifact a : artifacts) { + if (a.getURI().endsWith(".jar")) { + + InputStream stream; + JarInputStream jar = null; + Object name; + Object version; + try { + + URL artifactURL = new URL(a.getLocation()); + stream = artifactURL.openStream(); + jar = new JarInputStream(artifactURL.openStream()); + Manifest manifest = jar.getManifest(); + name = manifest.getMainAttributes().get(new Attributes.Name("Bundle-SymbolicName")); + version = manifest.getMainAttributes().get(new Attributes.Name("Bundle-Version")); + + if (bundleSymbolicName.equals(name) && (bundleVersion == null || version == null || bundleVersion + .equals(version))) { + + Object bundle = osgiRuntime.installBundle(a.getLocation(), stream); + + bundleReference = new BundleReference(bundle, bundleSymbolicName, bundleVersion, a.getURI()); + + break; + } + + } catch (Exception e) { + + // If OSGi cannot process the jar, treat the bundle as a plain jar file. + } finally { + try { + if (jar != null) + jar.close(); + } catch (IOException e) { + } + } + } + } + return bundleReference; + } + + private void initialize() { + try { + if (!initializedOSGi) { + initializedOSGi = true; + osgiRuntime = OSGiRuntime.getRuntime(); + } + } catch (Exception e) { + } + } +} diff --git a/java/sca/contrib/modules/contribution-osgi/src/main/java/org/apache/tuscany/sca/contribution/osgi/impl/OSGiBundleReferenceModelResolver.java b/java/sca/contrib/modules/contribution-osgi/src/main/java/org/apache/tuscany/sca/contribution/osgi/impl/OSGiBundleReferenceModelResolver.java new file mode 100644 index 0000000000..07e80f66f3 --- /dev/null +++ b/java/sca/contrib/modules/contribution-osgi/src/main/java/org/apache/tuscany/sca/contribution/osgi/impl/OSGiBundleReferenceModelResolver.java @@ -0,0 +1,154 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.contribution.osgi.impl; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.tuscany.sca.contribution.Contribution; +import org.apache.tuscany.sca.contribution.Import; +import org.apache.tuscany.sca.contribution.ModelFactoryExtensionPoint; +import org.apache.tuscany.sca.contribution.osgi.BundleReference; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.osgi.runtime.OSGiRuntime; +import org.osgi.framework.Bundle; + +/** + * A Model Resolver for BundleReferences. + * + * @version $Rev$ $Date$ + */ +public class OSGiBundleReferenceModelResolver implements ModelResolver { + private Contribution contribution; + private Map map = new HashMap(); + + OSGiRuntime osgiRuntime; + private OSGiBundleProcessor bundleProcessor; + + public OSGiBundleReferenceModelResolver(Contribution contribution, ModelFactoryExtensionPoint modelFactories) { + this.contribution = contribution; + this.bundleProcessor = new OSGiBundleProcessor(); + } + + public void addModel(Object resolved) { + BundleReference bundleRef = (BundleReference)resolved; + map.put(bundleRef.getBundleUniqueName(), bundleRef); + } + + public Object removeModel(Object resolved) { + return map.remove(((BundleReference)resolved).getBundleUniqueName()); + } + + /** + * Handle artifact resolution when the specific class reference is imported from another contribution + * @param unresolved + * @return + */ + private BundleReference resolveImportedModel(BundleReference unresolved) { + BundleReference resolved = unresolved; + + if( this.contribution != null) { + for (Import import_ : this.contribution.getImports()) { + + resolved = import_.getModelResolver().resolveModel(BundleReference.class, unresolved); + if (resolved != unresolved) + break; + } + + } + return resolved; + } + + + public T resolveModel(Class modelClass, T unresolved) { + Object resolved = map.get(unresolved); + + if (resolved != null ){ + return modelClass.cast(resolved); + } + + try { + if (osgiRuntime == null) + osgiRuntime = OSGiRuntime.getRuntime(); + } catch (Exception e) { + } + if (osgiRuntime == null) + return unresolved; + + //Load a class on demand + Object bundle = null; + String bundleName = ((BundleReference)unresolved).getBundleName(); + String bundleVersion = ((BundleReference)unresolved).getBundleVersion(); + + bundle = osgiRuntime.findBundle(bundleName, bundleVersion); + BundleReference bundleReference; + + if (bundle == null) + bundleReference = bundleProcessor.installNestedBundle(contribution, bundleName, bundleVersion); + else { + bundleReference = new BundleReference(bundle, + ((BundleReference)unresolved).getBundleName(), + bundleVersion, + getBundleFileName(bundle) + ); + } + + + if (bundleReference != null) { + //if we load the class + + map.put(((BundleReference)unresolved).getBundleUniqueName(), bundleReference); + + // Return the resolved BundleReference + return modelClass.cast(bundleReference); + } else { + //delegate resolution of the class + resolved = this.resolveImportedModel((BundleReference)unresolved); + return modelClass.cast(resolved); + } + + + } + + + private String getBundleFileName(Object bundle) { + if (bundle instanceof Bundle) { + String path = ((Bundle)bundle).getLocation(); + if (path.endsWith("/")) + path = path.substring(0, path.length()-1); + if (path.startsWith(contribution.getLocation())) { + if (path.equals(contribution.getLocation())) { + int index = path.lastIndexOf('/'); + if (index > 0 && index < path.length()-1) + path = path.substring(index+1); + } else { + path = path.substring(contribution.getLocation().length()); + if (path.startsWith("/")) + path = path.substring(1); + } + } else if (path.lastIndexOf('/') >= 0) + path = path.substring(path.lastIndexOf('/')+1); + return path; + } + return null; + + } + +} diff --git a/java/sca/contrib/modules/contribution-osgi/src/main/java/org/apache/tuscany/sca/contribution/osgi/impl/OSGiClassReferenceModelResolver.java b/java/sca/contrib/modules/contribution-osgi/src/main/java/org/apache/tuscany/sca/contribution/osgi/impl/OSGiClassReferenceModelResolver.java new file mode 100644 index 0000000000..528a287328 --- /dev/null +++ b/java/sca/contrib/modules/contribution-osgi/src/main/java/org/apache/tuscany/sca/contribution/osgi/impl/OSGiClassReferenceModelResolver.java @@ -0,0 +1,137 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.contribution.osgi.impl; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.tuscany.sca.contribution.Contribution; +import org.apache.tuscany.sca.contribution.Import; +import org.apache.tuscany.sca.contribution.ModelFactoryExtensionPoint; +import org.apache.tuscany.sca.contribution.resolver.ClassReference; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.osgi.runtime.OSGiRuntime; +import org.osgi.framework.Bundle; + +/** + * A Model Resolver for ClassReferences. + * + * @version $Rev$ $Date$ + */ +public class OSGiClassReferenceModelResolver implements ModelResolver { + private Contribution contribution; + private Map map = new HashMap(); + private Bundle bundle; + private boolean initialized; + private boolean useOSGi; + + public OSGiClassReferenceModelResolver(Contribution contribution, ModelFactoryExtensionPoint modelFactories) { + this.contribution = contribution; + } + + public void addModel(Object resolved) { + ClassReference clazz = (ClassReference)resolved; + map.put(clazz.getClassName(), clazz); + } + + public Object removeModel(Object resolved) { + return map.remove(((ClassReference)resolved).getClassName()); + } + + /** + * Handle artifact resolution when the specific class reference is imported from another contribution + * @param unresolved + * @return + */ + private ClassReference resolveImportedModel(ClassReference unresolved) { + ClassReference resolved = unresolved; + + if (this.contribution != null) { + for (Import import_ : this.contribution.getImports()) { + + if (resolved == unresolved && bundle != null) { + resolved = import_.getModelResolver().resolveModel(ClassReference.class, unresolved); + if (resolved != unresolved) + break; + } + } + + } + return resolved; + } + + public T resolveModel(Class modelClass, T unresolved) { + Object resolved = map.get(unresolved); + + if (resolved != null) { + return modelClass.cast(resolved); + } + initialize(); + if (!useOSGi) + return unresolved; + + //Load a class on demand + Class clazz = null; + if (bundle != null) { + try { + clazz = bundle.loadClass(((ClassReference)unresolved).getClassName()); + } catch (Exception e) { + // we will later try to delegate to imported model resolvers + } + } + + if (clazz != null) { + //if we load the class + // Store a new ClassReference wrapping the loaded class + ClassReference classReference = new ClassReference(clazz); + map.put(getPackageName(classReference), classReference); + + // Return the resolved ClassReference + return modelClass.cast(classReference); + } else { + //delegate resolution of the class + resolved = this.resolveImportedModel((ClassReference)unresolved); + return modelClass.cast(resolved); + } + + } + + /*************** + * Helper methods + ***************/ + + private String getPackageName(ClassReference clazz) { + int pos = clazz.getClassName().lastIndexOf("."); + return clazz.getClassName().substring(0, pos - 1); + } + + private void initialize() { + if (initialized) + return; + + initialized = true; + try { + bundle = OSGiRuntime.findInstalledBundle(contribution.getLocation()); + useOSGi = bundle != null; + } catch (Throwable e) { + // Ignore errors, default to ClassReferenceModelResolver + } + } +} diff --git a/java/sca/contrib/modules/contribution-osgi/src/main/java/org/apache/tuscany/sca/contribution/osgi/impl/OSGiImportExportListener.java b/java/sca/contrib/modules/contribution-osgi/src/main/java/org/apache/tuscany/sca/contribution/osgi/impl/OSGiImportExportListener.java new file mode 100644 index 0000000000..15ad0bd948 --- /dev/null +++ b/java/sca/contrib/modules/contribution-osgi/src/main/java/org/apache/tuscany/sca/contribution/osgi/impl/OSGiImportExportListener.java @@ -0,0 +1,215 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.contribution.osgi.impl; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.net.URL; +import java.util.HashSet; +import java.util.jar.JarOutputStream; +import java.util.jar.Manifest; +import java.util.zip.ZipEntry; + +import org.apache.tuscany.sca.contribution.Contribution; +import org.apache.tuscany.sca.contribution.Export; +import org.apache.tuscany.sca.contribution.Import; +import org.apache.tuscany.sca.contribution.java.JavaExport; +import org.apache.tuscany.sca.contribution.java.JavaImport; +import org.apache.tuscany.sca.contribution.service.ContributionListener; +import org.apache.tuscany.sca.contribution.service.ContributionRepository; +import org.apache.tuscany.sca.osgi.runtime.OSGiRuntime; + +/** + * Namespace Import/Export contribution listener + * The listener would process all import/export from a given contribution + * and initialize the model resolvers properly + * + * @version $Rev$ $Date$ + */ +public class OSGiImportExportListener implements ContributionListener { + + private OSGiBundleProcessor bundleProcessor; + + public OSGiImportExportListener() { + bundleProcessor = new OSGiBundleProcessor(); + } + + /** + * Initialize the import/export model resolvers + * Export model resolvers are same as Contribution model resolver + * Import model resolvers are matched to a specific contribution if a location URI is specified, + * otherwise it try to resolve against all the other contributions + */ + public void contributionAdded(ContributionRepository repository, Contribution contribution) { + + OSGiRuntime osgiRuntime = null; + try { + if (bundleProcessor.installContributionBundle(contribution) == null) { + return; + } else { + osgiRuntime = OSGiRuntime.getRuntime(); + } + } catch (Exception e) { + return; + } + + HashSet bundlesToInstall = new HashSet(); + // Initialize the contribution imports + for (Import import_ : contribution.getImports()) { + boolean initialized = false; + + if (import_ instanceof JavaImport) { + JavaImport javaImport = (JavaImport)import_; + String packageName = javaImport.getPackage(); + + //Find a matching contribution + if (javaImport.getLocation() != null) { + Contribution targetContribution = repository.getContribution(javaImport.getLocation()); + if (targetContribution != null) { + + // Find a matching contribution export + for (Export export : targetContribution.getExports()) { + if (export instanceof JavaExport) { + JavaExport javaExport = (JavaExport)export; + if (packageName.equals(javaExport.getPackage())) { + + if (osgiRuntime.findBundle(targetContribution.getLocation()) == null) + bundlesToInstall.add(targetContribution); + + initialized = true; + + } + } + if (initialized) + break; + } + } + } + } + if (!initialized) { + for (Contribution c : repository.getContributions()) { + + // Go over all exports in the contribution + for (Export export : c.getExports()) { + // If the export matches our namespace, try to the resolve the model object + if (import_.match(export) && osgiRuntime.findBundle(c.getLocation()) == null) { + bundlesToInstall.add(c); + } + } + } + } + } + for (Contribution c : bundlesToInstall) { + try { + installDummyBundle(osgiRuntime, c); + } catch (Exception e) { + } + } + + } + + public void contributionRemoved(ContributionRepository repository, Contribution contribution) { + + } + + public void contributionUpdated(ContributionRepository repository, + Contribution oldContribution, + Contribution contribution) { + + } + + private void installDummyBundle(OSGiRuntime osgiRuntime, Contribution contribution) throws Exception { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + + String EOL = System.getProperty("line.separator"); + + String bundleName = contribution.getURI(); + URL contribURL = new URL(contribution.getLocation()); + String contribName = contribURL.getPath(); + if (contribName.endsWith("/")) + contribName = contribName.substring(0, contribName.length()-1); + if (contribName.lastIndexOf("/") >= 0) + contribName = contribName.substring(contribName.lastIndexOf("/")+1); + + StringBuffer exportPackageNames = new StringBuffer(); + for (Export export : contribution.getExports()) { + if (export instanceof JavaExport) { + if (exportPackageNames.length() > 0) + exportPackageNames.append(","); + exportPackageNames.append(((JavaExport)export).getPackage()); + } + } + StringBuffer importPackageNames = new StringBuffer(); + for (Import import_ : contribution.getImports()) { + if (import_ instanceof JavaImport) { + if (importPackageNames.length() > 0) + importPackageNames.append(","); + importPackageNames.append(((JavaImport)import_).getPackage()); + } + } + + String manifestStr = + "Manifest-Version: 1.0" + EOL + + "Bundle-ManifestVersion: 2" + + EOL + + "Bundle-Name: " + + bundleName + + EOL + + "Bundle-SymbolicName: " + + bundleName + + EOL + + "Bundle-Version: " + + "1.0.0" + + EOL + + "Bundle-Localization: plugin" + + EOL; + + StringBuilder manifestBuf = new StringBuilder(); + manifestBuf.append(manifestStr); + manifestBuf.append("Export-Package: " + exportPackageNames + EOL); + manifestBuf.append("Import-Package: " + importPackageNames + EOL); + manifestBuf.append("Bundle-ClassPath: .," + contribName + EOL); + + ByteArrayInputStream manifestStream = new ByteArrayInputStream(manifestBuf.toString().getBytes()); + Manifest manifest = new Manifest(); + manifest.read(manifestStream); + + JarOutputStream jarOut = new JarOutputStream(out, manifest); + + ZipEntry ze = new ZipEntry(contribName); + jarOut.putNextEntry(ze); + InputStream stream = contribURL.openStream(); + + byte[] bytes = new byte[stream.available()]; + stream.read(bytes); + jarOut.write(bytes); + stream.close(); + + jarOut.close(); + out.close(); + + ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); + + osgiRuntime.installBundle("file://" + bundleName + ".jar", in); + + } + +} diff --git a/java/sca/contrib/modules/contribution-osgi/src/main/java/org/apache/tuscany/sca/contribution/osgi/impl/OSGiModelResolverImpl.java b/java/sca/contrib/modules/contribution-osgi/src/main/java/org/apache/tuscany/sca/contribution/osgi/impl/OSGiModelResolverImpl.java new file mode 100644 index 0000000000..e624b1d3b5 --- /dev/null +++ b/java/sca/contrib/modules/contribution-osgi/src/main/java/org/apache/tuscany/sca/contribution/osgi/impl/OSGiModelResolverImpl.java @@ -0,0 +1,119 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.contribution.osgi.impl; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Hashtable; +import java.util.Map; + +import org.apache.tuscany.sca.contribution.osgi.BundleReference; +import org.apache.tuscany.sca.contribution.resolver.ClassReference; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.osgi.framework.Bundle; + +/** + * An implementation of an artifact resolver for OSGi bundles. + * + * @version $Rev$ $Date$ + */ +public class OSGiModelResolverImpl implements ModelResolver { + private static final long serialVersionUID = -7826976465762296634L; + + private Map map = new HashMap(); + + private Hashtable bundles; + public OSGiModelResolverImpl(Hashtable bundles) { + this.bundles = bundles; + } + + + public T resolveModel(Class modelClass, T unresolved) { + Object resolved = map.get(unresolved); + if (resolved != null) { + + // Return the resolved object + return modelClass.cast(resolved); + + } else if (unresolved instanceof ClassReference) { + + // Load a class on demand + ClassReference classReference = (ClassReference)unresolved; + Class clazz = null; + for (Bundle bundle : bundles.values()) { + try { + clazz = bundle.loadClass(classReference.getClassName()); + } catch (ClassNotFoundException e) { + continue; + } + break; + } + if (clazz == null) { + + // Return the unresolved object + return unresolved; + } + + // Store a new ClassReference wrapping the loaded class + resolved = new ClassReference(clazz); + map.put(resolved, resolved); + + // Return the resolved ClassReference + return modelClass.cast(resolved); + + } else if (unresolved instanceof BundleReference) { + for (String bundlePath: bundles.keySet()) { + Bundle bundle = bundles.get(bundlePath); + BundleReference bundleRef = (BundleReference)unresolved; + String bundleVersion = (String)bundle.getHeaders().get("Bundle-Version"); + if (bundle.getSymbolicName().equals(bundleRef.getBundleName())&& + (bundleVersion == null || bundleRef.getBundleVersion() == null || + bundleVersion.equals(bundleRef.getBundleVersion()))) { + + resolved = new BundleReference(bundle, + bundle.getSymbolicName(), + bundleVersion, + bundlePath); + map.put(resolved, resolved); + + // Return the resolved BundleReference + return modelClass.cast(resolved); + + } + } + } + + // Return the unresolved object + return unresolved; + } + + public void addModel(Object resolved) { + map.put(resolved, resolved); + } + + public Object removeModel(Object resolved) { + return map.remove(resolved); + } + + public Collection getModels() { + return map.values(); + } + +} diff --git a/java/sca/contrib/modules/contribution-osgi/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.PackageProcessor b/java/sca/contrib/modules/contribution-osgi/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.PackageProcessor new file mode 100644 index 0000000000..632d135cb5 --- /dev/null +++ b/java/sca/contrib/modules/contribution-osgi/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.PackageProcessor @@ -0,0 +1,18 @@ +# 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. + +org.apache.tuscany.sca.contribution.osgi.impl.OSGiBundleContributionProcessor;type=application/osgi.bundle diff --git a/java/sca/contrib/modules/contribution-osgi/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.resolver.ModelResolver b/java/sca/contrib/modules/contribution-osgi/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.resolver.ModelResolver new file mode 100644 index 0000000000..02e8b411eb --- /dev/null +++ b/java/sca/contrib/modules/contribution-osgi/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.resolver.ModelResolver @@ -0,0 +1,18 @@ +# 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. + +org.apache.tuscany.sca.contribution.osgi.impl.OSGiBundleReferenceModelResolver;model=org.apache.tuscany.sca.contribution.osgi.BundleReference diff --git a/java/sca/contrib/modules/contribution-osgi/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.service.ContributionListener b/java/sca/contrib/modules/contribution-osgi/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.service.ContributionListener new file mode 100644 index 0000000000..8dec190930 --- /dev/null +++ b/java/sca/contrib/modules/contribution-osgi/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.service.ContributionListener @@ -0,0 +1,18 @@ +# 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. + +org.apache.tuscany.sca.contribution.osgi.impl.OSGiImportExportListener diff --git a/java/sca/contrib/modules/contribution-resource/META-INF/MANIFEST.MF b/java/sca/contrib/modules/contribution-resource/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..364c48b8bc --- /dev/null +++ b/java/sca/contrib/modules/contribution-resource/META-INF/MANIFEST.MF @@ -0,0 +1,26 @@ +Manifest-Version: 1.0 +Export-Package: org.apache.tuscany.sca.contribution.resource;uses:="or + g.apache.tuscany.sca.contribution";version="2.0.0" +Private-Package: org.apache.tuscany.sca.contribution.resource.impl;ver + sion="1.4" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA Resource Import/Export Model +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397365937 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA Resource Import/Export Model +Import-Package: javax.xml.namespace, + javax.xml.stream, + org.apache.tuscany.sca.assembly;version="2.0.0", + org.apache.tuscany.sca.contribution;version="2.0.0", + org.apache.tuscany.sca.contribution.processor;version="2.0.0", + org.apache.tuscany.sca.contribution.resolver;version="2.0.0", + org.apache.tuscany.sca.contribution.resource;version="2.0.0", + org.apache.tuscany.sca.core;version="2.0.0", + org.apache.tuscany.sca.monitor;version="2.0.0" +Bundle-SymbolicName: org.apache.tuscany.sca.contribution.resource +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/contribution-resource/pom.xml b/java/sca/contrib/modules/contribution-resource/pom.xml new file mode 100644 index 0000000000..14cf357291 --- /dev/null +++ b/java/sca/contrib/modules/contribution-resource/pom.xml @@ -0,0 +1,58 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + tuscany-contribution-resource + Apache Tuscany SCA Resource Import/Export Model + + + + org.apache.tuscany.sca + tuscany-contribution + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-core-spi + 2.0-SNAPSHOT + + + + org.codehaus.woodstox + wstx-asl + 3.2.4 + runtime + + + stax + stax-api + + + + + + diff --git a/java/sca/contrib/modules/contribution-resource/src/main/java/org/apache/tuscany/sca/contribution/resource/ResourceExport.java b/java/sca/contrib/modules/contribution-resource/src/main/java/org/apache/tuscany/sca/contribution/resource/ResourceExport.java new file mode 100644 index 0000000000..0bd30c19dd --- /dev/null +++ b/java/sca/contrib/modules/contribution-resource/src/main/java/org/apache/tuscany/sca/contribution/resource/ResourceExport.java @@ -0,0 +1,46 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.contribution.resource; + +import org.apache.tuscany.sca.contribution.Export; + + +/** + * The representation of an resource export. + * + * @version $Rev$ $Date$ + */ +public interface ResourceExport extends Export { + + /** + * Get Resource URI that identifies the export. + * + * @return The exported resource URI + */ + String getURI(); + + /** + * Set Resource URI that identifies the export. + * + * @param uri The exported resource URI + */ + void setURI(String uri); + +} diff --git a/java/sca/contrib/modules/contribution-resource/src/main/java/org/apache/tuscany/sca/contribution/resource/ResourceImport.java b/java/sca/contrib/modules/contribution-resource/src/main/java/org/apache/tuscany/sca/contribution/resource/ResourceImport.java new file mode 100644 index 0000000000..07eac9d843 --- /dev/null +++ b/java/sca/contrib/modules/contribution-resource/src/main/java/org/apache/tuscany/sca/contribution/resource/ResourceImport.java @@ -0,0 +1,59 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.contribution.resource; + +import org.apache.tuscany.sca.contribution.Import; + +/** + * The representation of an resource import. + * + * @version $Rev$ $Date$ + */ +public interface ResourceImport extends Import { + + /** + * Get the location used to resolve the definitions for this import + * + * @return The import location + */ + String getLocation(); + + /** + * Set the location used to resolve the definitions for this import + * + * @param location The import location + */ + void setLocation(String location); + + /** + * Get URI that identifies the resource import + * + * @return The URI + */ + String getURI(); + + /** + * Set URI that identifies the resource import + * + * @param uri The resource URI + */ + void setURI(String uri); + +} \ No newline at end of file diff --git a/java/sca/contrib/modules/contribution-resource/src/main/java/org/apache/tuscany/sca/contribution/resource/ResourceImportExportFactory.java b/java/sca/contrib/modules/contribution-resource/src/main/java/org/apache/tuscany/sca/contribution/resource/ResourceImportExportFactory.java new file mode 100644 index 0000000000..4119c344ce --- /dev/null +++ b/java/sca/contrib/modules/contribution-resource/src/main/java/org/apache/tuscany/sca/contribution/resource/ResourceImportExportFactory.java @@ -0,0 +1,42 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.contribution.resource; + +/** + * Base Resource import/export model factory + * + * @version $Rev$ $Date$ + */ +public interface ResourceImportExportFactory { + + /** + * Create a resource import model object + * + * @return The new ResourceImport model object + */ + ResourceImport createResourceImport(); + + /** + * Create a resource export model object + * + * @return The new ResourceExport model object + */ + ResourceExport createResourceExport(); +} diff --git a/java/sca/contrib/modules/contribution-resource/src/main/java/org/apache/tuscany/sca/contribution/resource/impl/ArtifactModelResolver.java b/java/sca/contrib/modules/contribution-resource/src/main/java/org/apache/tuscany/sca/contribution/resource/impl/ArtifactModelResolver.java new file mode 100644 index 0000000000..5c6bb5e245 --- /dev/null +++ b/java/sca/contrib/modules/contribution-resource/src/main/java/org/apache/tuscany/sca/contribution/resource/impl/ArtifactModelResolver.java @@ -0,0 +1,86 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.contribution.resource.impl; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.tuscany.sca.contribution.Artifact; +import org.apache.tuscany.sca.contribution.Contribution; +import org.apache.tuscany.sca.contribution.Import; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.contribution.resource.ResourceImport; +import org.apache.tuscany.sca.core.FactoryExtensionPoint; + +/** + * A Model Resolver for contribution artifacts. + * + * @version $Rev$ $Date$ + */ +public class ArtifactModelResolver implements ModelResolver { + private Contribution contribution; + private Map map = new HashMap(); + + public ArtifactModelResolver(Contribution contribution, FactoryExtensionPoint modelFactories) { + this.contribution = contribution; + } + + public void addModel(Object resolved) { + Artifact artifact = (Artifact)resolved; + map.put(artifact.getURI(), artifact); + } + + public Object removeModel(Object resolved) { + return map.remove(((Artifact)resolved).getURI()); + } + + public T resolveModel(Class modelClass, T unresolved) { + + // Get the artifact URI + String uri = ((Artifact)unresolved).getURI(); + if (uri == null) { + return (T)unresolved; + } + + // Lookup the artifact + Artifact resolved = (Artifact) map.get(uri); + if (resolved != null) { + return modelClass.cast(resolved); + } + + // If not found, delegate the resolution to the imports (in this case based on the resource imports) + for (Import import_ : this.contribution.getImports()) { + if (import_ instanceof ResourceImport) { + ResourceImport resourceImport = (ResourceImport)import_; + //check the import location against the computed package name from the componentType URI + if (resourceImport.getURI().equals(uri)) { + // Delegate the resolution to the import resolver + resolved = resourceImport.getModelResolver().resolveModel(Artifact.class, (Artifact)unresolved); + if (!resolved.isUnresolved()) { + return modelClass.cast(resolved); + } + } + } + } + + return (T)unresolved; + } + +} diff --git a/java/sca/contrib/modules/contribution-resource/src/main/java/org/apache/tuscany/sca/contribution/resource/impl/ResourceExportImpl.java b/java/sca/contrib/modules/contribution-resource/src/main/java/org/apache/tuscany/sca/contribution/resource/impl/ResourceExportImpl.java new file mode 100644 index 0000000000..c2d525dfef --- /dev/null +++ b/java/sca/contrib/modules/contribution-resource/src/main/java/org/apache/tuscany/sca/contribution/resource/impl/ResourceExportImpl.java @@ -0,0 +1,58 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.contribution.resource.impl; + +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.contribution.resource.ResourceExport; + +/** + * The representation of an export for the contribution + * + * @version $Rev$ $Date$ + */ +public class ResourceExportImpl implements ResourceExport { + /** + * The resource URI to be exported + */ + private String uri; + + private ModelResolver modelResolver; + + protected ResourceExportImpl() { + super(); + } + + public String getURI() { + return uri; + } + + public void setURI(String uri) { + this.uri = uri; + } + + public ModelResolver getModelResolver() { + return modelResolver; + } + + public void setModelResolver(ModelResolver modelResolver) { + this.modelResolver = modelResolver; + } + +} diff --git a/java/sca/contrib/modules/contribution-resource/src/main/java/org/apache/tuscany/sca/contribution/resource/impl/ResourceExportModelResolver.java b/java/sca/contrib/modules/contribution-resource/src/main/java/org/apache/tuscany/sca/contribution/resource/impl/ResourceExportModelResolver.java new file mode 100644 index 0000000000..fd568e533d --- /dev/null +++ b/java/sca/contrib/modules/contribution-resource/src/main/java/org/apache/tuscany/sca/contribution/resource/impl/ResourceExportModelResolver.java @@ -0,0 +1,65 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.contribution.resource.impl; + +import org.apache.tuscany.sca.contribution.Artifact; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.contribution.resource.ResourceExport; + +/** + * A model resolver for resource exports. + * + * @version $Rev$ $Date$ + */ +public class ResourceExportModelResolver implements ModelResolver { + + private ResourceExport export; + private ModelResolver resolver; + + public ResourceExportModelResolver(ResourceExport export, ModelResolver resolver) { + this.export = export; + this.resolver = resolver; + } + + public void addModel(Object resolved) { + throw new IllegalStateException(); + } + + public Object removeModel(Object resolved) { + throw new IllegalStateException(); + } + + public T resolveModel(Class modelClass, T unresolved) { + + // Filter based on the artifact URI + Artifact artifact = (Artifact)unresolved; + if (export.getURI().equals(artifact.getURI())) { + + // The artifact URI matches the exported URI, delegate to the + // contribution's resolver + return resolver.resolveModel(modelClass, unresolved); + } else { + + // The artifact URI is not exported, return the unresolved object + return unresolved; + } + } + +} diff --git a/java/sca/contrib/modules/contribution-resource/src/main/java/org/apache/tuscany/sca/contribution/resource/impl/ResourceExportProcessor.java b/java/sca/contrib/modules/contribution-resource/src/main/java/org/apache/tuscany/sca/contribution/resource/impl/ResourceExportProcessor.java new file mode 100644 index 0000000000..885427e92c --- /dev/null +++ b/java/sca/contrib/modules/contribution-resource/src/main/java/org/apache/tuscany/sca/contribution/resource/impl/ResourceExportProcessor.java @@ -0,0 +1,161 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.contribution.resource.impl; + +import static javax.xml.stream.XMLStreamConstants.START_ELEMENT; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamConstants; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; + +import org.apache.tuscany.sca.contribution.processor.ContributionReadException; +import org.apache.tuscany.sca.contribution.processor.ContributionResolveException; +import org.apache.tuscany.sca.contribution.processor.ContributionWriteException; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.contribution.resource.ResourceExport; +import org.apache.tuscany.sca.contribution.resource.ResourceImportExportFactory; +import org.apache.tuscany.sca.core.FactoryExtensionPoint; +import org.apache.tuscany.sca.monitor.Monitor; +import org.apache.tuscany.sca.monitor.Problem; +import org.apache.tuscany.sca.monitor.Problem.Severity; + +/** + * Artifact processor for Resource export + * + * @version $Rev$ $Date$ + */ +public class ResourceExportProcessor implements StAXArtifactProcessor { + + private static final String SCA10_NS = "http://www.osoa.org/xmlns/sca/1.0"; + private static final QName EXPORT_RESOURCE = new QName(SCA10_NS, "export.resource"); + private static final String URI = "uri"; + + private final ResourceImportExportFactory factory; + private final Monitor monitor; + + public ResourceExportProcessor(FactoryExtensionPoint modelFactories, Monitor monitor) { + this.factory = modelFactories.getFactory(ResourceImportExportFactory.class); + this.monitor = monitor; + } + + /** + * Report a error. + * + * @param problems + * @param message + * @param model + */ + private void error(String message, Object model, Object... messageParameters) { + if (monitor != null) { + Problem problem = monitor.createProblem(this.getClass().getName(), "contribution-resource-validation-messages", Severity.ERROR, model, message, (Object[])messageParameters); + monitor.problem(problem); + } + } + + /** + * Report a exception. + * + * @param problems + * @param message + * @param model + */ + private void error(String message, Object model, Exception ex) { + if (monitor != null) { + Problem problem = new ProblemImpl(this.getClass().getName(), "contribution-resource-validation-messages", Severity.ERROR, model, message, ex); + monitor.problem(problem); + } + } + + public QName getArtifactType() { + return EXPORT_RESOURCE; + } + + public Class getModelType() { + return ResourceExport.class; + } + + /** + * Process + */ + public ResourceExport read(XMLStreamReader reader) throws ContributionReadException { + ResourceExport resourceExport = this.factory.createResourceExport(); + QName element = null; + + try { + while (reader.hasNext()) { + int event = reader.getEventType(); + switch (event) { + case START_ELEMENT: + element = reader.getName(); + + // Read + if (EXPORT_RESOURCE.equals(element)) { + String uri = reader.getAttributeValue(null, URI); + if (uri == null) { + error("AttributeURIMissing", reader); + //throw new ContributionReadException("Attribute 'uri' is missing"); + } else + resourceExport.setURI(uri); + } + + break; + case XMLStreamConstants.END_ELEMENT: + if (EXPORT_RESOURCE.equals(reader.getName())) { + return resourceExport; + } + break; + } + + // Read the next element + if (reader.hasNext()) { + reader.next(); + } + } + } + catch (XMLStreamException e) { + ContributionReadException ex = new ContributionReadException(e); + error("XMLStreamException", reader, ex); + } + + return resourceExport; + } + + public void write(ResourceExport resourceExport, XMLStreamWriter writer) throws ContributionWriteException, XMLStreamException { + + // Write + writer.writeStartElement(EXPORT_RESOURCE.getNamespaceURI(), EXPORT_RESOURCE.getLocalPart()); + + if (resourceExport.getURI() != null) { + writer.writeAttribute(URI, resourceExport.getURI()); + } + + writer.writeEndElement(); + } + + public void resolve(ResourceExport resourceExport, ModelResolver resolver) throws ContributionResolveException { + + if (resourceExport.getURI() != null) + // Initialize the export's model resolver + resourceExport.setModelResolver(new ResourceExportModelResolver(resourceExport, resolver)); + } +} diff --git a/java/sca/contrib/modules/contribution-resource/src/main/java/org/apache/tuscany/sca/contribution/resource/impl/ResourceImportExportFactoryImpl.java b/java/sca/contrib/modules/contribution-resource/src/main/java/org/apache/tuscany/sca/contribution/resource/impl/ResourceImportExportFactoryImpl.java new file mode 100644 index 0000000000..880f5f5786 --- /dev/null +++ b/java/sca/contrib/modules/contribution-resource/src/main/java/org/apache/tuscany/sca/contribution/resource/impl/ResourceImportExportFactoryImpl.java @@ -0,0 +1,41 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.contribution.resource.impl; + +import org.apache.tuscany.sca.contribution.resource.ResourceExport; +import org.apache.tuscany.sca.contribution.resource.ResourceImport; +import org.apache.tuscany.sca.contribution.resource.ResourceImportExportFactory; + +/** + * Resource Import/Export model factory implementation + * + * @version $Rev$ $Date$ + */ +public class ResourceImportExportFactoryImpl implements ResourceImportExportFactory { + + public ResourceImport createResourceImport() { + return new ResourceImportImpl(); + } + + public ResourceExport createResourceExport() { + return new ResourceExportImpl(); + } + +} diff --git a/java/sca/contrib/modules/contribution-resource/src/main/java/org/apache/tuscany/sca/contribution/resource/impl/ResourceImportImpl.java b/java/sca/contrib/modules/contribution-resource/src/main/java/org/apache/tuscany/sca/contribution/resource/impl/ResourceImportImpl.java new file mode 100644 index 0000000000..cd33f1290f --- /dev/null +++ b/java/sca/contrib/modules/contribution-resource/src/main/java/org/apache/tuscany/sca/contribution/resource/impl/ResourceImportImpl.java @@ -0,0 +1,107 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.contribution.resource.impl; + +import java.util.List; + +import org.apache.tuscany.sca.contribution.Contribution; +import org.apache.tuscany.sca.contribution.Export; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.contribution.resource.ResourceExport; +import org.apache.tuscany.sca.contribution.resource.ResourceImport; + +/** + * The representation of an import for the contribution + * + * @version $Rev$ $Date$ + */ +public class ResourceImportImpl implements ResourceImport { + /** + * The resource URI to be imported + */ + private String uri; + + private ModelResolver modelResolver; + private List exportContributions; + + /** + * Optional location URI pointing to a Contribution that exports the resource + */ + private String location; + + + protected ResourceImportImpl() { + super(); + } + + public String getLocation() { + return location; + } + + public void setLocation(String location) { + this.location = location; + } + + public String getURI() { + return uri; + } + + public void setURI(String uri) { + this.uri = uri; + } + + public ModelResolver getModelResolver() { + return modelResolver; + } + + public void setModelResolver(ModelResolver modelResolver) { + this.modelResolver = modelResolver; + } + + public List getExportContributions() { + return exportContributions; + } + + public void setExportContributions(List contributions) { + this.exportContributions = contributions; + } + + /** + * Match a ResourceImport to a given ResourceExport based on : + * location is not provided + * import and export resource URI match + */ + public boolean match(Export export) { + if (export instanceof ResourceExport) { + if (this.getLocation() == null || this.getLocation().length() == 0) { + if (this.getURI().equals(((ResourceExport)export).getURI())) { + return true; + } + } + + } + return false; + } + + @Override + public String toString() { + return String.valueOf(uri); + } +} diff --git a/java/sca/contrib/modules/contribution-resource/src/main/java/org/apache/tuscany/sca/contribution/resource/impl/ResourceImportProcessor.java b/java/sca/contrib/modules/contribution-resource/src/main/java/org/apache/tuscany/sca/contribution/resource/impl/ResourceImportProcessor.java new file mode 100644 index 0000000000..865ab8ff25 --- /dev/null +++ b/java/sca/contrib/modules/contribution-resource/src/main/java/org/apache/tuscany/sca/contribution/resource/impl/ResourceImportProcessor.java @@ -0,0 +1,167 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.contribution.resource.impl; + +import static javax.xml.stream.XMLStreamConstants.START_ELEMENT; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamConstants; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; + +import org.apache.tuscany.sca.contribution.processor.ContributionReadException; +import org.apache.tuscany.sca.contribution.processor.ContributionResolveException; +import org.apache.tuscany.sca.contribution.processor.ContributionWriteException; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.contribution.resource.ResourceImport; +import org.apache.tuscany.sca.contribution.resource.ResourceImportExportFactory; +import org.apache.tuscany.sca.core.FactoryExtensionPoint; +import org.apache.tuscany.sca.monitor.Monitor; +import org.apache.tuscany.sca.monitor.Problem; +import org.apache.tuscany.sca.monitor.Problem.Severity; + +/** + * Artifact processor for Namespace import + * + * @version $Rev$ $Date$ + */ +public class ResourceImportProcessor implements StAXArtifactProcessor { + private static final String SCA10_NS = "http://www.osoa.org/xmlns/sca/1.0"; + + private static final QName IMPORT_RESOURCE = new QName(SCA10_NS, "import.resource"); + + private static final String URI = "uri"; + private static final String LOCATION = "location"; + + private final ResourceImportExportFactory factory; + private final Monitor monitor; + + public ResourceImportProcessor(FactoryExtensionPoint modelFactories, Monitor monitor) { + this.factory = modelFactories.getFactory(ResourceImportExportFactory.class); + this.monitor = monitor; + } + + /** + * Report a warning. + * + * @param problems + * @param message + * @param model + */ + private void error(String message, Object model, Object... messageParameters) { + if (monitor != null) { + Problem problem = monitor.createProblem(this.getClass().getName(), "contribution-resource-validation-messages", Severity.ERROR, model, message, (Object[])messageParameters); + monitor.problem(problem); + } + } + + /** + * Report a exception. + * + * @param problems + * @param message + * @param model + */ + private void error(String message, Object model, Exception ex) { + if (monitor != null) { + Problem problem = new ProblemImpl(this.getClass().getName(), "contribution-resource-validation-messages", Severity.ERROR, model, message, ex); + monitor.problem(problem); + } + } + + public QName getArtifactType() { + return IMPORT_RESOURCE; + } + + public Class getModelType() { + return ResourceImport.class; + } + + /** + * Process + */ + public ResourceImport read(XMLStreamReader reader) throws ContributionReadException { + ResourceImport resourceImport = this.factory.createResourceImport(); + QName element; + + try { + while (reader.hasNext()) { + int event = reader.getEventType(); + switch (event) { + case START_ELEMENT: + element = reader.getName(); + + // Read + if (IMPORT_RESOURCE.equals(element)) { + String uri = reader.getAttributeValue(null, URI); + if (uri == null) { + error("AttributeURIMissing", reader); + //throw new ContributionReadException("Attribute 'uri' is missing"); + } else + resourceImport.setURI(uri); + + String location = reader.getAttributeValue(null, LOCATION); + if (location != null) { + resourceImport.setLocation(location); + } + } + break; + case XMLStreamConstants.END_ELEMENT: + if (IMPORT_RESOURCE.equals(reader.getName())) { + return resourceImport; + } + break; + } + + // Read the next element + if (reader.hasNext()) { + reader.next(); + } + } + } + catch (XMLStreamException e) { + ContributionReadException ex = new ContributionReadException(e); + error("XMLStreamException", reader, ex); + } + + return resourceImport; + } + + public void write(ResourceImport resourceImport, XMLStreamWriter writer) throws ContributionWriteException, XMLStreamException { + + // Write + writer.writeStartElement(IMPORT_RESOURCE.getNamespaceURI(), IMPORT_RESOURCE.getLocalPart()); + + if (resourceImport.getURI() != null) { + writer.writeAttribute(URI, resourceImport.getURI()); + } + if (resourceImport.getLocation() != null) { + writer.writeAttribute(LOCATION, resourceImport.getLocation()); + } + + writer.writeEndElement(); + } + + + public void resolve(ResourceImport model, ModelResolver resolver) throws ContributionResolveException { + } +} diff --git a/java/sca/contrib/modules/contribution-resource/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor b/java/sca/contrib/modules/contribution-resource/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor new file mode 100644 index 0000000000..14eb81546d --- /dev/null +++ b/java/sca/contrib/modules/contribution-resource/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor @@ -0,0 +1,19 @@ +# 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. + +org.apache.tuscany.sca.contribution.resource.impl.ResourceImportProcessor;qname=http://www.osoa.org/xmlns/sca/1.0#import.resource,model=org.apache.tuscany.sca.contribution.resource.ResourceImport +org.apache.tuscany.sca.contribution.resource.impl.ResourceExportProcessor;qname=http://www.osoa.org/xmlns/sca/1.0#export.resource,model=org.apache.tuscany.sca.contribution.resource.ResourceExport diff --git a/java/sca/contrib/modules/contribution-resource/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.resolver.ModelResolver b/java/sca/contrib/modules/contribution-resource/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.resolver.ModelResolver new file mode 100644 index 0000000000..08d2b1c338 --- /dev/null +++ b/java/sca/contrib/modules/contribution-resource/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.resolver.ModelResolver @@ -0,0 +1,18 @@ +# 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. + +org.apache.tuscany.sca.contribution.resource.impl.ArtifactModelResolver;model=org.apache.tuscany.sca.contribution.Artifact \ No newline at end of file diff --git a/java/sca/contrib/modules/contribution-resource/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.resource.ResourceImportExportFactory b/java/sca/contrib/modules/contribution-resource/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.resource.ResourceImportExportFactory new file mode 100644 index 0000000000..d39a5065c2 --- /dev/null +++ b/java/sca/contrib/modules/contribution-resource/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.resource.ResourceImportExportFactory @@ -0,0 +1,18 @@ +# 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. + +org.apache.tuscany.sca.contribution.resource.impl.ResourceImportExportFactoryImpl diff --git a/java/sca/contrib/modules/contribution-resource/src/main/resources/contribution-resource-validation-messages.properties b/java/sca/contrib/modules/contribution-resource/src/main/resources/contribution-resource-validation-messages.properties new file mode 100644 index 0000000000..9df66cce52 --- /dev/null +++ b/java/sca/contrib/modules/contribution-resource/src/main/resources/contribution-resource-validation-messages.properties @@ -0,0 +1,23 @@ +# +# +# 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. +# +# +AttributeURIMissing = Attribute 'uri' is missing +XMLStreamException = XMLStreamException occured due to : {0} + diff --git a/java/sca/contrib/modules/contribution-resource/src/test/java/org/apache/tuscany/sca/contribution/resource/impl/ResourceExportProcessorTestCase.java b/java/sca/contrib/modules/contribution-resource/src/test/java/org/apache/tuscany/sca/contribution/resource/impl/ResourceExportProcessorTestCase.java new file mode 100644 index 0000000000..52ec0b4cfc --- /dev/null +++ b/java/sca/contrib/modules/contribution-resource/src/test/java/org/apache/tuscany/sca/contribution/resource/impl/ResourceExportProcessorTestCase.java @@ -0,0 +1,106 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.contribution.resource.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.io.StringReader; + +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sca.contribution.processor.ExtensibleStAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessorExtensionPoint; +import org.apache.tuscany.sca.contribution.resource.ResourceExport; +import org.apache.tuscany.sca.core.DefaultExtensionPointRegistry; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.core.UtilityExtensionPoint; +import org.apache.tuscany.sca.monitor.DefaultMonitorFactory; +import org.apache.tuscany.sca.monitor.Monitor; +import org.apache.tuscany.sca.monitor.MonitorFactory; +import org.apache.tuscany.sca.monitor.Problem; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * Test NamespaceExportProcessorTestCase + * + * @version $Rev$ $Date$ + */ +public class ResourceExportProcessorTestCase { + + private static final String VALID_XML = + "" + ""; + + private static final String INVALID_XML = + "" + ""; + + private static XMLInputFactory inputFactory; + private static StAXArtifactProcessor staxProcessor; + private static Monitor monitor; + + @BeforeClass + public static void setUp() throws Exception { + ExtensionPointRegistry extensionPoints = new DefaultExtensionPointRegistry(); + inputFactory = XMLInputFactory.newInstance(); + // Create a monitor + UtilityExtensionPoint utilities = extensionPoints.getExtensionPoint(UtilityExtensionPoint.class); + MonitorFactory monitorFactory = new DefaultMonitorFactory(); + if (monitorFactory != null) { + monitor = monitorFactory.createMonitor(); + utilities.addUtility(monitorFactory); + } + StAXArtifactProcessorExtensionPoint staxProcessors = + extensionPoints.getExtensionPoint(StAXArtifactProcessorExtensionPoint.class); + staxProcessor = new ExtensibleStAXArtifactProcessor(staxProcessors, inputFactory, null, null); + } + + /** + * Test loading a valid export element from a contribution metadata stream + * @throws Exception + */ + @Test + public void testLoad() throws Exception { + XMLStreamReader reader = inputFactory.createXMLStreamReader(new StringReader(VALID_XML)); + ResourceExport resourceExport = (ResourceExport)staxProcessor.read(reader); + assertEquals("helloworld/HelloWorldService.componentType", resourceExport.getURI()); + } + + /** + * Test loading an INVALID export element from a contribution metadata stream + * @throws Exception + */ + @Test + public void testLoadInvalid() throws Exception { + XMLStreamReader reader = inputFactory.createXMLStreamReader(new StringReader(INVALID_XML)); + /*try { + staxProcessor.read(reader); + fail("readerException should have been thrown"); + } catch (ContributionReadException e) { + assertTrue(true); + }*/ + staxProcessor.read(reader); + Problem problem = monitor.getLastProblem(); + assertNotNull(problem); + assertEquals("AttributeURIMissing", problem.getMessageId()); + } +} diff --git a/java/sca/contrib/modules/contribution-resource/src/test/java/org/apache/tuscany/sca/contribution/resource/impl/ResourceImportProcessorTestCase.java b/java/sca/contrib/modules/contribution-resource/src/test/java/org/apache/tuscany/sca/contribution/resource/impl/ResourceImportProcessorTestCase.java new file mode 100644 index 0000000000..1fc439f073 --- /dev/null +++ b/java/sca/contrib/modules/contribution-resource/src/test/java/org/apache/tuscany/sca/contribution/resource/impl/ResourceImportProcessorTestCase.java @@ -0,0 +1,107 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.contribution.resource.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.io.StringReader; + +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sca.contribution.processor.ExtensibleStAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessorExtensionPoint; +import org.apache.tuscany.sca.contribution.resource.ResourceImport; +import org.apache.tuscany.sca.core.DefaultExtensionPointRegistry; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.core.UtilityExtensionPoint; +import org.apache.tuscany.sca.monitor.DefaultMonitorFactory; +import org.apache.tuscany.sca.monitor.Monitor; +import org.apache.tuscany.sca.monitor.MonitorFactory; +import org.apache.tuscany.sca.monitor.Problem; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * Test NamespaceImportProcessorTestCase + * + * @version $Rev$ $Date$ + */ +public class ResourceImportProcessorTestCase { + + private static final String VALID_XML = + "" + ""; + + private static final String INVALID_XML = + "" + ""; + + private static XMLInputFactory inputFactory; + private static StAXArtifactProcessor staxProcessor; + private static Monitor monitor; + + @BeforeClass + public static void setUp() throws Exception { + ExtensionPointRegistry extensionPoints = new DefaultExtensionPointRegistry(); + inputFactory = XMLInputFactory.newInstance(); + // Create a monitor + UtilityExtensionPoint utilities = extensionPoints.getExtensionPoint(UtilityExtensionPoint.class); + MonitorFactory monitorFactory = new DefaultMonitorFactory(); + if (monitorFactory != null) { + monitor = monitorFactory.createMonitor(); + utilities.addUtility(monitorFactory); + } + StAXArtifactProcessorExtensionPoint staxProcessors = + extensionPoints.getExtensionPoint(StAXArtifactProcessorExtensionPoint.class); + staxProcessor = new ExtensibleStAXArtifactProcessor(staxProcessors, inputFactory, null, null); + } + + /** + * Test loading a valid import element from a contribution metadata stream + * @throws Exception + */ + @Test + public void testLoad() throws Exception { + XMLStreamReader reader = inputFactory.createXMLStreamReader(new StringReader(VALID_XML)); + ResourceImport namespaceImport = (ResourceImport)staxProcessor.read(reader); + assertEquals("helloworld/HelloWorldService.componentType", namespaceImport.getURI()); + assertEquals("sca://contributions/001", namespaceImport.getLocation()); + } + + /** + * Test loading a INVALID import element from a contribution metadata stream + * @throws Exception + */ + @Test + public void testLoadInvalid() throws Exception { + XMLStreamReader reader = inputFactory.createXMLStreamReader(new StringReader(INVALID_XML)); + /*try { + staxProcessor.read(reader); + fail("readerException should have been thrown"); + } catch (ContributionReadException e) { + assertTrue(true); + }*/ + staxProcessor.read(reader); + Problem problem = monitor.getLastProblem(); + assertNotNull(problem); + assertEquals("AttributeURIMissing", problem.getMessageId()); + } +} diff --git a/java/sca/contrib/modules/data-api/LICENSE b/java/sca/contrib/modules/data-api/LICENSE new file mode 100644 index 0000000000..8aa906c321 --- /dev/null +++ b/java/sca/contrib/modules/data-api/LICENSE @@ -0,0 +1,205 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + + diff --git a/java/sca/contrib/modules/data-api/META-INF/MANIFEST.MF b/java/sca/contrib/modules/data-api/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..39743da4f3 --- /dev/null +++ b/java/sca/contrib/modules/data-api/META-INF/MANIFEST.MF @@ -0,0 +1,17 @@ +Manifest-Version: 1.0 +Export-Package: org.apache.tuscany.sca.data.collection;uses:="org.oasisopen + .sca.annotations";version="2.0.0" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA Data API +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397254562 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA Data API +Import-Package: org.apache.tuscany.sca.data.collection;version="2.0.0", + org.oasisopen.sca.annotation;version="2.0.0" +Bundle-SymbolicName: org.apache.tuscany.sca.data.api +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/data-api/NOTICE b/java/sca/contrib/modules/data-api/NOTICE new file mode 100644 index 0000000000..25bb89c9b2 --- /dev/null +++ b/java/sca/contrib/modules/data-api/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/data-api/pom.xml b/java/sca/contrib/modules/data-api/pom.xml new file mode 100644 index 0000000000..392c2871bf --- /dev/null +++ b/java/sca/contrib/modules/data-api/pom.xml @@ -0,0 +1,39 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + tuscany-data-api + Apache Tuscany SCA Data API + + + + org.apache.tuscany.sca + tuscany-sca-api + 2.0-SNAPSHOT + + + + diff --git a/java/sca/contrib/modules/data-api/src/main/java/org/apache/tuscany/sca/data/collection/Collection.java b/java/sca/contrib/modules/data-api/src/main/java/org/apache/tuscany/sca/data/collection/Collection.java new file mode 100644 index 0000000000..f1841c975e --- /dev/null +++ b/java/sca/contrib/modules/data-api/src/main/java/org/apache/tuscany/sca/data/collection/Collection.java @@ -0,0 +1,78 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.data.collection; + +import org.oasisopen.sca.annotation.Remotable; + +/** + * Provides access to a collection of data items. + * + * @version $Rev$ $Date$ + */ +@Remotable +public interface Collection { + + /** + * Get the whole collection. + * + * @return the whole collection. + */ + Entry[] getAll(); + + /** + * Returns a collection resulting from a query. + * + * @return the collection. + */ + Entry[] query(String queryString); + + /** + * Creates a new item. + * + * @param key + * @param item + * @return + */ + K post(K key, D item); + + /** + * Retrieves an item. + * + * @param key + * @return + */ + D get(K key) throws NotFoundException; + + /** + * Updates an item. + * + * @param key + * @param item + * @return + */ + void put(K key, D item) throws NotFoundException; + + /** + * Delete an item. + * + * @param key + */ + void delete(K key) throws NotFoundException; + +} diff --git a/java/sca/contrib/modules/data-api/src/main/java/org/apache/tuscany/sca/data/collection/Entry.java b/java/sca/contrib/modules/data-api/src/main/java/org/apache/tuscany/sca/data/collection/Entry.java new file mode 100644 index 0000000000..5903fd95a4 --- /dev/null +++ b/java/sca/contrib/modules/data-api/src/main/java/org/apache/tuscany/sca/data/collection/Entry.java @@ -0,0 +1,85 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.data.collection; + + +/** + * Represents a key/data pair in a data collection. + * + * @version $Rev$ $Date$ + */ +public class Entry { + + private K key; + private D data; + + /** + * Constructs a new entry. + */ + public Entry() { + } + + /** + * Constructs a new entry. + * @param key the entry key + * @param data the entry data + */ + public Entry(K key, D data) { + this.key = key; + this.data = data; + } + + /** + * Returns the entry key. + * @return the key + */ + public K getKey() { + return key; + } + + /** + * Sets the entry key. + * @param key the key + */ + public void setKey(K key) { + this.key = key; + } + + /** + * Returns the entry data. + * @return the entry data + */ + public D getData() { + return data; + } + + /** + * Sets the entry data + * @param data the entry data + */ + public void setData(D data) { + this.data = data; + } + + //FIXME Temporary methods to make JAXB register the Item + // class when the Entry class is registered in a JAXB context + public void setDummy(Item item) {} + public Item getDummy() { return null; } + +} diff --git a/java/sca/contrib/modules/data-api/src/main/java/org/apache/tuscany/sca/data/collection/Item.java b/java/sca/contrib/modules/data-api/src/main/java/org/apache/tuscany/sca/data/collection/Item.java new file mode 100644 index 0000000000..37042c0895 --- /dev/null +++ b/java/sca/contrib/modules/data-api/src/main/java/org/apache/tuscany/sca/data/collection/Item.java @@ -0,0 +1,159 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.data.collection; + +import java.util.Date; + + +/** + * Represents a data item. + * + * @version $Rev$ $Date$ + */ +public class Item { + + private String title; + private String contents; + private String link; + private String related; + private String alternate; + private Date date; + + /** + * Constructs a new item. + */ + public Item() { + } + + /** + * Constructs a new item. + * @param title the item title + * @param contents the item contents + * @param link the item link to a web resource + * @param related the item link to a related web resource + * @param date the item date + */ + public Item(String title, String contents, String link, String related, Date date) { + this.title = title; + this.contents = contents; + this.link = link; + this.related = related; + this.date = date; + } + + /** + * Returns the item title. + * @return the item title + */ + public String getTitle() { + return title; + } + + /** + * Sets the item title. + * @param title the item title + */ + public void setTitle(String title) { + this.title = title; + } + + /** + * Returns the item contents + * @return the item contents + */ + public String getContents() { + return contents; + } + + /** + * Sets the item contents + * @param contents the item contents + */ + public void setContents(String contents) { + this.contents = contents; + } + + /** + * Returns the item link to a web resource + * @return the item link to a web resource + */ + public String getLink() { + return link; + } + + /** + * Sets the item link to a web resource + * @param link the item link to a web resource + */ + public void setLink(String link) { + this.link = link; + } + + /** + * Returns the item link to a related web resource + * @return the item link to a related web resource + */ + public String getRelated() { + return related; + } + + /** + * Sets the item link to a related web resource. + * + * @param related the item link to a related web resource + */ + public void setRelated(String related) { + this.related = related; + } + + /** + * Returns the item link to an alternate web resource + * @return the item link to an alternate web resource + */ + public String getAlternate() { + return alternate; + } + + /** + * Sets the item link to an alternate web resource. + * + * @param alternate the item link to an alternate web resource + */ + public void setAlternate(String alternate) { + this.alternate = alternate; + } + + /** + * Returns the item date + * @return the item date + */ + public Date getDate() { + return date; + } + + /** + * Sets the item date + * @param date the item date + */ + public void setDate(Date date) { + this.date = date; + } + + +} diff --git a/java/sca/contrib/modules/data-api/src/main/java/org/apache/tuscany/sca/data/collection/ItemCollection.java b/java/sca/contrib/modules/data-api/src/main/java/org/apache/tuscany/sca/data/collection/ItemCollection.java new file mode 100644 index 0000000000..229b29f5cd --- /dev/null +++ b/java/sca/contrib/modules/data-api/src/main/java/org/apache/tuscany/sca/data/collection/ItemCollection.java @@ -0,0 +1,30 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.data.collection; + +import org.oasisopen.sca.annotation.Remotable; + +/** + * Provides access to a collection of data items. + * + * @version $Rev$ $Date$ + */ +@Remotable +public interface ItemCollection extends Collection { +} diff --git a/java/sca/contrib/modules/data-api/src/main/java/org/apache/tuscany/sca/data/collection/LocalItemCollection.java b/java/sca/contrib/modules/data-api/src/main/java/org/apache/tuscany/sca/data/collection/LocalItemCollection.java new file mode 100644 index 0000000000..69512058b7 --- /dev/null +++ b/java/sca/contrib/modules/data-api/src/main/java/org/apache/tuscany/sca/data/collection/LocalItemCollection.java @@ -0,0 +1,28 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.data.collection; + + +/** + * Provides access to a collection of data items. + * + * @version $Rev$ $Date$ + */ +public interface LocalItemCollection extends Collection { +} diff --git a/java/sca/contrib/modules/data-api/src/main/java/org/apache/tuscany/sca/data/collection/NotFoundException.java b/java/sca/contrib/modules/data-api/src/main/java/org/apache/tuscany/sca/data/collection/NotFoundException.java new file mode 100644 index 0000000000..7f13db5228 --- /dev/null +++ b/java/sca/contrib/modules/data-api/src/main/java/org/apache/tuscany/sca/data/collection/NotFoundException.java @@ -0,0 +1,45 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.data.collection; + +/** + * Indicates that an item could not be found in a collection. + * + * @version $Rev$ $Date$ + */ +public class NotFoundException extends Exception { + private static final long serialVersionUID = 6792367409396084646L; + + public NotFoundException() { + } + + public NotFoundException(String message) { + super(message); + } + + public NotFoundException(Throwable cause) { + super(cause); + } + + public NotFoundException(String message, Throwable cause) { + super(message, cause); + } + +} diff --git a/java/sca/contrib/modules/databinding-fastinfoset/LICENSE b/java/sca/contrib/modules/databinding-fastinfoset/LICENSE new file mode 100644 index 0000000000..d645695673 --- /dev/null +++ b/java/sca/contrib/modules/databinding-fastinfoset/LICENSE @@ -0,0 +1,202 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/java/sca/contrib/modules/databinding-fastinfoset/META-INF/MANIFEST.MF b/java/sca/contrib/modules/databinding-fastinfoset/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..8fc38ffe23 --- /dev/null +++ b/java/sca/contrib/modules/databinding-fastinfoset/META-INF/MANIFEST.MF @@ -0,0 +1,28 @@ +Manifest-Version: 1.0 +Private-Package: org.apache.tuscany.sca.databinding.fastinfoset;versio + n="1.4" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany Data Binding for FastInfoset +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397405343 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany Data Binding for FastInfoset +Import-Package: com.sun.xml.fastinfoset, + com.sun.xml.fastinfoset.dom, + com.sun.xml.fastinfoset.sax, + com.sun.xml.fastinfoset.stax, + javax.xml.parsers, + javax.xml.stream, + + org.apache.tuscany.sca.databinding;version="2.0.0", + org.apache.tuscany.sca.databinding.impl;version="2.0.0", + org.apache.tuscany.sca.databinding.xml;version="2.0.0", + org.w3c.dom, + org.xml.sax, + org.xml.sax.helpers +Bundle-SymbolicName: org.apache.tuscany.sca.databinding.fastinfoset +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/databinding-fastinfoset/NOTICE b/java/sca/contrib/modules/databinding-fastinfoset/NOTICE new file mode 100644 index 0000000000..25bb89c9b2 --- /dev/null +++ b/java/sca/contrib/modules/databinding-fastinfoset/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/databinding-fastinfoset/pom.xml b/java/sca/contrib/modules/databinding-fastinfoset/pom.xml new file mode 100644 index 0000000000..955f9d615e --- /dev/null +++ b/java/sca/contrib/modules/databinding-fastinfoset/pom.xml @@ -0,0 +1,70 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + tuscany-databinding-fastinfoset + Apache Tuscany Data Binding for FastInfoset + Tuscany FastInfoset Data Binding + + + + org.apache.tuscany.sca + tuscany-core-spi + 2.0-SNAPSHOT + + + org.apache.tuscany.sca + tuscany-databinding + 2.0-SNAPSHOT + + + + com.sun.xml.fastinfoset + FastInfoset + 1.2.2 + compile + + + + junit + junit + 4.5 + test + + + + + + true + + java.net + java.net Maven 1.x Repository + http://download.java.net/maven/1 + legacy + + + + diff --git a/java/sca/contrib/modules/databinding-fastinfoset/src/main/java/org/apache/tuscany/sca/databinding/fastinfoset/FastInfoset2Node.java b/java/sca/contrib/modules/databinding-fastinfoset/src/main/java/org/apache/tuscany/sca/databinding/fastinfoset/FastInfoset2Node.java new file mode 100644 index 0000000000..2e0aa629f3 --- /dev/null +++ b/java/sca/contrib/modules/databinding-fastinfoset/src/main/java/org/apache/tuscany/sca/databinding/fastinfoset/FastInfoset2Node.java @@ -0,0 +1,70 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.fastinfoset; + +import java.io.InputStream; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.apache.tuscany.sca.databinding.impl.DOMHelper; +import org.w3c.dom.Document; +import org.w3c.dom.Node; + +import com.sun.xml.fastinfoset.dom.DOMDocumentParser; + +/** + * @version $Rev$ $Date$ + */ +public class FastInfoset2Node extends BaseTransformer implements + PullTransformer { + + @Override + protected Class getSourceType() { + return InputStream.class; + } + + @Override + protected Class getTargetType() { + return Node.class; + } + + public Node transform(InputStream source, TransformationContext context) { + try { + DOMDocumentParser parser = new DOMDocumentParser(); + Document doc = DOMHelper.newDocument(); + parser.parse(doc, source); + return doc.getDocumentElement(); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + public int getWeight() { + return 20; + } + + @Override + public String getSourceDataBinding() { + return "xml:fastinfoset:java.io.InputStream"; + } +} diff --git a/java/sca/contrib/modules/databinding-fastinfoset/src/main/java/org/apache/tuscany/sca/databinding/fastinfoset/FastInfoset2SAX.java b/java/sca/contrib/modules/databinding-fastinfoset/src/main/java/org/apache/tuscany/sca/databinding/fastinfoset/FastInfoset2SAX.java new file mode 100644 index 0000000000..77f6b77636 --- /dev/null +++ b/java/sca/contrib/modules/databinding-fastinfoset/src/main/java/org/apache/tuscany/sca/databinding/fastinfoset/FastInfoset2SAX.java @@ -0,0 +1,71 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.fastinfoset; + +import java.io.InputStream; + +import org.apache.tuscany.sca.databinding.PushTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.xml.sax.ContentHandler; + +import com.sun.xml.fastinfoset.sax.SAXDocumentParser; + +/** + * @version $Rev$ $Date$ + */ +public class FastInfoset2SAX extends BaseTransformer implements + PushTransformer { + + @Override + protected Class getSourceType() { + return InputStream.class; + } + + @Override + protected Class getTargetType() { + return ContentHandler.class; + } + + + /** + * @see org.apache.tuscany.sca.databinding.PushTransformer#transform(java.lang.Object, java.lang.Object, org.apache.tuscany.sca.databinding.TransformationContext) + */ + public void transform(InputStream source, ContentHandler target, TransformationContext context) { + try { + SAXDocumentParser parser = new SAXDocumentParser(); + parser.setContentHandler(target); + parser.parse(source); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + public int getWeight() { + return 20; + } + + @Override + public String getSourceDataBinding() { + return "xml:fastinfoset:java.io.InputStream"; + } +} diff --git a/java/sca/contrib/modules/databinding-fastinfoset/src/main/java/org/apache/tuscany/sca/databinding/fastinfoset/FastInfoset2XMLStreamReader.java b/java/sca/contrib/modules/databinding-fastinfoset/src/main/java/org/apache/tuscany/sca/databinding/fastinfoset/FastInfoset2XMLStreamReader.java new file mode 100644 index 0000000000..73d549f4f8 --- /dev/null +++ b/java/sca/contrib/modules/databinding-fastinfoset/src/main/java/org/apache/tuscany/sca/databinding/fastinfoset/FastInfoset2XMLStreamReader.java @@ -0,0 +1,67 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.fastinfoset; + +import java.io.InputStream; + +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; + +import com.sun.xml.fastinfoset.stax.StAXDocumentParser; + +/** + * @version $Rev$ $Date$ + */ +public class FastInfoset2XMLStreamReader extends BaseTransformer implements + PullTransformer { + + @Override + protected Class getSourceType() { + return InputStream.class; + } + + @Override + protected Class getTargetType() { + return XMLStreamReader.class; + } + + public XMLStreamReader transform(InputStream source, TransformationContext context) { + try { + StAXDocumentParser parser = new StAXDocumentParser(source); + return parser; + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + public int getWeight() { + return 20; + } + + @Override + public String getSourceDataBinding() { + return "xml:fastinfoset:java.io.InputStream"; + } +} diff --git a/java/sca/contrib/modules/databinding-fastinfoset/src/main/java/org/apache/tuscany/sca/databinding/fastinfoset/Node2FastInfoset.java b/java/sca/contrib/modules/databinding-fastinfoset/src/main/java/org/apache/tuscany/sca/databinding/fastinfoset/Node2FastInfoset.java new file mode 100644 index 0000000000..1c12a5dcad --- /dev/null +++ b/java/sca/contrib/modules/databinding-fastinfoset/src/main/java/org/apache/tuscany/sca/databinding/fastinfoset/Node2FastInfoset.java @@ -0,0 +1,71 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.fastinfoset; + +import java.io.OutputStream; + +import org.apache.tuscany.sca.databinding.PushTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.w3c.dom.Node; + +import com.sun.xml.fastinfoset.dom.DOMDocumentSerializer; + +/** + * @version $Rev$ $Date$ + */ +public class Node2FastInfoset extends BaseTransformer implements + PushTransformer { + + @Override + protected Class getSourceType() { + return Node.class; + } + + @Override + protected Class getTargetType() { + return OutputStream.class; + } + + + /** + * @see org.apache.tuscany.sca.databinding.PushTransformer#transform(java.lang.Object, java.lang.Object, org.apache.tuscany.sca.databinding.TransformationContext) + */ + public void transform(Node source, OutputStream target, TransformationContext context) { + try { + DOMDocumentSerializer serializer = new DOMDocumentSerializer(); + serializer.setOutputStream(target); + serializer.serialize(source); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + public int getWeight() { + return 20; + } + + @Override + public String getTargetDataBinding() { + return "xml:fastinfoset:java.io.OutputStream"; + } +} diff --git a/java/sca/contrib/modules/databinding-fastinfoset/src/main/java/org/apache/tuscany/sca/databinding/fastinfoset/XMLInputStream2FastInfoset.java b/java/sca/contrib/modules/databinding-fastinfoset/src/main/java/org/apache/tuscany/sca/databinding/fastinfoset/XMLInputStream2FastInfoset.java new file mode 100644 index 0000000000..b0d56b3bb6 --- /dev/null +++ b/java/sca/contrib/modules/databinding-fastinfoset/src/main/java/org/apache/tuscany/sca/databinding/fastinfoset/XMLInputStream2FastInfoset.java @@ -0,0 +1,89 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.fastinfoset; + +import java.io.InputStream; +import java.io.OutputStream; + +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; + +import org.apache.tuscany.sca.databinding.PushTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; + +import com.sun.xml.fastinfoset.sax.SAXDocumentSerializer; + +/** + * @version $Rev$ $Date$ + */ +public class XMLInputStream2FastInfoset extends BaseTransformer implements + PushTransformer { + + @Override + protected Class getSourceType() { + return InputStream.class; + } + + @Override + protected Class getTargetType() { + return OutputStream.class; + } + + /** + * @see org.apache.tuscany.sca.databinding.PushTransformer#transform(java.lang.Object, java.lang.Object, org.apache.tuscany.sca.databinding.TransformationContext) + */ + public void transform(InputStream source, OutputStream target, TransformationContext context) { + try { + + // Create Fast Infoset SAX serializer + SAXDocumentSerializer saxDocumentSerializer = new SAXDocumentSerializer(); + // Set the output stream + saxDocumentSerializer.setOutputStream(target); + + // Instantiate JAXP SAX parser factory + SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); + /* Set parser to be namespace aware + * Very important to do otherwise invalid FI documents will be + * created by the SAXDocumentSerializer + */ + saxParserFactory.setNamespaceAware(true); + // Instantiate the JAXP SAX parser + SAXParser saxParser = saxParserFactory.newSAXParser(); + // Set the lexical handler + saxParser.setProperty("http://xml.org/sax/properties/lexical-handler", saxDocumentSerializer); + // Parse the XML document and convert to a fast infoset document + saxParser.parse(source, saxDocumentSerializer); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + public int getWeight() { + return 20; + } + + @Override + public String getTargetDataBinding() { + return "xml:fastinfoset:java.io.OutputStream"; + } +} diff --git a/java/sca/contrib/modules/databinding-fastinfoset/src/main/java/org/apache/tuscany/sca/databinding/fastinfoset/XMLStreamReader2FastInfoset.java b/java/sca/contrib/modules/databinding-fastinfoset/src/main/java/org/apache/tuscany/sca/databinding/fastinfoset/XMLStreamReader2FastInfoset.java new file mode 100644 index 0000000000..d18206600c --- /dev/null +++ b/java/sca/contrib/modules/databinding-fastinfoset/src/main/java/org/apache/tuscany/sca/databinding/fastinfoset/XMLStreamReader2FastInfoset.java @@ -0,0 +1,75 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.fastinfoset; + +import java.io.OutputStream; + +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sca.databinding.PushTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.apache.tuscany.sca.databinding.xml.XMLStreamSerializer; + +import com.sun.xml.fastinfoset.stax.StAXDocumentSerializer; + +/** + * @version $Rev$ $Date$ + */ +public class XMLStreamReader2FastInfoset extends BaseTransformer implements + PushTransformer { + + @Override + protected Class getSourceType() { + return XMLStreamReader.class; + } + + @Override + protected Class getTargetType() { + return OutputStream.class; + } + + + /** + * @see org.apache.tuscany.sca.databinding.PushTransformer#transform(java.lang.Object, java.lang.Object, org.apache.tuscany.sca.databinding.TransformationContext) + */ + public void transform(XMLStreamReader source, OutputStream target, TransformationContext context) { + try { + StAXDocumentSerializer serializer = new StAXDocumentSerializer(target); + XMLStreamSerializer streamSerializer = new XMLStreamSerializer(); + streamSerializer.serialize(source, serializer); + serializer.flush(); + source.close(); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + public int getWeight() { + return 20; + } + + @Override + public String getTargetDataBinding() { + return "xml:fastinfoset:java.io.OutputStream"; + } +} diff --git a/java/sca/contrib/modules/databinding-fastinfoset/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PullTransformer b/java/sca/contrib/modules/databinding-fastinfoset/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PullTransformer new file mode 100644 index 0000000000..ea47ee7191 --- /dev/null +++ b/java/sca/contrib/modules/databinding-fastinfoset/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PullTransformer @@ -0,0 +1,22 @@ +# 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. + +# Implementation classes for the transformers +org.apache.tuscany.sca.databinding.fastinfoset.FastInfoset2Node;source=xml:fastinfoset:java.io.InputStream,target=org.w3c.dom.Node,weight=100 +org.apache.tuscany.sca.databinding.fastinfoset.FastInfoset2XMLStreamReader;source=xml:fastinfoset:java.io.InputStream,target=javax.xml.stream.XMLStreamReader,weight=80 + + diff --git a/java/sca/contrib/modules/databinding-fastinfoset/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PushTransformer b/java/sca/contrib/modules/databinding-fastinfoset/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PushTransformer new file mode 100644 index 0000000000..1610b4f54d --- /dev/null +++ b/java/sca/contrib/modules/databinding-fastinfoset/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PushTransformer @@ -0,0 +1,22 @@ +# 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. + +# Implementation classes for the transformers +org.apache.tuscany.sca.databinding.fastinfoset.FastInfoset2SAX;source=xml:fastinfoset:java.io.InputStream,target=org.xml.sax.ContentHandler ,weight=80 +org.apache.tuscany.sca.databinding.fastinfoset.Node2FastInfoset;source=org.w3c.dom.Node,target=xml:fastinfoset:java.io.OutputStream,weight=100 +org.apache.tuscany.sca.databinding.fastinfoset.XMLInputStream2FastInfoset;source=java.io.InputStream,target=xml:fastinfoset:java.io.OutputStream,weight=120 +org.apache.tuscany.sca.databinding.fastinfoset.XMLStreamReader2FastInfoset;source=javax.xml.stream.XMLStreamReader,target=xml:fastinfoset:java.io.OutputStream,weight=70 diff --git a/java/sca/contrib/modules/databinding-fastinfoset/src/test/java/org/apache/tuscany/sca/databinding/fastinfoset/FastInfosetTransformerTestCase.java b/java/sca/contrib/modules/databinding-fastinfoset/src/test/java/org/apache/tuscany/sca/databinding/fastinfoset/FastInfosetTransformerTestCase.java new file mode 100644 index 0000000000..bb8adf39be --- /dev/null +++ b/java/sca/contrib/modules/databinding-fastinfoset/src/test/java/org/apache/tuscany/sca/databinding/fastinfoset/FastInfosetTransformerTestCase.java @@ -0,0 +1,127 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.fastinfoset; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.StringReader; + +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamReader; + +import junit.framework.TestCase; + +import org.apache.tuscany.sca.databinding.xml.InputStream2Node; +import org.apache.tuscany.sca.databinding.xml.Node2OutputStream; +import org.apache.tuscany.sca.databinding.xml.Node2String; +import org.w3c.dom.Node; + +/** + * + * @version $Rev$ $Date$ + */ +public class FastInfosetTransformerTestCase extends TestCase { + private static final String IPO_XML = + "" + "" + + " " + + " Helen Zoe" + + " 47 Eden Street" + + " Cambridge" + + " CB1 1JR" + + " " + + " " + + " Robert Smith" + + " 8 Oak Avenue" + + " Old Town" + + " PA" + + " 95819" + + " " + + " " + + " " + + " Lapis necklace" + + " 1" + + " 99.95" + + " Want this for the holidays" + + " 1999-12-05" + + " " + + " " + + ""; + + public void testXML2FastInfoset() throws Exception { + XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(IPO_XML)); + XMLStreamReader2FastInfoset t1 = new XMLStreamReader2FastInfoset(); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + + t1.transform(reader, bos, null); + // System.out.println(bos.toString()); + + ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); + FastInfoset2Node t2 = new FastInfoset2Node(); + Node node = t2.transform(bis, null); + String xml = new Node2String().transform(node, null); + + // System.out.println(xml); + + } + + public void testPerf() throws Exception { + byte[] str = IPO_XML.getBytes(); + ByteArrayInputStream bis = new ByteArrayInputStream(str); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + XMLInputStream2FastInfoset t = new XMLInputStream2FastInfoset(); + t.transform(bis, bos, null); + byte[] fast = bos.toByteArray(); + System.out.println(str.length + ".vs." + fast.length); + + long d1 = 0L; + long d2 = 0L; + for (int i = 0; i < 100; i++) { + InputStream2Node t1 = new InputStream2Node(); + FastInfoset2Node t2 = new FastInfoset2Node(); + InputStream is1 = new ByteArrayInputStream(str); + InputStream is2 = new ByteArrayInputStream(fast); + long s1 = System.currentTimeMillis(); + Node n1 = t1.transform(is1, null); + long s2 = System.currentTimeMillis(); + Node n2 = t2.transform(is2, null); + long s3 = System.currentTimeMillis(); + d1 += s2 - s1; // from plain xml + d2 += s3 - s2; // from fastinfoset + Node2OutputStream t3 = new Node2OutputStream(); + Node2FastInfoset t4 = new Node2FastInfoset(); + ByteArrayOutputStream os1 = new ByteArrayOutputStream(); + ByteArrayOutputStream os2 = new ByteArrayOutputStream(); + long s4 = System.currentTimeMillis(); + t3.transform(n1, os1, null); + long s5 = System.currentTimeMillis(); + t4.transform(n2, os2, null); + long s6 = System.currentTimeMillis(); + d1 += s5 - s4; // to plain xml + d2 += s6 - s5; // to fastinfoset + } + System.out.println("POX " + d1 + ".vs. FIS " + d2); + } + +} diff --git a/java/sca/contrib/modules/databinding-fastinfoset/src/test/resources/ipo.xsd b/java/sca/contrib/modules/databinding-fastinfoset/src/test/resources/ipo.xsd new file mode 100644 index 0000000000..5a493e1746 --- /dev/null +++ b/java/sca/contrib/modules/databinding-fastinfoset/src/test/resources/ipo.xsd @@ -0,0 +1,136 @@ + + + + + + International Purchase order schema for Example.com + Copyright 2000 Example.com. All rights reserved. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/java/sca/contrib/modules/databinding-json/LICENSE b/java/sca/contrib/modules/databinding-json/LICENSE new file mode 100644 index 0000000000..d645695673 --- /dev/null +++ b/java/sca/contrib/modules/databinding-json/LICENSE @@ -0,0 +1,202 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/java/sca/contrib/modules/databinding-json/META-INF/MANIFEST.MF b/java/sca/contrib/modules/databinding-json/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..8826f3b1b0 --- /dev/null +++ b/java/sca/contrib/modules/databinding-json/META-INF/MANIFEST.MF @@ -0,0 +1,34 @@ +Manifest-Version: 1.0 +Private-Package: org.apache.tuscany.sca.databinding.json;version="2.0.0" + ,org.apache.tuscany.sca.databinding.json.axiom;version="2.0.0" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA Data Binding for JSON +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397312078 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA Data Binding for JSON +Import-Package: com.metaparadigm.jsonrpc, + javax.xml.namespace, + javax.xml.stream, + org.apache.axiom.om, + org.apache.tuscany.sca.databinding;version="2.0.0", + org.apache.tuscany.sca.databinding.impl;version="2.0.0", + org.apache.tuscany.sca.databinding.javabeans;version="2.0.0", + org.apache.tuscany.sca.databinding.json;version="2.0.0", + org.apache.tuscany.sca.databinding.xml;version="2.0.0", + org.apache.tuscany.sca.interfacedef;version="2.0.0", + org.apache.tuscany.sca.interfacedef.impl;version="2.0.0";resolution:=optional, + org.apache.tuscany.sca.interfacedef.util;version="2.0.0", + org.codehaus.jettison.badgerfish, + org.codehaus.jettison.json, + org.codehaus.jettison.mapped, + org.json, + + org.oasisopen.sca.annotation;version="2.0.0" +Bundle-SymbolicName: org.apache.tuscany.sca.databinding.json +Bundle-DocURL: http://www.apache.org/ +Export-Package: org.apache.tuscany.sca.databinding.json;version="2.0.0" + diff --git a/java/sca/contrib/modules/databinding-json/NOTICE b/java/sca/contrib/modules/databinding-json/NOTICE new file mode 100644 index 0000000000..25bb89c9b2 --- /dev/null +++ b/java/sca/contrib/modules/databinding-json/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/databinding-json/pom.xml b/java/sca/contrib/modules/databinding-json/pom.xml new file mode 100644 index 0000000000..d1961bcdb6 --- /dev/null +++ b/java/sca/contrib/modules/databinding-json/pom.xml @@ -0,0 +1,118 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + tuscany-databinding-json + Apache Tuscany SCA Data Binding for JSON + + + + org.apache.tuscany.sca + tuscany-core-spi + 2.0-SNAPSHOT + + + org.apache.tuscany.sca + tuscany-databinding + 2.0-SNAPSHOT + + + + com.metaparadigm + json-rpc + 1.0 + compile + + + + org.codehaus.jettison + jettison + 1.0.1 + compile + + + stax + stax-api + + + + + + org.apache.ws.commons.axiom + axiom-api + 1.2.7 + + + xerces + xercesImpl + + + javax.mail + mail + + + commons-logging + commons-logging + + + stax + stax-api + + + + + + org.apache.ws.commons.axiom + axiom-impl + 1.2.7 + runtime + + + + junit + junit + 4.5 + test + + + + commons-logging + commons-logging + 1.1.1 + + + commons-logging + commons-logging + + + javax.servlet + servlet-api + + + + + + diff --git a/java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JSON2JavaBean.java b/java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JSON2JavaBean.java new file mode 100644 index 0000000000..b1813c9eab --- /dev/null +++ b/java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JSON2JavaBean.java @@ -0,0 +1,73 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.json; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.javabeans.JavaBeansDataBinding; + +import com.metaparadigm.jsonrpc.JSONSerializer; +import com.metaparadigm.jsonrpc.SerializerState; + +/** + * @version $Rev$ $Date$ + */ +public class JSON2JavaBean implements PullTransformer { + private JSONSerializer serializer; + + public JSON2JavaBean() { + super(); + serializer = new JSONSerializer(); + try { + serializer.registerDefaultSerializers(); + } catch (Exception e) { + throw new TransformationException(e); + } + serializer.setMarshallClassHints(true); + serializer.setMarshallNullAttributes(true); + } + + public Object transform(Object source, TransformationContext context) { + if (source == null) { + return null; + } + + try { + SerializerState state = new SerializerState(); + return serializer.unmarshall(state, context.getTargetDataType().getPhysical(), source); + } catch (Exception e) { + throw new TransformationException(e); + } + + } + + public String getSourceDataBinding() { + return JSONDataBinding.NAME; + } + + public String getTargetDataBinding() { + return JavaBeansDataBinding.NAME; + } + + public int getWeight() { + return 5000; + } +} diff --git a/java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JSON2String.java b/java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JSON2String.java new file mode 100644 index 0000000000..4e08384f09 --- /dev/null +++ b/java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JSON2String.java @@ -0,0 +1,61 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.json; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; + +/** + * @version $Rev$ $Date$ + */ +public class JSON2String extends BaseTransformer implements + PullTransformer { + + @Override + protected Class getSourceType() { + return Object.class; + } + + @Override + protected Class getTargetType() { + return String.class; + } + + public String transform(Object source, TransformationContext context) { + try { + return source.toString(); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + public int getWeight() { + return 500; + } + + @Override + public String getSourceDataBinding() { + return JSONDataBinding.NAME; + } + +} diff --git a/java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JSON2XMLStreamReader.java b/java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JSON2XMLStreamReader.java new file mode 100644 index 0000000000..b70f772696 --- /dev/null +++ b/java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JSON2XMLStreamReader.java @@ -0,0 +1,65 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.json; + +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.codehaus.jettison.badgerfish.BadgerFishXMLStreamReader; +import org.codehaus.jettison.json.JSONObject; + +/** + * @version $Rev$ $Date$ + */ +public class JSON2XMLStreamReader extends BaseTransformer implements + PullTransformer { + + @Override + protected Class getSourceType() { + return Object.class; + } + + @Override + protected Class getTargetType() { + return XMLStreamReader.class; + } + + public XMLStreamReader transform(Object source, TransformationContext context) { + try { + JSONObject json = JSONHelper.toJettison(source); + return new BadgerFishXMLStreamReader(json); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + public int getWeight() { + return 500; + } + @Override + public String getSourceDataBinding() { + return JSONDataBinding.NAME; + } + +} diff --git a/java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JSONDataBinding.java b/java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JSONDataBinding.java new file mode 100644 index 0000000000..28cadc6666 --- /dev/null +++ b/java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JSONDataBinding.java @@ -0,0 +1,74 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.json; + + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.databinding.impl.BaseDataBinding; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.interfacedef.util.XMLType; +import org.codehaus.jettison.json.JSONObject; + +/** + * JAXB DataBinding + * + * @version $Rev$ $Date$ + */ +public class JSONDataBinding extends BaseDataBinding { + public static final String NAME = "JSON"; + + public static final String ROOT_NAMESPACE = "http://tuscany.apache.org/xmlns/sca/databinding/json/1.0"; + public static final QName ROOT_ELEMENT = new QName(ROOT_NAMESPACE, "root"); + + public JSONDataBinding() { + super(NAME, org.json.JSONObject.class); + } + + @Override + public boolean introspect(DataType type, Operation operation) { + assert type != null; + Class cls = type.getPhysical(); + if (JSONObject.class.isAssignableFrom(cls) || org.json.JSONObject.class.isAssignableFrom(cls)) { + type.setDataBinding(getName()); + if (type.getLogical() == null) { + type.setLogical(XMLType.UNKNOWN); + } + return true; + } + return false; + } + + @SuppressWarnings("unchecked") + @Override + public Object copy(Object arg, DataType dataType, Operation operation) { + if (arg == null) { + return null; + } + try { + Class type = arg != null ? arg.getClass() : null; + return JSONHelper.toJSON(arg.toString(), type); + } catch (Exception e) { + throw new IllegalArgumentException(e); + } + } + +} diff --git a/java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JSONHelper.java b/java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JSONHelper.java new file mode 100644 index 0000000000..fb29710506 --- /dev/null +++ b/java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JSONHelper.java @@ -0,0 +1,91 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.json; + +import java.text.ParseException; + +import org.codehaus.jettison.json.JSONException; +import org.codehaus.jettison.json.JSONObject; + +/** + * @version $Rev$ $Date$ + */ +public class JSONHelper { + private JSONHelper() { + + } + + /** + * Convert to Jettison JSONObject + * @param source + * @return + */ + public static JSONObject toJettison(Object source) { + JSONObject json = null; + if (source instanceof JSONObject) { + json = (JSONObject)source; + } else if (source instanceof org.json.JSONObject) { + try { + json = new JSONObject(((org.json.JSONObject)source).toString()); + } catch (JSONException e) { + throw new IllegalArgumentException(e); + } + } + return json; + } + + /** + * Convert to org.json.JSONObject + * @param source + * @return + */ + public static org.json.JSONObject toJSONOrg(Object source) { + org.json.JSONObject json = null; + if (source instanceof JSONObject) { + try { + json = new org.json.JSONObject(((JSONObject)source).toString()); + } catch (ParseException e) { + throw new IllegalArgumentException(e); + } + } else if (source instanceof org.json.JSONObject) { + json = (org.json.JSONObject)source; + } + return json; + } + + public static T toJSON(String json, Class type) { + if (type == JSONObject.class) { + try { + return type.cast(new JSONObject(json)); + } catch (JSONException e) { + throw new IllegalArgumentException(e); + } + } else { + if (type == null) { + type = (Class)org.json.JSONObject.class; + } + try { + return type.cast(new org.json.JSONObject(json)); + } catch (ParseException e) { + throw new IllegalArgumentException(e); + } + } + } +} diff --git a/java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JavaBean2JSON.java b/java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JavaBean2JSON.java new file mode 100644 index 0000000000..a928deef22 --- /dev/null +++ b/java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JavaBean2JSON.java @@ -0,0 +1,82 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.json; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.apache.tuscany.sca.databinding.javabeans.JavaBeansDataBinding; + +import com.metaparadigm.jsonrpc.JSONSerializer; +import com.metaparadigm.jsonrpc.SerializerState; + +public class JavaBean2JSON extends BaseTransformer implements PullTransformer { + private JSONSerializer serializer; + + public JavaBean2JSON() { + serializer = new JSONSerializer(); + try { + serializer.registerDefaultSerializers(); + } catch (Exception e) { + throw new TransformationException(e); + } + serializer.setMarshallClassHints(true); + serializer.setMarshallNullAttributes(true); + } + + @Override + public String getSourceDataBinding() { + return JavaBeansDataBinding.NAME; + } + + @Override + protected Class getSourceType() { + return Object.class; + } + + @Override + public String getTargetDataBinding() { + return JSONDataBinding.NAME; + } + + @Override + protected Class getTargetType() { + return Object.class; + } + + public Object toJSON(Object source) throws Exception { + if (source == null) { + return org.json.JSONObject.NULL; + } + + SerializerState state = new SerializerState(); + return serializer.marshall(state, source); + } + + public Object transform(Object source, TransformationContext context) { + try { + return toJSON(source); + } catch (Exception e) { + throw new TransformationException(e); + } + } + +} diff --git a/java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JavaBean2JSONObject.java b/java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JavaBean2JSONObject.java new file mode 100644 index 0000000000..de023157bc --- /dev/null +++ b/java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JavaBean2JSONObject.java @@ -0,0 +1,139 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.json; + +import java.beans.BeanInfo; +import java.beans.Introspector; +import java.beans.PropertyDescriptor; +import java.lang.reflect.Array; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.apache.tuscany.sca.databinding.impl.SimpleTypeMapperImpl; +import org.apache.tuscany.sca.databinding.javabeans.JavaBeansDataBinding; +import org.apache.tuscany.sca.interfacedef.util.TypeInfo; +import org.codehaus.jettison.json.JSONArray; +import org.codehaus.jettison.json.JSONObject; + +public class JavaBean2JSONObject extends BaseTransformer implements PullTransformer { + private static final Comparator COMPARATOR = new Comparator() { + public int compare(PropertyDescriptor o1, PropertyDescriptor o2) { + return o1.getName().compareTo(o2.getName()); + } + }; + + private static final SimpleTypeMapperImpl MAPPER = new SimpleTypeMapperImpl(); + private static final Object[] NULL = null; + + private static String getStringValue(Object o) { + if (o == null) { + return null; + } + TypeInfo info = SimpleTypeMapperImpl.getXMLType(o.getClass()); + if (info != null) { + return MAPPER.toXMLLiteral(info.getQName(), o, null); + } else { + return String.valueOf(o); + } + } + + private static boolean isSimpleType(Class javaType) { + return SimpleTypeMapperImpl.getXMLType(javaType) != null; + } + + public JavaBean2JSONObject() { + } + + @Override + public String getSourceDataBinding() { + return JavaBeansDataBinding.NAME; + } + + @Override + protected Class getSourceType() { + return Object.class; + } + + @Override + public String getTargetDataBinding() { + return JSONDataBinding.NAME; + } + + @Override + protected Class getTargetType() { + return Object.class; + } + + public Object toJSON(Object source) throws Exception { + if (source == null) { + return JSONObject.NULL; + } + Class type = source.getClass(); + if (isSimpleType(type)) { + return source; + } else if (type.isArray()) { + JSONArray array = new JSONArray(); + int i1 = Array.getLength(source); + for (int j = 0; j < i1; j++) { + Object o = Array.get(source, j); + array.put(toJSON(o)); + } + return array; + } else if (Collection.class.isAssignableFrom(type)) { + Collection c = (Collection)source; + JSONArray array = new JSONArray(); + for (Object element : c) { + array.put(toJSON(element)); + } + return array; + } + JSONObject json = new JSONObject(); + BeanInfo beanInfo = Introspector.getBeanInfo(type); + PropertyDescriptor[] propDescs = beanInfo.getPropertyDescriptors(); + Collections.sort(Arrays.asList(propDescs), COMPARATOR); + + for (int i = 0; i < propDescs.length; i++) { + PropertyDescriptor propDesc = propDescs[i]; + Class pType = propDesc.getPropertyType(); + if ("class".equals(propDesc.getName())) { + continue; + } + Object pValue = propDesc.getReadMethod().invoke(source, NULL); + json.put(propDesc.getName(), toJSON(pValue)); + } + return json; + + } + + public Object transform(Object source, TransformationContext context) { + try { + return toJSON(source); + } catch (Exception e) { + throw new TransformationException(e); + } + } + +} diff --git a/java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/String2JSON.java b/java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/String2JSON.java new file mode 100644 index 0000000000..ff5968bccd --- /dev/null +++ b/java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/String2JSON.java @@ -0,0 +1,64 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.json; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; + +/** + * @version $Rev$ $Date$ + */ +public class String2JSON extends BaseTransformer implements PullTransformer { + + @Override + protected Class getSourceType() { + return String.class; + } + + @Override + protected Class getTargetType() { + return Object.class; + } + + public Object transform(String source, TransformationContext context) { + try { + Class type = null; + if (context != null && context.getTargetDataType() != null) { + type = context.getTargetDataType().getPhysical(); + } + return JSONHelper.toJSON(source, type); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + public int getWeight() { + return 500; + } + + @Override + public String getTargetDataBinding() { + return JSONDataBinding.NAME; + } + +} diff --git a/java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/XMLStreamReader2JSON.java b/java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/XMLStreamReader2JSON.java new file mode 100644 index 0000000000..aa75afc9d4 --- /dev/null +++ b/java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/XMLStreamReader2JSON.java @@ -0,0 +1,77 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.json; + +import java.io.StringWriter; + +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.apache.tuscany.sca.databinding.xml.XMLStreamSerializer; +import org.codehaus.jettison.badgerfish.BadgerFishXMLStreamWriter; + +/** + * @version $Rev$ $Date$ + */ +public class XMLStreamReader2JSON extends BaseTransformer implements + PullTransformer { + + @Override + protected Class getSourceType() { + return XMLStreamReader.class; + } + + @Override + protected Class getTargetType() { + return Object.class; + } + + public Object transform(XMLStreamReader source, TransformationContext context) { + try { + StringWriter writer = new StringWriter(); + XMLStreamWriter jsonWriter = new BadgerFishXMLStreamWriter(writer); + XMLStreamSerializer serializer = new XMLStreamSerializer(); + serializer.serialize(source, jsonWriter); + source.close(); + Class type = null; + if (context != null && context.getTargetDataType() != null) { + type = context.getTargetDataType().getPhysical(); + } + return JSONHelper.toJSON(writer.toString(), type); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + public int getWeight() { + return 500; + } + + @Override + public String getTargetDataBinding() { + return JSONDataBinding.NAME; + } + +} diff --git a/java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/axiom/JSON2OMElement.java b/java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/axiom/JSON2OMElement.java new file mode 100644 index 0000000000..fb02d27b05 --- /dev/null +++ b/java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/axiom/JSON2OMElement.java @@ -0,0 +1,94 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.json.axiom; + + +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.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.Transformer; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.apache.tuscany.sca.databinding.json.JSONDataBinding; +import org.apache.tuscany.sca.databinding.json.JSONHelper; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.util.XMLType; +import org.codehaus.jettison.json.JSONObject; +import org.oasisopen.sca.annotation.Service; + +/** + * @version $Rev$ $Date$ + */ +@Service(Transformer.class) +public class JSON2OMElement extends BaseTransformer implements PullTransformer { + + private OMFactory factory = OMAbstractFactory.getOMFactory(); + + @Override + protected Class getSourceType() { + return Object.class; + } + + @Override + protected Class getTargetType() { + return OMElement.class; + } + + public OMElement transform(Object source, TransformationContext context) { + try { + JSONObject json = JSONHelper.toJettison(source); + if (json == null) { + return null; + } + String ns = JSONDataBinding.ROOT_ELEMENT.getNamespaceURI(); + String name = JSONDataBinding.ROOT_ELEMENT.getLocalPart(); + if (context != null) { + DataType dataType = context.getTargetDataType(); + Object logical = dataType.getLogical(); + if (logical instanceof XMLType) { + XMLType xmlType = (XMLType)logical; + if (xmlType.isElement()) { + ns = xmlType.getElementName().getNamespaceURI(); + name = xmlType.getElementName().getLocalPart(); + } + } + } + JSONBadgerfishDataSource ds = new JSONBadgerfishDataSource(json); + OMNamespace namespace = factory.createOMNamespace(ns, ""); + return factory.createOMElement(ds, name, namespace); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + public int getWeight() { + return 500; + } + + @Override + public String getSourceDataBinding() { + return JSONDataBinding.NAME; + } + +} diff --git a/java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/axiom/JSONBadgerfishDataSource.java b/java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/axiom/JSONBadgerfishDataSource.java new file mode 100644 index 0000000000..adc38772be --- /dev/null +++ b/java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/axiom/JSONBadgerfishDataSource.java @@ -0,0 +1,57 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.json.axiom; + +import javax.xml.stream.XMLStreamException; + +import org.codehaus.jettison.badgerfish.BadgerFishXMLStreamReader; +import org.codehaus.jettison.json.JSONException; +import org.codehaus.jettison.json.JSONObject; + +/** + * JSONDataSource keeps the JSON String inside and consumes it when needed. This is to be kept in the + * OMSourcedElementImpl and can be used either to expand the tree or get the JSON String directly without expanding. + * This uses the "Badgerfish" JSON convention. + * + * @version $Rev$ $Date$ + */ + +public class JSONBadgerfishDataSource extends JSONDataSource { + + public JSONBadgerfishDataSource(JSONObject json) { + super(json); + } + + /** + * Gives the StAX reader using the "Badgerfish" formatted input JSON String. + * + * @return The XMLStreamReader according to the JSON String. + * @throws javax.xml.stream.XMLStreamException if there is an error while making the StAX reader. + */ + @Override + public javax.xml.stream.XMLStreamReader getReader() throws XMLStreamException { + try { + return new BadgerFishXMLStreamReader(json); + } catch (JSONException e) { + throw new XMLStreamException(e); + } + + } +} diff --git a/java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/axiom/JSONDataSource.java b/java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/axiom/JSONDataSource.java new file mode 100644 index 0000000000..5b0312056e --- /dev/null +++ b/java/sca/contrib/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/axiom/JSONDataSource.java @@ -0,0 +1,176 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.json.axiom; + +import java.io.IOException; +import java.io.OutputStream; +import java.io.Writer; +import java.util.HashMap; +import java.util.Map; + +import javax.xml.stream.XMLStreamConstants; +import javax.xml.stream.XMLStreamReader; + +import org.apache.axiom.om.OMDataSource; +import org.apache.axiom.om.OMException; +import org.apache.axiom.om.OMOutputFormat; +import org.codehaus.jettison.json.JSONObject; +import org.codehaus.jettison.json.JSONTokener; +import org.codehaus.jettison.mapped.MappedXMLInputFactory; + +/** + * JSONDataSource keeps the JSON String inside and consumes it when needed. This is to be kept in the + * OMSourcedElementImpl and can be used either to expand the tree or get the JSON String directly without expanding. + * This uses the "Mapped" JSON convention. + * + * @version $Rev$ $Date$ + */ + +public class JSONDataSource implements OMDataSource { + protected JSONObject json; + + public JSONDataSource(JSONObject json) { + this.json = json; + } + + /** + * Writes JSON into the output stream. As this should write JSON, it directly gets the JSON string and writes it + * without expanding the tree. + * + * @param outputStream the stream to be written into + * @param omOutputFormat format of the message, this is ignored. + * @throws javax.xml.stream.XMLStreamException if there is an error while writing the message in to the output + * stream. + */ + public void serialize(OutputStream outputStream, OMOutputFormat omOutputFormat) + throws javax.xml.stream.XMLStreamException { + try { + String encoding = omOutputFormat == null ? "UTF-8" : omOutputFormat.getCharSetEncoding(); + outputStream.write(getJSONString().getBytes(encoding)); + } catch (IOException e) { + throw new OMException(); + } + } + + /** + * Writes JSON through the writer. As this should write JSON, it directly gets the JSON string and writes it without + * expanding the tree. + * + * @param writer Writer to be written into + * @param omOutputFormat format of the message, this is ignored. + * @throws javax.xml.stream.XMLStreamException if there is an error while writing the message through the writer. + */ + public void serialize(Writer writer, OMOutputFormat omOutputFormat) throws javax.xml.stream.XMLStreamException { + try { + writer.write(getJSONString()); + } catch (IOException e) { + throw new OMException(); + } + } + + /** + * Writes XML through the XMLStreamWriter. As the input data source is JSON, this method needs to get a StAX reader + * from that JSON String. Therefore this uses the getReader() method to get the StAX reader writes the events into + * the XMLStreamWriter. + * + * @param xmlStreamWriter StAX writer to be written into + * @throws javax.xml.stream.XMLStreamException if there is an error while writing the message through the StAX + * writer. + */ + public void serialize(javax.xml.stream.XMLStreamWriter xmlStreamWriter) throws javax.xml.stream.XMLStreamException { + XMLStreamReader reader = getReader(); + xmlStreamWriter.writeStartDocument(); + while (reader.hasNext()) { + int x = reader.next(); + switch (x) { + case XMLStreamConstants.START_ELEMENT: + xmlStreamWriter.writeStartElement(reader.getPrefix(), reader.getLocalName(), reader + .getNamespaceURI()); + int namespaceCount = reader.getNamespaceCount(); + for (int i = namespaceCount - 1; i >= 0; i--) { + xmlStreamWriter.writeNamespace(reader.getNamespacePrefix(i), reader.getNamespaceURI(i)); + } + int attributeCount = reader.getAttributeCount(); + for (int i = 0; i < attributeCount; i++) { + xmlStreamWriter.writeAttribute(reader.getAttributePrefix(i), + reader.getAttributeNamespace(i), + reader.getAttributeLocalName(i), + reader.getAttributeValue(i)); + } + break; + case XMLStreamConstants.START_DOCUMENT: + break; + case XMLStreamConstants.CHARACTERS: + xmlStreamWriter.writeCharacters(reader.getText()); + break; + case XMLStreamConstants.CDATA: + xmlStreamWriter.writeCData(reader.getText()); + break; + case XMLStreamConstants.END_ELEMENT: + xmlStreamWriter.writeEndElement(); + break; + case XMLStreamConstants.END_DOCUMENT: + xmlStreamWriter.writeEndDocument(); + break; + case XMLStreamConstants.SPACE: + break; + case XMLStreamConstants.COMMENT: + xmlStreamWriter.writeComment(reader.getText()); + break; + case XMLStreamConstants.DTD: + xmlStreamWriter.writeDTD(reader.getText()); + break; + case XMLStreamConstants.PROCESSING_INSTRUCTION: + xmlStreamWriter.writeProcessingInstruction(reader.getPITarget(), reader.getPIData()); + break; + case XMLStreamConstants.ENTITY_REFERENCE: + xmlStreamWriter.writeEntityRef(reader.getLocalName()); + break; + default: + throw new OMException(); + } + } + xmlStreamWriter.writeEndDocument(); + } + + /** + * Gives the StAX reader using the "Mapped" formatted input JSON String. + * + * @return The XMLStreamReader according to the JSON String. + * @throws javax.xml.stream.XMLStreamException if there is an error while making the StAX reader. + */ + + public javax.xml.stream.XMLStreamReader getReader() throws javax.xml.stream.XMLStreamException { + + Map nsMap = new HashMap(); + nsMap.put("", ""); + + // input factory for "Mapped" convention + MappedXMLInputFactory inputFactory = new MappedXMLInputFactory(nsMap); + String jsonString = this.getJSONString(); + return inputFactory.createXMLStreamReader(new JSONTokener(jsonString)); + } + + // returns the json string by consuming the JSON input stream. + protected String getJSONString() { + return json.toString(); + } + +} diff --git a/java/sca/contrib/modules/databinding-json/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.DataBinding b/java/sca/contrib/modules/databinding-json/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.DataBinding new file mode 100644 index 0000000000..400507296f --- /dev/null +++ b/java/sca/contrib/modules/databinding-json/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.DataBinding @@ -0,0 +1,19 @@ +# 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. + +# implementation classes for the databindings +org.apache.tuscany.sca.databinding.json.JSONDataBinding;name=JSON diff --git a/java/sca/contrib/modules/databinding-json/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PullTransformer b/java/sca/contrib/modules/databinding-json/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PullTransformer new file mode 100644 index 0000000000..b122533f6e --- /dev/null +++ b/java/sca/contrib/modules/databinding-json/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PullTransformer @@ -0,0 +1,31 @@ +# 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. + +# Implementation classes for the transformers +org.apache.tuscany.sca.databinding.json.JSON2XMLStreamReader;source=JSON,target=javax.xml.stream.XMLStreamReader,weight=5000 +org.apache.tuscany.sca.databinding.json.XMLStreamReader2JSON;source=javax.xml.stream.XMLStreamReader,target=JSON,weight=5000,public=false +org.apache.tuscany.sca.databinding.json.JavaBean2JSON;source=java:complexType,target=JSON,weight=80000,public=false +org.apache.tuscany.sca.databinding.json.JavaBean2JSON;source=java:simpleType,target=JSON,weight=80000,public=false +org.apache.tuscany.sca.databinding.json.axiom.JSON2OMElement;source=JSON,target=org.apache.axiom.om.OMElement,weight=500 +org.apache.tuscany.sca.databinding.json.JavaBean2JSON;source=java:array,target=JSON,weight=80000,public=false +org.apache.tuscany.sca.databinding.json.JavaBean2JSON;source=commonj.sdo.DataObject,target=JSON,weight=80000,public=false +org.apache.tuscany.sca.databinding.json.JavaBean2JSON;source=javax.xml.bind.JAXBElement,target=JSON,weight=80000,public=false +org.apache.tuscany.sca.databinding.json.JSON2JavaBean;source=JSON,target=java:complexType,weight=80000,public=false +org.apache.tuscany.sca.databinding.json.JSON2JavaBean;source=JSON,target=java:simpleType,weight=80000,public=false +org.apache.tuscany.sca.databinding.json.JSON2JavaBean;source=JSON,target=commonj.sdo.DataObject,weight=80000,public=false +org.apache.tuscany.sca.databinding.json.JSON2JavaBean;source=JSON,target=javax.xml.bind.JAXBElement,weight=80000,public=false +org.apache.tuscany.sca.databinding.json.JSON2JavaBean;source=JSON,target=java:array,weight=80000,public=false diff --git a/java/sca/contrib/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/JSONTransformerTestCase.java b/java/sca/contrib/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/JSONTransformerTestCase.java new file mode 100644 index 0000000000..3c7f151ed7 --- /dev/null +++ b/java/sca/contrib/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/JSONTransformerTestCase.java @@ -0,0 +1,128 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.json; + +import java.io.StringReader; +import java.io.StringWriter; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLOutputFactory; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.axiom.om.OMElement; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.impl.TransformationContextImpl; +import org.apache.tuscany.sca.databinding.json.axiom.JSON2OMElement; +import org.apache.tuscany.sca.databinding.xml.XMLStreamSerializer; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.impl.DataTypeImpl; +import org.apache.tuscany.sca.interfacedef.util.XMLType; +import org.json.JSONObject; + +public class JSONTransformerTestCase extends TestCase { + private static final String IPO_XML = "" + "" + + " " + + " Helen Zoe" + + " 47 Eden Street" + + " Cambridge" + + " CB1 1JR" + + " " + + " " + + " Robert Smith" + + " 8 Oak Avenue" + + " Old Town" + + " PA" + + " 95819" + + " " + + " " + + " " + + " Lapis necklace" + + " 1" + + " 99.95" + + " Want this for the holidays" + + " 1999-12-05" + + " " + + " " + + ""; + + private static final String JSON_STR = "{\"xsl:root\":{\"@xmlns\":{\"xsl\":\"http://foo.com\"},\"data\":{\"$\":\"my json string\"}}}"; + + public void testXML2JSON() throws Exception { + XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(IPO_XML)); + XMLStreamReader2JSON t1 = new XMLStreamReader2JSON(); + JSONObject json = (JSONObject) t1.transform(reader, null); + Assert.assertNotNull(json); + + // Cannot round-trip as we hit a bug in Jettison: http://jira.codehaus.org/browse/JETTISON-37 + /* + JSON2XMLStreamReader t2 = new JSON2XMLStreamReader(); + XMLStreamReader reader2 = t2.transform(json, null); + StringWriter sw = new StringWriter(); + XMLStreamWriter streamWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(sw); + new XMLStreamSerializer().serialize(reader2, streamWriter); + streamWriter.flush(); + System.out.println(sw.toString()); + */ + + } + + public void testJSON2XML() throws Exception { + JSON2XMLStreamReader t2 = new JSON2XMLStreamReader(); + XMLStreamReader reader2 = t2.transform(new JSONObject(JSON_STR), null); + StringWriter sw = new StringWriter(); + XMLStreamWriter streamWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(sw); + new XMLStreamSerializer().serialize(reader2, streamWriter); + streamWriter.flush(); + Assert.assertTrue(sw.toString() + .contains("my json string")); + } + + public void testJSON2OMElement() throws Exception { + JSON2OMElement t1 = new JSON2OMElement(); + TransformationContext context = new TransformationContextImpl(); + DataType dt = new DataTypeImpl(Object.class, new XMLType(new QName("http://foo.com", "root"), null)); + context.setTargetDataType(dt); + OMElement element = t1.transform(new JSONObject(JSON_STR), context); + StringWriter writer = new StringWriter(); + element.serialize(writer); + // System.out.println(writer.toString()); + } + + public void testString2JSON() throws Exception { + String json = "{\"name\":\"John\",\"age\":25}"; + String2JSON t1 = new String2JSON(); + JSONObject jsonObject = (JSONObject) t1.transform(json, null); + assertEquals(jsonObject.getString("name"), "John"); + assertEquals(jsonObject.getInt("age"), 25); + JSON2String t2 = new JSON2String(); + String str = t2.transform(jsonObject, null); + assertTrue(str.contains("\"name\":\"John\"")); + assertTrue(str.contains("\"age\":25")); + } +} diff --git a/java/sca/contrib/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/JavaBean2JSONTestCase.java b/java/sca/contrib/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/JavaBean2JSONTestCase.java new file mode 100644 index 0000000000..3b36f5be74 --- /dev/null +++ b/java/sca/contrib/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/JavaBean2JSONTestCase.java @@ -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. + */ + +package org.apache.tuscany.sca.databinding.json; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.Assert; + +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.impl.TransformationContextImpl; +import org.apache.tuscany.sca.interfacedef.impl.DataTypeImpl; +import org.json.JSONObject; +import org.junit.Test; + +/** + * @version $Rev$ $Date$ + */ +public class JavaBean2JSONTestCase { + + public static class MyBean { + private String name; + private int age; + private boolean vip; + private String friends[]; + private List books; + private YourBean you; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public boolean isVip() { + return vip; + } + + public void setVip(boolean vip) { + this.vip = vip; + } + + public String[] getFriends() { + return friends; + } + + public void setFriends(String[] friends) { + this.friends = friends; + } + + public List getBooks() { + return books; + } + + public void setBooks(List books) { + this.books = books; + } + + public YourBean getYou() { + return you; + } + + public void setYou(YourBean you) { + this.you = you; + } + + } + + public static class YourBean { + private int id; + private String name; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + } + + @Test + public void testBean2JSON() throws Exception { + MyBean me = new MyBean(); + me.setAge(30); + me.setBooks(new ArrayList()); + me.setFriends(new String[] {"John", "Mike"}); + me.setVip(true); + me.setName("Me"); + YourBean you = new YourBean(); + you.setId(123); + you.setName(null); + me.setYou(you); + JavaBean2JSON t1 = new JavaBean2JSON(); + Object result = t1.transform(me, null); + System.out.println(result); + JSON2JavaBean t2 = new JSON2JavaBean(); + TransformationContext context = new TransformationContextImpl(); + context.setTargetDataType(new DataTypeImpl(MyBean.class, null)); + Object v = t2.transform(new JSONObject(result.toString()), context); + Assert.assertTrue(v instanceof MyBean); + // String json = + // "{\"age\":30,\"books\":[],\"friends\":[\"John\",\"Mike\"],\"name\":\"Me\",\"vip\":true,\"you\":{\"id\":123,\"name\":null}}"; + // Assert.assertEquals(json, result.toString()); + } + + @Test + public void testString2JSON() throws Exception { + JavaBean2JSONObject t1 = new JavaBean2JSONObject(); + Object result = t1.transform("ABC", null); + System.out.println(result); + JSON2JavaBean t2 = new JSON2JavaBean(); + TransformationContext context = new TransformationContextImpl(); + context.setTargetDataType(new DataTypeImpl(String.class, null)); + Object v = t2.transform(result, context); + Assert.assertTrue(v instanceof String); + Assert.assertEquals("ABC", v); + } + + @Test + public void testStringArray2JSON() throws Exception { + JavaBean2JSON t1 = new JavaBean2JSON(); + Object result = t1.transform(new String[] {"ABC", "DF"}, null); + System.out.println(result); + JSON2JavaBean t2 = new JSON2JavaBean(); + TransformationContext context = new TransformationContextImpl(); + context.setTargetDataType(new DataTypeImpl(String[].class, null)); + Object v = t2.transform(result, context); + Assert.assertTrue(v instanceof String[]); + String[] strs = (String[])v; + Assert.assertEquals("ABC", strs[0]); + Assert.assertEquals("DF", strs[1]); + } + +} diff --git a/java/sca/contrib/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/MyBean.java b/java/sca/contrib/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/MyBean.java new file mode 100644 index 0000000000..60b293c1d4 --- /dev/null +++ b/java/sca/contrib/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/MyBean.java @@ -0,0 +1,158 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.databinding.json; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class MyBean { + private int age; + private String name; + private float[] rates = new float[] {1.0f, 2.0f}; + private List notes = new ArrayList(); + private Map map = new HashMap(); + private Object service; + private Object otherService; + private boolean good; + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getNotes() { + return notes; + } + + public void setNotes(List notes) { + this.notes = notes; + } + + public float[] getRates() { + return rates; + } + + public void setRates(float[] rates) { + this.rates = rates; + } + + public Map getMap() { + return map; + } + + public void setMap(Map map) { + this.map = map; + } + + public Object getService() { + return service; + } + + public void setService(Object service) { + this.service = service; + } + + public Object getOtherService() { + return otherService; + } + + public void setOtherService(Object otherService) { + this.otherService = otherService; + } + + public boolean isGood() { + return good; + } + + public void setGood(boolean good) { + this.good = good; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + age; + result = prime * result + (good ? 1231 : 1237); + result = prime * result + ((map == null) ? 0 : map.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + ((notes == null) ? 0 : notes.hashCode()); + result = prime * result + ((otherService == null) ? 0 : otherService.hashCode()); + result = prime * result + Arrays.hashCode(rates); + result = prime * result + ((service == null) ? 0 : service.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final MyBean other = (MyBean)obj; + if (age != other.age) + return false; + if (good != other.good) + return false; + if (map == null) { + if (other.map != null) + return false; + } else if (!map.equals(other.map)) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + if (notes == null) { + if (other.notes != null) + return false; + } else if (!notes.equals(other.notes)) + return false; + if (otherService == null) { + if (other.otherService != null) + return false; + } else if (!otherService.equals(other.otherService)) + return false; + if (!Arrays.equals(rates, other.rates)) + return false; + if (service == null) { + if (other.service != null) + return false; + } else if (!service.equals(other.service)) + return false; + return true; + } +} diff --git a/java/sca/contrib/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/MyInterface.java b/java/sca/contrib/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/MyInterface.java new file mode 100644 index 0000000000..d32e0763c7 --- /dev/null +++ b/java/sca/contrib/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/MyInterface.java @@ -0,0 +1,29 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.json; + +/** + * @version $Rev$ $Date$ + */ +public interface MyInterface { + void setId(String id); + + String getId(); +} diff --git a/java/sca/contrib/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/MyInterfaceImpl.java b/java/sca/contrib/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/MyInterfaceImpl.java new file mode 100644 index 0000000000..3a2b95a4e2 --- /dev/null +++ b/java/sca/contrib/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/MyInterfaceImpl.java @@ -0,0 +1,67 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.json; + +/** + * @version $Rev$ $Date$ + */ +public class MyInterfaceImpl implements MyInterface { + private String id; + + /** + * @see org.apache.tuscany.databinding.jaxb.MyInterface#getId() + */ + public String getId() { + return id; + } + + /** + * @see org.apache.tuscany.databinding.jaxb.MyInterface#setId(java.lang.String) + */ + public void setId(String id) { + this.id = id; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final MyInterfaceImpl other = (MyInterfaceImpl)obj; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + return true; + } + +} diff --git a/java/sca/contrib/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/POJOTestCase.java b/java/sca/contrib/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/POJOTestCase.java new file mode 100644 index 0000000000..84995baadf --- /dev/null +++ b/java/sca/contrib/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/POJOTestCase.java @@ -0,0 +1,87 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.databinding.json; + +import java.lang.reflect.Array; + +import junit.framework.TestCase; + +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.impl.TransformationContextImpl; +import org.apache.tuscany.sca.interfacedef.impl.DataTypeImpl; + +public class POJOTestCase extends TestCase { + public void testPOJO() throws Exception { + MyBean bean = new MyBean(); + bean.setName("Test"); + bean.setAge(20); + bean.getNotes().add("1"); + bean.getNotes().add("2"); + bean.getMap().put("1", 1); + MyInterface service = new MyInterfaceImpl(); + service.setId("ID001"); + bean.setService(service); + bean.setOtherService(service); + + roundTrip(bean); + } + + private void roundTrip(T bean) { + JavaBean2JSON t1 = new JavaBean2JSON(); + + Object json = t1.transform(bean, null); + System.out.println(json); + JSON2JavaBean t2 = new JSON2JavaBean(); + + TransformationContext context = new TransformationContextImpl(); + context.setTargetDataType(new DataTypeImpl(bean == null ? Object.class : bean.getClass(), null)); + Object newBean = t2.transform(json, context); + + if (newBean != null && newBean.getClass().isArray()) { + int len = Array.getLength(newBean); + assertEquals(Array.getLength(bean), len); + for (int i = 0; i < len; i++) { + assertEquals(Array.get(bean, i), Array.get(newBean, i)); + } + return; + } + assertEquals(bean, newBean); + } + + public void testString() throws Exception { + roundTrip("ABC"); + } + + public void testNull() throws Exception { + roundTrip(null); + } + + public void testArray() throws Exception { + roundTrip(new String[] {"123", "ABC"}); + } + + public void testByteArray() throws Exception { + roundTrip("ABC".getBytes()); + } + + public void testPrimitive() throws Exception { + roundTrip(123); + } + +} diff --git a/java/sca/contrib/modules/databinding-json/src/test/resources/ipo.xsd b/java/sca/contrib/modules/databinding-json/src/test/resources/ipo.xsd new file mode 100644 index 0000000000..5a493e1746 --- /dev/null +++ b/java/sca/contrib/modules/databinding-json/src/test/resources/ipo.xsd @@ -0,0 +1,136 @@ + + + + + + International Purchase order schema for Example.com + Copyright 2000 Example.com. All rights reserved. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/java/sca/contrib/modules/databinding-saxon/LICENSE b/java/sca/contrib/modules/databinding-saxon/LICENSE new file mode 100644 index 0000000000..d645695673 --- /dev/null +++ b/java/sca/contrib/modules/databinding-saxon/LICENSE @@ -0,0 +1,202 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/java/sca/contrib/modules/databinding-saxon/META-INF/MANIFEST.MF b/java/sca/contrib/modules/databinding-saxon/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..3c9e95f67d --- /dev/null +++ b/java/sca/contrib/modules/databinding-saxon/META-INF/MANIFEST.MF @@ -0,0 +1,38 @@ +Manifest-Version: 1.0 +Export-Package: org.apache.tuscany.sca.databinding.saxon;uses:="org.ap + ache.tuscany.sca.databinding,net.sf.saxon.value,org.apache.tuscany.sc + a.databinding.impl,net.sf.saxon.trans,javax.xml.transform.dom,commonj + .sdo.helper,net.sf.saxon,org.apache.tuscany.sca.interfacedef,org.apac + he.tuscany.sca.databinding.saxon.collection,org.w3c.dom,net.sf.saxon. + query,commonj.sdo,net.sf.saxon.event,javax.xml.transform,net.sf.saxon + .om";version="2.0.0",org.apache.tuscany.sca.databinding.saxon.collectio + n;version="2.0.0" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA Data Binding for Saxon +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397384281 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA Data Binding for Saxon +Import-Package: commonj.sdo;version="2.1", + commonj.sdo.helper;version="2.1", + javax.xml.transform, + javax.xml.transform.dom, + net.sf.saxon, + net.sf.saxon.event, + net.sf.saxon.om, + net.sf.saxon.query, + net.sf.saxon.trans, + net.sf.saxon.value, + org.apache.tuscany.sca.databinding;version="2.0.0", + org.apache.tuscany.sca.databinding.impl;version="2.0.0", + org.apache.tuscany.sca.databinding.javabeans;version="2.0.0", + org.apache.tuscany.sca.databinding.saxon;version="2.0.0", + org.apache.tuscany.sca.databinding.saxon.collection;version="2.0.0", + org.apache.tuscany.sca.interfacedef;version="2.0.0", + org.w3c.dom +Bundle-SymbolicName: org.apache.tuscany.sca.databinding.saxon +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/databinding-saxon/NOTICE b/java/sca/contrib/modules/databinding-saxon/NOTICE new file mode 100644 index 0000000000..25bb89c9b2 --- /dev/null +++ b/java/sca/contrib/modules/databinding-saxon/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/databinding-saxon/pom.xml b/java/sca/contrib/modules/databinding-saxon/pom.xml new file mode 100644 index 0000000000..33a379c107 --- /dev/null +++ b/java/sca/contrib/modules/databinding-saxon/pom.xml @@ -0,0 +1,106 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + tuscany-databinding-saxon + Apache Tuscany SCA Data Binding for Saxon + + + + + false + + rfeng + Tuscany Maven 2.0 Repository + http://svn.apache.org/repos/asf/incubator/tuscany/maven + default + + + + + + org.apache.tuscany.sca + tuscany-core-spi + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-databinding + 2.0-SNAPSHOT + + + + + + net.sf.saxon + saxon + 8.7 + + + + net.sf.saxon + saxon-dom + 8.7 + + + + org.apache.tuscany.sdo + tuscany-sdo-lib + 1.1.1 + + + + org.apache.tuscany.sdo + tuscany-sdo-impl + 1.1.1 + + + + junit + junit + 4.1 + test + + + + diff --git a/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/DataObject2NodeInfoTransformer.java b/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/DataObject2NodeInfoTransformer.java new file mode 100644 index 0000000000..25f8ee886f --- /dev/null +++ b/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/DataObject2NodeInfoTransformer.java @@ -0,0 +1,99 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.databinding.saxon; + +import javax.xml.transform.dom.DOMResult; + +import net.sf.saxon.om.NodeInfo; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.apache.tuscany.sca.databinding.impl.DOMHelper; + +import commonj.sdo.DataObject; +import commonj.sdo.helper.XMLDocument; +import commonj.sdo.helper.XMLHelper; + +/** + * Transforms SDO DataObject-s to NodeInfo objects needed by Saxon parser. + * + * For root element when Serializing the DataObject the name of its + * implemented interface is used with its first letter made lowercase. + * Also any namespaces that are defined are deleted, because otherwise + * the SaxonB parser does not work + * + * @version $Rev$ $Date$ + */ +public class DataObject2NodeInfoTransformer extends BaseTransformer implements + PullTransformer { + + private Node2NodeInfoTransformer node2NodeInfoTransformer; + + public DataObject2NodeInfoTransformer(Node2NodeInfoTransformer node2NodeInfoTransformer) { + this.node2NodeInfoTransformer = node2NodeInfoTransformer; + } + + public DataObject2NodeInfoTransformer() { + this.node2NodeInfoTransformer = new Node2NodeInfoTransformer(); + } + + public NodeInfo transform(DataObject source, TransformationContext context) { + // FIXME: Need to create the HelperContext from the transformation context + // FIXME: This is a big hack to create a document using the class name + XMLHelper helper = XMLHelper.INSTANCE; + String name = null; + if (source.getClass().getInterfaces().length > 0) { + name = source.getClass().getInterfaces()[0].getSimpleName(); + } else { + name = source.getClass().getName(); + } + + if (name.length() > 0) { + name = Character.toLowerCase(name.charAt(0)) + name.substring(1, name.length()); + } + + try { + DOMResult domResult = new DOMResult(DOMHelper.newDocument()); + XMLDocument xmlDoc = helper.createDocument(source, null, name); + helper.save(xmlDoc, domResult, null); + return node2NodeInfoTransformer.transform(domResult.getNode(), context); + } catch (Exception e) { + throw new TransformationException(e); + } + + } + + @Override + protected Class getSourceType() { + return DataObject.class; + } + + @Override + protected Class getTargetType() { + return NodeInfo.class; + } + + @Override + public int getWeight() { + return 30 + node2NodeInfoTransformer.getWeight(); + } + +} diff --git a/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/ItemList2ObjectTransformer.java b/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/ItemList2ObjectTransformer.java new file mode 100644 index 0000000000..7122217b8b --- /dev/null +++ b/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/ItemList2ObjectTransformer.java @@ -0,0 +1,153 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.databinding.saxon; + +import java.lang.reflect.Array; + +import net.sf.saxon.om.Item; +import net.sf.saxon.om.NodeInfo; +import net.sf.saxon.trans.XPathException; +import net.sf.saxon.value.Value; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.apache.tuscany.sca.databinding.saxon.collection.ItemList; + +/** + * Transforms each object contained in the ItemList object. + * + * If the object type is the same as the target type, it is not transformed. + * + * If the object is a NodeInfo, it's transformed to a DataObject. + * + * If the object is a Value, it's transformed to a Java object. + * + * If the target type is not an array, the first transformed object is returned. + * + * If the first transformed object type is not a target type, then a + * TransformException is thrown + * + * If the target type is an array, a array of this type is created containing + * all transformed objects and it is returned + * + * If any transformed object is not a target type, then a TransformException is + * thrown + * + * @version $Rev: 659284 $ $Date: 2008-05-22 14:26:18 -0800 (Thu, 22 May 2008) $ + */ +public class ItemList2ObjectTransformer extends BaseTransformer implements + PullTransformer { + + private NodeInfo2DataObjectTransformer nodeInfo2DataObjectTransformer = new NodeInfo2DataObjectTransformer(); + + public ItemList2ObjectTransformer() { + } + + @Override + protected Class getSourceType() { + return ItemList.class; + } + + @Override + protected Class getTargetType() { + return Object.class; + } + + @Override + public int getWeight() { + return 30 + nodeInfo2DataObjectTransformer.getWeight(); + } + + public Object transform(ItemList source, TransformationContext context) { + + if (source.size() == 0) { + return null; + } + + Class targetType = context.getTargetDataType().getPhysical(); + + if (targetType.isArray()) { + int i = 0; + Class componentClass = targetType.getComponentType(); + Object[] result = (Object[])Array.newInstance(componentClass, source.size()); + + try { + + if (componentClass.isAssignableFrom(NodeInfo.class) || componentClass.isAssignableFrom(Value.class)) { + + for (Item item : source) { + result[i++] = item; + } + + } else { + + for (Item item : source) { + + if (item instanceof NodeInfo) { + result[i] = nodeInfo2DataObjectTransformer.transform((NodeInfo)item, context); + + } else if (item instanceof Value) { + result[i] = Value.convert(item); + + } else { + result[i] = item; + } + + i++; + + } + + } + + } catch (ArrayStoreException ex) { + throw new TransformationException(ex); + + } catch (XPathException ex) { + throw new TransformationException(ex); + } + + return result; + + } else { + Item item = source.iterator().next(); + + if (item.getClass().isAssignableFrom(targetType)) { + return item; + + } else if (item instanceof NodeInfo) { + return nodeInfo2DataObjectTransformer.transform((NodeInfo)item, context); + + } else { + + try { + return Value.convert(item); + + } catch (XPathException e) { + throw new TransformationException(e); + } + + } + + } + + } + +} diff --git a/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/Node2NodeInfoTransformer.java b/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/Node2NodeInfoTransformer.java new file mode 100644 index 0000000000..fabadd34ea --- /dev/null +++ b/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/Node2NodeInfoTransformer.java @@ -0,0 +1,77 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.databinding.saxon; + +import javax.xml.transform.dom.DOMSource; + +import net.sf.saxon.Configuration; +import net.sf.saxon.event.Builder; +import net.sf.saxon.om.NodeInfo; +import net.sf.saxon.trans.XPathException; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.apache.tuscany.sca.databinding.impl.DOMHelper; +import org.w3c.dom.Node; + +/** + * Transforms DOM Node-s to NodeInfo objects needed by Saxon parser. + * + * Any namespaces that are defined are deleted, because otherwise + * the SaxonB parser does not work + * + * @version $Rev$ $Date$ + */ +public class Node2NodeInfoTransformer extends BaseTransformer implements + PullTransformer { + + public NodeInfo transform(Node source, TransformationContext context) { + Configuration configuration = SaxonDataBindingHelper.CURR_EXECUTING_CONFIG; + if (configuration == null) { + configuration = new Configuration(); + } + + NodeInfo docInfo = null; + try { + source = DOMHelper.promote(source); + docInfo = Builder.build(new DOMSource(source), null, configuration); + } catch (XPathException e) { + throw new TransformationException(e); + } + return docInfo; + } + + @Override + protected Class getSourceType() { + return Node.class; + } + + @Override + protected Class getTargetType() { + return NodeInfo.class; + } + + @Override + public int getWeight() { + return 10; + } + +} diff --git a/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/NodeInfo2DataObjectTransformer.java b/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/NodeInfo2DataObjectTransformer.java new file mode 100644 index 0000000000..a5093f8cdf --- /dev/null +++ b/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/NodeInfo2DataObjectTransformer.java @@ -0,0 +1,91 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.databinding.saxon; + +import java.io.IOException; + +import javax.xml.transform.dom.DOMSource; + +import net.sf.saxon.om.NodeInfo; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.w3c.dom.Document; + +import commonj.sdo.DataObject; +import commonj.sdo.helper.XMLHelper; + +/** + * Transforms NodeInfo objects to SDO DataObjects. + * + * Before constructing the data object, resulting XML is populated + * with correct namespaces (which are taken from the logical target data type) + * These namespaces are crucial for constructing the right instance of + * the DataObject (i.e. if there is a SDO factory, an instance from this factory will + * be used, not the generic any data object) + * + * @version $Rev$ $Date$ + */ +public class NodeInfo2DataObjectTransformer extends BaseTransformer implements + PullTransformer { + + private NodeInfo2NodeTransformer nodeInfo2NodeTransformer; + + public NodeInfo2DataObjectTransformer(NodeInfo2NodeTransformer nodeInfo2NodeTransformer) { + this.nodeInfo2NodeTransformer = nodeInfo2NodeTransformer; + } + + public NodeInfo2DataObjectTransformer() { + this.nodeInfo2NodeTransformer = new NodeInfo2NodeTransformer(); + } + + @Override + protected Class getSourceType() { + return NodeInfo.class; + } + + @Override + protected Class getTargetType() { + return DataObject.class; + } + + @Override + public int getWeight() { + return 30 + nodeInfo2NodeTransformer.getWeight(); + } + + public DataObject transform(NodeInfo source, TransformationContext context) { + Document doc = (Document)nodeInfo2NodeTransformer.transform(source, context); + + return produceResult(doc); + } + + private DataObject produceResult(Document doc) { + try { + // FIXME: [rfeng] We should use the HelperContext from the context + DataObject resultingObject = + XMLHelper.INSTANCE.load(new DOMSource(doc), doc.getDocumentURI(), null).getRootObject(); + return resultingObject; + } catch (IOException e) { + throw new TransformationException(e); + } + } +} diff --git a/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/NodeInfo2JavaArrayTransformer.java b/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/NodeInfo2JavaArrayTransformer.java new file mode 100644 index 0000000000..36ebac3aea --- /dev/null +++ b/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/NodeInfo2JavaArrayTransformer.java @@ -0,0 +1,76 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.databinding.saxon; + +import java.lang.reflect.Array; + +import net.sf.saxon.om.Item; +import net.sf.saxon.om.NodeInfo; +import net.sf.saxon.trans.XPathException; +import net.sf.saxon.value.Value; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.apache.tuscany.sca.databinding.saxon.collection.ItemList; + +import commonj.sdo.DataObject; + +/** + * Transforms a NodeInfo object to a DataObject and return it in an array. + * + * @version $Rev: 659284 $ $Date: 2008-05-22 14:26:18 -0800 (Thu, 22 May 2008) $ + */ +public class NodeInfo2JavaArrayTransformer extends + BaseTransformer implements + PullTransformer { + + private NodeInfo2DataObjectTransformer nodeInfo2DataObjectTransformer = new NodeInfo2DataObjectTransformer(); + + public NodeInfo2JavaArrayTransformer() {} + + @Override + protected Class getSourceType() { + return NodeInfo.class; + } + + @Override + protected Class getTargetType() { + return Object[].class; + } + + @Override + public int getWeight() { + return 30 + nodeInfo2DataObjectTransformer.getWeight(); + } + + public Object[] transform(NodeInfo source, TransformationContext context) { + Object object = nodeInfo2DataObjectTransformer.transform(source, context); + + Class componentClass = context.getTargetDataType().getPhysical().getComponentType(); + Object[] result = (Object[]) Array.newInstance(componentClass, 1); + + result[0] = object; + + return result; + + } + +} diff --git a/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/NodeInfo2NodeTransformer.java b/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/NodeInfo2NodeTransformer.java new file mode 100644 index 0000000000..1e5b816662 --- /dev/null +++ b/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/NodeInfo2NodeTransformer.java @@ -0,0 +1,71 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.databinding.saxon; + +import java.util.Properties; + +import javax.xml.transform.OutputKeys; +import javax.xml.transform.dom.DOMResult; + +import net.sf.saxon.om.NodeInfo; +import net.sf.saxon.query.QueryResult; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.w3c.dom.Node; + +/** + * Transforms NodeInfo objects to SDO DataObjects. + * + * @version $Rev$ $Date$ + */ +public class NodeInfo2NodeTransformer extends BaseTransformer implements + PullTransformer { + + public Node transform(NodeInfo source, TransformationContext context) { + DOMResult destination = new DOMResult(); + try { + Properties props = new Properties(); + props.setProperty(OutputKeys.METHOD, "xml"); + props.setProperty(OutputKeys.INDENT, "yes"); + QueryResult.serialize(source, destination, props, source.getConfiguration()); + } catch (Exception e) { + throw new TransformationException(e); + } + return destination.getNode(); + } + + @Override + protected Class getSourceType() { + return NodeInfo.class; + } + + @Override + protected Class getTargetType() { + return Node.class; + } + + @Override + public int getWeight() { + return 10; + } + +} diff --git a/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/Object2ValueTransformer.java b/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/Object2ValueTransformer.java new file mode 100644 index 0000000000..616bcca6c5 --- /dev/null +++ b/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/Object2ValueTransformer.java @@ -0,0 +1,65 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.databinding.saxon; + +import net.sf.saxon.value.FloatValue; +import net.sf.saxon.value.ObjectValue; +import net.sf.saxon.value.Value; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.apache.tuscany.sca.databinding.javabeans.JavaBeansDataBinding; + +/** + * Transforms generic java objects to Value objects needed by Saxon parser. + * + * @version $Rev$ $Date$ + */ +public class Object2ValueTransformer extends BaseTransformer implements PullTransformer { + + @Override + protected Class getSourceType() { + return Object.class; + } + + @Override + protected Class getTargetType() { + return Value.class; + } + + @Override + public String getSourceDataBinding() { + return JavaBeansDataBinding.NAME; + } + + @Override + public int getWeight() { + return 10000; + } + + public Value transform(Object source, TransformationContext context) { + // WORKAROUND for ClassCastException in ObjectValue.toJavaObject(float) + if (source instanceof Float) { + return new FloatValue(((Float)source).floatValue()); + } + return new ObjectValue(source); + } + +} diff --git a/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/SaxonDataBindingHelper.java b/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/SaxonDataBindingHelper.java new file mode 100644 index 0000000000..ecb20b24b5 --- /dev/null +++ b/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/SaxonDataBindingHelper.java @@ -0,0 +1,41 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.databinding.saxon; + +import net.sf.saxon.Configuration; + +/** + * Provides helper functionality for Saxon data bindings + * @version $Rev$ $Date$ + */ +public class SaxonDataBindingHelper { + /** + * This variable is meaningful only in the context of XQoery expression + * execution. It is used by the DataObject2NodeInfoTransformer and + * Node2NodeInfoTransformer to create the correct NodeInfo objects + * in the Output2Output transformations. + * For Input2Input transformations it is meaningless: + * - if it is null - it is ignored by the transformers as they create new + * configuration objects + * - if it is not null - it is reused + * However the XQueryInvoker transforms all NodeInfo-s to NodeInfo-s with + * its current configuration, so there is no effect for Input2Input transformations + */ + public static Configuration CURR_EXECUTING_CONFIG = null; +} diff --git a/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/SaxonNodeDataBinding.java b/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/SaxonNodeDataBinding.java new file mode 100644 index 0000000000..ccf842710d --- /dev/null +++ b/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/SaxonNodeDataBinding.java @@ -0,0 +1,54 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.databinding.saxon; + + +import net.sf.saxon.om.NodeInfo; + +import org.apache.tuscany.sca.databinding.impl.BaseDataBinding; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.Operation; + +/** + * Represents data binding for parameters of type NodeInfo. + * + * The NodeInfo type is the type accepted by the Saxon XQuery processor for + * all XML - based content (i.e. not strings and simple types) + * + * @version $Rev$ $Date$ + */ +public class SaxonNodeDataBinding extends BaseDataBinding { + + public static final String NAME = NodeInfo.class.getName(); + public static final String[] ALIASES = new String[] {"saxon_node"}; + + public SaxonNodeDataBinding() { + super(NAME, NodeInfo.class); + } + + @Override + public boolean introspect(DataType type, Operation operation) { + if (super.introspect(type, operation)) { + // type.setLogical(XMLType.UNKNOWN); + return true; + } else { + return false; + } + } +} diff --git a/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/SaxonValueDataBinding.java b/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/SaxonValueDataBinding.java new file mode 100644 index 0000000000..2f51cf86ec --- /dev/null +++ b/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/SaxonValueDataBinding.java @@ -0,0 +1,53 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.databinding.saxon; + + +import net.sf.saxon.value.Value; + +import org.apache.tuscany.sca.databinding.impl.BaseDataBinding; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.Operation; + +/** + * Represents data binding for parameters of type Value. + * + * The Value type is the type accepted by the Saxon XQuery processor for + * all simple types and strings + * + * @version $Rev$ $Date$ + */ +public class SaxonValueDataBinding extends BaseDataBinding { + public static final String NAME = Value.class.getName(); + public static final String[] ALIASES = new String[] {"saxon_value"}; + + public SaxonValueDataBinding() { + super(NAME, Value.class); + } + + @Override + public boolean introspect(DataType type, Operation operation) { + if (super.introspect(type, operation)) { + // type.setLogical(XMLType.UNKNOWN); + return true; + } else { + return false; + } + } +} diff --git a/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/SimpleType2ValueTransformer.java b/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/SimpleType2ValueTransformer.java new file mode 100644 index 0000000000..67d89a6e0b --- /dev/null +++ b/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/SimpleType2ValueTransformer.java @@ -0,0 +1,87 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.databinding.saxon; + +import java.math.BigDecimal; + +import net.sf.saxon.value.DecimalValue; +import net.sf.saxon.value.DoubleValue; +import net.sf.saxon.value.FloatValue; +import net.sf.saxon.value.IntegerValue; +import net.sf.saxon.value.ObjectValue; +import net.sf.saxon.value.StringValue; +import net.sf.saxon.value.Value; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.apache.tuscany.sca.databinding.javabeans.SimpleJavaDataBinding; + +/** + * Transforms simple types and strings to Value objects needed by Saxon parser + * @version $Rev$ $Date$ + */ +public class SimpleType2ValueTransformer extends BaseTransformer implements + PullTransformer { + + @Override + public String getSourceDataBinding() { + return SimpleJavaDataBinding.NAME; + } + + @Override + protected Class getSourceType() { + return Object.class; + } + + @Override + protected Class getTargetType() { + return Value.class; + } + + @Override + public int getWeight() { + return 10000; + } + + public Value transform(Object source, TransformationContext context) { + Value result = null; + if (source instanceof Integer) { + result = new IntegerValue((Integer)source); + } else if (source instanceof Long) { + result = new IntegerValue((Long)source); + } else if (source instanceof Short) { + result = new IntegerValue((Short)source); + } else if (source instanceof Byte) { + result = new IntegerValue((Byte)source); + } else if (source instanceof Double) { + result = new DoubleValue((Double)source); + } else if (source instanceof Float) { + result = new FloatValue((Float)source); + } else if (source instanceof BigDecimal) { + result = new DecimalValue((BigDecimal)source); + } else if (source instanceof String) { + result = new StringValue(((String)source)); + } else { + result = new ObjectValue(source); + } + + return result; + } +} diff --git a/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/Value2JavaArray.java b/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/Value2JavaArray.java new file mode 100644 index 0000000000..16d5f524bb --- /dev/null +++ b/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/Value2JavaArray.java @@ -0,0 +1,74 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.databinding.saxon; + +import java.lang.reflect.Array; + +import net.sf.saxon.trans.XPathException; +import net.sf.saxon.value.Value; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; + +/** + * Transforms a Value object to a Java Object and return it in an array. + * + * @version $Rev: 659284 $ $Date: 2008-05-22 14:26:18 -0800 (Thu, 22 May 2008) $ + */ +public class Value2JavaArray extends BaseTransformer implements PullTransformer { + + public Value2JavaArray() { + } + + @Override + protected Class getSourceType() { + return Value.class; + } + + @Override + protected Class getTargetType() { + return Object[].class; + } + + @Override + public int getWeight() { + return super.getWeight() + 100; + } + + public Object[] transform(Value source, TransformationContext context) { + + try { + Object object = Value.convert(Value.asItem(source)); + + Class componentClass = context.getTargetDataType().getPhysical().getComponentType(); + Object[] result = (Object[])Array.newInstance(componentClass, 1); + + result[0] = object; + + return result; + + } catch (XPathException e) { + throw new TransformationException(e.getMessage()); + } + + } + +} diff --git a/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/Value2ObjectTransformer.java b/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/Value2ObjectTransformer.java new file mode 100644 index 0000000000..7589f6789b --- /dev/null +++ b/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/Value2ObjectTransformer.java @@ -0,0 +1,66 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.databinding.saxon; + +import net.sf.saxon.trans.XPathException; +import net.sf.saxon.value.Value; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.apache.tuscany.sca.databinding.javabeans.JavaBeansDataBinding; + +/** + * Transforms Value objects to generic java objects + * @version $Rev$ $Date$ + */ +public class Value2ObjectTransformer extends BaseTransformer implements PullTransformer { + + public Object transform(Value source, TransformationContext context) { + Object object; + try { + object = Value.convert(Value.asItem(source)); + } catch (XPathException e) { + throw new TransformationException(e); + } + return object; + } + + @Override + protected Class getSourceType() { + return Value.class; + } + + @Override + protected Class getTargetType() { + return Object.class; + } + + @Override + public String getTargetDataBinding() { + return JavaBeansDataBinding.NAME; + } + + @Override + public int getWeight() { + return 10000; + } + +} diff --git a/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/Value2SimpleTypeTransformer.java b/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/Value2SimpleTypeTransformer.java new file mode 100644 index 0000000000..5da4effcfd --- /dev/null +++ b/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/Value2SimpleTypeTransformer.java @@ -0,0 +1,65 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.databinding.saxon; + +import net.sf.saxon.trans.XPathException; +import net.sf.saxon.value.Value; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.apache.tuscany.sca.databinding.javabeans.SimpleJavaDataBinding; + +/** + * Transforms Value objects to simple types + * @version $Rev$ $Date$ + */ +public class Value2SimpleTypeTransformer extends BaseTransformer implements + PullTransformer { + public Object transform(Value source, TransformationContext context) { + Object object; + try { + object = Value.convert(Value.asItem(source)); + } catch (XPathException e) { + throw new TransformationException(e); + } + return object; + } + + @Override + public String getTargetDataBinding() { + return SimpleJavaDataBinding.NAME; + } + + @Override + protected Class getSourceType() { + return Value.class; + } + + @Override + protected Class getTargetType() { + return Object.class; + } + + @Override + public int getWeight() { + return 10000; + } +} diff --git a/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/collection/ItemList.java b/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/collection/ItemList.java new file mode 100644 index 0000000000..065121520b --- /dev/null +++ b/java/sca/contrib/modules/databinding-saxon/src/main/java/org/apache/tuscany/sca/databinding/saxon/collection/ItemList.java @@ -0,0 +1,34 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.saxon.collection; + +import java.util.ArrayList; + +import net.sf.saxon.om.Item; + +/** + * Stores a list of Item objects. + * + * Used by the implementation.xquery to store a collection of results + * generated by the xquery execution. + * + * @version $Rev: 659284 $ $Date: 2008-05-22 14:26:18 -0800 (Thu, 22 May 2008) $ + */ +public class ItemList extends ArrayList {} diff --git a/java/sca/contrib/modules/databinding-saxon/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.DataBinding b/java/sca/contrib/modules/databinding-saxon/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.DataBinding new file mode 100644 index 0000000000..e15021b972 --- /dev/null +++ b/java/sca/contrib/modules/databinding-saxon/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.DataBinding @@ -0,0 +1,20 @@ +# 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. + +# implementation classes for the databindings +org.apache.tuscany.sca.databinding.saxon.SaxonNodeDataBinding;name=net.sf.saxon.om.NodeInfo +org.apache.tuscany.sca.databinding.saxon.SaxonValueDataBinding;name=net.sf.saxon.value.Value diff --git a/java/sca/contrib/modules/databinding-saxon/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PullTransformer b/java/sca/contrib/modules/databinding-saxon/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PullTransformer new file mode 100644 index 0000000000..4d927ce53d --- /dev/null +++ b/java/sca/contrib/modules/databinding-saxon/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PullTransformer @@ -0,0 +1,34 @@ +# 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. + +# Implementation classes for the transformers +org.apache.tuscany.sca.databinding.saxon.Node2NodeInfoTransformer;source=org.w3c.dom.Node,target=net.sf.saxon.om.NodeInfo,weight=2000 +org.apache.tuscany.sca.databinding.saxon.NodeInfo2NodeTransformer;source=net.sf.saxon.om.NodeInfo,target=org.w3c.dom.Node,weight=2000 +org.apache.tuscany.sca.databinding.saxon.Object2ValueTransformer;source=java:complexType,target=net.sf.saxon.value.Value,weight=80000 +org.apache.tuscany.sca.databinding.saxon.Value2ObjectTransformer;source=net.sf.saxon.value.Value,target=java:complexType,weight=80000 +org.apache.tuscany.sca.databinding.saxon.SimpleType2ValueTransformer;source=java:simpleType,target=net.sf.saxon.value.Value,weight=80000 +org.apache.tuscany.sca.databinding.saxon.Value2SimpleTypeTransformer;source=net.sf.saxon.value.Value,target=java:simpleType,weight=80000 +org.apache.tuscany.sca.databinding.saxon.NodeInfo2DataObjectTransformer;source=net.sf.saxon.om.NodeInfo,target=commonj.sdo.DataObject,weight=1000 +org.apache.tuscany.sca.databinding.saxon.DataObject2NodeInfoTransformer;source=commonj.sdo.DataObject,target=net.sf.saxon.om.NodeInfo,weight=1000 +org.apache.tuscany.sca.databinding.saxon.ItemList2ObjectTransformer;source=org.apache.tuscany.sca.databinding.saxon.collection.ItemList,target=net.sf.saxon.om.NodeInfo,weight=1000 +org.apache.tuscany.sca.databinding.saxon.ItemList2ObjectTransformer;source=org.apache.tuscany.sca.databinding.saxon.collection.ItemList,target=net.sf.saxon.value.Value,weight=1000 +org.apache.tuscany.sca.databinding.saxon.ItemList2ObjectTransformer;source=org.apache.tuscany.sca.databinding.saxon.collection.ItemList,target=commonj.sdo.DataObject,weight=1000 +org.apache.tuscany.sca.databinding.saxon.ItemList2ObjectTransformer;source=org.apache.tuscany.sca.databinding.saxon.collection.ItemList,target=java:complex,weight=1000 +org.apache.tuscany.sca.databinding.saxon.ItemList2ObjectTransformer;source=org.apache.tuscany.sca.databinding.saxon.collection.ItemList,target=java:simple,weight=1000 +org.apache.tuscany.sca.databinding.saxon.ItemList2ObjectTransformer;source=org.apache.tuscany.sca.databinding.saxon.collection.ItemList,target=java:array,weight=1000 +org.apache.tuscany.sca.databinding.saxon.NodeInfo2JavaArrayTransformer;source=net.sf.saxon.om.NodeInfo,target=java:array,weight=1000 +org.apache.tuscany.sca.databinding.saxon.Value2JavaArrayTransformer;source=net.sf.saxon.value.Value,target=java:array,weight=1000 diff --git a/java/sca/contrib/modules/databinding-sdo-axiom/LICENSE b/java/sca/contrib/modules/databinding-sdo-axiom/LICENSE new file mode 100644 index 0000000000..8aa906c321 --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo-axiom/LICENSE @@ -0,0 +1,205 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + + diff --git a/java/sca/contrib/modules/databinding-sdo-axiom/META-INF/MANIFEST.MF b/java/sca/contrib/modules/databinding-sdo-axiom/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..76259a7555 --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo-axiom/META-INF/MANIFEST.MF @@ -0,0 +1,40 @@ +Manifest-Version: 1.0 +Private-Package: com.example.ipo.sdo;version="2.0.0",com.example.ipo.sdo + .impl;version="2.0.0",com.example.stock.sdo;version="2.0.0",com.example.s + tock.sdo.impl;version="2.0.0",org.apache.tuscany.sca.databinding.sdo2om + ;version="2.0.0" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA Data Binding for SDO/AXIOM +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397381546 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA Data Binding for SDO/AXIOM +Import-Package: commonj.sdo;version="2.1", + commonj.sdo.helper;version="2.1", + commonj.sdo.impl;resolution:=optional, + javax.xml.namespace, + javax.xml.stream, + + org.apache.axiom.om, + org.apache.axiom.om.impl.builder, + org.apache.axiom.om.impl.serialize, + org.apache.tuscany.sca.databinding;version="2.0.0", + org.apache.tuscany.sca.databinding.impl;version="2.0.0", + org.apache.tuscany.sca.databinding.sdo;version="2.0.0", + org.apache.tuscany.sca.interfacedef;version="2.0.0", + org.apache.tuscany.sca.interfacedef.impl;version="2.0.0";resolution:=optional, + org.apache.tuscany.sca.interfacedef.util;version="2.0.0", + org.apache.tuscany.sdo.api, + org.apache.tuscany.sdo.helper, + org.apache.tuscany.sdo.impl, + org.apache.tuscany.sdo.model, + org.apache.tuscany.sdo.model.impl, + org.eclipse.emf.common.notify, + org.eclipse.emf.ecore, + org.eclipse.emf.ecore.util +Bundle-SymbolicName: org.apache.tuscany.sca.databinding.sdo.axiom +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/databinding-sdo-axiom/NOTICE b/java/sca/contrib/modules/databinding-sdo-axiom/NOTICE new file mode 100644 index 0000000000..25bb89c9b2 --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo-axiom/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/databinding-sdo-axiom/pom.xml b/java/sca/contrib/modules/databinding-sdo-axiom/pom.xml new file mode 100644 index 0000000000..4737cfd963 --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo-axiom/pom.xml @@ -0,0 +1,153 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + tuscany-databinding-sdo-axiom + Apache Tuscany SCA Data Binding for SDO/AXIOM + + + + org.apache.tuscany.sca + tuscany-databinding + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-databinding-sdo + 2.0-SNAPSHOT + + + + org.apache.ws.commons.axiom + axiom-api + 1.2.7 + + + xerces + xercesImpl + + + javax.mail + mail + + + commons-logging + commons-logging + + + xml-apis + xml-apis + + + + + + org.apache.ws.commons.axiom + axiom-impl + 1.2.7 + runtime + + + + commons-logging + commons-logging + 1.1.1 + + + commons-logging + commons-logging + + + javax.servlet + servlet-api + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.0 + + + add-test-source + generate-sources + + add-test-source + + + + target/sdo-source + + + + + + + org.apache.tuscany.sdo + tuscany-sdo-plugin + 1.1.1 + + + generate-po-sdo + generate-test-sources + + ${basedir}/src/test/resources/ipo.xsd + com.example.ipo.sdo + true + true + true + + + generate + + + + generate-stock-sdo + generate-test-sources + + ${basedir}/src/test/resources/stock.xsd + com.example.stock.sdo + Stock + true + true + true + + + generate + + + + + + + + + diff --git a/java/sca/contrib/modules/databinding-sdo-axiom/src/main/java/org/apache/tuscany/sca/databinding/sdo2om/AxiomHelper.java b/java/sca/contrib/modules/databinding-sdo-axiom/src/main/java/org/apache/tuscany/sca/databinding/sdo2om/AxiomHelper.java new file mode 100644 index 0000000000..02f43000b4 --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo-axiom/src/main/java/org/apache/tuscany/sca/databinding/sdo2om/AxiomHelper.java @@ -0,0 +1,142 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.sdo2om; + +import javax.xml.namespace.QName; + +import org.apache.axiom.om.OMAbstractFactory; +import org.apache.axiom.om.OMDataSource; +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.OMFactory; +import org.apache.axiom.om.OMNamespace; +import org.apache.axiom.om.OMXMLParserWrapper; +import org.apache.axiom.om.impl.builder.StAXBuilder; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.util.XMLType; + +/** + * Helper for AXIOM + * + * @version $Rev$ $Date$ + */ +public class AxiomHelper { + private static final String DEFAULT_PREFIX = "_ns_"; + + private AxiomHelper() { + } + + /** + * See http://issues.apache.org/jira/browse/WSCOMMONS-240 + * @param om + */ + public static void completeAndClose(OMElement om) { + // Get the builder associated with the om element + OMXMLParserWrapper builder = om.getBuilder(); + if (builder != null) { + if (builder instanceof StAXBuilder) { + ((StAXBuilder)builder).releaseParserOnClose(true); + } + OMElement document = builder.getDocumentElement(); + if (document != null) { + document.build(); + } + } + if (builder instanceof StAXBuilder) { + ((StAXBuilder)builder).close(); + } + } + + /** + * This method will close the builder immediately. Any subsequent Axiom objects won't + * be built or accessible. + */ + public static void closeImmediately(OMElement om) { + // Get the builder associated with the om element + OMXMLParserWrapper builder = om.getBuilder(); + if (builder != null) { + if (builder instanceof StAXBuilder) { + ((StAXBuilder)builder).releaseParserOnClose(true); + ((StAXBuilder)builder).close(); + } + // builder.close(); + } + } + + /** + * @param context + * @param element + */ + public static void adjustElementName(TransformationContext context, OMElement element) { + if (context != null) { + DataType dataType = context.getTargetDataType(); + Object logical = dataType == null ? null : dataType.getLogical(); + if (!(logical instanceof XMLType)) { + return; + } + XMLType xmlType = (XMLType)logical; + if (xmlType.isElement() && !xmlType.getElementName().equals(element.getQName())) { + // FIXME:: Throw exception or switch to the new Element? + OMFactory factory = OMAbstractFactory.getOMFactory(); + QName name = xmlType.getElementName(); + OMNamespace namespace = factory.createOMNamespace(name.getNamespaceURI(), name.getPrefix()); + element.setNamespace(namespace); + element.setLocalName(name.getLocalPart()); + } + } + } + + public static OMElement createOMElement(OMFactory factory, QName element) { + String localName = element.getLocalPart(); + OMNamespace ns = createOMNamespace(factory, element); + + return factory.createOMElement(localName, ns); + + } + + public static OMElement createOMElement(OMFactory factory, QName element, OMDataSource dataSource) { + String localName = element.getLocalPart(); + OMNamespace ns = createOMNamespace(factory, element); + + return factory.createOMElement(dataSource, localName, ns); + + } + + /** + * @param factory + * @param name + * @return + */ + public static OMNamespace createOMNamespace(OMFactory factory, QName name) { + String namespaceURI = name.getNamespaceURI(); + String prefix = name.getPrefix(); + + OMNamespace ns = null; + if (namespaceURI.length() != 0) { + // Qualified Element: we need an OMNamespace + if (prefix.length() == 0) { + // The prefix does not appear to be specified, let's create one + prefix = DEFAULT_PREFIX; + } + ns = factory.createOMNamespace(namespaceURI, prefix); + } + return ns; + } +} diff --git a/java/sca/contrib/modules/databinding-sdo-axiom/src/main/java/org/apache/tuscany/sca/databinding/sdo2om/DataObject2OMElement.java b/java/sca/contrib/modules/databinding-sdo-axiom/src/main/java/org/apache/tuscany/sca/databinding/sdo2om/DataObject2OMElement.java new file mode 100644 index 0000000000..aa7f99724d --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo-axiom/src/main/java/org/apache/tuscany/sca/databinding/sdo2om/DataObject2OMElement.java @@ -0,0 +1,86 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.databinding.sdo2om; + +import static org.apache.tuscany.sca.databinding.sdo.SDODataBinding.ROOT_ELEMENT; + +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.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.apache.tuscany.sca.databinding.sdo.SDOContextHelper; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.util.XMLType; + +import commonj.sdo.DataObject; +import commonj.sdo.helper.HelperContext; +import commonj.sdo.helper.XMLDocument; + +/** + * SDO DataObject --> AXIOM OMElement transformer + * + * @version $Rev$ $Date$ + */ +public class DataObject2OMElement extends BaseTransformer implements + PullTransformer { + + public OMElement transform(DataObject source, TransformationContext context) { + HelperContext helperContext = SDOContextHelper.getHelperContext(context, true); + OMFactory factory = OMAbstractFactory.getOMFactory(); + + QName name = ROOT_ELEMENT; + if (context != null) { + DataType dataType = context.getTargetDataType(); + Object logical = dataType == null ? null : dataType.getLogical(); + if (logical instanceof XMLType) { + XMLType xmlType = (XMLType)logical; + if (xmlType.isElement()) { + name = xmlType.getElementName(); + } + } + } + + XMLDocument document = helperContext.getXMLHelper().createDocument(source, + name.getNamespaceURI(), + name.getLocalPart()); + SDODataSource dataSource = new SDODataSource(document, helperContext); + OMElement element = AxiomHelper.createOMElement(factory, name, dataSource); + return element; + } + + @Override + protected Class getSourceType() { + return DataObject.class; + } + + @Override + protected Class getTargetType() { + return OMElement.class; + } + + @Override + public int getWeight() { + return 10; + } + +} diff --git a/java/sca/contrib/modules/databinding-sdo-axiom/src/main/java/org/apache/tuscany/sca/databinding/sdo2om/SDODataSource.java b/java/sca/contrib/modules/databinding-sdo-axiom/src/main/java/org/apache/tuscany/sca/databinding/sdo2om/SDODataSource.java new file mode 100644 index 0000000000..dc3c2610a4 --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo-axiom/src/main/java/org/apache/tuscany/sca/databinding/sdo2om/SDODataSource.java @@ -0,0 +1,89 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.sdo2om; + +import static org.apache.tuscany.sca.databinding.sdo.SDODataBinding.ROOT_ELEMENT; + +import java.io.IOException; +import java.io.OutputStream; +import java.io.Writer; + +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; + +import org.apache.axiom.om.OMDataSource; +import org.apache.axiom.om.OMOutputFormat; +import org.apache.axiom.om.impl.serialize.StreamingOMSerializer; +import org.apache.tuscany.sdo.api.SDOUtil; +import org.apache.tuscany.sdo.api.XMLStreamHelper; + +import commonj.sdo.DataObject; +import commonj.sdo.helper.HelperContext; +import commonj.sdo.helper.XMLDocument; + +/** + * + * @version $Rev$ $Date$ + */ +public class SDODataSource implements OMDataSource { + private HelperContext helperContext; + private XMLDocument sourceDocument; + + public SDODataSource(XMLDocument source, HelperContext helperContext) { + this.sourceDocument = source; + this.helperContext = helperContext; + } + + public SDODataSource(DataObject obj, HelperContext helperContext) { + this.helperContext = helperContext; + this.sourceDocument = + helperContext.getXMLHelper().createDocument(obj, + ROOT_ELEMENT.getNamespaceURI(), + ROOT_ELEMENT.getLocalPart()); + } + + public XMLStreamReader getReader() throws XMLStreamException { + XMLStreamHelper streamHelper = SDOUtil.createXMLStreamHelper(helperContext); + return streamHelper.createXMLStreamReader(sourceDocument); + } + + public void serialize(XMLStreamWriter xmlWriter) throws XMLStreamException { + StreamingOMSerializer serializer = new StreamingOMSerializer(); + serializer.serialize(getReader(), xmlWriter); + } + + public void serialize(OutputStream output, OMOutputFormat format) throws XMLStreamException { + try { + helperContext.getXMLHelper().save(sourceDocument, output, null); + } catch (Exception e) { + throw new XMLStreamException(e); + } + } + + public void serialize(Writer writer, OMOutputFormat format) throws XMLStreamException { + try { + helperContext.getXMLHelper().save(sourceDocument, writer, null); + } catch (IOException e) { + throw new XMLStreamException(e); + } + } + +} diff --git a/java/sca/contrib/modules/databinding-sdo-axiom/src/main/java/org/apache/tuscany/sca/databinding/sdo2om/XMLDocument2OMElement.java b/java/sca/contrib/modules/databinding-sdo-axiom/src/main/java/org/apache/tuscany/sca/databinding/sdo2om/XMLDocument2OMElement.java new file mode 100644 index 0000000000..a55a9f37cb --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo-axiom/src/main/java/org/apache/tuscany/sca/databinding/sdo2om/XMLDocument2OMElement.java @@ -0,0 +1,65 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.databinding.sdo2om; + +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.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.apache.tuscany.sca.databinding.sdo.SDOContextHelper; + +import commonj.sdo.helper.HelperContext; +import commonj.sdo.helper.XMLDocument; + +/** + * SDO XMLDocument --> AXIOM OMElement transformer + * @version $Rev$ $Date$ + */ +public class XMLDocument2OMElement extends BaseTransformer implements + PullTransformer { + + public OMElement transform(XMLDocument source, TransformationContext context) { + HelperContext helperContext = SDOContextHelper.getHelperContext(context, true); + SDODataSource dataSource = new SDODataSource(source, helperContext); + OMFactory factory = OMAbstractFactory.getOMFactory(); + QName name = new QName(source.getRootElementURI(), source.getRootElementName()); + OMElement element = AxiomHelper.createOMElement(factory, name, dataSource); + return element; + } + + @Override + protected Class getSourceType() { + return XMLDocument.class; + } + + @Override + protected Class getTargetType() { + return OMElement.class; + } + + @Override + public int getWeight() { + return 10; + } + +} diff --git a/java/sca/contrib/modules/databinding-sdo-axiom/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PullTransformer b/java/sca/contrib/modules/databinding-sdo-axiom/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PullTransformer new file mode 100644 index 0000000000..c870ec2406 --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo-axiom/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PullTransformer @@ -0,0 +1,20 @@ +# 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. + +# Implementation classes for the transformers +org.apache.tuscany.sca.databinding.sdo2om.DataObject2OMElement;source=commonj.sdo.DataObject,target=org.apache.axiom.om.OMElement,weight=3000 +org.apache.tuscany.sca.databinding.sdo2om.XMLDocument2OMElement;source=commonj.sdo.helper.XMLDocument,target=org.apache.axiom.om.OMElement,weight=3000 diff --git a/java/sca/contrib/modules/databinding-sdo-axiom/src/test/java/org/apache/tuscany/sca/databinding/sdo2om/DataObject2OMElementTestCase.java b/java/sca/contrib/modules/databinding-sdo-axiom/src/test/java/org/apache/tuscany/sca/databinding/sdo2om/DataObject2OMElementTestCase.java new file mode 100644 index 0000000000..57dd056526 --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo-axiom/src/test/java/org/apache/tuscany/sca/databinding/sdo2om/DataObject2OMElementTestCase.java @@ -0,0 +1,78 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.sdo2om; + +import java.io.StringWriter; + +import javax.xml.stream.XMLStreamException; + +import junit.framework.Assert; + +import org.apache.axiom.om.OMAbstractFactory; +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.OMNamespace; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.impl.DataTypeImpl; +import org.apache.tuscany.sca.interfacedef.util.XMLType; + +import commonj.sdo.DataObject; + +/** + * + * @version $Rev$ $Date$ + */ +public class DataObject2OMElementTestCase extends SDOTransformerTestCaseBase { + + @Override + protected DataType getSourceDataType() { + return new DataTypeImpl(DataObject.class.getName(), DataObject.class, new XMLType(ORDER_QNAME, null)); + } + + @Override + protected DataType getTargetDataType() { + return new DataTypeImpl(OMElement.class.getName(), OMElement.class, new XMLType(ORDER_QNAME, null)); + } + + public final void testTransform() throws XMLStreamException { + OMElement element = new DataObject2OMElement().transform(dataObject, context); + Assert.assertEquals(ORDER_QNAME.getNamespaceURI(), element.getNamespace().getNamespaceURI()); + Assert.assertEquals(ORDER_QNAME.getLocalPart(), element.getLocalName()); + // TODO: See https://issues.apache.org/jira/browse/WSCOMMONS-226 + // element.getBuilder().setCache(false); + StringWriter writer = new StringWriter(); + element.serialize(writer); + } + + public final void testTransformWrapper() throws XMLStreamException { + OMElement element = new DataObject2OMElement().transform(dataObject, context); + Assert.assertEquals(ORDER_QNAME.getNamespaceURI(), element.getNamespace().getNamespaceURI()); + Assert.assertEquals(ORDER_QNAME.getLocalPart(), element.getLocalName()); + + OMNamespace ns = OMAbstractFactory.getOMFactory().createOMNamespace("http://ns1", "ns1"); + element.setNamespace(ns); + element.setLocalName("dummy"); + // TODO: See https://issues.apache.org/jira/browse/WSCOMMONS-226 + // element.getBuilder().setCache(true); + StringWriter writer = new StringWriter(); + element.serializeAndConsume(writer); + // System.out.println(writer); + } + +} diff --git a/java/sca/contrib/modules/databinding-sdo-axiom/src/test/java/org/apache/tuscany/sca/databinding/sdo2om/SDOTransformerTestCaseBase.java b/java/sca/contrib/modules/databinding-sdo-axiom/src/test/java/org/apache/tuscany/sca/databinding/sdo2om/SDOTransformerTestCaseBase.java new file mode 100644 index 0000000000..f69ef598b8 --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo-axiom/src/test/java/org/apache/tuscany/sca/databinding/sdo2om/SDOTransformerTestCaseBase.java @@ -0,0 +1,82 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.sdo2om; + +import javax.xml.namespace.QName; + +import junit.framework.TestCase; + +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.impl.TransformationContextImpl; +import org.apache.tuscany.sca.interfacedef.DataType; + +import com.example.ipo.sdo.PurchaseOrderType; +import com.example.ipo.sdo.SdoFactory; +import com.example.ipo.sdo.USAddress; +import commonj.sdo.DataObject; +import commonj.sdo.helper.HelperContext; +import commonj.sdo.impl.HelperProvider; + +/** + * The base class for SDO-related test cases + * + * @version $Rev$ $Date$ + */ +public abstract class SDOTransformerTestCaseBase extends TestCase { + protected static final QName ORDER_QNAME = new QName("http://www.example.com/IPO", "purchaseOrder"); + + protected HelperContext helperContext; + protected String binding = DataObject.class.getName(); + protected TransformationContext context; + protected TransformationContext reversedContext; + protected DataObject dataObject; + + /** + * @see junit.framework.TestCase#setUp() + */ + @Override + protected void setUp() throws Exception { + super.setUp(); + helperContext = HelperProvider.getDefaultContext(); + SdoFactory.INSTANCE.register(helperContext); + + context = new TransformationContextImpl(); + context.setSourceDataType(getSourceDataType()); + context.setTargetDataType(getTargetDataType()); + + reversedContext = new TransformationContextImpl(); + reversedContext.setSourceDataType(getTargetDataType()); + reversedContext.setTargetDataType(getSourceDataType()); + + PurchaseOrderType po = SdoFactory.INSTANCE.createPurchaseOrderType(); + USAddress address = SdoFactory.INSTANCE.createUSAddress(); + address.setCity("San Jose"); + address.setStreet("123 ABC St"); + address.setState("CA"); + address.setStreet("95131"); + po.setBillTo(address); + dataObject = (DataObject) po; + } + + protected abstract DataType getSourceDataType(); + + protected abstract DataType getTargetDataType(); + +} diff --git a/java/sca/contrib/modules/databinding-sdo-axiom/src/test/java/org/apache/tuscany/sca/databinding/sdo2om/XMLDocument2OMElementTestCase.java b/java/sca/contrib/modules/databinding-sdo-axiom/src/test/java/org/apache/tuscany/sca/databinding/sdo2om/XMLDocument2OMElementTestCase.java new file mode 100644 index 0000000000..5015a1b697 --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo-axiom/src/test/java/org/apache/tuscany/sca/databinding/sdo2om/XMLDocument2OMElementTestCase.java @@ -0,0 +1,63 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.sdo2om; + +import java.io.StringWriter; + +import javax.xml.stream.XMLStreamException; + +import junit.framework.Assert; + +import org.apache.axiom.om.OMElement; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.impl.DataTypeImpl; +import org.apache.tuscany.sca.interfacedef.util.XMLType; + +import commonj.sdo.helper.XMLDocument; + +/** + * + * @version $Rev$ $Date$ + */ +public class XMLDocument2OMElementTestCase extends SDOTransformerTestCaseBase { + + @Override + protected DataType getSourceDataType() { + return new DataTypeImpl(XMLDocument.class.getName(), XMLDocument.class, new XMLType(ORDER_QNAME, null)); + } + + @Override + protected DataType getTargetDataType() { + return new DataTypeImpl(OMElement.class.getName(), OMElement.class, new XMLType(ORDER_QNAME, null)); + } + + public final void testTransform() throws XMLStreamException { + XMLDocument document = + helperContext.getXMLHelper().createDocument(dataObject, + ORDER_QNAME.getNamespaceURI(), + ORDER_QNAME.getLocalPart()); + OMElement element = new XMLDocument2OMElement().transform(document, context); + Assert.assertEquals(ORDER_QNAME.getNamespaceURI(), element.getNamespace().getNamespaceURI()); + Assert.assertEquals(ORDER_QNAME.getLocalPart(), element.getLocalName()); + StringWriter writer = new StringWriter(); + element.serialize(writer); + } + +} diff --git a/java/sca/contrib/modules/databinding-sdo-axiom/src/test/resources/ipo.xsd b/java/sca/contrib/modules/databinding-sdo-axiom/src/test/resources/ipo.xsd new file mode 100644 index 0000000000..241ec15d36 --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo-axiom/src/test/resources/ipo.xsd @@ -0,0 +1,136 @@ + + + + + + International Purchase order schema for Example.com + Copyright 2000 Example.com. All rights reserved. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/java/sca/contrib/modules/databinding-sdo-axiom/src/test/resources/stock.xsd b/java/sca/contrib/modules/databinding-sdo-axiom/src/test/resources/stock.xsd new file mode 100644 index 0000000000..a0a6717371 --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo-axiom/src/test/resources/stock.xsd @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/java/sca/contrib/modules/databinding-sdo/LICENSE b/java/sca/contrib/modules/databinding-sdo/LICENSE new file mode 100644 index 0000000000..8aa906c321 --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo/LICENSE @@ -0,0 +1,205 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + + diff --git a/java/sca/contrib/modules/databinding-sdo/META-INF/MANIFEST.MF b/java/sca/contrib/modules/databinding-sdo/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..798df260ff --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo/META-INF/MANIFEST.MF @@ -0,0 +1,66 @@ +Manifest-Version: 1.0 +Export-Package: org.apache.tuscany.sca.databinding.sdo;uses:="org.apac + he.tuscany.sca.databinding,commonj.sdo.impl,org.apache.tuscany.sca.in + terfacedef.util,org.apache.tuscany.sca.assembly.impl,javax.xml.transf + orm.dom,org.apache.tuscany.sca.core,commonj.sdo.helper,javax.xml.name + space,javax.xml.stream,org.w3c.dom.ls,org.apache.tuscany.sca.contribu + tion.resolver,org.apache.tuscany.sca.databinding.util,org.oasisopen.sca,or + g.apache.ws.commons.schema,org.apache.tuscany.sca.databinding.impl,or + g.apache.tuscany.sca.contribution,org.apache.tuscany.sca.monitor,org. + apache.tuscany.sdo.api,org.w3c.dom,org.apache.tuscany.sca.interfacede + f,org.w3c.dom.bootstrap,commonj.sdo,javax.xml.transform,org.apache.tu + scany.sca.interfacedef.impl,org.apache.tuscany.sca.contribution.proce + ssor,org.apache.tuscany.sca.xsd";version="2.0.0" +Private-Package: com.example.ipo.sdo;version="2.0.0",com.example.ipo.sdo + .impl;version="2.0.0",com.example.stock.sdo;version="2.0.0",com.example.s + tock.sdo.impl;version="2.0.0" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA Data Binding for SDO +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397376421 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA Data Binding for SDO +Import-Package: commonj.sdo;version="2.1", + commonj.sdo.helper;version="2.1", + commonj.sdo.impl, + javax.xml.namespace, + javax.xml.stream, + javax.xml.transform, + javax.xml.transform.dom, + + org.apache.tuscany.sca.assembly;version="2.0.0", + org.apache.tuscany.sca.contribution;version="2.0.0", + org.apache.tuscany.sca.contribution.processor;version="2.0.0", + org.apache.tuscany.sca.contribution.resolver;version="2.0.0", + org.apache.tuscany.sca.core;version="2.0.0", + org.apache.tuscany.sca.databinding;version="2.0.0", + org.apache.tuscany.sca.databinding.impl;version="2.0.0", + org.apache.tuscany.sca.databinding.sdo;version="2.0.0", + org.apache.tuscany.sca.databinding.util;version="2.0.0", + org.apache.tuscany.sca.databinding.xml;version="2.0.0";resolution:=optional, + org.apache.tuscany.sca.interfacedef;version="2.0.0", + org.apache.tuscany.sca.interfacedef.impl;version="2.0.0", + org.apache.tuscany.sca.interfacedef.util;version="2.0.0", + org.apache.tuscany.sca.monitor;version="2.0.0", + org.apache.tuscany.sca.policy;version="2.0.0", + org.apache.tuscany.sca.xsd;version="2.0.0", + org.apache.tuscany.sdo.api, + org.apache.tuscany.sdo.helper, + org.apache.tuscany.sdo.impl, + org.apache.tuscany.sdo.model, + org.apache.tuscany.sdo.model.impl, + org.apache.ws.commons.schema, + org.eclipse.emf.common.notify, + org.eclipse.emf.ecore, + org.eclipse.emf.ecore.util, + + org.oasisopen.sca;version="2.0.0", + org.w3c.dom, + org.w3c.dom.bootstrap, + org.w3c.dom.ls +Bundle-SymbolicName: org.apache.tuscany.sca.databinding.sdo +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/databinding-sdo/NOTICE b/java/sca/contrib/modules/databinding-sdo/NOTICE new file mode 100644 index 0000000000..25bb89c9b2 --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/databinding-sdo/pom.xml b/java/sca/contrib/modules/databinding-sdo/pom.xml new file mode 100644 index 0000000000..6d2de7c2db --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo/pom.xml @@ -0,0 +1,119 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + tuscany-databinding-sdo + Apache Tuscany SCA Data Binding for SDO + + + + org.apache.tuscany.sca + tuscany-core-spi + 2.0-SNAPSHOT + + + org.apache.tuscany.sca + tuscany-databinding + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-implementation-java-xml + 2.0-SNAPSHOT + + + org.apache.tuscany.sdo + tuscany-sdo-lib + 1.1.1 + + + org.apache.tuscany.sdo + tuscany-sdo-impl + 1.1.1 + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.0 + + + add-test-source + generate-sources + + add-test-source + + + + target/sdo-source + + + + + + + org.apache.tuscany.sdo + tuscany-sdo-plugin + 1.1.1 + + + generate-po-sdo + generate-test-sources + + ${basedir}/src/test/resources/ipo.xsd + com.example.ipo.sdo + true + true + true + + + generate + + + + generate-stock-sdo + generate-test-sources + + ${basedir}/src/test/resources/stock.xsd + com.example.stock.sdo + Stock + true + true + true + + + generate + + + + + + + diff --git a/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/DataObject2Node.java b/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/DataObject2Node.java new file mode 100644 index 0000000000..503e54e530 --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/DataObject2Node.java @@ -0,0 +1,73 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.databinding.sdo; + +import javax.xml.namespace.QName; +import javax.xml.transform.dom.DOMResult; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.apache.tuscany.sca.databinding.impl.DOMHelper; +import org.w3c.dom.Document; +import org.w3c.dom.Node; + +import commonj.sdo.DataObject; +import commonj.sdo.helper.HelperContext; +import commonj.sdo.helper.XMLDocument; +import commonj.sdo.helper.XMLHelper; + +public class DataObject2Node extends BaseTransformer implements + PullTransformer { + + public Node transform(DataObject source, TransformationContext context) { + if (source == null) { + return null; + } + try { + HelperContext helperContext = SDOContextHelper.getHelperContext(context, true); + XMLHelper xmlHelper = helperContext.getXMLHelper(); + QName elementName = SDOContextHelper.getElement(context); + Document doc = DOMHelper.newDocument(); + DOMResult result = new DOMResult(doc); + XMLDocument xmlDoc = xmlHelper.createDocument(source, elementName.getNamespaceURI(), elementName.getLocalPart()); + xmlHelper.save(xmlDoc, result, null); + return doc.getDocumentElement(); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + protected Class getSourceType() { + return DataObject.class; + } + + @Override + protected Class getTargetType() { + return Node.class; + } + + @Override + public int getWeight() { + return 40; + } + +} diff --git a/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/DataObject2String.java b/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/DataObject2String.java new file mode 100644 index 0000000000..8ce8eae587 --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/DataObject2String.java @@ -0,0 +1,64 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.databinding.sdo; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; + +import commonj.sdo.DataObject; +import commonj.sdo.helper.HelperContext; +import commonj.sdo.helper.XMLHelper; + +public class DataObject2String extends BaseTransformer implements + PullTransformer { + + public String transform(DataObject source, TransformationContext context) { + if (source == null) { + return null; + } + try { + HelperContext helperContext = SDOContextHelper.getHelperContext(context, true); + XMLHelper xmlHelper = helperContext.getXMLHelper(); + QName elementName = SDOContextHelper.getElement(context); + return xmlHelper.save(source, elementName.getNamespaceURI(), elementName.getLocalPart()); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + protected Class getSourceType() { + return DataObject.class; + } + + @Override + protected Class getTargetType() { + return String.class; + } + + @Override + public int getWeight() { + return 40; + } + +} diff --git a/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/DataObject2XMLStreamReader.java b/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/DataObject2XMLStreamReader.java new file mode 100644 index 0000000000..116ac4c553 --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/DataObject2XMLStreamReader.java @@ -0,0 +1,82 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.databinding.sdo; + +import java.security.AccessController; +import java.security.PrivilegedAction; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.apache.tuscany.sdo.api.SDOUtil; +import org.apache.tuscany.sdo.api.XMLStreamHelper; + +import commonj.sdo.DataObject; +import commonj.sdo.helper.HelperContext; +import commonj.sdo.helper.XMLDocument; +import commonj.sdo.helper.XMLHelper; + +public class DataObject2XMLStreamReader extends BaseTransformer implements + PullTransformer { + + public XMLStreamReader transform(final DataObject source, TransformationContext context) { + if (source == null) { + return null; + } + try { + HelperContext helperContext = SDOContextHelper.getHelperContext(context, true); + XMLStreamHelper streamHelper = SDOUtil.createXMLStreamHelper(helperContext); + final QName elementName = SDOContextHelper.getElement(context); + final XMLHelper xmlHelper = helperContext.getXMLHelper(); + // Allow privileged access to read properties. REquires java.util.PropertyPermission + // XML.load.form.lax read in security policy. + XMLDocument document = AccessController.doPrivileged(new PrivilegedAction() { + public XMLDocument run() { + return xmlHelper.createDocument(source, elementName.getNamespaceURI(), elementName.getLocalPart()); + } + }); + + return streamHelper.createXMLStreamReader(document); + } catch (XMLStreamException e) { + // TODO: Add context to the exception + throw new TransformationException(e); + } + } + + @Override + protected Class getSourceType() { + return DataObject.class; + } + + @Override + protected Class getTargetType() { + return XMLStreamReader.class; + } + + @Override + public int getWeight() { + return 10; + } + +} diff --git a/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/ImportSDO.java b/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/ImportSDO.java new file mode 100644 index 0000000000..7afb7d9463 --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/ImportSDO.java @@ -0,0 +1,87 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.sdo; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.assembly.Base; + +import commonj.sdo.helper.HelperContext; + +/** + * The model object for import.sdo + * + * @version $Rev$ $Date$ + */ +public class ImportSDO implements Base { + public static final QName IMPORT_SDO = + new QName("http://tuscany.apache.org/xmlns/sca/databinding/sdo/1.0", "import.sdo"); + + private HelperContext helperContext; + private String factoryClassName; + private String schemaLocation; + private boolean unresolved; + + public boolean isUnresolved() { + return unresolved; + } + + public void setUnresolved(boolean undefined) { + this.unresolved = undefined; + } + + public ImportSDO(HelperContext helperContext) { + super(); + this.helperContext = helperContext; + setUnresolved(true); + } + + public HelperContext getHelperContext() { + return helperContext; + } + + /** + * @return the factoryClassName + */ + public String getFactoryClassName() { + return factoryClassName; + } + + /** + * @param factoryClassName the factoryClassName to set + */ + public void setFactoryClassName(String factoryClassName) { + this.factoryClassName = factoryClassName; + } + + /** + * @return the schemaLocation + */ + public String getSchemaLocation() { + return schemaLocation; + } + + /** + * @param schemaLocation the schemaLocation to set + */ + public void setSchemaLocation(String schemaLocation) { + this.schemaLocation = schemaLocation; + } +} \ No newline at end of file diff --git a/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/ImportSDOProcessor.java b/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/ImportSDOProcessor.java new file mode 100644 index 0000000000..1e2f3a795c --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/ImportSDOProcessor.java @@ -0,0 +1,211 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.databinding.sdo; + +import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; +import static org.apache.tuscany.sca.databinding.sdo.ImportSDO.IMPORT_SDO; + +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.net.URL; +import java.net.URLConnection; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; + +import org.apache.tuscany.sca.contribution.Artifact; +import org.apache.tuscany.sca.contribution.ContributionFactory; +import org.apache.tuscany.sca.contribution.processor.ContributionReadException; +import org.apache.tuscany.sca.contribution.processor.ContributionResolveException; +import org.apache.tuscany.sca.contribution.processor.ContributionWriteException; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.resolver.ClassReference; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.core.FactoryExtensionPoint; +import org.apache.tuscany.sca.monitor.Monitor; +import org.apache.tuscany.sca.monitor.Problem; +import org.apache.tuscany.sca.monitor.Problem.Severity; + +import commonj.sdo.helper.HelperContext; +import commonj.sdo.helper.XSDHelper; + +/** + * Loader that handles <import.sdo> elements. + * + * @version $Rev$ $Date$ + * @deprecated + */ +@Deprecated +public class ImportSDOProcessor implements StAXArtifactProcessor { + + private ContributionFactory contributionFactory; + private Monitor monitor; + + public ImportSDOProcessor(FactoryExtensionPoint modelFactories, Monitor monitor) { + this.contributionFactory = modelFactories.getFactory(ContributionFactory.class); + this.monitor = monitor; + } + + /** + * Report a error. + * + * @param problems + * @param message + * @param model + */ + private void error(String message, Object model, Object... messageParameters) { + if (monitor != null) { + Problem problem = monitor.createProblem(this.getClass().getName(), "databinding-sdo-validation-messages", Severity.ERROR, model, message, (Object[])messageParameters); + monitor.problem(problem); + } + } + + /** + * Report a exception. + * + * @param problems + * @param message + * @param model + */ + private void error(String message, Object model, Exception ex) { + if (monitor != null) { + Problem problem = monitor.createProblem(this.getClass().getName(), "databinding-sdo-validation-messages", Severity.ERROR, model, message, ex); + monitor.problem(problem); + } + } + + public QName getXMLType() { + return IMPORT_SDO; + } + + public ImportSDO read(XMLStreamReader reader) throws ContributionReadException, XMLStreamException { + assert IMPORT_SDO.equals(reader.getName()); + + // FIXME: How do we associate the application HelperContext with the one + // imported by the composite + ImportSDO importSDO = new ImportSDO(SDOContextHelper.getDefaultHelperContext()); + String factoryName = reader.getAttributeValue(null, "factory"); + if (factoryName != null) { + importSDO.setFactoryClassName(factoryName); + } + String location = reader.getAttributeValue(null, "location"); + if (location != null) { + importSDO.setSchemaLocation(location); + } + + // Skip to end element + while (reader.hasNext()) { + if (reader.next() == END_ELEMENT && ImportSDO.IMPORT_SDO.equals(reader.getName())) { + break; + } + } + return importSDO; + } + + private void importFactory(ImportSDO importSDO, ModelResolver resolver) throws ContributionResolveException { + String factoryName = importSDO.getFactoryClassName(); + if (factoryName != null) { + ClassReference reference = new ClassReference(factoryName); + ClassReference resolved = resolver.resolveModel(ClassReference.class, reference); + if (resolved != null && !resolved.isUnresolved()) { + try { + Class factoryClass = resolved.getJavaClass(); + register(factoryClass, importSDO.getHelperContext()); + importSDO.setUnresolved(false); + } catch (Exception e) { + ContributionResolveException ce = new ContributionResolveException(e); + error("ContributionResolveException", resolver, ce); + //throw ce; + } + } else { + error("FailToResolveClass", resolver, factoryName); + //ContributionResolveException loaderException = + //new ContributionResolveException("Fail to resolve class: " + factoryName); + //throw loaderException; + } + } + } + + private static void register(Class factoryClass, HelperContext helperContext) throws Exception { + Field field = factoryClass.getField("INSTANCE"); + Object factory = field.get(null); + Method method = factory.getClass().getMethod("register", new Class[] {HelperContext.class}); + method.invoke(factory, new Object[] {helperContext}); + + // HelperContext defaultContext = HelperProvider.getDefaultContext(); + // method.invoke(factory, new Object[] {defaultContext}); + } + + private void importWSDL(ImportSDO importSDO, ModelResolver resolver) throws ContributionResolveException { + String location = importSDO.getSchemaLocation(); + if (location != null) { + try { + Artifact artifact = contributionFactory.createArtifact(); + artifact.setURI(location); + artifact = resolver.resolveModel(Artifact.class, artifact); + if (artifact.getLocation() != null) { + String wsdlURL = artifact.getLocation(); + URLConnection connection = new URL(wsdlURL).openConnection(); + connection.setUseCaches(false); + InputStream xsdInputStream = connection.getInputStream(); + try { + XSDHelper xsdHelper = importSDO.getHelperContext().getXSDHelper(); + xsdHelper.define(xsdInputStream, wsdlURL); + } finally { + xsdInputStream.close(); + } + importSDO.setUnresolved(false); + } else { + error("FailToResolveLocation", resolver, location); + //ContributionResolveException loaderException = new ContributionResolveException("Fail to resolve location: " + location); + //throw loaderException; + } + } catch (IOException e) { + ContributionResolveException ce = new ContributionResolveException(e); + error("ContributionResolveException", resolver, ce); + //throw ce; + } + } + } + + public QName getArtifactType() { + return ImportSDO.IMPORT_SDO; + } + + public void write(ImportSDO model, XMLStreamWriter outputSource) throws ContributionWriteException { + // Not implemented as is deprecated + } + + public Class getModelType() { + return ImportSDO.class; + } + + public void resolve(ImportSDO importSDO, ModelResolver resolver) throws ContributionResolveException { + importFactory(importSDO, resolver); + importWSDL(importSDO, resolver); + if (!importSDO.isUnresolved()) { + resolver.addModel(importSDO); + } + } + +} diff --git a/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/Node2DataObject.java b/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/Node2DataObject.java new file mode 100644 index 0000000000..4a05492dd8 --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/Node2DataObject.java @@ -0,0 +1,69 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.databinding.sdo; + +import javax.xml.transform.dom.DOMSource; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.apache.tuscany.sca.databinding.impl.DOMHelper; +import org.w3c.dom.Document; +import org.w3c.dom.Node; + +import commonj.sdo.DataObject; +import commonj.sdo.helper.HelperContext; +import commonj.sdo.helper.XMLDocument; +import commonj.sdo.helper.XMLHelper; + +public class Node2DataObject extends BaseTransformer implements PullTransformer { + + public DataObject transform(Node source, TransformationContext context) { + if (source == null) { + return null; + } + try { + HelperContext helperContext = SDOContextHelper.getHelperContext(context, false); + XMLHelper xmlHelper = helperContext.getXMLHelper(); + Document doc = DOMHelper.promote(source); + DOMSource domSource = new DOMSource(doc); + XMLDocument xmlDoc = xmlHelper.load(domSource, doc.getDocumentURI(), null); + return xmlDoc.getRootObject(); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + protected Class getSourceType() { + return Node.class; + } + + @Override + protected Class getTargetType() { + return DataObject.class; + } + + @Override + public int getWeight() { + return 40; + } + +} diff --git a/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/SDOContextHelper.java b/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/SDOContextHelper.java new file mode 100644 index 0000000000..695722be18 --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/SDOContextHelper.java @@ -0,0 +1,208 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.sdo; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.util.DataTypeHelper; +import org.apache.tuscany.sca.databinding.util.LRUCache; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.interfacedef.util.XMLType; +import org.apache.tuscany.sdo.api.SDOUtil; + +import commonj.sdo.DataObject; +import commonj.sdo.Type; +import commonj.sdo.helper.HelperContext; +import commonj.sdo.helper.TypeHelper; +import commonj.sdo.impl.HelperProvider; + +/** + * Helper class to get TypeHelper from the context + * + * @version $Rev$ $Date$ + */ +public final class SDOContextHelper { + private static final LRUCache cache = new LRUCache(1024); + + private SDOContextHelper() { + } + + public static HelperContext getHelperContext(TransformationContext context, boolean source) { + if (context == null) { + return getDefaultHelperContext(); + } + + HelperContext helperContext = null; + Operation op = source ? context.getSourceOperation() : context.getTargetOperation(); + if (op == null) { + DataType dt = source ? context.getSourceDataType() : context.getTargetDataType(); + + helperContext = dt.getMetaData(HelperContext.class); + if (helperContext != null) { + return helperContext; + } + helperContext = SDOUtil.createHelperContext(); + boolean found = register(helperContext, dt); + if (!found) { + helperContext = getDefaultHelperContext(); + } + dt.setMetaData(HelperContext.class, helperContext); + return helperContext; + } else { + return getHelperContext(op); + } + + } + + public static HelperContext getHelperContext(Operation op) { + if (op == null) { + return getDefaultHelperContext(); + } + + HelperContext helperContext = op.getInputType().getMetaData(HelperContext.class); + + if (helperContext != null) { + return helperContext; + } + + // Use the default HelperContext until a type is registered later on + helperContext = getDefaultHelperContext(); + + /* + List dataTypes = DataTypeHelper.getDataTypes(op, false); + boolean found = false; + for (DataType d : dataTypes) { + if (register(helperContext, d)) { + found = true; + } + } + if (!found) { + helperContext = getDefaultHelperContext(); + } + */ + op.getInputType().setMetaData(HelperContext.class, helperContext); + return helperContext; + } + + /** + * @param helperContext + * @param dataType + * @return + */ + private static boolean register(HelperContext helperContext, DataType dataType) { + if (dataType == null) { + return false; + } + Set> classes = DataTypeHelper.findClasses(dataType); + boolean found = false; + for (Class cls : classes) { + found = register(helperContext, dataType.getPhysical()) || found; + } + return found; + } + + /** + * FIXME: [rfeng] This is a hack to get the factory out a SDO class + * @param helperContext + * @param javaType + */ + + public static boolean register(HelperContext helperContext, Class javaType) { + if (javaType == null || DataObject.class == javaType) { + return false; + } + try { + Type type = helperContext.getTypeHelper().getType(javaType); + if (type != null && (!type.isDataType())) { + Method method = type.getClass().getMethod("getEPackage"); + Object factory = method.invoke(type, new Object[] {}); + method = factory.getClass().getMethod("register", HelperContext.class); + method.invoke(factory, new Object[] {helperContext}); + return true; + } + return false; + } catch (Exception e) { + throw new TransformationException(e); + } + } + + public static HelperContext getDefaultHelperContext() { + // SDOUtil.createHelperContext(); + return HelperProvider.getDefaultContext(); + } + + public static QName getElement(TransformationContext context) { + if (context == null) { + return SDODataBinding.ROOT_ELEMENT; + } + DataType dataType = context.getTargetDataType(); + Object logical = dataType.getLogical(); + QName elementName = null; + if (logical instanceof XMLType) { + XMLType xmlType = (XMLType)logical; + QName element = xmlType.getElementName(); + if (element != null) { + elementName = element; + } + } + if (elementName == null) { + // Try source type + dataType = context.getSourceDataType(); + logical = dataType.getLogical(); + if (logical instanceof XMLType) { + XMLType xmlType = (XMLType)logical; + QName element = xmlType.getElementName(); + if (element != null) { + elementName = element; + } + } + } + if (elementName != null) { + return elementName; + } else { + return SDODataBinding.ROOT_ELEMENT; + } + } + + public static String generateSchema(HelperContext context, Class[] classes) { + TypeHelper typeHelper = context.getTypeHelper(); + List types = new ArrayList(); + for (Class cls : classes) { + Type type = typeHelper.getType(cls); + if (type != null) { + types.add(type); + } + } + return generateSchema(context, types); + } + + public static String generateSchema(HelperContext context, List types) { + // FIXME: SDO throws IllegalArgumentException for types generated from existing XSDs + return context.getXSDHelper().generate(types); + } +} diff --git a/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/SDODataBinding.java b/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/SDODataBinding.java new file mode 100644 index 0000000000..0b58be9e41 --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/SDODataBinding.java @@ -0,0 +1,146 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.sdo; + +import java.security.AccessController; +import java.security.PrivilegedAction; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.databinding.WrapperHandler; +import org.apache.tuscany.sca.databinding.XMLTypeHelper; +import org.apache.tuscany.sca.databinding.impl.BaseDataBinding; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.interfacedef.util.XMLType; +import org.apache.tuscany.sdo.api.SDOUtil; + +import commonj.sdo.DataObject; +import commonj.sdo.Type; +import commonj.sdo.helper.CopyHelper; +import commonj.sdo.helper.HelperContext; +import commonj.sdo.helper.XMLDocument; + +/** + * SDO Databinding + * + * @version $Rev$ $Date$ + */ +public class SDODataBinding extends BaseDataBinding { + public static final String NAME = DataObject.class.getName(); + + public static final String ROOT_NAMESPACE = "commonj.sdo"; + public static final QName ROOT_ELEMENT = new QName(ROOT_NAMESPACE, "dataObject"); + + private WrapperHandler wrapperHandler; + private XMLTypeHelper xmlTypeHelper; + + public SDODataBinding() { + super(NAME, DataObject.class); + wrapperHandler = new SDOWrapperHandler(); + xmlTypeHelper = new SDOTypeHelper(); + } + + @Override + public boolean introspect(DataType dataType, final Operation operation) { + final Class javaType = dataType.getPhysical(); + // Allow privileged access to read system properties. Requires PropertyPermission + // java.specification.version read in security policy. + final HelperContext context = AccessController.doPrivileged(new PrivilegedAction() { + public HelperContext run() { + return SDOContextHelper.getHelperContext(operation); + } + }); + + Type type = context.getTypeHelper().getType(javaType); + if (type == null) { + // FIXME: Need a better to test dynamic SDO + if (DataObject.class.isAssignableFrom(javaType)) { + // Dynamic SDO + dataType.setDataBinding(getName()); + if (dataType.getLogical() == null) { + dataType.setLogical(XMLType.UNKNOWN); + } + return true; + } + return false; + } + if (type.isDataType()) { + // FIXME: Ignore simple types? + return false; + } + + // Found a SDO type, replace the default context with a private one + AccessController.doPrivileged(new PrivilegedAction() { + public Object run() { + if (context == SDOContextHelper.getDefaultHelperContext()) { + HelperContext newContext = SDOUtil.createHelperContext(); + SDOContextHelper.register(newContext, javaType); + if (operation != null) { + operation.getInputType().setMetaData(HelperContext.class, newContext); + } + } + return null; + } + }); + + String namespace = type.getURI(); + String name = context.getXSDHelper().getLocalName(type); + QName xmlType = new QName(namespace, name); + dataType.setDataBinding(getName()); + QName elementName = null; + Object logical = dataType.getLogical(); + if (logical instanceof XMLType) { + elementName = ((XMLType)logical).getElementName(); + } + dataType.setLogical(new XMLType(elementName, xmlType)); + + return true; + } + + @Override + public WrapperHandler getWrapperHandler() { + return wrapperHandler; + } + + @Override + public XMLTypeHelper getXMLTypeHelper() { + // return new SDOTypeHelper(); + return xmlTypeHelper; + } + + @Override + public Object copy(Object arg, DataType dataType, Operation operation) { + HelperContext context = SDOContextHelper.getHelperContext(operation); + CopyHelper copyHelper = context.getCopyHelper(); + if (arg instanceof XMLDocument) { + XMLDocument document = (XMLDocument)arg; + DataObject dataObject = copyHelper.copy(document.getRootObject()); + return context.getXMLHelper().createDocument(dataObject, + document.getRootElementURI(), + document.getRootElementName()); + } else if (arg instanceof DataObject) { + return context.getCopyHelper().copy((DataObject)arg); + } else { + return super.copy(arg, dataType, operation); + } + } + +} diff --git a/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/SDOSimpleTypeMapper.java b/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/SDOSimpleTypeMapper.java new file mode 100644 index 0000000000..c83ec53b01 --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/SDOSimpleTypeMapper.java @@ -0,0 +1,68 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.sdo; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.databinding.SimpleTypeMapper; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sdo.api.SDOUtil; + +import commonj.sdo.Type; +import commonj.sdo.helper.HelperContext; +import commonj.sdo.helper.TypeHelper; + +/** + * SDO Java/XML mapping for simple XSD types + * + * @version $Rev$ $Date$ + */ +public class SDOSimpleTypeMapper implements SimpleTypeMapper { + public static final String URI_2001_SCHEMA_XSD = "http://www.w3.org/2001/XMLSchema"; + + public SDOSimpleTypeMapper() { + super(); + } + + public Object toJavaObject(QName typeName, String value, TransformationContext context) { + Type type = null; + if (URI_2001_SCHEMA_XSD.equals(typeName.getNamespaceURI())) { + type = SDOUtil.getXSDSDOType(typeName.getLocalPart()); + } else { + HelperContext helperContext = SDOContextHelper.getHelperContext(context, false); + TypeHelper typeHelper = helperContext.getTypeHelper(); + type = typeHelper.getType(typeName.getNamespaceURI(), typeName.getLocalPart()); + } + return SDOUtil.createFromString(type, value); + } + + public String toXMLLiteral(QName typeName, Object obj, TransformationContext context) { + Type type = null; + if (URI_2001_SCHEMA_XSD.equals(typeName.getNamespaceURI())) { + type = SDOUtil.getXSDSDOType(typeName.getLocalPart()); + } else { + HelperContext helperContext = SDOContextHelper.getHelperContext(context, true); + TypeHelper typeHelper = helperContext.getTypeHelper(); + type = typeHelper.getType(typeName.getNamespaceURI(), typeName.getLocalPart()); + } + return SDOUtil.convertToString(type, obj); + } + +} diff --git a/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/SDOTypeHelper.java b/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/SDOTypeHelper.java new file mode 100644 index 0000000000..0927f87f3b --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/SDOTypeHelper.java @@ -0,0 +1,235 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.sdo; + +import java.beans.Introspector; +import java.io.StringReader; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.databinding.XMLTypeHelper; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.Interface; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.interfacedef.util.JavaXMLMapper; +import org.apache.tuscany.sca.interfacedef.util.TypeInfo; +import org.apache.tuscany.sca.interfacedef.util.WrapperInfo; +import org.apache.tuscany.sca.interfacedef.util.XMLType; +import org.apache.tuscany.sca.xsd.XSDFactory; +import org.apache.tuscany.sca.xsd.XSDefinition; +import org.oasisopen.sca.ServiceRuntimeException; +import org.w3c.dom.DOMImplementation; +import org.w3c.dom.Document; +import org.w3c.dom.bootstrap.DOMImplementationRegistry; +import org.w3c.dom.ls.DOMImplementationLS; +import org.w3c.dom.ls.LSInput; +import org.w3c.dom.ls.LSParser; + +import commonj.sdo.Type; +import commonj.sdo.helper.TypeHelper; +import commonj.sdo.helper.XSDHelper; + +public class SDOTypeHelper implements XMLTypeHelper { + private static final String SCHEMA_NS = "http://www.w3.org/2001/XMLSchema"; + + private TypeHelper typeHelper; + private XSDHelper xsdHelper; + // private Map> xsdTypesMap = new HashMap>(); + // private Map> typesMap = new HashMap>(); + + public SDOTypeHelper() { + super(); + typeHelper = SDOContextHelper.getDefaultHelperContext().getTypeHelper(); + xsdHelper = SDOContextHelper.getDefaultHelperContext().getXSDHelper(); + } + + public TypeInfo getTypeInfo(Class javaType, Object logical) { + QName xmlType = JavaXMLMapper.getXMLType(javaType); + if (xmlType != null) { + return new TypeInfo(xmlType, true, null); + } else { + // introspect(javaType, xsdTypesMap, typesMap); + if (logical instanceof XMLType) { + xmlType = ((XMLType)logical).getTypeName(); + } + if (xmlType == null) { + xmlType = + new QName(JavaXMLMapper.getNamespace(javaType), Introspector.decapitalize(javaType.getSimpleName())); + } + return new TypeInfo(xmlType, false, null); + } + } + + private void introspect(Class javaType, Map> xsdTypesMap, Map> typesMap) { + Type type = typeHelper.getType(javaType); + if (type == null) { + return; + } + if (xsdHelper.isXSD(type)) { + addToMap(xsdTypesMap, type); + } else { + addToMap(typesMap, type); + } + } + + private void addToMap(Map> map, Type type) { + List types = map.get(type.getURI()); + if (types == null) { + types = new ArrayList(); + map.put(type.getURI(), types); + } + if (!types.contains(type)) { + types.add(type); + } + } + + /* + public List getSchemaDefinitions(XSDFactory factory, ModelResolver resolver) { + List definitions = new ArrayList(); + generateSDOSchemas(definitions, factory, typesMap); + addResolvedXSDs(definitions, factory, resolver, xsdTypesMap); + return definitions; + } + */ + + private void generateSDOSchemas(List definitions, XSDFactory factory, Map> map) { + for (Map.Entry> entry : map.entrySet()) { + List types = entry.getValue(); + String ns = entry.getKey(); + generateSchema(definitions, factory, types, ns); + } + } + + private void generateSchema(List definitions, XSDFactory factory, List types, String ns) { + String schema = xsdHelper.generate(types); + DOMImplementationRegistry registry = null; + try { + registry = DOMImplementationRegistry.newInstance(); + } catch (Exception e) { + throw new ServiceRuntimeException(e); + } + DOMImplementation impl = registry.getDOMImplementation("XML 3.0"); + DOMImplementationLS ls = (DOMImplementationLS)impl.getFeature("LS", "3.0"); + LSParser parser = ls.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, SCHEMA_NS); + LSInput input = ls.createLSInput(); + input.setCharacterStream(new StringReader(schema)); + Document document = parser.parse(input); + XSDefinition definition = factory.createXSDefinition(); + definition.setUnresolved(true); + definition.setDocument(document); + definition.setNamespace(ns); + definitions.add(definition); + } + + private void addResolvedXSDs(List definitions, + XSDFactory factory, + ModelResolver resolver, + Map> map) { + for (Map.Entry> entry : map.entrySet()) { + XSDefinition definition = factory.createXSDefinition(); + definition.setUnresolved(true); + definition.setNamespace(entry.getKey()); + //FIXME: set location URI + XSDefinition resolved = resolver.resolveModel(XSDefinition.class, definition); + if (resolved.getSchema() == null) { + //FIXME: create a checked exception and propagate it back up to the activator + throw new RuntimeException("No XSD found for namespace " + entry.getKey()); + } + // make sure all the required types are defined in the resolved schema + for (Type type : entry.getValue()) { + String name = xsdHelper.getLocalName(type); + QName typeName = null; + if (name.endsWith("_._type")) { + // FIXME: Anonymous tyype + name = name.substring(0, name.length() - "_._type".length()); + typeName = new QName(type.getURI(), name); + if (resolved.getXmlSchemaElement(typeName) == null) { + //FIXME: create a checked exception and propagate it back up to the activator + throw new RuntimeException("No XSD found for " + typeName.toString()); + } + } else { + typeName = new QName(type.getURI(), name); + if (resolved.getXmlSchemaType(typeName) == null) { + //FIXME: create a checked exception and propagate it back up to the activator + throw new RuntimeException("No XSD found for " + typeName.toString()); + } + } + + } + definitions.add(resolved); + } + } + + private static List getDataTypes(Interface intf) { + List dataTypes = new ArrayList(); + for (Operation op : intf.getOperations()) { + WrapperInfo wrapper = op.getWrapper(); + if (wrapper != null) { + DataType dt1 = wrapper.getInputWrapperType(); + if (dt1 != null) { + dataTypes.add(dt1); + } + DataType dt2 = wrapper.getOutputWrapperType(); + if (dt2 != null) { + dataTypes.add(dt2); + } + } else { + for (DataType dt1 : op.getInputType().getLogical()) { + dataTypes.add(dt1); + } + DataType dt2 = op.getOutputType(); + if (dt2 != null) { + dataTypes.add(dt2); + } + for (DataType dt3 : op.getFaultTypes()) { + DataType dt4 = dt3.getLogical(); + if (dt4 != null) { + dataTypes.add(dt4); + } + } + } + } + return dataTypes; + } + + public List getSchemaDefinitions(XSDFactory factory, ModelResolver resolver, Interface intf) { + return getSchemaDefinitions(factory, resolver, getDataTypes(intf)); + } + + public List getSchemaDefinitions(XSDFactory factory, ModelResolver resolver, List dataTypes) { + Map> xsdTypesMap = new HashMap>(); + Map> typesMap = new HashMap>(); + for (DataType d : dataTypes) { + if (SDODataBinding.NAME.equals(d.getDataBinding())) { + introspect(d.getPhysical(), xsdTypesMap, typesMap); + } + } + List definitions = new ArrayList(); + generateSDOSchemas(definitions, factory, typesMap); + addResolvedXSDs(definitions, factory, resolver, xsdTypesMap); + return definitions; + } + +} diff --git a/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/SDOWrapperHandler.java b/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/SDOWrapperHandler.java new file mode 100644 index 0000000000..8a1cd666d8 --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/SDOWrapperHandler.java @@ -0,0 +1,177 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.sdo; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.databinding.WrapperHandler; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.interfacedef.impl.DataTypeImpl; +import org.apache.tuscany.sca.interfacedef.util.ElementInfo; +import org.apache.tuscany.sca.interfacedef.util.TypeInfo; +import org.apache.tuscany.sca.interfacedef.util.WrapperInfo; +import org.apache.tuscany.sca.interfacedef.util.XMLType; + +import commonj.sdo.DataObject; +import commonj.sdo.Property; +import commonj.sdo.Sequence; +import commonj.sdo.Type; +import commonj.sdo.helper.DataFactory; +import commonj.sdo.helper.HelperContext; +import commonj.sdo.helper.XMLDocument; +import commonj.sdo.helper.XSDHelper; + +/** + * SDO Wrapper Handler + * + * @version $Rev$ $Date$ + */ +public class SDOWrapperHandler implements WrapperHandler { + + public Object create(Operation operation, boolean input) { + WrapperInfo wrapperInfo = operation.getWrapper(); + ElementInfo element = input ? wrapperInfo.getInputWrapperElement() : wrapperInfo.getOutputWrapperElement(); + // Class wrapperClass = input ? wrapperInfo.getInputWrapperClass() : wrapperInfo.getOutputWrapperClass(); + HelperContext helperContext = SDOContextHelper.getHelperContext(operation); + Type sdoType = getSDOType(helperContext, element); + if (sdoType != null) { + DataFactory dataFactory = helperContext.getDataFactory(); + return dataFactory.create(sdoType); + } + return null; + } + + public void setChildren(Object wrapper, Object[] childObjects, Operation operation, boolean input) { + List childElements = + input ? operation.getWrapper().getInputChildElements() : operation.getWrapper().getOutputChildElements(); + for (int i = 0; i < childElements.size(); i++) { + setChild(wrapper, i, childElements.get(i), childObjects[i]); + } + } + + /** + * @see org.apache.tuscany.sca.databinding.WrapperHandler#setChild(java.lang.Object, int, ElementInfo, + * java.lang.Object) + */ + public void setChild(Object wrapper, int i, ElementInfo childElement, Object value) { + DataObject wrapperDO = + (wrapper instanceof XMLDocument) ? ((XMLDocument)wrapper).getRootObject() : (DataObject)wrapper; + String name = childElement.getQName().getLocalPart(); + if (childElement.isMany()) { + // FIXME: If we look up by name, we need to make sure the WrapperInfo has the correct element names + wrapperDO.getList(i).addAll((Collection)value); + } else { + wrapperDO.set(i, value); + } + } + + @SuppressWarnings("unchecked") + public List getChildren(Object wrapper, Operation operation, boolean input) { + DataObject wrapperDO = + (wrapper instanceof XMLDocument) ? ((XMLDocument)wrapper).getRootObject() : (DataObject)wrapper; + List properties = wrapperDO.getInstanceProperties(); + List elements = new ArrayList(); + Type type = wrapperDO.getType(); + if (type.isSequenced()) { + // Add values in the sequence + Sequence sequence = wrapperDO.getSequence(); + for (int i = 0; i < sequence.size(); i++) { + // Skip mixed text + if (sequence.getProperty(i) != null) { + elements.add(sequence.getValue(i)); + } + } + } else { + for (Property p : properties) { + Object child = wrapperDO.get(p); + if (p.isMany()) { + for (Object c : (Collection)child) { + elements.add(c); + } + } else { + elements.add(child); + } + } + } + return elements; + } + + /** + * @see org.apache.tuscany.sca.databinding.WrapperHandler#getWrapperType(Operation, boolean) + */ + public DataType getWrapperType(Operation operation, boolean input) { + WrapperInfo wrapper = operation.getWrapper(); + ElementInfo element = input ? wrapper.getInputWrapperElement() : wrapper.getOutputWrapperElement(); + HelperContext helperContext = SDOContextHelper.getHelperContext(operation); + Type sdoType = getSDOType(helperContext, element); + if (sdoType != null) { + // Check if child elements matches + Class physical = sdoType.getInstanceClass(); + DataType wrapperType = + new DataTypeImpl(SDODataBinding.NAME, physical, new XMLType(element)); + return wrapperType; + } else { + return null; + } + } + + /** + * @param helperContext + * @param element + * @return + */ + private Type getSDOType(HelperContext helperContext, ElementInfo element) { + XSDHelper xsdHelper = helperContext.getXSDHelper(); + Type sdoType = null; + Property prop = + xsdHelper.getGlobalProperty(element.getQName().getNamespaceURI(), element.getQName().getLocalPart(), true); + if (prop != null) { + sdoType = prop.getType(); + } else { + TypeInfo type = element.getType(); + QName typeName = type != null ? type.getQName() : null; + if (typeName != null) { + sdoType = helperContext.getTypeHelper().getType(typeName.getNamespaceURI(), typeName.getLocalPart()); + } + } + return sdoType; + } + + /** + * @see org.apache.tuscany.sca.databinding.WrapperHandler#isInstance(java.lang.Object, Operation, boolean) + */ + public boolean isInstance(Object wrapper, Operation operation, boolean input) { + WrapperInfo wrapperInfo = operation.getWrapper(); + ElementInfo element = input ? wrapperInfo.getInputWrapperElement() : wrapperInfo.getOutputWrapperElement(); + // List childElements = + // input ? wrapperInfo.getInputChildElements() : wrapperInfo.getOutputChildElements(); + HelperContext helperContext = SDOContextHelper.getHelperContext(operation); + Type sdoType = getSDOType(helperContext, element); + if (sdoType != null) { + return sdoType.isInstance(wrapper); + } + return false; + } +} diff --git a/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/String2DataObject.java b/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/String2DataObject.java new file mode 100644 index 0000000000..7ac423f8d8 --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/String2DataObject.java @@ -0,0 +1,61 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.databinding.sdo; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; + +import commonj.sdo.DataObject; +import commonj.sdo.helper.HelperContext; +import commonj.sdo.helper.XMLHelper; + +public class String2DataObject extends BaseTransformer implements + PullTransformer { + + public DataObject transform(String source, TransformationContext context) { + if (source == null) { + return null; + } + try { + HelperContext helperContext = SDOContextHelper.getHelperContext(context, false); + XMLHelper xmlHelper = helperContext.getXMLHelper(); + return xmlHelper.load(source).getRootObject(); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + protected Class getSourceType() { + return String.class; + } + + @Override + protected Class getTargetType() { + return DataObject.class; + } + + @Override + public int getWeight() { + return 50; + } + +} diff --git a/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/XMLDocument2String.java b/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/XMLDocument2String.java new file mode 100644 index 0000000000..4e5aa1d5fd --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/XMLDocument2String.java @@ -0,0 +1,65 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.databinding.sdo; + +import java.io.StringWriter; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; + +import commonj.sdo.helper.HelperContext; +import commonj.sdo.helper.XMLDocument; +import commonj.sdo.helper.XMLHelper; + +public class XMLDocument2String extends BaseTransformer implements + PullTransformer { + + public String transform(XMLDocument source, TransformationContext context) { + if (source == null) { + return null; + } + try { + HelperContext helperContext = SDOContextHelper.getHelperContext(context, true); + XMLHelper xmlHelper = helperContext.getXMLHelper(); + StringWriter writer = new StringWriter(); + xmlHelper.save(source, writer, null); + return writer.toString(); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + protected Class getSourceType() { + return XMLDocument.class; + } + + @Override + protected Class getTargetType() { + return String.class; + } + + @Override + public int getWeight() { + return 40; + } + +} diff --git a/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/XMLDocument2XMLStreamReader.java b/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/XMLDocument2XMLStreamReader.java new file mode 100644 index 0000000000..e70fa08477 --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/XMLDocument2XMLStreamReader.java @@ -0,0 +1,69 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.databinding.sdo; + +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.apache.tuscany.sdo.api.SDOUtil; +import org.apache.tuscany.sdo.api.XMLStreamHelper; + +import commonj.sdo.helper.HelperContext; +import commonj.sdo.helper.XMLDocument; + +public class XMLDocument2XMLStreamReader extends BaseTransformer implements + PullTransformer { + /** + * @param source + * @param context + * @return + */ + public XMLStreamReader transform(XMLDocument source, TransformationContext context) { + if (source == null) { + return null; + } + try { + HelperContext helperContext = SDOContextHelper.getHelperContext(context, true); + XMLStreamHelper streamHelper = SDOUtil.createXMLStreamHelper(helperContext); + return streamHelper.createXMLStreamReader(source); + } catch (XMLStreamException e) { + throw new TransformationException(e); + } + } + + @Override + protected Class getSourceType() { + return XMLDocument.class; + } + + @Override + protected Class getTargetType() { + return XMLStreamReader.class; + } + + @Override + public int getWeight() { + return 10; + } + +} diff --git a/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/XMLStreamReader2DataObject.java b/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/XMLStreamReader2DataObject.java new file mode 100644 index 0000000000..baf3e2e90a --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/XMLStreamReader2DataObject.java @@ -0,0 +1,72 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.databinding.sdo; + +import javax.xml.stream.XMLStreamConstants; +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.apache.tuscany.sdo.api.SDOUtil; +import org.apache.tuscany.sdo.api.XMLStreamHelper; + +import commonj.sdo.DataObject; +import commonj.sdo.helper.HelperContext; + +public class XMLStreamReader2DataObject extends BaseTransformer implements + PullTransformer { + + public DataObject transform(XMLStreamReader source, TransformationContext context) { + if (source == null) { + return null; + } + try { + HelperContext helperContext = SDOContextHelper.getHelperContext(context, false); + XMLStreamHelper streamHelper = SDOUtil.createXMLStreamHelper(helperContext); + // The XMLStreamHelper requires that the reader is positioned at + // START_ELEMENT + while (source.getEventType() != XMLStreamConstants.START_ELEMENT && source.hasNext()) { + source.next(); + } + DataObject target = streamHelper.loadObject(source); + source.close(); + return target; + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + protected Class getTargetType() { + return DataObject.class; + } + + @Override + protected Class getSourceType() { + return XMLStreamReader.class; + } + + @Override + public int getWeight() { + return 15; + } + +} diff --git a/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/XMLStreamReader2XMLDocument.java b/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/XMLStreamReader2XMLDocument.java new file mode 100644 index 0000000000..ac452910f6 --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo/src/main/java/org/apache/tuscany/sca/databinding/sdo/XMLStreamReader2XMLDocument.java @@ -0,0 +1,66 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.databinding.sdo; + +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.apache.tuscany.sdo.api.SDOUtil; +import org.apache.tuscany.sdo.api.XMLStreamHelper; + +import commonj.sdo.helper.HelperContext; +import commonj.sdo.helper.XMLDocument; + +public class XMLStreamReader2XMLDocument extends BaseTransformer implements + PullTransformer { + + public XMLDocument transform(XMLStreamReader source, TransformationContext context) { + if (source == null) { + return null; + } + try { + HelperContext helperContext = SDOContextHelper.getHelperContext(context, false); + XMLStreamHelper streamHelper = SDOUtil.createXMLStreamHelper(helperContext); + XMLDocument target = streamHelper.load(source); + source.close(); + return target; + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + protected Class getTargetType() { + return XMLDocument.class; + } + + @Override + protected Class getSourceType() { + return XMLStreamReader.class; + } + + @Override + public int getWeight() { + return 15; + } + +} diff --git a/java/sca/contrib/modules/databinding-sdo/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor b/java/sca/contrib/modules/databinding-sdo/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor new file mode 100644 index 0000000000..ffe8b895b8 --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor @@ -0,0 +1,18 @@ +# 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. + +org.apache.tuscany.sca.databinding.sdo.ImportSDOProcessor;qname=http://tuscany.apache.org/xmlns/sca/databinding/sdo/1.0#import.sdo,model=org.apache.tuscany.sca.databinding.sdo.ImportSDO diff --git a/java/sca/contrib/modules/databinding-sdo/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.DataBinding b/java/sca/contrib/modules/databinding-sdo/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.DataBinding new file mode 100644 index 0000000000..5ae557cc74 --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.DataBinding @@ -0,0 +1,19 @@ +# 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. + +# implementation classes for the databindings +org.apache.tuscany.sca.databinding.sdo.SDODataBinding;name=commonj.sdo.DataObject diff --git a/java/sca/contrib/modules/databinding-sdo/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PullTransformer b/java/sca/contrib/modules/databinding-sdo/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PullTransformer new file mode 100644 index 0000000000..b1916fd32a --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PullTransformer @@ -0,0 +1,27 @@ +# 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. + +# Implementation classes for the transformers +org.apache.tuscany.sca.databinding.sdo.DataObject2String;source=commonj.sdo.DataObject,target=java.lang.String,weight=510 +org.apache.tuscany.sca.databinding.sdo.DataObject2XMLStreamReader;source=commonj.sdo.DataObject,target=javax.xml.stream.XMLStreamReader,weight=490 +org.apache.tuscany.sca.databinding.sdo.XMLDocument2String;source=commonj.sdo.helper.XMLDocument,target=java.lang.String,weight=510 +org.apache.tuscany.sca.databinding.sdo.String2DataObject;source=java.lang.String,target=commonj.sdo.DataObject,weight=500 +org.apache.tuscany.sca.databinding.sdo.XMLDocument2XMLStreamReader;source=commonj.sdo.helper.XMLDocument,target=javax.xml.stream.XMLStreamReader,weight=490 +org.apache.tuscany.sca.databinding.sdo.XMLStreamReader2DataObject;source=javax.xml.stream.XMLStreamReader,target=commonj.sdo.DataObject,weight=490 +org.apache.tuscany.sca.databinding.sdo.XMLStreamReader2XMLDocument;source=javax.xml.stream.XMLStreamReader,target=commonj.sdo.helper.XMLDocument,weight=490 +org.apache.tuscany.sca.databinding.sdo.DataObject2Node;source=commonj.sdo.DataObject,target=org.w3c.dom.Node,weight=500 +org.apache.tuscany.sca.databinding.sdo.Node2DataObject;source=org.w3c.dom.Node,target=commonj.sdo.DataObject,weight=500 diff --git a/java/sca/contrib/modules/databinding-sdo/src/main/resources/databinding-sdo-validation-messages.properties b/java/sca/contrib/modules/databinding-sdo/src/main/resources/databinding-sdo-validation-messages.properties new file mode 100644 index 0000000000..f53f08f377 --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo/src/main/resources/databinding-sdo-validation-messages.properties @@ -0,0 +1,23 @@ +# +# +# 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. +# +# +FailToResolveClass = Fail to resolve class: {0} +FailToResolveLocation = Fail to resolve location: {0} +ContributionResolveException = ContributionResolveException occured due to: diff --git a/java/sca/contrib/modules/databinding-sdo/src/test/java/com/example/stock/sdo/fault/InvalidSymbolFault_Exception.java b/java/sca/contrib/modules/databinding-sdo/src/test/java/com/example/stock/sdo/fault/InvalidSymbolFault_Exception.java new file mode 100644 index 0000000000..5a0208b290 --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo/src/test/java/com/example/stock/sdo/fault/InvalidSymbolFault_Exception.java @@ -0,0 +1,70 @@ +/* + * 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. + */ + +package com.example.stock.sdo.fault; + +import javax.xml.namespace.QName; + +import com.example.stock.sdo.InvalidSymbolFault; + +/** + * Hand-crafted java exception for SDO fault + * + * @version $Rev$ $Date$ + */ +public class InvalidSymbolFault_Exception extends Exception { + private static final long serialVersionUID = 8602157311925253920L; + + /** + * Generated QName for the fault element + */ + public static final QName FAULT_ELEMENT = new QName("http://www.example.com/stock", "InvalidSymbolFault"); + /** + * Java type that goes as soapenv:Fault detail element. + */ + private InvalidSymbolFault faultInfo; + + /** + * @param faultInfo + * @param message + */ + public InvalidSymbolFault_Exception(String message, InvalidSymbolFault faultInfo) { + super(message); + this.faultInfo = faultInfo; + } + + /** + * @param faultInfo + * @param message + * @param cause + */ + public InvalidSymbolFault_Exception(String message, InvalidSymbolFault faultInfo, Throwable cause) { + super(message, cause); + this.faultInfo = faultInfo; + } + + /** + * @return returns fault bean: + * org.apache.tuscany.sca.test.exceptions.impl.jaxb.InvalidSymbolFault + */ + public InvalidSymbolFault getFaultInfo() { + return faultInfo; + } + +} diff --git a/java/sca/contrib/modules/databinding-sdo/src/test/java/org/apache/tuscany/sca/databinding/sdo/DataObject2NodeTestCase.java b/java/sca/contrib/modules/databinding-sdo/src/test/java/org/apache/tuscany/sca/databinding/sdo/DataObject2NodeTestCase.java new file mode 100644 index 0000000000..4bc41a5541 --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo/src/test/java/org/apache/tuscany/sca/databinding/sdo/DataObject2NodeTestCase.java @@ -0,0 +1,60 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.sdo; + +import junit.framework.Assert; + +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.impl.DataTypeImpl; +import org.apache.tuscany.sca.interfacedef.util.XMLType; +import org.w3c.dom.Element; +import org.w3c.dom.Node; + +import com.example.ipo.sdo.PurchaseOrderType; +import commonj.sdo.DataObject; + +/** + * + * @version $Rev$ $Date$ + */ +public class DataObject2NodeTestCase extends SDOTransformerTestCaseBase { + @Override + protected DataType getSourceDataType() { + return new DataTypeImpl(binding, PurchaseOrderType.class, new XMLType(ORDER_QNAME, null)); + } + + @Override + protected DataType getTargetDataType() { + return new DataTypeImpl>(String.class, String.class); + } + + public final void testTransform() { + Node node = new DataObject2Node().transform(dataObject, context); + Assert.assertNotNull(node); + Element element = (Element) node; + Assert.assertEquals(ORDER_QNAME.getNamespaceURI(), element.getNamespaceURI()); + Assert.assertEquals(ORDER_QNAME.getLocalPart(), element.getLocalName()); + DataObject po = new Node2DataObject().transform(node, reversedContext); + Assert.assertTrue(po instanceof PurchaseOrderType); + PurchaseOrderType orderType = (PurchaseOrderType)po; + Assert.assertEquals("San Jose", orderType.getBillTo().getCity()); + } + +} diff --git a/java/sca/contrib/modules/databinding-sdo/src/test/java/org/apache/tuscany/sca/databinding/sdo/DataObject2StringTestCase.java b/java/sca/contrib/modules/databinding-sdo/src/test/java/org/apache/tuscany/sca/databinding/sdo/DataObject2StringTestCase.java new file mode 100644 index 0000000000..44d11cd586 --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo/src/test/java/org/apache/tuscany/sca/databinding/sdo/DataObject2StringTestCase.java @@ -0,0 +1,65 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.sdo; + +import junit.framework.Assert; + +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.impl.DataTypeImpl; +import org.apache.tuscany.sca.interfacedef.util.XMLType; + +import com.example.ipo.sdo.PurchaseOrderType; +import commonj.sdo.DataObject; + +/** + * + * @version $Rev$ $Date$ + */ +public class DataObject2StringTestCase extends SDOTransformerTestCaseBase { + @Override + protected DataType getSourceDataType() { + return new DataTypeImpl(binding, PurchaseOrderType.class, new XMLType(ORDER_QNAME, null)); + } + + @Override + protected DataType getTargetDataType() { + return new DataTypeImpl>(String.class, String.class); + } + + public final void testTransform() { + String xml = new DataObject2String().transform(dataObject, context); + Assert.assertTrue(xml.indexOf("San Jose") != -1); + DataObject po = new String2DataObject().transform(xml, reversedContext); + Assert.assertTrue(po instanceof PurchaseOrderType); + PurchaseOrderType orderType = (PurchaseOrderType)po; + Assert.assertEquals("San Jose", orderType.getBillTo().getCity()); + } + + public final void testXML() { + String xml = + ""; + DataObject dataObject = new String2DataObject().transform(xml, reversedContext); + context.setSourceDataType(new DataTypeImpl(DataObject.class.getName(), DataObject.class, null)); + xml = new DataObject2String().transform(dataObject, context); + Assert.assertTrue(xml.contains("xsi:type=\"ipo:USAddress\"")); + } + +} diff --git a/java/sca/contrib/modules/databinding-sdo/src/test/java/org/apache/tuscany/sca/databinding/sdo/DataObject2XMLStreamReaderTestCase.java b/java/sca/contrib/modules/databinding-sdo/src/test/java/org/apache/tuscany/sca/databinding/sdo/DataObject2XMLStreamReaderTestCase.java new file mode 100644 index 0000000000..6a82a7fb18 --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo/src/test/java/org/apache/tuscany/sca/databinding/sdo/DataObject2XMLStreamReaderTestCase.java @@ -0,0 +1,75 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.sdo; + +import javax.xml.stream.XMLStreamConstants; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sca.databinding.xml.Node2String; +import org.apache.tuscany.sca.databinding.xml.XMLStreamReader2Node; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.impl.DataTypeImpl; +import org.apache.tuscany.sca.interfacedef.util.XMLType; + +import com.example.ipo.sdo.PurchaseOrderType; +import commonj.sdo.DataObject; +import commonj.sdo.helper.EqualityHelper; + +/** + * + * @version $Rev$ $Date$ + */ +public class DataObject2XMLStreamReaderTestCase extends SDOTransformerTestCaseBase { + + @Override + protected DataType getSourceDataType() { + return new DataTypeImpl(binding, PurchaseOrderType.class, new XMLType(ORDER_QNAME, null)); + } + + @Override + protected DataType getTargetDataType() { + return new DataTypeImpl>(XMLStreamReader.class, XMLStreamReader.class); + } + + public final void testTransform() throws XMLStreamException { + XMLStreamReader reader = new DataObject2XMLStreamReader().transform(dataObject, context); + while (reader.hasNext()) { + int event = reader.next(); + if (event == XMLStreamConstants.START_ELEMENT) { + break; + } + } + DataObject d = new XMLStreamReader2DataObject().transform(reader, reversedContext); + assertNotNull(d); + assertTrue(EqualityHelper.INSTANCE.equal(dataObject, d)); + } + + public final void testTransform1() throws XMLStreamException { + XMLStreamReader reader = new DataObject2XMLStreamReader().transform(dataObject, context); + XMLStreamReader2Node t2 = new XMLStreamReader2Node(); + org.w3c.dom.Node node = t2.transform(reader, context); + assertNotNull(node); + Node2String t3 = new Node2String(); + String xml = t3.transform(node, context); + assertTrue(xml.contains("xmlns:xsi")); + } + +} diff --git a/java/sca/contrib/modules/databinding-sdo/src/test/java/org/apache/tuscany/sca/databinding/sdo/ImportSDOProcessorTestCase.java b/java/sca/contrib/modules/databinding-sdo/src/test/java/org/apache/tuscany/sca/databinding/sdo/ImportSDOProcessorTestCase.java new file mode 100644 index 0000000000..26c0f3ecb6 --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo/src/test/java/org/apache/tuscany/sca/databinding/sdo/ImportSDOProcessorTestCase.java @@ -0,0 +1,90 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.databinding.sdo; + +import java.io.StringReader; + +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import junit.framework.TestCase; + +import org.apache.tuscany.sca.contribution.resolver.ClassReference; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.core.DefaultExtensionPointRegistry; +import org.apache.tuscany.sca.core.DefaultFactoryExtensionPoint; + +import com.example.ipo.sdo.SdoFactory; + +/** + * @version $Rev$ $Date$ + */ +public class ImportSDOProcessorTestCase extends TestCase { + private static boolean inited; + + private ImportSDOProcessor loader; + private XMLInputFactory xmlFactory; + + public void testMinimal() throws Exception { + String xml = ""; + XMLStreamReader reader = getReader(xml); + assertTrue(loader.read(reader) instanceof ImportSDO); + } + + public void testLocation() throws Exception { + String xml = ""; + XMLStreamReader reader = getReader(xml); + assertTrue(loader.read(reader) instanceof ImportSDO); + } + + public void testFactory() throws Exception { + String xml = ""; + XMLStreamReader reader = getReader(xml); + assertFalse(inited); + ImportSDO importSDO = loader.read(reader); + assertNotNull(importSDO); + ModelResolver resolver = new TestModelResolver(); + resolver.addModel(new ClassReference(MockFactory.class)); + loader.resolve(importSDO, resolver); + assertTrue(inited); + } + + @Override + protected void setUp() throws Exception { + loader = new ImportSDOProcessor(new DefaultFactoryExtensionPoint(new DefaultExtensionPointRegistry()), null); + xmlFactory = XMLInputFactory.newInstance(); + } + + protected XMLStreamReader getReader(String xml) throws XMLStreamException { + XMLStreamReader reader = xmlFactory.createXMLStreamReader(new StringReader(xml)); + reader.next(); + return reader; + } + + public static class MockFactory { + public static final Object INSTANCE = SdoFactory.INSTANCE; + + static { + ImportSDOProcessorTestCase.inited = true; + } + } +} diff --git a/java/sca/contrib/modules/databinding-sdo/src/test/java/org/apache/tuscany/sca/databinding/sdo/SDOContextHelperTestCase.java b/java/sca/contrib/modules/databinding-sdo/src/test/java/org/apache/tuscany/sca/databinding/sdo/SDOContextHelperTestCase.java new file mode 100644 index 0000000000..e0d1c9bf12 --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo/src/test/java/org/apache/tuscany/sca/databinding/sdo/SDOContextHelperTestCase.java @@ -0,0 +1,55 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.sdo; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; + +import junit.framework.Assert; + +import org.apache.tuscany.sdo.api.SDOUtil; +import org.junit.Test; + +import commonj.sdo.Type; +import commonj.sdo.helper.HelperContext; +import commonj.sdo.helper.TypeHelper; +import commonj.sdo.helper.XSDHelper; + +/** + * @version $Rev$ $Date$ + */ +public class SDOContextHelperTestCase { + @Test + public void testGenerateSchema() throws IOException { + HelperContext context = SDOUtil.createHelperContext(); + URL url = getClass().getResource("/ipo.xsd"); + Assert.assertNotNull(url); + InputStream is = url.openStream(); + XSDHelper xsdHelper = context.getXSDHelper(); + xsdHelper.define(is, url.toExternalForm()); + TypeHelper typeHelper = context.getTypeHelper(); + Type type = typeHelper.getType("http://www.example.com/IPO", "PurchaseOrderType"); + Assert.assertNotNull(type); + /* + SDOContextHelper.generateSchema(context, Arrays.asList(type)); + */ + } +} diff --git a/java/sca/contrib/modules/databinding-sdo/src/test/java/org/apache/tuscany/sca/databinding/sdo/SDODataBindingTestCase.java b/java/sca/contrib/modules/databinding-sdo/src/test/java/org/apache/tuscany/sca/databinding/sdo/SDODataBindingTestCase.java new file mode 100644 index 0000000000..3c21b56c9f --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo/src/test/java/org/apache/tuscany/sca/databinding/sdo/SDODataBindingTestCase.java @@ -0,0 +1,114 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.sdo; + +import javax.xml.namespace.QName; + +import junit.framework.TestCase; + +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.interfacedef.impl.DataTypeImpl; +import org.apache.tuscany.sca.interfacedef.util.XMLType; + +import com.example.ipo.sdo.PurchaseOrderType; +import com.example.ipo.sdo.SdoFactory; +import com.example.ipo.sdo.USAddress; +import commonj.sdo.DataObject; +import commonj.sdo.helper.HelperContext; +import commonj.sdo.helper.XMLDocument; +import commonj.sdo.impl.HelperProvider; + +/** + * + * @version $Rev$ $Date$ + */ +public class SDODataBindingTestCase extends TestCase { + protected static final QName ORDER_QNAME = new QName("http://www.example.com/IPO", "purchaseOrder"); + private SDODataBinding binding; + private HelperContext context; + + /** + * @see junit.framework.TestCase#setUp() + */ + @Override + protected void setUp() throws Exception { + super.setUp(); + binding = new SDODataBinding(); + context = HelperProvider.getDefaultContext(); + SdoFactory.INSTANCE.register(context); + } + + public final void testIntrospect() { + Operation op = null; + DataType dataType = new DataTypeImpl(DataObject.class, null); + boolean yes = binding.introspect(dataType, op); + assertTrue(yes); + assertTrue(dataType.getDataBinding().equals(binding.getName())); + assertTrue(dataType.getPhysical() == DataObject.class && dataType.getLogical() == XMLType.UNKNOWN); + dataType = new DataTypeImpl(PurchaseOrderType.class, null); + yes = binding.introspect(dataType, op); + assertTrue(yes); + assertEquals(PurchaseOrderType.class, dataType.getPhysical()); + assertEquals(new QName("http://www.example.com/IPO", "PurchaseOrderType"), ((XMLType)dataType.getLogical()) + .getTypeName()); + dataType = new DataTypeImpl(USAddress.class, null); + yes = binding.introspect(dataType, op); + assertTrue(yes); + assertEquals(USAddress.class, dataType.getPhysical()); + assertEquals(new QName("http://www.example.com/IPO", "USAddress"), ((XMLType)dataType.getLogical()) + .getTypeName()); + } + + public final void testCopyRoot() { + PurchaseOrderType po = SdoFactory.INSTANCE.createPurchaseOrderType(); + po.setComment("Comment"); + Object copy = binding.copy(po, null, null); + assertTrue(copy instanceof PurchaseOrderType); + assertTrue(po != copy); + assertTrue(context.getEqualityHelper().equal((DataObject)po, (DataObject)copy)); + assertEquals("Comment", ((PurchaseOrderType)copy).getComment()); + } + + public final void testCopyNonRoot() { + USAddress address = SdoFactory.INSTANCE.createUSAddress(); + address.setCity("San Jose"); + Object copy = binding.copy(address, null, null); + assertTrue(copy instanceof USAddress); + assertTrue(address != copy); + assertTrue(context.getEqualityHelper().equal((DataObject)address, (DataObject)copy)); + assertEquals("San Jose", ((USAddress)copy).getCity()); + } + + public final void testCopyXMLDocument() { + PurchaseOrderType po = SdoFactory.INSTANCE.createPurchaseOrderType(); + po.setComment("Comment"); + XMLDocument doc = + context.getXMLHelper().createDocument((DataObject)po, + ORDER_QNAME.getNamespaceURI(), + ORDER_QNAME.getLocalPart()); + Object copy = binding.copy(doc, null, null); + assertTrue(copy instanceof XMLDocument); + XMLDocument docCopy = (XMLDocument)copy; + assertTrue(doc != copy); + assertTrue(context.getEqualityHelper().equal((DataObject)po, docCopy.getRootObject())); + assertEquals("Comment", ((PurchaseOrderType)docCopy.getRootObject()).getComment()); + } +} diff --git a/java/sca/contrib/modules/databinding-sdo/src/test/java/org/apache/tuscany/sca/databinding/sdo/SDOTransformerTestCaseBase.java b/java/sca/contrib/modules/databinding-sdo/src/test/java/org/apache/tuscany/sca/databinding/sdo/SDOTransformerTestCaseBase.java new file mode 100644 index 0000000000..2aaae3c6d8 --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo/src/test/java/org/apache/tuscany/sca/databinding/sdo/SDOTransformerTestCaseBase.java @@ -0,0 +1,82 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.sdo; + +import javax.xml.namespace.QName; + +import junit.framework.TestCase; + +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.impl.TransformationContextImpl; +import org.apache.tuscany.sca.interfacedef.DataType; + +import com.example.ipo.sdo.PurchaseOrderType; +import com.example.ipo.sdo.SdoFactory; +import com.example.ipo.sdo.USAddress; +import commonj.sdo.DataObject; +import commonj.sdo.helper.HelperContext; +import commonj.sdo.impl.HelperProvider; + +/** + * The base class for SDO-related test cases + * + * @version $Rev$ $Date$ + */ +public abstract class SDOTransformerTestCaseBase extends TestCase { + protected static final QName ORDER_QNAME = new QName("http://www.example.com/IPO", "purchaseOrder"); + + protected HelperContext helperContext; + protected String binding = DataObject.class.getName(); + protected TransformationContext context; + protected TransformationContext reversedContext; + protected DataObject dataObject; + + /** + * @see junit.framework.TestCase#setUp() + */ + @Override + protected void setUp() throws Exception { + super.setUp(); + helperContext = HelperProvider.getDefaultContext(); + SdoFactory.INSTANCE.register(helperContext); + + context = new TransformationContextImpl(); + context.setSourceDataType(getSourceDataType()); + context.setTargetDataType(getTargetDataType()); + + reversedContext = new TransformationContextImpl(); + reversedContext.setSourceDataType(getTargetDataType()); + reversedContext.setTargetDataType(getSourceDataType()); + + PurchaseOrderType po = SdoFactory.INSTANCE.createPurchaseOrderType(); + USAddress address = SdoFactory.INSTANCE.createUSAddress(); + address.setCity("San Jose"); + address.setStreet("123 ABC St"); + address.setState("CA"); + address.setStreet("95131"); + po.setBillTo(address); + dataObject = (DataObject) po; + } + + protected abstract DataType getSourceDataType(); + + protected abstract DataType getTargetDataType(); + +} diff --git a/java/sca/contrib/modules/databinding-sdo/src/test/java/org/apache/tuscany/sca/databinding/sdo/SDOWrapperHandlerTestCase.java b/java/sca/contrib/modules/databinding-sdo/src/test/java/org/apache/tuscany/sca/databinding/sdo/SDOWrapperHandlerTestCase.java new file mode 100644 index 0000000000..11d8495de8 --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo/src/test/java/org/apache/tuscany/sca/databinding/sdo/SDOWrapperHandlerTestCase.java @@ -0,0 +1,83 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.databinding.sdo; + +import java.util.List; + +import javax.xml.namespace.QName; + +import junit.framework.TestCase; + +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.interfacedef.impl.OperationImpl; +import org.apache.tuscany.sca.interfacedef.util.ElementInfo; +import org.apache.tuscany.sca.interfacedef.util.WrapperInfo; +import org.apache.tuscany.sdo.api.SDOUtil; + +import commonj.sdo.DataObject; +import commonj.sdo.helper.HelperContext; +import commonj.sdo.helper.XMLDocument; +import commonj.sdo.helper.XMLHelper; +import commonj.sdo.helper.XSDHelper; +import commonj.sdo.impl.HelperProvider; + +/** + * @version $Rev$ $Date$ + */ +public class SDOWrapperHandlerTestCase extends TestCase { + private HelperContext context; + private SDOWrapperHandler handler; + + @Override + public void setUp() throws Exception { + context = SDOUtil.createHelperContext(); + handler = new SDOWrapperHandler(); + } + + public void testWrapperAnyType() throws Exception { + XMLHelper xmlHelper = context.getXMLHelper(); + XMLDocument document = xmlHelper.load(getClass().getResourceAsStream("/wrapper.xml")); + Operation op = new OperationImpl(); + List children = handler.getChildren(document, op, true); + assertEquals(5, children.size()); + } + + public void testWrapper() throws Exception { + XSDHelper xsdHelper = context.getXSDHelper(); + xsdHelper.define(getClass().getResourceAsStream("/wrapper.xsd"), null); + XMLHelper xmlHelper = context.getXMLHelper(); + XMLDocument document = xmlHelper.load(getClass().getResourceAsStream("/wrapper.xml")); + Operation op = new OperationImpl(); + List children = handler.getChildren(document, op, true); + assertEquals(5, children.size()); + } + + public void testCreate() { + HelperContext context = HelperProvider.getDefaultContext(); + XSDHelper xsdHelper = context.getXSDHelper(); + xsdHelper.define(getClass().getResourceAsStream("/wrapper.xsd"), null); + ElementInfo element = new ElementInfo(new QName("http://www.example.com/wrapper", "op"), null); + Operation op = new OperationImpl(); + WrapperInfo wrapperInfo = new WrapperInfo(SDODataBinding.NAME, element, null, null, null); + op.setWrapper(wrapperInfo); + DataObject wrapper = (DataObject) handler.create(op, true); + assertNotNull(wrapper); + } + +} diff --git a/java/sca/contrib/modules/databinding-sdo/src/test/java/org/apache/tuscany/sca/databinding/sdo/TestModelResolver.java b/java/sca/contrib/modules/databinding-sdo/src/test/java/org/apache/tuscany/sca/databinding/sdo/TestModelResolver.java new file mode 100644 index 0000000000..ce04f5be3f --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo/src/test/java/org/apache/tuscany/sca/databinding/sdo/TestModelResolver.java @@ -0,0 +1,63 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.sdo; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; + + +/** + * A default implementation of an artifact resolver, based on a map. + * + * @version $Rev$ $Date$ + */ +public class TestModelResolver implements ModelResolver { + private static final long serialVersionUID = -7826976465762296634L; + + private Map map = new HashMap(); + + public TestModelResolver() { + } + + public T resolveModel(Class modelClass, T unresolved) { + Object resolved = map.get(unresolved); + if (resolved != null) { + + // Return the resolved object + return modelClass.cast(resolved); + + } else { + + // Return the unresolved object + return unresolved; + } + } + + public void addModel(Object resolved) { + map.put(resolved, resolved); + } + + public Object removeModel(Object resolved) { + return map.remove(resolved); + } + +} diff --git a/java/sca/contrib/modules/databinding-sdo/src/test/java/org/apache/tuscany/sca/databinding/sdo/XMLDocument2XMLStreamReaderTestCase.java b/java/sca/contrib/modules/databinding-sdo/src/test/java/org/apache/tuscany/sca/databinding/sdo/XMLDocument2XMLStreamReaderTestCase.java new file mode 100644 index 0000000000..114c568c38 --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo/src/test/java/org/apache/tuscany/sca/databinding/sdo/XMLDocument2XMLStreamReaderTestCase.java @@ -0,0 +1,62 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.sdo; + +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import junit.framework.Assert; + +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.impl.DataTypeImpl; +import org.apache.tuscany.sca.interfacedef.util.XMLType; + +import com.example.ipo.sdo.PurchaseOrderType; +import commonj.sdo.helper.XMLDocument; + +/** + * + * @version $Rev$ $Date$ + */ +public class XMLDocument2XMLStreamReaderTestCase extends SDOTransformerTestCaseBase { + + @Override + protected DataType getSourceDataType() { + return new DataTypeImpl(XMLDocument.class.getName(), XMLDocument.class, new XMLType(ORDER_QNAME, null)); + } + + @Override + protected DataType getTargetDataType() { + return new DataTypeImpl>(XMLStreamReader.class, XMLStreamReader.class); + } + + public final void testTransform() throws XMLStreamException { + XMLDocument document = + helperContext.getXMLHelper().createDocument(dataObject, + ORDER_QNAME.getNamespaceURI(), + ORDER_QNAME.getLocalPart()); + XMLStreamReader reader = new XMLDocument2XMLStreamReader().transform(document, context); + XMLDocument document2 = new XMLStreamReader2XMLDocument().transform(reader, reversedContext); + Assert.assertEquals(ORDER_QNAME.getNamespaceURI(), document2.getRootElementURI()); + Assert.assertEquals(ORDER_QNAME.getLocalPart(), document2.getRootElementName()); + Assert.assertTrue(document2.getRootObject() instanceof PurchaseOrderType); + } + +} diff --git a/java/sca/contrib/modules/databinding-sdo/src/test/resources/ipo.xsd b/java/sca/contrib/modules/databinding-sdo/src/test/resources/ipo.xsd new file mode 100755 index 0000000000..241ec15d36 --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo/src/test/resources/ipo.xsd @@ -0,0 +1,136 @@ + + + + + + International Purchase order schema for Example.com + Copyright 2000 Example.com. All rights reserved. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/java/sca/contrib/modules/databinding-sdo/src/test/resources/model/sca-core.xsd b/java/sca/contrib/modules/databinding-sdo/src/test/resources/model/sca-core.xsd new file mode 100755 index 0000000000..56c6977254 --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo/src/test/resources/model/sca-core.xsd @@ -0,0 +1,233 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/java/sca/contrib/modules/databinding-sdo/src/test/resources/model/sca-implementation-mock.xsd b/java/sca/contrib/modules/databinding-sdo/src/test/resources/model/sca-implementation-mock.xsd new file mode 100755 index 0000000000..bbaf58f00c --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo/src/test/resources/model/sca-implementation-mock.xsd @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + diff --git a/java/sca/contrib/modules/databinding-sdo/src/test/resources/stock.xsd b/java/sca/contrib/modules/databinding-sdo/src/test/resources/stock.xsd new file mode 100644 index 0000000000..a0a6717371 --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo/src/test/resources/stock.xsd @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/java/sca/contrib/modules/databinding-sdo/src/test/resources/wrapper.xml b/java/sca/contrib/modules/databinding-sdo/src/test/resources/wrapper.xml new file mode 100644 index 0000000000..2526629409 --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo/src/test/resources/wrapper.xml @@ -0,0 +1,27 @@ + + + + message + symbol + message1 + symbol1 + symbol2 + diff --git a/java/sca/contrib/modules/databinding-sdo/src/test/resources/wrapper.xsd b/java/sca/contrib/modules/databinding-sdo/src/test/resources/wrapper.xsd new file mode 100644 index 0000000000..ea4dc5f7f3 --- /dev/null +++ b/java/sca/contrib/modules/databinding-sdo/src/test/resources/wrapper.xsd @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/java/sca/contrib/modules/databinding-xmlbeans/LICENSE b/java/sca/contrib/modules/databinding-xmlbeans/LICENSE new file mode 100755 index 0000000000..d645695673 --- /dev/null +++ b/java/sca/contrib/modules/databinding-xmlbeans/LICENSE @@ -0,0 +1,202 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/java/sca/contrib/modules/databinding-xmlbeans/META-INF/MANIFEST.MF b/java/sca/contrib/modules/databinding-xmlbeans/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..dfddbeb6c8 --- /dev/null +++ b/java/sca/contrib/modules/databinding-xmlbeans/META-INF/MANIFEST.MF @@ -0,0 +1,27 @@ +Manifest-Version: 1.0 +Private-Package: org.apache.tuscany.sca.databinding.xmlbeans;version=" + 1.4" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA Data Binding for XmlBeans +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397402000 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA Data Binding for XmlBeans +Import-Package: javax.xml.namespace, + javax.xml.stream, + org.apache.tuscany.sca.databinding;version="2.0.0", + org.apache.tuscany.sca.databinding.impl;version="2.0.0", + org.apache.tuscany.sca.interfacedef;version="2.0.0", + org.apache.tuscany.sca.interfacedef.util;version="2.0.0", + org.apache.xmlbeans, + org.apache.xmlbeans.impl.values;resolution:=optional, + org.apache.xmlbeans.xml.stream;resolution:=optional, + org.oasisopen.sca;version="2.0.0", + org.oasisopen.sca.annotation;version="2.0.0", + org.w3c.dom +Bundle-SymbolicName: org.apache.tuscany.sca.databinding.xmlbeans +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/databinding-xmlbeans/NOTICE b/java/sca/contrib/modules/databinding-xmlbeans/NOTICE new file mode 100644 index 0000000000..25bb89c9b2 --- /dev/null +++ b/java/sca/contrib/modules/databinding-xmlbeans/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/databinding-xmlbeans/pom.xml b/java/sca/contrib/modules/databinding-xmlbeans/pom.xml new file mode 100644 index 0000000000..bee5c8f44e --- /dev/null +++ b/java/sca/contrib/modules/databinding-xmlbeans/pom.xml @@ -0,0 +1,119 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + tuscany-databinding-xmlbeans + Apache Tuscany SCA Data Binding for XmlBeans + + + + org.apache.tuscany.sca + tuscany-core-spi + 2.0-SNAPSHOT + + + org.apache.tuscany.sca + tuscany-databinding + 2.0-SNAPSHOT + + + + org.apache.xmlbeans + xmlbeans + 2.3.0 + compile + + + stax + stax-api + + + + + junit + junit + 4.5 + test + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.0 + + + add-test-source + generate-sources + + add-test-source + + + + target/xmlbeans-source + + + + + + + maven-antrun-plugin + + + + ant + ant-trax + 1.6.5 + + + + + + generate-xmlbeans + generate-sources + + + + + + + + run + + + + + + + + + diff --git a/java/sca/contrib/modules/databinding-xmlbeans/src/main/java/org/apache/tuscany/sca/databinding/xmlbeans/Node2XmlObject.java b/java/sca/contrib/modules/databinding-xmlbeans/src/main/java/org/apache/tuscany/sca/databinding/xmlbeans/Node2XmlObject.java new file mode 100644 index 0000000000..e7b240b781 --- /dev/null +++ b/java/sca/contrib/modules/databinding-xmlbeans/src/main/java/org/apache/tuscany/sca/databinding/xmlbeans/Node2XmlObject.java @@ -0,0 +1,61 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.databinding.xmlbeans; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.apache.xmlbeans.XmlException; +import org.apache.xmlbeans.XmlObject; +import org.w3c.dom.Node; + +/** + * Transforms a DOM Node to an XML Object. + * + * @version $Rev$ $Date$ + */ +public class Node2XmlObject extends BaseTransformer implements + PullTransformer { + // private XmlOptions options; + + public XmlObject transform(Node source, TransformationContext context) { + try { + return XmlObject.Factory.parse(source); + } catch (XmlException e) { + throw new TransformationException(e); + } + } + + @Override + protected Class getTargetType() { + return XmlObject.class; + } + + @Override + protected Class getSourceType() { + return Node.class; + } + + @Override + public int getWeight() { + return 30; + } + +} diff --git a/java/sca/contrib/modules/databinding-xmlbeans/src/main/java/org/apache/tuscany/sca/databinding/xmlbeans/XMLBeansDataBinding.java b/java/sca/contrib/modules/databinding-xmlbeans/src/main/java/org/apache/tuscany/sca/databinding/xmlbeans/XMLBeansDataBinding.java new file mode 100644 index 0000000000..4e557522fe --- /dev/null +++ b/java/sca/contrib/modules/databinding-xmlbeans/src/main/java/org/apache/tuscany/sca/databinding/xmlbeans/XMLBeansDataBinding.java @@ -0,0 +1,82 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.xmlbeans; + +import java.lang.reflect.Field; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.databinding.WrapperHandler; +import org.apache.tuscany.sca.databinding.impl.BaseDataBinding; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.interfacedef.util.XMLType; +import org.apache.xmlbeans.SchemaType; +import org.apache.xmlbeans.XmlObject; +import org.oasisopen.sca.ServiceRuntimeException; + +/** + * XMLBeans DataBinding + * + * @version $Rev$ $Date$ + */ +public class XMLBeansDataBinding extends BaseDataBinding { + public static final String NAME = XmlObject.class.getName(); + public static final String[] ALIASES = {"xmlbeans"}; + + public XMLBeansDataBinding() { + super(NAME, XmlObject.class); + } + + @Override + public WrapperHandler getWrapperHandler() { + return new XMLBeansWrapperHandler(); + } + + @Override + public boolean introspect(DataType type, Operation operation) { + if (XmlObject.class.isAssignableFrom(type.getPhysical())) { + Class cls = type.getPhysical(); + SchemaType schemaType = null; + try { + Field f = cls.getField("type"); + schemaType = (SchemaType)f.get(null); + } catch (Throwable e) { + throw new ServiceRuntimeException(e); + } + QName typeName = schemaType.getName(); + Object logical = type.getLogical(); + QName elementName = null; + if (logical instanceof XMLType) { + elementName = ((XMLType)logical).getElementName(); + } + type.setLogical(new XMLType(elementName, typeName)); + type.setMetaData(SchemaType.class, schemaType); + return true; + } + return false; + } + + @Override + public Object copy(Object object, DataType dataType, Operation operation) { + return ((XmlObject)object).copy(); + } + +} diff --git a/java/sca/contrib/modules/databinding-xmlbeans/src/main/java/org/apache/tuscany/sca/databinding/xmlbeans/XMLBeansWrapperHandler.java b/java/sca/contrib/modules/databinding-xmlbeans/src/main/java/org/apache/tuscany/sca/databinding/xmlbeans/XMLBeansWrapperHandler.java new file mode 100644 index 0000000000..506c42e40f --- /dev/null +++ b/java/sca/contrib/modules/databinding-xmlbeans/src/main/java/org/apache/tuscany/sca/databinding/xmlbeans/XMLBeansWrapperHandler.java @@ -0,0 +1,110 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.databinding.xmlbeans; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; + +import org.apache.tuscany.sca.databinding.WrapperHandler; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.interfacedef.util.ElementInfo; +import org.apache.tuscany.sca.interfacedef.util.WrapperInfo; +import org.apache.xmlbeans.SchemaProperty; +import org.apache.xmlbeans.SimpleValue; +import org.apache.xmlbeans.XmlObject; + +/** + * @version $Rev$ $Date$ + */ +public class XMLBeansWrapperHandler implements WrapperHandler { + + /** + * @see org.apache.tuscany.sca.databinding.WrapperHandler#create(org.apache.tuscany.sca.interfacedef.Operation, boolean) + */ + public XmlObject create(Operation operation, boolean input) { + WrapperInfo wrapperInfo = operation.getWrapper(); + ElementInfo element = input ? wrapperInfo.getInputWrapperElement() : wrapperInfo.getOutputWrapperElement(); + return null; + } + + /** + * @see org.apache.tuscany.sca.databinding.WrapperHandler#getChildren(java.lang.Object, org.apache.tuscany.sca.interfacedef.Operation, boolean) + */ + public List getChildren(XmlObject wrapper, Operation operation, boolean input) { + List children = new ArrayList(); + + List childElements = + input ? operation.getWrapper().getInputChildElements() : operation.getWrapper().getOutputChildElements(); + for (ElementInfo e : childElements) { + XmlObject[] objects = wrapper.selectChildren(e.getQName()); + if (objects != null && objects.length == 1) { + if (objects[0] instanceof SimpleValue) { + children.add(((SimpleValue)objects[0]).getObjectValue()); + } else { + children.add(objects[0]); + } + } + // FIXME: What should we do for many-value? + } + return children; + } + + /** + * @see org.apache.tuscany.sca.databinding.WrapperHandler#getWrapperType(org.apache.tuscany.sca.interfacedef.Operation, boolean) + */ + public DataType getWrapperType(Operation operation, boolean input) { + // TODO Auto-generated method stub + return null; + } + + /** + * @see org.apache.tuscany.sca.databinding.WrapperHandler#isInstance(java.lang.Object, org.apache.tuscany.sca.interfacedef.Operation, boolean) + */ + public boolean isInstance(Object wrapper, Operation operation, boolean input) { + WrapperInfo wrapperInfo = operation.getWrapper(); + ElementInfo element = input ? wrapperInfo.getInputWrapperElement() : wrapperInfo.getOutputWrapperElement(); + return true; + } + + /** + * @see org.apache.tuscany.sca.databinding.WrapperHandler#setChildren(java.lang.Object, java.lang.Object[], org.apache.tuscany.sca.interfacedef.Operation, boolean) + */ + public void setChildren(XmlObject wrapper, Object[] childObjects, Operation operation, boolean input) { + List childElements = + input ? operation.getWrapper().getInputChildElements() : operation.getWrapper().getOutputChildElements(); + int i = 0; + for (ElementInfo c : childElements) { + SchemaProperty property = wrapper.schemaType().getElementProperty(c.getQName()); + + String prop = property.getJavaPropertyName(); + + Method setter; + try { + setter = wrapper.schemaType().getJavaClass().getMethod("set" + prop, property.getType().getJavaClass()); + setter.invoke(wrapper, childObjects[i++]); + } catch (Throwable e) { + throw new IllegalArgumentException(e); + } + } + } + +} diff --git a/java/sca/contrib/modules/databinding-xmlbeans/src/main/java/org/apache/tuscany/sca/databinding/xmlbeans/XMLStreamReader2XmlObject.java b/java/sca/contrib/modules/databinding-xmlbeans/src/main/java/org/apache/tuscany/sca/databinding/xmlbeans/XMLStreamReader2XmlObject.java new file mode 100644 index 0000000000..ca84f961b1 --- /dev/null +++ b/java/sca/contrib/modules/databinding-xmlbeans/src/main/java/org/apache/tuscany/sca/databinding/xmlbeans/XMLStreamReader2XmlObject.java @@ -0,0 +1,62 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.databinding.xmlbeans; + +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.apache.xmlbeans.XmlObject; + +/** + * Transforms an XMLStreamReader to an XML Object. + * + * @version $Rev$ $Date$ + */ +public class XMLStreamReader2XmlObject extends BaseTransformer implements PullTransformer { + // private XmlOptions options; + + public XmlObject transform(XMLStreamReader source, TransformationContext context) { + try { + XmlObject target = XmlObject.Factory.parse(source); + source.close(); + return target; + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + protected Class getTargetType() { + return XmlObject.class; + } + + @Override + protected Class getSourceType() { + return XMLStreamReader.class; + } + + @Override + public int getWeight() { + return 10; + } + +} diff --git a/java/sca/contrib/modules/databinding-xmlbeans/src/main/java/org/apache/tuscany/sca/databinding/xmlbeans/XmlObject2Node.java b/java/sca/contrib/modules/databinding-xmlbeans/src/main/java/org/apache/tuscany/sca/databinding/xmlbeans/XmlObject2Node.java new file mode 100644 index 0000000000..9620d38eaf --- /dev/null +++ b/java/sca/contrib/modules/databinding-xmlbeans/src/main/java/org/apache/tuscany/sca/databinding/xmlbeans/XmlObject2Node.java @@ -0,0 +1,60 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.databinding.xmlbeans; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.Transformer; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.apache.xmlbeans.XmlObject; +import org.oasisopen.sca.annotation.Service; +import org.w3c.dom.Node; + +/** + * Transforms an XML Object to a DOM Node. + * + * @version $Rev$ $Date$ + */ +@Service(Transformer.class) +public class XmlObject2Node extends BaseTransformer implements + PullTransformer { + // private XmlOptions options; + + public Node transform(XmlObject source, TransformationContext context) { + if (source == null) + return null; + return source.newDomNode(); + } + + @Override + protected Class getSourceType() { + return XmlObject.class; + } + + @Override + protected Class getTargetType() { + return Node.class; + } + + @Override + public int getWeight() { + return 30; + } + +} diff --git a/java/sca/contrib/modules/databinding-xmlbeans/src/main/java/org/apache/tuscany/sca/databinding/xmlbeans/XmlObject2XMLStreamReader.java b/java/sca/contrib/modules/databinding-xmlbeans/src/main/java/org/apache/tuscany/sca/databinding/xmlbeans/XmlObject2XMLStreamReader.java new file mode 100644 index 0000000000..bbffb7d748 --- /dev/null +++ b/java/sca/contrib/modules/databinding-xmlbeans/src/main/java/org/apache/tuscany/sca/databinding/xmlbeans/XmlObject2XMLStreamReader.java @@ -0,0 +1,55 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.databinding.xmlbeans; + +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.apache.xmlbeans.XmlObject; + +/** + * Transforms an XML Object to an XMLStreamReader. + * + * @version $Rev$ $Date$ + */ +public class XmlObject2XMLStreamReader extends BaseTransformer implements PullTransformer { + // private XmlOptions options; + + public XMLStreamReader transform(XmlObject source, TransformationContext context) { + return source.newXMLStreamReader(); + } + + @Override + protected Class getSourceType() { + return XmlObject.class; + } + + @Override + protected Class getTargetType() { + return XMLStreamReader.class; + } + + @Override + public int getWeight() { + return 10; + } + +} diff --git a/java/sca/contrib/modules/databinding-xmlbeans/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.DataBinding b/java/sca/contrib/modules/databinding-xmlbeans/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.DataBinding new file mode 100644 index 0000000000..ac76c6ca9b --- /dev/null +++ b/java/sca/contrib/modules/databinding-xmlbeans/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.DataBinding @@ -0,0 +1,19 @@ +# 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. + +# implementation classes for the databindings +org.apache.tuscany.sca.databinding.xmlbeans.XMLBeansDataBinding;name=org.apache.xmlbeans.XmlObject diff --git a/java/sca/contrib/modules/databinding-xmlbeans/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PullTransformer b/java/sca/contrib/modules/databinding-xmlbeans/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PullTransformer new file mode 100644 index 0000000000..4e419de051 --- /dev/null +++ b/java/sca/contrib/modules/databinding-xmlbeans/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PullTransformer @@ -0,0 +1,22 @@ +# 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. + +# Implementation classes for the transformers +org.apache.tuscany.sca.databinding.xmlbeans.Node2XmlObject;source=org.w3c.dom.Node,target=org.apache.xmlbeans.XmlObject,weight=500 +org.apache.tuscany.sca.databinding.xmlbeans.XmlObject2Node;source=org.apache.xmlbeans.XmlObject,target=org.w3c.dom.Node,weight=500 +org.apache.tuscany.sca.databinding.xmlbeans.XmlObject2XMLStreamReader;source=org.apache.xmlbeans.XmlObject,target=javax.xml.stream.XMLStreamReader,weight=490 +org.apache.tuscany.sca.databinding.xmlbeans.XMLStreamReader2XmlObject;source=javax.xml.stream.XMLStreamReader,target=org.apache.xmlbeans.XmlObject,weight=490 diff --git a/java/sca/contrib/modules/databinding-xmlbeans/src/test/java/org/apache/tuscany/sca/databinding/xmlbeans/XmlObjectTestCase.java b/java/sca/contrib/modules/databinding-xmlbeans/src/test/java/org/apache/tuscany/sca/databinding/xmlbeans/XmlObjectTestCase.java new file mode 100644 index 0000000000..7b98ddb021 --- /dev/null +++ b/java/sca/contrib/modules/databinding-xmlbeans/src/test/java/org/apache/tuscany/sca/databinding/xmlbeans/XmlObjectTestCase.java @@ -0,0 +1,105 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.databinding.xmlbeans; + +import java.io.StringReader; + +import javax.xml.stream.XMLStreamReader; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.xmlbeans.XmlObject; +import org.w3c.dom.Node; + +import com.example.ipo.xmlbeans.PurchaseOrderDocument; + +/** + * Test cases for testing XML Object transformations. + * + * @version $Rev$ $Date$ + */ +public class XmlObjectTestCase extends TestCase { + private static final String IPO_XML = "" + "" + + " " + " Helen Zoe" + " 47 Eden Street" + + " Cambridge" + " CB1 1JR" + " " + " " + + " Robert Smith" + " 8 Oak Avenue" + " Old Town" + " PA" + + " 95819" + " " + " " + " " + + " Lapis necklace" + " 1" + " 99.95" + + " Want this for the holidays" + " 1999-12-05" + " " + " " + + ""; + + @Override + protected void setUp() throws Exception { + super.setUp(); + } + + public void testXmlObject() throws Exception { + // URL/Stream/Reader to XmlObject + XmlObject object = XmlObject.Factory.parse(new StringReader(IPO_XML)); + + // XmlObject to XMLStreamReader + XmlObject2XMLStreamReader t1 = new XmlObject2XMLStreamReader(); + XMLStreamReader reader = t1.transform(object, null); + + // XMLStreamReader to XmlObject + XMLStreamReader2XmlObject t2 = new XMLStreamReader2XmlObject(); + XmlObject object2 = t2.transform(reader, null); + + // XmlObject to Node + XmlObject2Node t3 = new XmlObject2Node(); + Node node = t3.transform(object2, null); + + // Node to XmlObject + Node2XmlObject t4 = new Node2XmlObject(); + XmlObject object3 = t4.transform(node, null); + Assert.assertNotNull(object3); + } + + public void testGeneratedXmlObject() throws Exception { + // URL xmlFile = getClass().getClassLoader().getResource("ipo.xml"); + // URL/Stream/Reader to XmlObject + PurchaseOrderDocument object = PurchaseOrderDocument.Factory.parse(new StringReader(IPO_XML)); + + // XmlObject to XMLStreamReader + XmlObject2XMLStreamReader t1 = new XmlObject2XMLStreamReader(); + XMLStreamReader reader = t1.transform(object, null); + + // XMLStreamReader to XmlObject + XMLStreamReader2XmlObject t2 = new XMLStreamReader2XmlObject(); + PurchaseOrderDocument object2 = (PurchaseOrderDocument) t2.transform(reader, null); + + // XmlObject to Node + XmlObject2Node t3 = new XmlObject2Node(); + Node node = t3.transform(object2, null); + + // Node to XmlObject + Node2XmlObject t4 = new Node2XmlObject(); + PurchaseOrderDocument object3 = (PurchaseOrderDocument) t4.transform(node, null); + Assert.assertNotNull(object3); + } + + @Override + protected void tearDown() throws Exception { + super.tearDown(); + } + +} diff --git a/java/sca/contrib/modules/databinding-xmlbeans/src/test/resources/ipo.xsd b/java/sca/contrib/modules/databinding-xmlbeans/src/test/resources/ipo.xsd new file mode 100755 index 0000000000..5a493e1746 --- /dev/null +++ b/java/sca/contrib/modules/databinding-xmlbeans/src/test/resources/ipo.xsd @@ -0,0 +1,136 @@ + + + + + + International Purchase order schema for Example.com + Copyright 2000 Example.com. All rights reserved. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/java/sca/contrib/modules/databinding-xmlbeans/src/test/resources/ipo.xsdconfig b/java/sca/contrib/modules/databinding-xmlbeans/src/test/resources/ipo.xsdconfig new file mode 100755 index 0000000000..a397182672 --- /dev/null +++ b/java/sca/contrib/modules/databinding-xmlbeans/src/test/resources/ipo.xsdconfig @@ -0,0 +1,21 @@ + + + + + com.example.ipo.xmlbeans + + + diff --git a/java/sca/contrib/modules/domain-manager/LICENSE b/java/sca/contrib/modules/domain-manager/LICENSE new file mode 100644 index 0000000000..8aa906c321 --- /dev/null +++ b/java/sca/contrib/modules/domain-manager/LICENSE @@ -0,0 +1,205 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + + diff --git a/java/sca/contrib/modules/domain-manager/META-INF/MANIFEST.MF b/java/sca/contrib/modules/domain-manager/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..482c048938 --- /dev/null +++ b/java/sca/contrib/modules/domain-manager/META-INF/MANIFEST.MF @@ -0,0 +1,69 @@ +Manifest-Version: 1.0 +Export-Package: org.apache.tuscany.sca.domain.manager.impl;uses:="org. + apache.commons.fileupload.disk,org.apache.tuscany.sca.runtime,org.apa + che.tuscany.sca.data.collection,org.apache.tuscany.sca.core.context,o + rg.apache.tuscany.sca.definitions,org.apache.tuscany.sca.binding.atom + ,org.apache.tuscany.sca.core,javax.xml.namespace,javax.servlet,javax. + xml.stream,org.apache.tuscany.sca.core.assembly,org.apache.tuscany.sc + a.contribution.resolver,org.apache.tuscany.sca.workspace,org.apache.t + uscany.sca.core.invocation,org.oasisopen.sca,org.apache.tuscany.sca.assemb + ly.builder,org.apache.tuscany.sca.implementation.node,org.oasisopen.sca.an + notations,org.apache.tuscany.sca.assembly,org.apache.commons.fileuplo + ad,org.apache.commons.fileupload.servlet,org.apache.tuscany.sca.works + pace.builder,javax.xml.parsers,org.apache.tuscany.sca.contribution,or + g.apache.tuscany.sca.interfacedef.java,org.apache.tuscany.sca.monitor + ,org.apache.tuscany.sca.interfacedef,org.w3c.dom,org.apache.xml.seria + lize,org.apache.tuscany.sca.contribution.processor,javax.servlet.http + ";version="2.0.0",org.apache.tuscany.sca.domain.manager.launcher;uses:= + "org.apache.tuscany.sca.domain.manager.impl,org.apache.tuscany.sca.no + de,org.oasisopen.sca";version="2.0.0" +Private-Package: icons;version="2.0.0" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA Domain Manager Application +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397422109 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA Domain Manager Application +Import-Package: javax.servlet, + javax.servlet.http, + javax.xml.namespace, + javax.xml.parsers, + javax.xml.stream, + + org.apache.commons.fileupload, + org.apache.commons.fileupload.disk, + org.apache.commons.fileupload.servlet, + org.apache.tuscany.sca.assembly;version="2.0.0", + org.apache.tuscany.sca.assembly.builder;version="2.0.0", + org.apache.tuscany.sca.assembly.xml;version="2.0.0", + org.apache.tuscany.sca.binding.atom;version="2.0.0", + org.apache.tuscany.sca.contribution;version="2.0.0", + org.apache.tuscany.sca.contribution.processor;version="2.0.0", + org.apache.tuscany.sca.contribution.resolver;version="2.0.0", + org.apache.tuscany.sca.core;version="2.0.0", + org.apache.tuscany.sca.core.assembly;version="2.0.0", + org.apache.tuscany.sca.core.context;version="2.0.0", + org.apache.tuscany.sca.core.invocation;version="2.0.0", + org.apache.tuscany.sca.data.collection;version="2.0.0", + org.apache.tuscany.sca.definitions;version="2.0.0", + org.apache.tuscany.sca.domain.manager.impl;version="2.0.0", + org.apache.tuscany.sca.domain.manager.launcher;version="2.0.0", + org.apache.tuscany.sca.implementation.node;version="2.0.0", + org.apache.tuscany.sca.interfacedef;version="2.0.0", + org.apache.tuscany.sca.interfacedef.java;version="2.0.0", + org.apache.tuscany.sca.monitor;version="2.0.0", + org.apache.tuscany.sca.node;version="2.0.0", + org.apache.tuscany.sca.policy;version="2.0.0", + org.apache.tuscany.sca.runtime;version="2.0.0", + org.apache.tuscany.sca.workspace;version="2.0.0", + org.apache.tuscany.sca.workspace.builder;version="2.0.0", + org.apache.xml.serialize, + org.oasisopen.sca;version="2.0.0", + org.oasisopen.sca.annotation;version="2.0.0", + org.w3c.dom +Bundle-SymbolicName: org.apache.tuscany.sca.domain.manager +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/domain-manager/NOTICE b/java/sca/contrib/modules/domain-manager/NOTICE new file mode 100644 index 0000000000..25bb89c9b2 --- /dev/null +++ b/java/sca/contrib/modules/domain-manager/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/domain-manager/pom.xml b/java/sca/contrib/modules/domain-manager/pom.xml new file mode 100644 index 0000000000..2eec0d53be --- /dev/null +++ b/java/sca/contrib/modules/domain-manager/pom.xml @@ -0,0 +1,181 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + tuscany-domain-manager + Apache Tuscany SCA Domain Manager Application + + + + org.apache.tuscany.sca + tuscany-workspace + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-workspace-xml + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-implementation-node + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-implementation-node-runtime + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-binding-atom + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-workspace-impl + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-node-api + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-core + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-node-impl + 2.0-SNAPSHOT + runtime + + + + org.apache.tuscany.sca + tuscany-data-api + 2.0-SNAPSHOT + + + + commons-fileupload + commons-fileupload + 1.1.1 + + + + xerces + xercesImpl + 2.8.1 + + + + javax.servlet + servlet-api + 2.5 + + + + org.apache.tuscany.sca + tuscany-host-jetty + 2.0-SNAPSHOT + runtime + + + + org.apache.tuscany.sca + tuscany-node-manager + 2.0-SNAPSHOT + runtime + + + + org.apache.tuscany.sca + tuscany-contribution-xml + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-contribution-java + 2.0-SNAPSHOT + runtime + + + + org.apache.tuscany.sca + tuscany-contribution-namespace + 2.0-SNAPSHOT + runtime + + + + org.apache.tuscany.sca + tuscany-contribution-resource + 2.0-SNAPSHOT + runtime + + + + org.apache.tuscany.sca + tuscany-implementation-java-runtime + 2.0-SNAPSHOT + runtime + + + + org.apache.tuscany.sca + tuscany-implementation-widget-runtime + 2.0-SNAPSHOT + runtime + + + + org.apache.tuscany.sca + tuscany-binding-atom-abdera + 2.0-SNAPSHOT + runtime + + + + org.apache.tuscany.sca + tuscany-binding-http-runtime + 2.0-SNAPSHOT + runtime + + + + diff --git a/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/CompositeConfigurationCollectionImpl.java b/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/CompositeConfigurationCollectionImpl.java new file mode 100644 index 0000000000..65959645ae --- /dev/null +++ b/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/CompositeConfigurationCollectionImpl.java @@ -0,0 +1,127 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.domain.manager.impl; + +import static org.apache.tuscany.sca.domain.manager.impl.DomainManagerUtil.compositeQName; +import static org.apache.tuscany.sca.domain.manager.impl.DomainManagerUtil.compositeTitle; +import static org.apache.tuscany.sca.domain.manager.impl.DomainManagerUtil.contributionURI; + +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Logger; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.data.collection.Entry; +import org.apache.tuscany.sca.data.collection.Item; +import org.apache.tuscany.sca.data.collection.ItemCollection; +import org.apache.tuscany.sca.data.collection.LocalItemCollection; +import org.apache.tuscany.sca.data.collection.NotFoundException; +import org.oasisopen.sca.annotation.Init; +import org.oasisopen.sca.annotation.Reference; +import org.oasisopen.sca.annotation.Scope; +import org.oasisopen.sca.annotation.Service; + +/** + * Implementation of a component that returns composite configuration collections. + * + * @version $Rev$ $Date$ + */ +@Scope("COMPOSITE") +@Service(interfaces={ItemCollection.class, LocalItemCollection.class}) +public class CompositeConfigurationCollectionImpl implements ItemCollection, LocalItemCollection { + + private static final Logger logger = Logger.getLogger(CompositeConfigurationCollectionImpl.class.getName()); + + @Reference + public LocalItemCollection contributionCollection; + + @Reference + public LocalItemCollection cloudCollection; + + /** + * Initialize the component. + */ + @Init + public void initialize() { + } + + public Entry[] getAll() { + throw new UnsupportedOperationException(); + } + + public Item get(String key) throws NotFoundException { + throw new UnsupportedOperationException(); + } + + public String post(String key, Item item) { + throw new UnsupportedOperationException(); + } + + public void put(String key, Item item) throws NotFoundException { + throw new UnsupportedOperationException(); + } + + public void delete(String key) throws NotFoundException { + throw new UnsupportedOperationException(); + } + + public Entry[] query(String queryString) { + logger.fine("query " + queryString); + + if (queryString.startsWith("composite=")) { + + // Expecting a key in the form: + // composite:contributionURI;namespace;localName + int e = queryString.indexOf('='); + String key = queryString.substring(e + 1); + String contributionURI = contributionURI(key); + QName qname = compositeQName(key); + + // Return a collection containing the following entries: + // the resolved version of the specified composite + // the required contributions + List> entries = new ArrayList>(); + + // Add the resolved composite entry + Entry compositeEntry = new Entry(); + Item compositeItem = new Item(); + compositeItem.setTitle(compositeTitle(contributionURI, qname)); + compositeItem.setLink("/composite-resolved/" + key); + compositeEntry.setKey(key); + compositeEntry.setData(compositeItem); + entries.add(compositeEntry); + + // Get the collection of required contributions + Entry[] contributionEntries = contributionCollection.query("alldependencies=" + contributionURI); + for (Entry entry: contributionEntries) { + Item item = entry.getData(); + item.setContents(null); + entries.add(entry); + } + + return entries.toArray(new Entry[entries.size()]); + + } else { + throw new UnsupportedOperationException(); + } + } + +} diff --git a/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/CompositeConfigurationServiceImpl.java b/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/CompositeConfigurationServiceImpl.java new file mode 100644 index 0000000000..b4b9f5dc0f --- /dev/null +++ b/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/CompositeConfigurationServiceImpl.java @@ -0,0 +1,515 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.domain.manager.impl; + +import static org.apache.tuscany.sca.domain.manager.impl.DomainManagerUtil.compositeQName; +import static org.apache.tuscany.sca.domain.manager.impl.DomainManagerUtil.contributionURI; +import static org.apache.tuscany.sca.domain.manager.impl.DomainManagerUtil.locationURL; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URL; +import java.net.URLDecoder; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.logging.Logger; + +import javax.servlet.Servlet; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.xml.namespace.QName; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLOutputFactory; +import javax.xml.stream.XMLStreamWriter; + +import org.apache.tuscany.sca.assembly.AssemblyFactory; +import org.apache.tuscany.sca.assembly.Component; +import org.apache.tuscany.sca.assembly.Composite; +import org.apache.tuscany.sca.assembly.builder.CompositeBuilder; +import org.apache.tuscany.sca.assembly.builder.CompositeBuilderException; +import org.apache.tuscany.sca.assembly.builder.CompositeBuilderExtensionPoint; +import org.apache.tuscany.sca.assembly.xml.Constants; +import org.apache.tuscany.sca.contribution.Artifact; +import org.apache.tuscany.sca.contribution.Contribution; +import org.apache.tuscany.sca.contribution.processor.ContributionReadException; +import org.apache.tuscany.sca.contribution.processor.ContributionResolveException; +import org.apache.tuscany.sca.contribution.processor.ExtensibleStAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.ExtensibleURLArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessorExtensionPoint; +import org.apache.tuscany.sca.contribution.processor.URLArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.URLArtifactProcessorExtensionPoint; +import org.apache.tuscany.sca.contribution.resolver.ExtensibleModelResolver; +import org.apache.tuscany.sca.contribution.resolver.ModelResolverExtensionPoint; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.core.FactoryExtensionPoint; +import org.apache.tuscany.sca.core.UtilityExtensionPoint; +import org.apache.tuscany.sca.data.collection.Entry; +import org.apache.tuscany.sca.data.collection.Item; +import org.apache.tuscany.sca.data.collection.LocalItemCollection; +import org.apache.tuscany.sca.data.collection.NotFoundException; +import org.apache.tuscany.sca.implementation.node.NodeImplementation; +import org.apache.tuscany.sca.monitor.Monitor; +import org.apache.tuscany.sca.monitor.MonitorFactory; +import org.apache.tuscany.sca.workspace.Workspace; +import org.apache.tuscany.sca.workspace.WorkspaceFactory; +import org.apache.tuscany.sca.workspace.builder.ContributionBuilder; +import org.apache.tuscany.sca.workspace.builder.ContributionBuilderException; +import org.apache.tuscany.sca.workspace.builder.ContributionBuilderExtensionPoint; +import org.oasisopen.sca.annotation.Init; +import org.oasisopen.sca.annotation.Reference; +import org.oasisopen.sca.annotation.Scope; +import org.oasisopen.sca.annotation.Service; + +/** + * Implementation of a service that returns a fully configured composite. + * + * @version $Rev$ $Date$ + */ +@Scope("COMPOSITE") +@Service(Servlet.class) +public class CompositeConfigurationServiceImpl extends HttpServlet implements Servlet { + private static final long serialVersionUID = -8809641932774129152L; + + private static final Logger logger = Logger.getLogger(CompositeConfigurationServiceImpl.class.getName()); + + @Reference + public LocalItemCollection contributionCollection; + + @Reference + public LocalItemCollection domainCompositeCollection; + + @Reference + public DomainManagerConfiguration domainManagerConfiguration; + + @Reference + public LocalItemCollection cloudCollection; + + private FactoryExtensionPoint modelFactories; + private ModelResolverExtensionPoint modelResolvers; + private AssemblyFactory assemblyFactory; + private WorkspaceFactory workspaceFactory; + private URLArtifactProcessor contributionProcessor; + private StAXArtifactProcessorExtensionPoint staxProcessors; + private StAXArtifactProcessor compositeProcessor; + private XMLOutputFactory outputFactory; + private ContributionBuilder contributionDependencyBuilder; + private CompositeBuilder compositeBuilder; + private CompositeBuilder compositeIncludeBuilder; + private CompositeBuilder nodeConfigurationBuilder; + private Monitor monitor; + + /** + * Initialize the component. + */ + @Init + public void initialize() throws ParserConfigurationException { + + ExtensionPointRegistry extensionPoints = domainManagerConfiguration.getExtensionPoints(); + + // Create a monitor + UtilityExtensionPoint utilities = extensionPoints.getExtensionPoint(UtilityExtensionPoint.class); + MonitorFactory monitorFactory = utilities.getUtility(MonitorFactory.class); + monitor = monitorFactory.createMonitor(); + + // Get model factories + modelFactories = extensionPoints.getExtensionPoint(FactoryExtensionPoint.class); + assemblyFactory = modelFactories.getFactory(AssemblyFactory.class); + XMLInputFactory inputFactory = modelFactories.getFactory(XMLInputFactory.class); + outputFactory = modelFactories.getFactory(XMLOutputFactory.class); + outputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true); + workspaceFactory = modelFactories.getFactory(WorkspaceFactory.class); + + // Get and initialize artifact processors + staxProcessors = extensionPoints.getExtensionPoint(StAXArtifactProcessorExtensionPoint.class); + compositeProcessor = (StAXArtifactProcessor)staxProcessors.getProcessor(Composite.class); + StAXArtifactProcessor staxProcessor = new ExtensibleStAXArtifactProcessor(staxProcessors, inputFactory, outputFactory, monitor); + + URLArtifactProcessorExtensionPoint urlProcessors = extensionPoints.getExtensionPoint(URLArtifactProcessorExtensionPoint.class); + URLArtifactProcessor urlProcessor = new ExtensibleURLArtifactProcessor(urlProcessors, monitor); + + // Create contribution processor + modelResolvers = extensionPoints.getExtensionPoint(ModelResolverExtensionPoint.class); + // contributionProcessor = new ContributionContentProcessor(modelFactories, modelResolvers, urlProcessor, staxProcessor, monitor); + contributionProcessor = urlProcessors.getProcessor(Contribution.class); + + // Get a contribution dependency builder + ContributionBuilderExtensionPoint contributionBuilders = extensionPoints.getExtensionPoint(ContributionBuilderExtensionPoint.class); + contributionDependencyBuilder = contributionBuilders.getContributionBuilder("org.apache.tuscany.sca.workspace.builder.ContributionDependencyBuilder"); + + // Get composite builders + CompositeBuilderExtensionPoint compositeBuilders = extensionPoints.getExtensionPoint(CompositeBuilderExtensionPoint.class); + compositeBuilder = compositeBuilders.getCompositeBuilder("org.apache.tuscany.sca.assembly.builder.CompositeBuilder"); + nodeConfigurationBuilder = compositeBuilders.getCompositeBuilder("org.apache.tuscany.sca.implementation.node.builder.NodeCompositeBuilder"); + compositeIncludeBuilder = compositeBuilders.getCompositeBuilder("org.apache.tuscany.sca.assembly.builder.CompositeIncludeBuilder"); + nodeConfigurationBuilder = compositeBuilders.getCompositeBuilder("org.apache.tuscany.sca.implementation.node.builder.NodeCompositeBuilder"); + } + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + // Get the request path + String path = URLDecoder.decode(request.getRequestURI().substring(request.getServletPath().length()), "UTF-8"); + String key; + if (path.startsWith("/")) { + if (path.length() > 1) { + key = path.substring(1); + } else { + key =""; + } + } else { + key =path; + } + logger.fine("get " + key); + + // Expect a key in the form composite:contributionURI;namespace;localName or + // a path in the form componentName/componentName/... + // and return the corresponding resolved composite + String requestedContributionURI = null; + QName requestedCompositeName = null; + String[] requestedComponentPath = null; + if (key.startsWith("composite:")) { + + // Extract the composite qname from the key + requestedContributionURI = contributionURI(key); + requestedCompositeName = compositeQName(key); + + } else if (key.length() != 0) { + + // Extract the path to the requested component from the key + requestedComponentPath = key.split("/"); + } + + // Somewhere to store the composite we expect to write out at the end + Composite requestedComposite = null; + + // Create a domain composite model + Composite domainComposite = assemblyFactory.createComposite(); + domainComposite.setName(new QName(Constants.SCA10_TUSCANY_NS, "domain")); + + // Get the domain composite items + Entry[] domainEntries = domainCompositeCollection.getAll(); + + // Populate the domain composite + Workspace workspace = workspaceFactory.createWorkspace(); + workspace.setModelResolver(new ExtensibleModelResolver(workspace, modelResolvers, modelFactories)); + + Map contributionMap = new HashMap(); + for (Entry domainEntry: domainEntries) { + + // Load the required contributions + String contributionURI = contributionURI(domainEntry.getKey()); + Contribution contribution = contributionMap.get(contributionURI); + if (contribution == null) { + + // The contribution has not been loaded yet, load it with all its dependencies + Entry[] entries = contributionCollection.query("alldependencies=" + contributionURI); + for (Entry entry: entries) { + Item dependencyItem = entry.getData(); + String dependencyURI = entry.getKey(); + + if (!contributionMap.containsKey(dependencyURI)) { + + // Read the contribution + Contribution dependency; + try { + String dependencyLocation = dependencyItem.getAlternate(); + dependency = contribution(workspace, dependencyURI, dependencyLocation); + } catch (ContributionReadException e) { + continue; + } + workspace.getContributions().add(dependency); + contributionMap.put(dependencyURI, dependency); + + if (contributionURI.equals(entry.getKey())) { + contribution = dependency; + } + } + } + } + + if (contribution == null) { + response.sendError(HttpServletResponse.SC_NOT_FOUND, contributionURI); + return; + } + + // Find the specified deployable composite in the contribution + Composite deployable = null; + QName qn = compositeQName(domainEntry.getKey()); + for (Composite d: contribution.getDeployables()) { + if (qn.equals(d.getName())) { + deployable = d; + break; + } + } + if (deployable == null) { + response.sendError(HttpServletResponse.SC_NOT_FOUND, qn.toString()); + return; + } + + // add the deployable composite to the domain composite + domainComposite.getIncludes().add(deployable); + + // Fuse includes into the deployable composite + try { + compositeIncludeBuilder.build(deployable, null, monitor); + } catch (CompositeBuilderException e) { + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); + } + + // Store away the requested composite + if (requestedCompositeName != null) { + if (requestedContributionURI.equals(contributionURI) && requestedCompositeName.equals(deployable.getName())){ + requestedComposite = deployable; + } + } + } + + // The requested composite was not found + if (requestedCompositeName != null && requestedComposite == null) { + response.sendError(HttpServletResponse.SC_NOT_FOUND, key); + return; + } + + // Get the clouds composite + Composite cloudsComposite; + try { + cloudsComposite = cloud(); + } catch (NotFoundException e) { + response.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage()); + return; + } + + // configure the endpoints for each composite in the domain + List domainIncludes = domainComposite.getIncludes(); + for (int i = 0, n =domainIncludes.size(); i < n; i++) { + Composite composite = domainIncludes.get(i); + QName compositeName = composite.getName(); + String contributionURI = contributionURI(domainEntries[i].getKey()); + + // find the node that will run this composite and the default + // bindings that it configures + Component nodeComponent = null; + QName nodeCompositeName = null; + for (Composite cloudComposite : cloudsComposite.getIncludes()) { + for (Component nc : cloudComposite.getComponents()) { + NodeImplementation nodeImplementation = (NodeImplementation)nc.getImplementation(); + if (nodeImplementation.getComposite().getName().equals(compositeName) && + nodeImplementation.getComposite().getURI().equals(contributionURI)) { + nodeImplementation.setComposite(composite); + nodeComponent = nc; + nodeCompositeName = cloudComposite.getName(); + break; + } + } + } + + if (nodeComponent != null) { + try { + Composite nodeComposite = assemblyFactory.createComposite(); + nodeComposite.setName(nodeCompositeName); + nodeComposite.getComponents().add(nodeComponent); + nodeConfigurationBuilder.build(nodeComposite, null, monitor); + } catch (CompositeBuilderException e) { + throw new ServletException(e); + } + } + } + + // Build the domain composite + try { + compositeBuilder.build(domainComposite, null, monitor); + } catch (CompositeBuilderException e) { + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); + return; + } + + // Return the requested composite + if (requestedComposite != null) { + + // Rebuild the requested composite from the domain composite + // we have to reverse the flattening that went on when the domain + // composite was built + List tempComponentList = new ArrayList(); + tempComponentList.addAll(requestedComposite.getComponents()); + requestedComposite.getComponents().clear(); + for (Component inputComponent : tempComponentList){ + for (Component deployComponent : domainComposite.getComponents()){ + if (deployComponent.getName().equals(inputComponent.getName())){ + requestedComposite.getComponents().add(deployComponent); + } + } + } + + } else if (requestedComponentPath != null) { + + // If a component path was specified, walk the path to get to the requested + // component and the composite that implements it + Composite nestedComposite = domainComposite; + for (String componentName: requestedComponentPath) { + Component component = null; + for (Component c: nestedComposite.getComponents()) { + if (componentName.equals(c.getName())) { + component = c; + break; + } + } + if (component == null) { + response.sendError(HttpServletResponse.SC_NOT_FOUND, key); + return; + } else { + if (component.getImplementation() instanceof Composite) { + nestedComposite = (Composite)component.getImplementation(); + } else { + response.sendError(HttpServletResponse.SC_NOT_FOUND, key); + return; + } + } + } + + // Return the nested composite + requestedComposite = nestedComposite; + + } else { + + + // Return the whole domain composite + requestedComposite = domainComposite; + } + + // Write the composite in the requested format + StAXArtifactProcessor processor; + String queryString = request.getQueryString(); + if (queryString != null && queryString.startsWith("format=")) { + String format = queryString.substring(7); + int s = format.indexOf(';'); + QName formatName = new QName(format.substring(0, s), format.substring(s +1)); + processor = (StAXArtifactProcessor)staxProcessors.getProcessor(formatName); + if (processor == null) { + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, new IllegalArgumentException(queryString).toString()); + return; + } + } else { + processor = compositeProcessor; + } + try { + response.setContentType("text/xml"); + XMLStreamWriter writer = outputFactory.createXMLStreamWriter(response.getOutputStream()); + processor.write(requestedComposite, writer); + } catch (Exception e) { + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); + return; + } + + + } + + /** + * Returns the cloud composite. + * + * @return the cloud composite + */ + private Composite cloud() throws NotFoundException { + + // Create a new composite for the clouds + Composite cloudComposite = assemblyFactory.createComposite(); + cloudComposite.setName(new QName(Constants.SCA10_TUSCANY_NS, "cloud")); + + // Get the collection of cloud composites + Entry[] cloudEntries = cloudCollection.getAll(); + + // Load the cloud contributions + Workspace workspace = workspaceFactory.createWorkspace(); + Map contributionMap = new HashMap(); + for (Entry cloudEntry: cloudEntries) { + String key = cloudEntry.getKey(); + String contributionURI = contributionURI(key); + + // Load the contribution + Contribution contribution = contributionMap.get(contributionURI); + if (contribution == null) { + Item contributionItem = contributionCollection.get(contributionURI); + + // Read the contribution + try { + contribution = contribution(workspace, contributionURI, contributionItem.getAlternate()); + } catch (ContributionReadException e) { + continue; + } + workspace.getContributions().add(contribution); + contributionMap.put(contributionURI, contribution); + + } + + // Include the cloud composite in the clouds composite + QName qname = compositeQName(key); + for (Artifact artifact : contribution.getArtifacts()) { + if (artifact.getModel() instanceof Composite) { + Composite composite = (Composite)artifact.getModel(); + if (composite.getName().equals(qname)) { + cloudComposite.getIncludes().add(composite); + } + } + } + } + + return cloudComposite; + } + + /** + * Returns the contribution with the given URI. + * + * @param workspace + * @param contributionURI + * @param contributionLocation + * @return + * @throws NotFoundException + */ + private Contribution contribution(Workspace workspace, String contributionURI, String contributionLocation) throws ContributionReadException { + try { + URI uri = URI.create(contributionURI); + URL location = locationURL(contributionLocation); + Contribution contribution = (Contribution)contributionProcessor.read(null, uri, location); + + // Resolve the contribution dependencies + try { + contributionDependencyBuilder.build(contribution, workspace, monitor); + } catch (ContributionBuilderException e) { + } + + contributionProcessor.resolve(contribution, workspace.getModelResolver()); + return contribution; + + } catch (ContributionReadException e) { + throw e; + } catch (ContributionResolveException e) { + throw new ContributionReadException(e); + } catch (MalformedURLException e) { + throw new ContributionReadException(e); + } + } + +} diff --git a/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/CompositeGeneratorServiceImpl.java b/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/CompositeGeneratorServiceImpl.java new file mode 100644 index 0000000000..a4f8f1722b --- /dev/null +++ b/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/CompositeGeneratorServiceImpl.java @@ -0,0 +1,256 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.domain.manager.impl; + +import static org.apache.tuscany.sca.domain.manager.impl.DomainManagerUtil.compositeQName; +import static org.apache.tuscany.sca.domain.manager.impl.DomainManagerUtil.contributionURI; +import static org.apache.tuscany.sca.domain.manager.impl.DomainManagerUtil.lastModified; +import static org.apache.tuscany.sca.domain.manager.impl.DomainManagerUtil.locationURL; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URL; +import java.net.URLDecoder; +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Logger; + +import javax.servlet.Servlet; +import javax.servlet.ServletException; +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.xml.namespace.QName; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLOutputFactory; +import javax.xml.stream.XMLStreamException; + +import org.apache.tuscany.sca.assembly.Composite; +import org.apache.tuscany.sca.contribution.Contribution; +import org.apache.tuscany.sca.contribution.processor.ContributionReadException; +import org.apache.tuscany.sca.contribution.processor.ContributionResolveException; +import org.apache.tuscany.sca.contribution.processor.ContributionWriteException; +import org.apache.tuscany.sca.contribution.processor.ExtensibleStAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.ExtensibleURLArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessorExtensionPoint; +import org.apache.tuscany.sca.contribution.processor.URLArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.URLArtifactProcessorExtensionPoint; +import org.apache.tuscany.sca.contribution.resolver.DefaultModelResolver; +import org.apache.tuscany.sca.contribution.resolver.ModelResolverExtensionPoint; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.core.FactoryExtensionPoint; +import org.apache.tuscany.sca.core.UtilityExtensionPoint; +import org.apache.tuscany.sca.data.collection.Item; +import org.apache.tuscany.sca.data.collection.LocalItemCollection; +import org.apache.tuscany.sca.data.collection.NotFoundException; +import org.apache.tuscany.sca.domain.manager.impl.CompositeGeneratorServiceImpl.Cache.ContributionCache; +import org.apache.tuscany.sca.monitor.Monitor; +import org.apache.tuscany.sca.monitor.MonitorFactory; +import org.oasisopen.sca.annotation.Init; +import org.oasisopen.sca.annotation.Reference; +import org.oasisopen.sca.annotation.Scope; +import org.oasisopen.sca.annotation.Service; + +/** + * Implementation of a service that generates a composite from a composite model. + * + * @version $Rev$ $Date$ + */ +@Scope("COMPOSITE") +@Service(interfaces={Servlet.class}) +public class CompositeGeneratorServiceImpl extends HttpServlet implements Servlet { + private static final long serialVersionUID = -6531448326726908269L; + + private static final Logger logger = Logger.getLogger(CompositeGeneratorServiceImpl.class.getName()); + + @Reference + public LocalItemCollection contributionCollection; + + @Reference + public DomainManagerConfiguration domainManagerConfiguration; + + private FactoryExtensionPoint modelFactories; + private ModelResolverExtensionPoint modelResolvers; + private URLArtifactProcessor contributionProcessor; + private StAXArtifactProcessor compositeProcessor; + private XMLOutputFactory outputFactory; + + /** + * Cache contribution models. + */ + static class Cache { + static class ContributionCache { + private Contribution contribution; + private long contributionLastModified; + } + private Map contributions = new HashMap(); + } + + private Cache cache = new Cache(); + + /** + * Initialize the component. + */ + @Init + public void initialize() throws ParserConfigurationException { + + ExtensionPointRegistry extensionPoints = domainManagerConfiguration.getExtensionPoints(); + + // Create a monitor + UtilityExtensionPoint services = extensionPoints.getExtensionPoint(UtilityExtensionPoint.class); + MonitorFactory monitorFactory = services.getUtility(MonitorFactory.class); + Monitor monitor = monitorFactory.createMonitor(); + + // Get model factories + modelFactories = extensionPoints.getExtensionPoint(FactoryExtensionPoint.class); + XMLInputFactory inputFactory = modelFactories.getFactory(XMLInputFactory.class); + outputFactory = modelFactories.getFactory(XMLOutputFactory.class); + outputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true); + + // Get and initialize artifact processors + StAXArtifactProcessorExtensionPoint staxProcessors = extensionPoints.getExtensionPoint(StAXArtifactProcessorExtensionPoint.class); + compositeProcessor = (StAXArtifactProcessor)staxProcessors.getProcessor(Composite.class); + StAXArtifactProcessor staxProcessor = new ExtensibleStAXArtifactProcessor(staxProcessors, inputFactory, outputFactory, monitor); + + URLArtifactProcessorExtensionPoint urlProcessors = extensionPoints.getExtensionPoint(URLArtifactProcessorExtensionPoint.class); + URLArtifactProcessor urlProcessor = new ExtensibleURLArtifactProcessor(urlProcessors, monitor); + + // Create contribution processor + modelResolvers = extensionPoints.getExtensionPoint(ModelResolverExtensionPoint.class); + // contributionProcessor = new ContributionContentProcessor(modelFactories, modelResolvers, urlProcessor, staxProcessor, monitor); + contributionProcessor = urlProcessors.getProcessor(Contribution.class); + + } + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + // Expect a key in the form + // composite:contributionURI;namespace;localName + // and return the corresponding source file + + // Get the request path + String path = URLDecoder.decode(request.getRequestURI().substring(request.getServletPath().length()), "UTF-8"); + String key = path.startsWith("/")? path.substring(1) : path; + logger.fine("get " + key); + + // Get the specified contribution info + String contributionURI = contributionURI(key); + Item contributionItem; + try { + contributionItem = contributionCollection.get(contributionURI); + } catch (NotFoundException e) { + response.sendError(HttpServletResponse.SC_NOT_FOUND, key); + return; + } + + // Read the contribution + Contribution contribution; + try { + contribution = contribution(contributionURI, contributionItem.getAlternate()); + } catch (ContributionReadException e) { + response.sendError(HttpServletResponse.SC_NOT_FOUND, key); + return; + } + + // Find the specified deployable composite + QName qname = compositeQName(key); + Composite composite = null; + for (Composite deployable: contribution.getDeployables()) { + if (qname.equals(deployable.getName())) { + if (!deployable.isUnresolved()) { + composite = deployable; + } + break; + } + } + if (composite == null) { + response.sendError(HttpServletResponse.SC_NOT_FOUND, key); + return; + } + + // Write the composite + response.setContentType("text/xml"); + ServletOutputStream os = response.getOutputStream(); + try { + compositeProcessor.write(composite, outputFactory.createXMLStreamWriter(os)); + } catch (ContributionWriteException e) { + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); + return; + } catch (XMLStreamException e) { + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); + return; + } + os.flush(); + } + + /** + * Returns the contribution with the given URI. + * + * @param contributionURI + * @param contributionLocation + * @return + * @throws NotFoundException + */ + private Contribution contribution(String contributionURI, String contributionLocation) throws ContributionReadException { + try { + URI uri = URI.create(contributionURI); + URL location = locationURL(contributionLocation); + + // Get contribution from cache + ContributionCache contributionCache = cache.contributions.get(location); + long lastModified = lastModified(location); + if (contributionCache != null) { + if (contributionCache.contributionLastModified == lastModified) { + return contributionCache.contribution; + } + + // Reset contribution cache + cache.contributions.remove(location); + } + + Contribution contribution = (Contribution)contributionProcessor.read(null, uri, location); + + contributionProcessor.resolve(contribution, new DefaultModelResolver()); + + // Cache contribution + contributionCache = new ContributionCache(); + contributionCache.contribution = contribution; + contributionCache.contributionLastModified = lastModified; + cache.contributions.put(location, contributionCache); + + return contribution; + + } catch (ContributionReadException e) { + throw e; + } catch (MalformedURLException e) { + throw new ContributionReadException(e); + } catch (IOException e) { + throw new ContributionReadException(e); + } catch (ContributionResolveException e) { + throw new ContributionReadException(e); + } + } + +} diff --git a/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/ContributionCollectionImpl.java b/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/ContributionCollectionImpl.java new file mode 100644 index 0000000000..3cf10fc587 --- /dev/null +++ b/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/ContributionCollectionImpl.java @@ -0,0 +1,687 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.domain.manager.impl; + +import static javax.xml.stream.XMLStreamConstants.START_ELEMENT; +import static org.apache.tuscany.sca.domain.manager.impl.DomainManagerUtil.DEPLOYMENT_CONTRIBUTION_URI; +import static org.apache.tuscany.sca.domain.manager.impl.DomainManagerUtil.compositeSimpleTitle; +import static org.apache.tuscany.sca.domain.manager.impl.DomainManagerUtil.compositeSourceLink; +import static org.apache.tuscany.sca.domain.manager.impl.DomainManagerUtil.lastModified; +import static org.apache.tuscany.sca.domain.manager.impl.DomainManagerUtil.locationURL; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URL; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.logging.Logger; + +import javax.xml.namespace.QName; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLOutputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; + +import org.apache.tuscany.sca.assembly.Composite; +import org.apache.tuscany.sca.contribution.Contribution; +import org.apache.tuscany.sca.contribution.ContributionFactory; +import org.apache.tuscany.sca.contribution.DefaultExport; +import org.apache.tuscany.sca.contribution.DefaultImport; +import org.apache.tuscany.sca.contribution.Export; +import org.apache.tuscany.sca.contribution.Import; +import org.apache.tuscany.sca.contribution.processor.ContributionReadException; +import org.apache.tuscany.sca.contribution.processor.ExtensibleStAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessorExtensionPoint; +import org.apache.tuscany.sca.contribution.processor.URLArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.URLArtifactProcessorExtensionPoint; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.core.FactoryExtensionPoint; +import org.apache.tuscany.sca.core.UtilityExtensionPoint; +import org.apache.tuscany.sca.data.collection.Entry; +import org.apache.tuscany.sca.data.collection.Item; +import org.apache.tuscany.sca.data.collection.ItemCollection; +import org.apache.tuscany.sca.data.collection.LocalItemCollection; +import org.apache.tuscany.sca.data.collection.NotFoundException; +import org.apache.tuscany.sca.domain.manager.impl.ContributionCollectionImpl.Cache.ContributionCache; +import org.apache.tuscany.sca.monitor.Monitor; +import org.apache.tuscany.sca.monitor.MonitorFactory; +import org.apache.tuscany.sca.monitor.Problem; +import org.apache.tuscany.sca.monitor.Problem.Severity; +import org.apache.tuscany.sca.workspace.Workspace; +import org.apache.tuscany.sca.workspace.WorkspaceFactory; +import org.apache.tuscany.sca.workspace.builder.ContributionBuilder; +import org.apache.tuscany.sca.workspace.builder.ContributionBuilderException; +import org.apache.tuscany.sca.workspace.builder.ContributionBuilderExtensionPoint; +import org.apache.xml.serialize.OutputFormat; +import org.apache.xml.serialize.XMLSerializer; +import org.oasisopen.sca.ServiceRuntimeException; +import org.oasisopen.sca.annotation.Init; +import org.oasisopen.sca.annotation.Property; +import org.oasisopen.sca.annotation.Reference; +import org.oasisopen.sca.annotation.Scope; +import org.oasisopen.sca.annotation.Service; +import org.w3c.dom.Document; + +/** + * Implementation of a contribution collection service component. + * + * @version $Rev$ $Date$ + */ +@Scope("COMPOSITE") +@Service(interfaces={ItemCollection.class, LocalItemCollection.class}) +public class ContributionCollectionImpl implements ItemCollection, LocalItemCollection { + + private static final Logger logger = Logger.getLogger(ContributionCollectionImpl.class.getName()); + + @Property + public String workspaceFile; + + @Property + public String deploymentContributionDirectory; + + @Reference + public DomainManagerConfiguration domainManagerConfiguration; + + private Monitor monitor; + private ContributionFactory contributionFactory; + private WorkspaceFactory workspaceFactory; + private StAXArtifactProcessor staxProcessor; + private URLArtifactProcessor contributionProcessor; + private XMLInputFactory inputFactory; + private XMLOutputFactory outputFactory; + private DocumentBuilder documentBuilder; + private ContributionBuilder contributionDependencyBuilder; + + /** + * Cache workspace and contribution models. + */ + static class Cache { + private Workspace workspace; + private long workspaceLastModified; + + static class ContributionCache { + private Contribution contribution; + private long contributionLastModified; + } + private Map contributions = new HashMap(); + } + + private Cache cache = new Cache(); + + /** + * Initialize the component. + */ + @Init + public void initialize() throws ParserConfigurationException { + + ExtensionPointRegistry extensionPoints = domainManagerConfiguration.getExtensionPoints(); + + // Create a validation monitor + UtilityExtensionPoint utilities = extensionPoints.getExtensionPoint(UtilityExtensionPoint.class); + MonitorFactory monitorFactory = utilities.getUtility(MonitorFactory.class); + monitor = monitorFactory.createMonitor(); + + // Create model factories + FactoryExtensionPoint modelFactories = extensionPoints.getExtensionPoint(FactoryExtensionPoint.class); + outputFactory = modelFactories.getFactory(XMLOutputFactory.class); + outputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true); + contributionFactory = modelFactories.getFactory(ContributionFactory.class); + workspaceFactory = modelFactories.getFactory(WorkspaceFactory.class); + + // Create artifact processors + inputFactory = modelFactories.getFactory(XMLInputFactory.class); + StAXArtifactProcessorExtensionPoint staxProcessors = extensionPoints.getExtensionPoint(StAXArtifactProcessorExtensionPoint.class); + staxProcessor = new ExtensibleStAXArtifactProcessor(staxProcessors, inputFactory, outputFactory, monitor); + + URLArtifactProcessorExtensionPoint urlProcessors = extensionPoints.getExtensionPoint(URLArtifactProcessorExtensionPoint.class); + + // Create contribution info processor + contributionProcessor = urlProcessors.getProcessor(".contribution/info"); + + // Create a document builder (used to pretty print XML) + documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + + // Get contribution dependency builder + ContributionBuilderExtensionPoint contributionBuilders = extensionPoints.getExtensionPoint(ContributionBuilderExtensionPoint.class); + contributionDependencyBuilder = contributionBuilders.getContributionBuilder("org.apache.tuscany.sca.workspace.builder.ContributionDependencyBuilder"); + + } + + public Entry[] getAll() { + logger.fine("getAll"); + + // Return all the contributions + List> entries = new ArrayList>(); + Workspace workspace = readContributions(readWorkspace()); + + for (Contribution contribution: workspace.getContributions()) { + if (contribution.getURI().equals(DEPLOYMENT_CONTRIBUTION_URI)) { + continue; + } + entries.add(entry(workspace, contribution, contributionDependencyBuilder, monitor)); + } + return entries.toArray(new Entry[entries.size()]); + } + + public Item get(String key) throws NotFoundException { + logger.fine("get " + key); + + // Returns the contribution with the given URI key + Workspace workspace = readContributions(readWorkspace()); + for (Contribution contribution: workspace.getContributions()) { + if (key.equals(contribution.getURI())) { + return item(workspace, contribution, contributionDependencyBuilder, monitor); + } + } + throw new NotFoundException(key); + } + + public String post(String key, Item item) { + logger.fine("post " + key); + + // Adds a new contribution to the workspace + Workspace workspace = readWorkspace(); + Contribution contribution = contributionFactory.createContribution(); + contribution.setURI(key); + try { + contribution.setLocation(locationURL(item.getLink()).toString()); + } catch (MalformedURLException e) { + throw new ServiceRuntimeException(e); + } + workspace.getContributions().add(contribution); + + // Write the workspace + writeWorkspace(workspace); + + return key; + } + + public void put(String key, Item item) throws NotFoundException { + + // Update a contribution already in the workspace + Workspace workspace = readWorkspace(); + Contribution newContribution = contributionFactory.createContribution(); + newContribution.setURI(key); + try { + newContribution.setLocation(locationURL(item.getLink()).toString()); + } catch (MalformedURLException e) { + throw new ServiceRuntimeException(e); + } + List contributions = workspace.getContributions(); + for (int i = 0, n = contributions.size(); i < n; i++) { + if (contributions.get(i).getURI().equals(key)) { + contributions.set(i, newContribution); + + // Write the workspace + writeWorkspace(workspace); + return; + } + } + throw new NotFoundException(key); + } + + public void delete(String key) throws NotFoundException { + logger.fine("delete " + key); + + // Delete a contribution from the workspace + Workspace workspace = readWorkspace(); + List contributions = workspace.getContributions(); + for (int i = 0, n = contributions.size(); i < n; i++) { + if (contributions.get(i).getURI().equals(key)) { + contributions.remove(i); + + // Write the workspace + writeWorkspace(workspace); + return; + } + } + throw new NotFoundException(key); + } + + public Entry[] query(String queryString) { + logger.fine("query " + queryString); + + if (queryString.startsWith("dependencies=") || queryString.startsWith("alldependencies=")) { + + // Return the collection of dependencies of the specified contribution + List> entries = new ArrayList>(); + + // Extract the contribution URI + int eq = queryString.indexOf('='); + String key = queryString.substring(eq+1); + + // Read the metadata for all the contributions + Workspace workspace = readContributions(readWorkspace()); + + // Look for the specified contribution + for (Contribution contribution: workspace.getContributions()) { + if (key.equals(contribution.getURI())) { + + // Compute the contribution dependencies + try { + contributionDependencyBuilder.build(contribution, workspace, monitor); + } catch (ContributionBuilderException e) { + } + List dependencies = contribution.getDependencies(); + + // Returns entries for the dependencies + // optionally skip the specified contribution + boolean allDependencies = queryString.startsWith("alldependencies="); + for (Contribution dependency: dependencies) { + if (!allDependencies && dependency == contribution) { + // Skip the specified contribution + continue; + } + entries.add(entry(workspace, dependency, contributionDependencyBuilder, monitor)); + } + break; + } + } + + return entries.toArray(new Entry[entries.size()]); + + } if (queryString.startsWith("suggestions=true")) { + + // Returns a list of contribution suggestions, scan the parent of the workspace + // directory for potential contribution directories + + // For now, recognize project directories that contain .project files + // Directories containing .classpath files are likely to be Java projects, we parse + // the .classpath file to determine the Java project output location + Workspace suggestionWorkspace = workspaceFactory.createWorkspace(); + List entries = new ArrayList(); + String rootDirectory = domainManagerConfiguration.getRootDirectory(); + File rootLocation = new File(new File(rootDirectory).toURI().normalize()); + for (File project: rootLocation.getParentFile().listFiles()) { + File dotProject = new File(project, ".project"); + if (!dotProject.exists()) { + continue; + } + + // We have a potential contribution + String uri = project.getName(); + File location = project; + + // If this is a Java project, parse its .classpath file to determine it's output location + File dotClasspath = new File(project, ".classpath"); + if (dotClasspath.exists()) { + try { + XMLStreamReader reader = inputFactory.createXMLStreamReader(new FileInputStream(dotClasspath)); + reader.nextTag(); + while (reader.hasNext()) { + int event = reader.getEventType(); + if (event == START_ELEMENT) { + if ("classpathentry".equals(reader.getName().getLocalPart())) { + if ("output".equals(reader.getAttributeValue("", "kind"))) { + location = new File(project, reader.getAttributeValue("", "path")); + break; + } + } + } + if (reader.hasNext()) { + reader.next(); + } + } + } catch (FileNotFoundException e) { + } catch (XMLStreamException e) { + } + + } + + // Create a contribution entry, skip the domain root directory and childrens of the + // domain root directory + String rootLocationPath = rootLocation.getPath(); + if (rootLocationPath.indexOf('\\') != -1 || rootLocationPath.indexOf(' ') != -1) { + rootLocationPath = new File(rootLocationPath.replace('\\', '/')).toURI().toString(); + } + String locationPath = location.getPath(); + if (locationPath.indexOf('\\') != -1 || locationPath.indexOf(' ') != -1) { + locationPath = new File(locationPath.replace('\\', '/')).toURI().toString(); + } + if (!locationPath.startsWith(rootLocationPath + "/") && !locationPath.equals(rootLocationPath)) { + Contribution contribution = contributionFactory.createContribution(); + contribution.setURI(uri); + contribution.setLocation(locationPath); + entries.add(entry(suggestionWorkspace, contribution, contributionDependencyBuilder, monitor)); + } + } + + return entries.toArray(new Entry[entries.size()]); + + } else { + throw new UnsupportedOperationException(); + } + } + + /** + * Returns an entry representing a contribution + * @param contribution + * @return + */ + private static Entry entry(Workspace workspace, Contribution contribution, + ContributionBuilder contributionDependencyBuilder, Monitor monitor) { + Entry entry = new Entry(); + entry.setKey(contribution.getURI()); + entry.setData(item(workspace, contribution, contributionDependencyBuilder, monitor)); + return entry; + } + + /** + * Returns an item representing a contribution. + * + * @param workspace + * @param contribution + * @param monitor + * @return + */ + private static Item item(Workspace workspace, Contribution contribution, + ContributionBuilder contributionDependencyBuilder, final Monitor monitor) { + String contributionURI = contribution.getURI(); + Item item = new Item(); + item.setTitle(title(contributionURI)); + item.setLink(link(contributionURI)); + item.setAlternate(contribution.getLocation()); + + // List the contribution dependencies in the item contents + final List problems = new ArrayList(); + Monitor recordingMonitor = new Monitor() { + public void problem(Problem problem) { + problems.add(problem.getMessageId() + " " + problem.getProblemObject().toString()); + } + + public List getProblems() { + return null; + } + + public Problem getLastProblem() { + // TODO Auto-generated method stub + return null; + } + + public Problem createProblem(String sourceClassName, String bundleName, Severity severity, Object problemObject, String messageId, Exception cause) { + return monitor.createProblem(sourceClassName, bundleName, severity, problemObject, messageId, cause); + } + + public Problem createProblem(String sourceClassName, String bundleName, Severity severity, Object problemObject, String messageId, Object... messageParams) { + return monitor.createProblem(sourceClassName, bundleName, severity, problemObject, messageId, messageParams); + } + }; + + StringBuffer sb = new StringBuffer(); + try { + contributionDependencyBuilder.build(contribution, workspace, recordingMonitor); + } catch (ContributionBuilderException e) { + } + List dependencies = contribution.getDependencies(); + if (dependencies.size() > 1) { + sb.append("Dependencies: "); + for (int i = 0, n = dependencies.size(); i < n ; i++) { + if (i > 0) { + sb.append(" "); + } + Contribution dependency = dependencies.get(i); + if (dependency != contribution) { + String dependencyURI = dependency.getURI(); + sb.append("" + title(dependencyURI) + ""); + } + } + sb.append("
      "); + } + + // List the deployables + List deployables = contribution.getDeployables(); + if (!deployables.isEmpty()) { + sb.append("Deployables: "); + for (int i = 0, n = deployables.size(); i < n ; i++) { + if (i > 0) { + sb.append(" "); + } + Composite deployable = deployables.get(i); + QName qname = deployable.getName(); + sb.append("" + compositeSimpleTitle(contributionURI, qname) + ""); + } + sb.append("
      "); + } + + // List the dependency problems + if (contribution.isUnresolved()) { + problems.add("Contribution not found"); + } + if (problems.size() > 0) { + sb.append(""); + for (int i = 0, n = problems.size(); i < n ; i++) { + sb.append("Problem: "+ problems.get(i) + "
      "); + } + sb.append("
      "); + } + + // Store in the item contents + item.setContents(sb.toString()); + + return item; + } + + /** + * Returns a link to a contribution. + * @param contributionURI + * @return + */ + private static String link(String contributionURI) { + return "/contribution/" + contributionURI; + } + + /** + * Returns a title for the given contribution + * + * @param contributionURI + * @return + */ + private static String title(String contributionURI) { + return contributionURI; + } + + + /** + * Read the workspace. + * + * @return + */ + private Workspace readWorkspace() { + String rootDirectory = domainManagerConfiguration.getRootDirectory(); + + Workspace workspace; + File file = new File(rootDirectory + "/" + workspaceFile); + if (file.exists()) { + + // Get workspace from cache + if (cache.workspace != null && file.lastModified() == cache.workspaceLastModified) { + workspace = cache.workspace; + + } else { + + try { + FileInputStream is = new FileInputStream(file); + XMLStreamReader reader = inputFactory.createXMLStreamReader(is); + reader.nextTag(); + workspace = (Workspace)staxProcessor.read(reader); + } catch (Exception e) { + throw new ServiceRuntimeException(e); + } + + // Cache workspace + cache.workspaceLastModified = file.lastModified(); + cache.workspace = workspace; + } + + } else { + + // Create new workspace + workspace = workspaceFactory.createWorkspace(); + + // Cache workspace + cache.workspaceLastModified = 0; + cache.workspace = workspace; + } + + // Make sure that the workspace contains the cloud contribution + // The cloud contribution contains the composites describing the + // SCA nodes declared in the cloud + Contribution cloudContribution = null; + for (Contribution contribution: workspace.getContributions()) { + if (contribution.getURI().equals(DEPLOYMENT_CONTRIBUTION_URI)) { + cloudContribution = contribution; + } + } + if (cloudContribution == null) { + Contribution contribution = contributionFactory.createContribution(); + contribution.setURI(DEPLOYMENT_CONTRIBUTION_URI); + File cloudDirectory = new File(rootDirectory + "/" + deploymentContributionDirectory); + contribution.setLocation(cloudDirectory.toURI().toString()); + workspace.getContributions().add(contribution); + } + + return workspace; + } + + /** + * Write the workspace back to disk + * + * @param workspace + */ + private void writeWorkspace(Workspace workspace) { + try { + String rootDirectory = domainManagerConfiguration.getRootDirectory(); + + // First write to a byte stream + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + XMLStreamWriter writer = outputFactory.createXMLStreamWriter(bos); + staxProcessor.write(workspace, writer); + + // Parse again to pretty format the document + Document document = documentBuilder.parse(new ByteArrayInputStream(bos.toByteArray())); + OutputFormat format = new OutputFormat(); + format.setIndenting(true); + format.setIndent(2); + + // Write to workspace.xml + File file = new File(rootDirectory + "/" + workspaceFile); + FileOutputStream os = new FileOutputStream(file); + XMLSerializer serializer = new XMLSerializer(os, format); + serializer.serialize(document); + os.close(); + + // Cache workspace + cache.workspace = workspace; + cache.workspaceLastModified = file.lastModified(); + + } catch (Exception e) { + throw new ServiceRuntimeException(e); + } + } + + /** + * Returns a workspace populated with the contribution info read from + * the contributions. + * + * @param workspace + * @return + */ + private Workspace readContributions(Workspace workspace) { + + Workspace contributions = workspaceFactory.createWorkspace(); + try { + for (Contribution c: workspace.getContributions()) { + URI uri = URI.create(c.getURI()); + URL location = locationURL(c.getLocation()); + + // Get contribution from cache + ContributionCache contributionCache = cache.contributions.get(location); + long lastModified = lastModified(location); + if (contributionCache != null) { + if (contributionCache.contributionLastModified == lastModified) { + Contribution contribution = contributionCache.contribution; + contribution.setUnresolved(false); + contributions.getContributions().add(contribution); + continue; + } + + // Reset contribution cache + cache.contributions.remove(location); + } + + try { + Contribution contribution = (Contribution)contributionProcessor.read(null, uri, location); + contribution.setUnresolved(false); + contributions.getContributions().add(contribution); + + // Cache contribution + contributionCache = new ContributionCache(); + contributionCache.contribution = contribution; + contributionCache.contributionLastModified = lastModified; + cache.contributions.put(location, contributionCache); + + + // Make sure that the cloud contribution does not contain + // default imports/exports as we want to isolate it from application + // provided contributions + if (contribution.getURI().equals(DEPLOYMENT_CONTRIBUTION_URI)) { + for (Iterator i = contribution.getImports().iterator(); i.hasNext(); ) { + Import import_ = i.next(); + if (import_ instanceof DefaultImport) { + i.remove(); + } + } + for (Iterator i = contribution.getExports().iterator(); i.hasNext(); ) { + Export export = i.next(); + if (export instanceof DefaultExport) { + i.remove(); + } + } + } + + } catch (ContributionReadException e) { + Contribution contribution = contributionFactory.createContribution(); + contribution.setURI(c.getURI()); + contribution.setLocation(c.getLocation()); + contribution.setUnresolved(true); + contributions.getContributions().add(contribution); + } + } + } catch (Exception e) { + throw new ServiceRuntimeException(e); + } + return contributions; + } + +} diff --git a/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/ContributionServiceImpl.java b/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/ContributionServiceImpl.java new file mode 100644 index 0000000000..46652984b9 --- /dev/null +++ b/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/ContributionServiceImpl.java @@ -0,0 +1,77 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.domain.manager.impl; + +import java.io.IOException; +import java.net.URLDecoder; +import java.util.logging.Logger; + +import javax.servlet.Servlet; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.tuscany.sca.data.collection.Item; +import org.apache.tuscany.sca.data.collection.LocalItemCollection; +import org.apache.tuscany.sca.data.collection.NotFoundException; +import org.oasisopen.sca.annotation.Reference; +import org.oasisopen.sca.annotation.Scope; +import org.oasisopen.sca.annotation.Service; + +/** + * Implementation of a contribution collection service component. + * + * @version $Rev$ $Date$ + */ +@Scope("COMPOSITE") +@Service(interfaces={Servlet.class}) +public class ContributionServiceImpl extends HttpServlet implements Servlet { + private static final long serialVersionUID = -4759297945439322773L; + + private static final Logger logger = Logger.getLogger(ContributionServiceImpl.class.getName()); + + @Reference + public LocalItemCollection contributionCollection; + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + // Get the request path + String path = URLDecoder.decode(request.getRequestURI().substring(request.getServletPath().length()), "UTF-8"); + + // The key is the contribution URI + String key = path.startsWith("/")? path.substring(1) : path; + logger.fine("get " + key); + + // Get the item describing the composite + Item item; + try { + item = contributionCollection.get(key); + } catch (NotFoundException e) { + response.sendError(HttpServletResponse.SC_NOT_FOUND, key); + return; + } + + // Redirect to the actual contribution location + response.sendRedirect("/files/" + item.getAlternate()); + } + +} diff --git a/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/DeployableCompositeCollectionImpl.java b/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/DeployableCompositeCollectionImpl.java new file mode 100644 index 0000000000..58aab75855 --- /dev/null +++ b/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/DeployableCompositeCollectionImpl.java @@ -0,0 +1,404 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.domain.manager.impl; + +import static org.apache.tuscany.sca.domain.manager.impl.DomainManagerUtil.compositeAlternateLink; +import static org.apache.tuscany.sca.domain.manager.impl.DomainManagerUtil.compositeKey; +import static org.apache.tuscany.sca.domain.manager.impl.DomainManagerUtil.compositeQName; +import static org.apache.tuscany.sca.domain.manager.impl.DomainManagerUtil.compositeSourceLink; +import static org.apache.tuscany.sca.domain.manager.impl.DomainManagerUtil.compositeTitle; +import static org.apache.tuscany.sca.domain.manager.impl.DomainManagerUtil.contributionURI; +import static org.apache.tuscany.sca.domain.manager.impl.DomainManagerUtil.lastModified; +import static org.apache.tuscany.sca.domain.manager.impl.DomainManagerUtil.locationURL; + +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URL; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.logging.Logger; + +import javax.xml.namespace.QName; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLOutputFactory; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.assembly.Component; +import org.apache.tuscany.sca.assembly.ComponentService; +import org.apache.tuscany.sca.assembly.Composite; +import org.apache.tuscany.sca.contribution.Contribution; +import org.apache.tuscany.sca.contribution.processor.ContributionReadException; +import org.apache.tuscany.sca.contribution.processor.ContributionResolveException; +import org.apache.tuscany.sca.contribution.processor.ExtensibleStAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.ExtensibleURLArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessorExtensionPoint; +import org.apache.tuscany.sca.contribution.processor.URLArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.URLArtifactProcessorExtensionPoint; +import org.apache.tuscany.sca.contribution.resolver.DefaultModelResolver; +import org.apache.tuscany.sca.contribution.resolver.ModelResolverExtensionPoint; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.core.FactoryExtensionPoint; +import org.apache.tuscany.sca.core.UtilityExtensionPoint; +import org.apache.tuscany.sca.data.collection.Entry; +import org.apache.tuscany.sca.data.collection.Item; +import org.apache.tuscany.sca.data.collection.ItemCollection; +import org.apache.tuscany.sca.data.collection.LocalItemCollection; +import org.apache.tuscany.sca.data.collection.NotFoundException; +import org.apache.tuscany.sca.domain.manager.impl.DeployableCompositeCollectionImpl.Cache.ContributionCache; +import org.apache.tuscany.sca.implementation.node.NodeImplementation; +import org.apache.tuscany.sca.monitor.Monitor; +import org.apache.tuscany.sca.monitor.MonitorFactory; +import org.apache.tuscany.sca.workspace.builder.ContributionBuilder; +import org.apache.tuscany.sca.workspace.builder.ContributionBuilderExtensionPoint; +import org.oasisopen.sca.annotation.Init; +import org.oasisopen.sca.annotation.Reference; +import org.oasisopen.sca.annotation.Scope; +import org.oasisopen.sca.annotation.Service; + +/** + * Implementation of a deployable composite collection service. + * + * @version $Rev$ $Date$ + */ +@Scope("COMPOSITE") +@Service(interfaces={ItemCollection.class, LocalItemCollection.class}) +public class DeployableCompositeCollectionImpl implements ItemCollection, LocalItemCollection { + + private static final Logger logger = Logger.getLogger(DeployableCompositeCollectionImpl.class.getName()); + + @Reference + public LocalItemCollection contributionCollection; + + @Reference + public DomainManagerConfiguration domainManagerConfiguration; + + private FactoryExtensionPoint modelFactories; + private ModelResolverExtensionPoint modelResolvers; + private URLArtifactProcessor contributionProcessor; + private XMLOutputFactory outputFactory; + private ContributionBuilder contributionDependencyBuilder; + private Monitor monitor; + + /** + * Cache contribution models. + */ + static class Cache { + static class ContributionCache { + private Contribution contribution; + private long contributionLastModified; + } + private Map contributions = new HashMap(); + } + + private Cache cache = new Cache(); + + /** + * Initialize the component. + */ + @Init + public void initialize() throws ParserConfigurationException { + + ExtensionPointRegistry extensionPoints = domainManagerConfiguration.getExtensionPoints(); + + // Create a monitor + UtilityExtensionPoint utilities = extensionPoints.getExtensionPoint(UtilityExtensionPoint.class); + MonitorFactory monitorFactory = utilities.getUtility(MonitorFactory.class); + monitor = monitorFactory.createMonitor(); + + // Get model factories + modelFactories = extensionPoints.getExtensionPoint(FactoryExtensionPoint.class); + XMLInputFactory inputFactory = modelFactories.getFactory(XMLInputFactory.class); + outputFactory = modelFactories.getFactory(XMLOutputFactory.class); + outputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true); + + // Get and initialize artifact processors + StAXArtifactProcessorExtensionPoint staxProcessors = extensionPoints.getExtensionPoint(StAXArtifactProcessorExtensionPoint.class); + StAXArtifactProcessor staxProcessor = new ExtensibleStAXArtifactProcessor(staxProcessors, inputFactory, outputFactory, monitor); + + URLArtifactProcessorExtensionPoint urlProcessors = extensionPoints.getExtensionPoint(URLArtifactProcessorExtensionPoint.class); + URLArtifactProcessor urlProcessor = new ExtensibleURLArtifactProcessor(urlProcessors, monitor); + + // Create contribution processor + modelResolvers = extensionPoints.getExtensionPoint(ModelResolverExtensionPoint.class); + // contributionProcessor = new ContributionContentProcessor(modelFactories, modelResolvers, urlProcessor, staxProcessor, monitor); + contributionProcessor = urlProcessors.getProcessor(Contribution.class); + + // Get a contribution dependency builder + ContributionBuilderExtensionPoint contributionBuilders = extensionPoints.getExtensionPoint(ContributionBuilderExtensionPoint.class); + contributionDependencyBuilder = contributionBuilders.getContributionBuilder("org.apache.tuscany.sca.workspace.builder.ContributionDependencyBuilder"); + } + + public Entry[] getAll() { + logger.fine("getAll"); + + // Return all the deployable composites in the contributions + List> entries = new ArrayList>(); + + // Get the list of contributions in the workspace + Entry[] contributionEntries = contributionCollection.getAll(); + + // Read contribution metadata + for (Entry contributionEntry: contributionEntries) { + Item contributionItem = contributionEntry.getData(); + Contribution contribution; + try { + contribution = contribution(contributionEntry.getKey(), contributionItem.getAlternate()); + } catch (ContributionReadException e) { + continue; + } + + // Create entries for the deployable composites + for (Composite deployable: contribution.getDeployables()) { + entries.add(entry(contribution, deployable)); + } + + } + return entries.toArray(new Entry[entries.size()]); + } + + public Item get(String key) throws NotFoundException { + logger.fine("get " + key); + + // Get the specified contribution info + String contributionURI = contributionURI(key); + Item contributionItem = contributionCollection.get(contributionURI); + + // Read the contribution + Contribution contribution; + try { + contribution = contribution(contributionURI, contributionItem.getAlternate()); + } catch (ContributionReadException e) { + throw new NotFoundException(key); + } + + // Find the specified deployable composite + QName qname = compositeQName(key); + for (Composite deployable: contribution.getDeployables()) { + if (qname.equals(deployable.getName())) { + if (deployable.isUnresolved()) { + throw new NotFoundException(key); + } + + // Return an item describing the deployable composite + return item(contribution, deployable); + } + } + + throw new NotFoundException(key); + } + + public String post(String key, Item item) { + throw new UnsupportedOperationException(); + } + + public void put(String key, Item item) throws NotFoundException { + throw new UnsupportedOperationException(); + } + + public void delete(String key) throws NotFoundException { + throw new UnsupportedOperationException(); + } + + public Entry[] query(String queryString) { + logger.fine("query " + queryString); + + if (queryString.startsWith("contribution=")) { + + // Return all the deployable composites in the specified + // contribution + List> entries = new ArrayList>(); + + // Get the specified contribution info + String contributionURI = queryString.substring(queryString.indexOf('=') + 1); + Item contributionItem; + try { + contributionItem = contributionCollection.get(contributionURI); + } catch (NotFoundException e) { + return entries.toArray(new Entry[entries.size()]); + } + + // Read the contribution + Contribution contribution; + try { + contribution = contribution(contributionURI, contributionItem.getAlternate()); + } catch (ContributionReadException e) { + return entries.toArray(new Entry[entries.size()]); + } + + // Create entries for the deployable composites + for (Composite deployable: contribution.getDeployables()) { + entries.add(entry(contribution, deployable)); + } + + return entries.toArray(new Entry[entries.size()]); + + } else { + throw new UnsupportedOperationException(); + } + } + + /** + * Returns the contribution with the given URI. + * + * @param contributionURI + * @param contributionLocation + * @return + * @throws NotFoundException + */ + private Contribution contribution(String contributionURI, String contributionLocation) throws ContributionReadException { + try { + URI uri = URI.create(contributionURI); + URL location = locationURL(contributionLocation); + + // Get contribution from cache + ContributionCache contributionCache = cache.contributions.get(location); + long lastModified = lastModified(location); + if (contributionCache != null) { + if (contributionCache.contributionLastModified == lastModified) { + return contributionCache.contribution; + } + + // Reset contribution cache + cache.contributions.remove(location); + } + + Contribution contribution = (Contribution)contributionProcessor.read(null, uri, location); + + contributionProcessor.resolve(contribution, new DefaultModelResolver()); + + // Cache contribution + contributionCache = new ContributionCache(); + contributionCache.contribution = contribution; + contributionCache.contributionLastModified = lastModified; + cache.contributions.put(location, contributionCache); + + return contribution; + + } catch (ContributionReadException e) { + throw e; + } catch (MalformedURLException e) { + throw new ContributionReadException(e); + } catch (ContributionResolveException e) { + throw new ContributionReadException(e); + } catch (Throwable e) { + throw new ContributionReadException(e); + } + } + + /** + * Returns the entry contents describing a composite. + * + * @param composite + * @return + */ + private static String content(Composite composite) { + StringBuffer sb = new StringBuffer(); + List components = composite.getComponents(); + for (int i = 0, n = components.size(); i < n; i++) { + Component component = components.get(i); + if (component.getImplementation() instanceof NodeImplementation) { + List services = component.getServices(); + if (!services.isEmpty()) { + List bindings = services.get(0).getBindings(); + if (!bindings.isEmpty()) { + + // List node URIs + sb.append("Node URI: "); + sb.append(component.getServices().get(0).getBindings().get(0).getURI()); + break; + } + } + } else { + + // List component names + if (sb.length() == 0) { + sb.append("Components: "); + } else { + sb.append(" "); + } + sb.append(component.getName()); + } + } + if (sb.length() != 0) { + sb.append(""); + } + return sb.toString(); + } + + /** + * Returns the link to the resource related to a composite. + * + * @param composite + * @return + */ + private static String relatedLink(Composite composite) { + for (Component component: composite.getComponents()) { + if (component.getImplementation() instanceof NodeImplementation) { + NodeImplementation nodeImplementation = (NodeImplementation)component.getImplementation(); + Composite deployable = nodeImplementation.getComposite(); + String contributionURI = deployable.getURI(); + QName qname = deployable.getName(); + String key = compositeKey(contributionURI, qname); + return "/composite-source/" + key; + } + } + return null; + } + + /** + * Returns an entry describing the given deployable. + * + * @param contribution + * @param deployable + * @return + */ + private static Entry entry(Contribution contribution, Composite deployable) { + Entry entry = new Entry(); + entry.setKey(DomainManagerUtil.compositeKey(contribution.getURI(), deployable.getName())); + entry.setData(item(contribution, deployable)); + return entry; + } + + /** + * Returns an item describing the given deployable. + * + * @param contribution + * @param deployable + * @return + */ + private static Item item(Contribution contribution, Composite deployable) { + String contributionURI = contribution.getURI(); + String contributionLocation = contribution.getLocation(); + QName qname = deployable.getName(); + String deployableURI = deployable.getURI(); + Item item = new Item(); + item.setTitle(compositeTitle(contributionURI, qname)); + item.setContents(content(deployable)); + item.setLink(compositeSourceLink(contributionURI, qname)); + item.setAlternate(compositeAlternateLink(contributionLocation, deployableURI)); + item.setRelated(relatedLink(deployable)); + return item; + } + +} diff --git a/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/DeployableCompositeServiceImpl.java b/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/DeployableCompositeServiceImpl.java new file mode 100644 index 0000000000..d36bf77c96 --- /dev/null +++ b/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/DeployableCompositeServiceImpl.java @@ -0,0 +1,128 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.domain.manager.impl; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.net.URLConnection; +import java.net.URLDecoder; +import java.util.logging.Logger; + +import javax.servlet.Servlet; +import javax.servlet.ServletException; +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.xml.parsers.ParserConfigurationException; + +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.data.collection.Item; +import org.apache.tuscany.sca.data.collection.LocalItemCollection; +import org.apache.tuscany.sca.data.collection.NotFoundException; +import org.oasisopen.sca.annotation.Init; +import org.oasisopen.sca.annotation.Reference; +import org.oasisopen.sca.annotation.Scope; +import org.oasisopen.sca.annotation.Service; + +/** + * Implementation of a service that returns the source of a deployable composite. + * + * @version $Rev$ $Date$ + */ +@Scope("COMPOSITE") +@Service(Servlet.class) +public class DeployableCompositeServiceImpl extends HttpServlet implements Servlet { + private static final long serialVersionUID = -3477992129462720902L; + + private static final Logger logger = Logger.getLogger(DeployableCompositeServiceImpl.class.getName()); + + @Reference + public DomainManagerConfiguration domainManagerConfiguration; + + @Reference + public LocalItemCollection deployableCollection; + + /** + * Initialize the component. + */ + @Init + public void initialize() throws ParserConfigurationException { + + ExtensionPointRegistry extensionPoints = domainManagerConfiguration.getExtensionPoints(); + } + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + // Expect a key in the form + // composite:contributionURI;namespace;localName + // and return the corresponding source file + + // Get the request path + String path = URLDecoder.decode(request.getRequestURI().substring(request.getServletPath().length()), "UTF-8"); + String key = path.startsWith("/")? path.substring(1) : path; + logger.fine("get " + key); + + // Get the item describing the composite + Item item; + try { + item = deployableCollection.get(key); + } catch (NotFoundException e) { + response.sendError(HttpServletResponse.SC_NOT_FOUND, key); + return; + } + + // Redirect if there is no composite file + String uri = item.getAlternate(); + if (uri == null) { + response.sendRedirect("/composite-generated/" + key); + return; + } + + // Read the composite file and write to response + InputStream is; + try { + URLConnection connection = new URL(uri).openConnection(); + connection.setUseCaches(false); + connection.connect(); + is = connection.getInputStream(); + } catch (FileNotFoundException ex) { + response.sendError(HttpServletResponse.SC_NOT_FOUND, key); + return; + } + + response.setContentType("text/xml"); + ServletOutputStream os = response.getOutputStream(); + byte[] buffer = new byte[4096]; + for (;;) { + int n = is.read(buffer); + if (n < 0) { + break; + } + os.write(buffer, 0, n); + } + is.close(); + os.flush(); + } + +} diff --git a/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/DeployedCompositeCollectionImpl.java b/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/DeployedCompositeCollectionImpl.java new file mode 100644 index 0000000000..d4f882185c --- /dev/null +++ b/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/DeployedCompositeCollectionImpl.java @@ -0,0 +1,378 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.domain.manager.impl; + +import static org.apache.tuscany.sca.domain.manager.impl.DomainManagerUtil.DEPLOYMENT_CONTRIBUTION_URI; +import static org.apache.tuscany.sca.domain.manager.impl.DomainManagerUtil.compositeKey; +import static org.apache.tuscany.sca.domain.manager.impl.DomainManagerUtil.compositeQName; +import static org.apache.tuscany.sca.domain.manager.impl.DomainManagerUtil.compositeSourceLink; +import static org.apache.tuscany.sca.domain.manager.impl.DomainManagerUtil.compositeTitle; +import static org.apache.tuscany.sca.domain.manager.impl.DomainManagerUtil.contributionURI; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Logger; + +import javax.xml.namespace.QName; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLOutputFactory; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; + +import org.apache.tuscany.sca.assembly.AssemblyFactory; +import org.apache.tuscany.sca.assembly.Composite; +import org.apache.tuscany.sca.assembly.xml.Constants; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessorExtensionPoint; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.core.FactoryExtensionPoint; +import org.apache.tuscany.sca.data.collection.Entry; +import org.apache.tuscany.sca.data.collection.Item; +import org.apache.tuscany.sca.data.collection.ItemCollection; +import org.apache.tuscany.sca.data.collection.LocalItemCollection; +import org.apache.tuscany.sca.data.collection.NotFoundException; +import org.apache.xml.serialize.OutputFormat; +import org.apache.xml.serialize.XMLSerializer; +import org.oasisopen.sca.ServiceRuntimeException; +import org.oasisopen.sca.annotation.Init; +import org.oasisopen.sca.annotation.Property; +import org.oasisopen.sca.annotation.Reference; +import org.oasisopen.sca.annotation.Scope; +import org.oasisopen.sca.annotation.Service; +import org.w3c.dom.Document; + +/** + * Implementation of a composite collection service. + * + * @version $Rev$ $Date$ + */ +@Scope("COMPOSITE") +@Service(interfaces={ItemCollection.class,LocalItemCollection.class}) +public class DeployedCompositeCollectionImpl implements ItemCollection, LocalItemCollection { + private static final Logger logger = Logger.getLogger(DeployedCompositeCollectionImpl.class.getName()); + + @Property + public String compositeFile; + + @Property + public String deploymentContributionDirectory; + + @Reference + public LocalItemCollection deployableCollection; + + @Reference(required=false) + public LocalItemCollection processCollection; + + @Reference + public DomainManagerConfiguration domainManagerConfiguration; + + private FactoryExtensionPoint modelFactories; + private AssemblyFactory assemblyFactory; + private StAXArtifactProcessor compositeProcessor; + private XMLOutputFactory outputFactory; + private DocumentBuilder documentBuilder; + + /** + * Cache domain composite model. + */ + static class Cache { + private Composite compositeCollection; + private long compositeCollectionLastModified; + } + + private Cache cache = new Cache(); + + /** + * Initialize the component. + */ + @Init + public void initialize() throws ParserConfigurationException { + + // Create factories + ExtensionPointRegistry extensionPoints = domainManagerConfiguration.getExtensionPoints(); + modelFactories = extensionPoints.getExtensionPoint(FactoryExtensionPoint.class); + assemblyFactory = modelFactories.getFactory(AssemblyFactory.class); + outputFactory = modelFactories.getFactory(XMLOutputFactory.class); + outputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true); + + // Create composite processor + StAXArtifactProcessorExtensionPoint staxProcessors = extensionPoints.getExtensionPoint(StAXArtifactProcessorExtensionPoint.class); + compositeProcessor = staxProcessors.getProcessor(Composite.class); + + // Create a document builder (used to pretty print XML) + documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + } + + public Entry[] getAll() { + logger.fine("getAll"); + + // Return all the composites in the domain composite + List> entries = new ArrayList>(); + Composite compositeCollection = readCompositeCollection(); + for (Composite composite: compositeCollection.getIncludes()) { + String contributionURI = composite.getURI(); + QName qname = composite.getName(); + String key = compositeKey(contributionURI, qname); + Item item; + try { + item = deployableCollection.get(key); + } catch (NotFoundException e) { + item = new Item(); + item.setTitle(compositeTitle(contributionURI, qname)); + item.setLink(compositeSourceLink(contributionURI, qname)); + item.setContents("Problem: Composite not found"); + } + Entry entry = new Entry(); + entry.setKey(key); + entry.setData(item); + entries.add(entry); + } + return entries.toArray(new Entry[entries.size()]); + } + + public Item get(String key) throws NotFoundException { + logger.fine("get " + key); + + String contributionURI = contributionURI(key); + QName qname = compositeQName(key); + + // Look for the specified composite in the domain composite + List> entries = new ArrayList>(); + Composite compositeCollection = readCompositeCollection(); + for (Composite composite: compositeCollection.getIncludes()) { + if (contributionURI.equals(composite.getURI()) && qname.equals(composite.getName())) { + return deployableCollection.get(key); + } + } + throw new NotFoundException(key); + } + + public String post(String key, Item item) { + logger.fine("post " + key); + + String contributionURI = contributionURI(key); + QName qname = compositeQName(key); + + // Adds a new composite to the domain composite + Composite compositeCollection = readCompositeCollection(); + Composite composite = assemblyFactory.createComposite(); + composite.setName(qname); + composite.setURI(contributionURI); + composite.setUnresolved(true); + compositeCollection.getIncludes().add(composite); + + // Optionally, write the composite contents in a new composite file + // under the deployment composites directory, if that directory is + // configured on this component + if (deploymentContributionDirectory != null && item.getContents() != null) { + String rootDirectory = domainManagerConfiguration.getRootDirectory(); + + File directory = new File(rootDirectory + "/" + deploymentContributionDirectory); + if (!directory.exists()) { + directory.mkdirs(); + } + File file = new File(directory, qname.getLocalPart() + ".composite"); + try { + Writer w = new OutputStreamWriter(new FileOutputStream(file)); + w.write("\n"); + w.write(item.getContents()); + w.close(); + } catch (IOException e) { + throw new ServiceRuntimeException(e); + } + } + + // Write the composite collection + writeCompositeCollection(compositeCollection); + + return key; + } + + public void put(String key, Item item) throws NotFoundException { + logger.fine("put " + key); + + String contributionURI = contributionURI(key); + QName qname = compositeQName(key); + + // Update a composite already in the domain composite + Composite compositeCollection = readCompositeCollection(); + Composite newComposite = assemblyFactory.createComposite(); + newComposite.setName(qname); + newComposite.setURI(contributionURI); + newComposite.setUnresolved(true); + List composites = compositeCollection.getIncludes(); + for (int i = 0, n = composites.size(); i < n; i++) { + Composite composite = composites.get(i); + if (contributionURI.equals(composite.getURI()) && qname.equals(composite.getName())) { + composites.set(i, newComposite); + + // Write the domain composite + writeCompositeCollection(compositeCollection); + + return; + } + } + throw new NotFoundException(key); + } + + public void delete(String key) throws NotFoundException { + logger.fine("delete " + key); + + String contributionURI = contributionURI(key); + QName qname = compositeQName(key); + + // Delete/stop the corresponding process, if any + try { + processCollection.delete(qname.getLocalPart()); + } catch (Exception e) {} + + // Delete a composite from the composite collection + Composite compositeCollection = readCompositeCollection(); + List composites = compositeCollection.getIncludes(); + Composite deleted = null; + for (int i = 0, n = composites.size(); i < n; i++) { + Composite composite = composites.get(i); + if (contributionURI.equals(composite.getURI()) && qname.equals(composite.getName())) { + composites.remove(i); + deleted = composite; + + // Write the domain composite + writeCompositeCollection(compositeCollection); + break; + } + } + + // Delete the file too if it is in the deployment contribution directory + if (deploymentContributionDirectory != null && contributionURI.equals(DEPLOYMENT_CONTRIBUTION_URI)) { + String rootDirectory = domainManagerConfiguration.getRootDirectory(); + + File file = new File(rootDirectory + "/" + deploymentContributionDirectory, qname.getLocalPart() + ".composite"); + if (file.exists()) { + file.delete(); + } + } + + if (deleted == null) { + throw new NotFoundException(key); + } + } + + public Entry[] query(String queryString) { + throw new UnsupportedOperationException(); + } + + /** + * Reads the domain composite. + * + * @return the domain composite + * @throws ServiceRuntimeException + */ + private Composite readCompositeCollection() throws ServiceRuntimeException { + String rootDirectory = domainManagerConfiguration.getRootDirectory(); + + Composite compositeCollection; + File file = new File(rootDirectory + "/" + compositeFile); + if (file.exists()) { + + // Get composite collection from cache + if (cache.compositeCollection != null && file.lastModified() == cache.compositeCollectionLastModified) { + compositeCollection = cache.compositeCollection; + + } else { + + XMLInputFactory inputFactory = modelFactories.getFactory(XMLInputFactory.class); + try { + FileInputStream is = new FileInputStream(file); + XMLStreamReader reader = inputFactory.createXMLStreamReader(is); + compositeCollection = compositeProcessor.read(reader); + } catch (Exception e) { + throw new ServiceRuntimeException(e); + } + + // Cache composite collection + cache.compositeCollectionLastModified = file.lastModified(); + cache.compositeCollection = compositeCollection; + } + + } else { + compositeCollection = assemblyFactory.createComposite(); + String name; + int d = compositeFile.lastIndexOf('.'); + if (d != -1) { + name = compositeFile.substring(0, d); + } else { + name = compositeFile; + } + compositeCollection.setName(new QName(Constants.SCA10_TUSCANY_NS, name)); + + // Cache composite collection + cache.compositeCollectionLastModified = 0; + cache.compositeCollection = compositeCollection; + } + return compositeCollection; + } + + /** + * Write the domain composite back to disk. + * + * @param compositeCollection + */ + private void writeCompositeCollection(Composite compositeCollection) { + try { + String rootDirectory = domainManagerConfiguration.getRootDirectory(); + + // First write to a byte stream + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + XMLStreamWriter writer = outputFactory.createXMLStreamWriter(bos); + compositeProcessor.write(compositeCollection, writer); + + // Parse again to pretty format the document + Document document = documentBuilder.parse(new ByteArrayInputStream(bos.toByteArray())); + OutputFormat format = new OutputFormat(); + format.setIndenting(true); + format.setIndent(2); + + // Write to domain.composite + File file = new File(rootDirectory + "/" + compositeFile); + FileOutputStream os = new FileOutputStream(file); + XMLSerializer serializer = new XMLSerializer(os, format); + serializer.serialize(document); + + // Cache composite collection + cache.compositeCollection = compositeCollection; + cache.compositeCollectionLastModified = file.lastModified(); + + } catch (Exception e) { + throw new ServiceRuntimeException(e); + } + } + +} diff --git a/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/DomainManagerConfiguration.java b/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/DomainManagerConfiguration.java new file mode 100644 index 0000000000..1831728f07 --- /dev/null +++ b/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/DomainManagerConfiguration.java @@ -0,0 +1,53 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.domain.manager.impl; + +import org.apache.tuscany.sca.core.ExtensionPointRegistry; + +/** + * Domain manager configuration service interface. + * + * @version $Rev$ $Date$ + */ +public interface DomainManagerConfiguration { + + /** + * Sets the domain manager root directory. + * + * @param rootDirectory + */ + void setRootDirectory(String rootDirectory); + + /** + * Returns the domain manager root directory. + * + * @return the domain manager root directory + */ + String getRootDirectory(); + + /** + * Returns the extension point registry used in the + * domain manager. + * + * @return + */ + ExtensionPointRegistry getExtensionPoints(); + +} diff --git a/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/DomainManagerConfigurationImpl.java b/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/DomainManagerConfigurationImpl.java new file mode 100644 index 0000000000..21c7cd4383 --- /dev/null +++ b/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/DomainManagerConfigurationImpl.java @@ -0,0 +1,85 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.domain.manager.impl; + +import org.apache.tuscany.sca.core.DefaultExtensionPointRegistry; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.core.ModuleActivator; +import org.apache.tuscany.sca.core.ModuleActivatorExtensionPoint; +import org.oasisopen.sca.annotation.Destroy; +import org.oasisopen.sca.annotation.Init; +import org.oasisopen.sca.annotation.Scope; +import org.oasisopen.sca.annotation.Service; + +/** + * Implementation of a domain manager configuration component. + * + * @version $Rev$ $Date$ + */ +@Scope("COMPOSITE") +@Service(DomainManagerConfiguration.class) +public class DomainManagerConfigurationImpl implements DomainManagerConfiguration { + + private String rootDirectory = "."; + private ExtensionPointRegistry extensionPoints; + + @Init + public void initialize() { + + // Create extension point registry + extensionPoints = new DefaultExtensionPointRegistry(); + + // Initialize module activators + ModuleActivatorExtensionPoint moduleActivators = extensionPoints.getExtensionPoint(ModuleActivatorExtensionPoint.class); + for (ModuleActivator activator: moduleActivators.getModuleActivators()) { + try { + activator.start(extensionPoints); + } catch (Exception e) { + //FIXME fix the module activators that have cross module dependencies + // and currently fail when the whole runtime is not present + } + } + } + + @Destroy + public void destroy() { + ModuleActivatorExtensionPoint moduleActivators = extensionPoints.getExtensionPoint(ModuleActivatorExtensionPoint.class); + for (ModuleActivator activator: moduleActivators.getModuleActivators()) { + try { + activator.stop(extensionPoints); + } catch (Exception e) { + //FIXME fix the module activators that have cross module dependencies + // and currently fail when the whole runtime is not present + } + } + } + + public String getRootDirectory() { + return rootDirectory; + } + + public void setRootDirectory(String rootDirectory) { + this.rootDirectory = rootDirectory; + } + + public ExtensionPointRegistry getExtensionPoints() { + return extensionPoints; + } +} diff --git a/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/DomainManagerUtil.java b/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/DomainManagerUtil.java new file mode 100644 index 0000000000..644ebd86d0 --- /dev/null +++ b/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/DomainManagerUtil.java @@ -0,0 +1,296 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.domain.manager.impl; + +import java.io.File; +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.URLConnection; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.assembly.AssemblyFactory; +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.assembly.Composite; +import org.apache.tuscany.sca.core.assembly.CompositeActivator; +import org.apache.tuscany.sca.core.context.ServiceReferenceImpl; +import org.apache.tuscany.sca.core.invocation.ProxyFactory; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.interfacedef.java.JavaInterfaceFactory; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.oasisopen.sca.ServiceReference; +import org.oasisopen.sca.ServiceRuntimeException; + +/** + * Common functions and constants used by the admin components. + * + * @version $Rev$ $Date$ + */ +public final class DomainManagerUtil { + + static final String DEPLOYMENT_CONTRIBUTION_URI = "http://tuscany.apache.org/cloud"; + + /** + * Extracts a qname from a key expressed as contributionURI;namespace;localpart. + * @param key + * @return + */ + static QName compositeQName(String key) { + int i = key.indexOf(';'); + key = key.substring(i + 1); + i = key.indexOf(';'); + return new QName(key.substring(0, i), key.substring(i + 1)); + } + + /** + * Returns a composite title expressed as contributionURI - namespace;localpart. + * @param qname + * @return + */ + static String compositeTitle(String uri, QName qname) { + if (uri.equals(DEPLOYMENT_CONTRIBUTION_URI)) { + return qname.getLocalPart(); + } else { + return uri + " - " + qname.getNamespaceURI() + ";" + qname.getLocalPart(); + } + } + + /** + * Extracts a contribution uri from a key expressed as contributionURI;namespace;localpart. + * @param key + * @return + */ + static String contributionURI(String key) { + int i = key.indexOf(';'); + return key.substring("composite:".length(), i); + } + + /** + * Returns a composite key expressed as contributionURI;namespace;localpart. + * @param qname + * @return + */ + static String compositeKey(String uri, QName qname) { + return "composite:" + uri + ';' + qname.getNamespaceURI() + ';' + qname.getLocalPart(); + } + + /** + * Returns a link to the source of a composite + * @param contributionURI + * @param qname + * @return + */ + static String compositeSourceLink(String contributionURI, QName qname) { + return "/composite-source/" + compositeKey(contributionURI, qname); + } + + /** + * Returns a composite title expressed as contributionURI - namespace;localpart. + * @param qname + * @return + */ + static String compositeSimpleTitle(String uri, QName qname) { + if (uri.equals(DomainManagerUtil.DEPLOYMENT_CONTRIBUTION_URI)) { + return qname.getLocalPart(); + } else { + return qname.getNamespaceURI() + ";" + qname.getLocalPart(); + } + } + + /** + * Returns a URL from a location string. + * @param location + * @return + * @throws MalformedURLException + */ + static URL locationURL(String location) throws MalformedURLException { + String scheme = null; + URI uri = null; + + IllegalArgumentException uriException = null; + try { + uri = URI.create(location); + scheme = uri.getScheme(); + }catch (java.lang.IllegalArgumentException e) { + uriException = e; + } + + if (scheme == null) { + File file = new File(location); + return file.toURI().toURL(); + } else if (scheme.equals("file")) { + File file = new File(location.substring(5)); + return file.toURI().toURL(); + } else if(uri == null){ + throw uriException; + } else { + return uri.toURL(); + } + } + + /** + * Returns a link to a deployable composite. + * + * If the containing contribution is a local directory, return the URI of the local composite file + * inside the contribution. + * + * If the containing contribution is a local or remote file, return a URI of the form: + * jar: contribution URI !/ composite URI. + * + * @param contributionLocation + * @param deployableURI + * @return + */ + static String compositeAlternateLink(String contributionLocation, String deployableURI) { + if (deployableURI == null) { + return null; + } + URI u = URI.create(contributionLocation); + String uri; + if ("file".equals(u.getScheme())) { + String path = u.toString().substring(5); + File file = new File(path); + if (file.isDirectory()) { + if (contributionLocation.endsWith("/")) { + uri = contributionLocation + deployableURI; + } else { + uri = contributionLocation + "/" + deployableURI; + } + } else { + uri = contributionLocation + "!/" + deployableURI; + } + } else { + uri = contributionLocation + "!/" + deployableURI; + } + int e = uri.indexOf("!/"); + if (e != -1) { + int s = uri.lastIndexOf('/', e - 2) +1; + if (uri.substring(s, e).contains(".")) { + uri = "jar:" + uri; + } else { + uri = uri.substring(0, e) + uri.substring(e + 1); + } + } + return uri; + } + + /** + * Extract a node URI from an ATOM entry content. + * + * @param content + * @return + */ + static String nodeURI(String content) { + if (content != null) { + int bs = content.indexOf(""); + if (bs != -1) { + content = content.substring(bs + 19); + int es = content.indexOf(""); + if (es != -1) { + return content.substring(0, es); + } + } + } + return null; + } + + /** + * Create a new service reference dynamically. + * + * @param + * @param businessInterface + * @param binding + * @param assemblyFactory + * @param compositeActivator + * @return + */ + static ServiceReference dynamicReference(Class businessInterface, Binding binding, AssemblyFactory assemblyFactory, CompositeActivator compositeActivator) { + try { + + Composite composite = assemblyFactory.createComposite(); + composite.setName(new QName("http://tempuri.org", "default")); + RuntimeComponent component = (RuntimeComponent)assemblyFactory.createComponent(); + component.setName("default"); + component.setURI("default"); + compositeActivator.configureComponentContext(component); + composite.getComponents().add(component); + RuntimeComponentReference reference = (RuntimeComponentReference)assemblyFactory.createComponentReference(); + reference.setName("default"); + JavaInterfaceFactory javaInterfaceFactory = compositeActivator.getJavaInterfaceFactory(); + InterfaceContract interfaceContract = javaInterfaceFactory.createJavaInterfaceContract(); + interfaceContract.setInterface(javaInterfaceFactory.createJavaInterface(businessInterface)); + reference.setInterfaceContract(interfaceContract); + component.getReferences().add(reference); + reference.setComponent(component); + reference.getBindings().add(binding); + + ProxyFactory proxyFactory = compositeActivator.getProxyFactory(); + return new ServiceReferenceImpl(businessInterface, component, reference, binding, proxyFactory, compositeActivator); + + } catch (Exception e) { + throw new ServiceRuntimeException(e); + } + } + + /** + * Returns the last modified time of the content at the given URL. + * + * @param url + * @return + * @throws IOException + */ + static long lastModified(URL url) throws IOException { + + if (url.getProtocol() == null || "file".equals(url.getProtocol())) { + return lastModified(new File(url.getPath())); + } else { + URLConnection connection = url.openConnection(); + long lastModified = connection.getLastModified(); + return lastModified; + } + } + + /** + * Returns the last modified time of the given file or directory. + * + * @param file + * @return + */ + static long lastModified(File file) { + if (file.isDirectory()) { + long lastModified = file.lastModified(); + + for (File child: file.listFiles()) { + long m = lastModified(child); + if (m > lastModified) { + lastModified = m; + } + } + return lastModified; + + } else { + return file.lastModified(); + } + } +} diff --git a/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/FileCollectionImpl.java b/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/FileCollectionImpl.java new file mode 100644 index 0000000000..22eff61840 --- /dev/null +++ b/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/FileCollectionImpl.java @@ -0,0 +1,136 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.domain.manager.impl; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Logger; + +import org.apache.tuscany.sca.data.collection.Entry; +import org.apache.tuscany.sca.data.collection.Item; +import org.apache.tuscany.sca.data.collection.ItemCollection; +import org.apache.tuscany.sca.data.collection.NotFoundException; +import org.oasisopen.sca.annotation.Init; +import org.oasisopen.sca.annotation.Property; +import org.oasisopen.sca.annotation.Reference; +import org.oasisopen.sca.annotation.Scope; +import org.oasisopen.sca.annotation.Service; + +/** + * Implementation of a file collection service component. + * + * @version $Rev$ $Date$ + */ +@Scope("COMPOSITE") +@Service(ItemCollection.class) +public class FileCollectionImpl implements ItemCollection { + + private static final Logger logger = Logger.getLogger(FileCollectionImpl.class.getName()); + + @Property + public String directoryName; + + @Reference + public DomainManagerConfiguration domainManagerConfiguration; + + /** + * Initialize the component. + */ + @Init + public void initialize() throws IOException { + } + + public Entry[] getAll() { + logger.fine("getAll"); + + String rootDirectory = domainManagerConfiguration.getRootDirectory(); + + // Return all the files + List> entries = new ArrayList>(); + File directory = new File(rootDirectory + "/" + directoryName); + if (directory.exists()) { + for (File file: directory.listFiles()) { + if (file.getName().startsWith(".")) { + continue; + } + entries.add(entry(file.getName())); + } + } + return entries.toArray(new Entry[entries.size()]); + } + + public Item get(String key) throws NotFoundException { + logger.fine("get " + key); + return item(key); + } + + public String post(String key, Item item) { + throw new UnsupportedOperationException(); + } + + public void put(String key, Item item) throws NotFoundException { + throw new UnsupportedOperationException(); + } + + public void delete(String key) throws NotFoundException { + logger.fine("delete " + key); + + String rootDirectory = domainManagerConfiguration.getRootDirectory(); + File directory = new File(rootDirectory + "/" + directoryName); + File file = new File(directory, key); + if (file.exists()) { + file.delete(); + } else { + throw new NotFoundException(key); + } + } + + public Entry[] query(String queryString) { + throw new UnsupportedOperationException(); + } + + /** + * Returns an entry representing a file. + * + * @param fileName + * @return + */ + private static Entry entry(String fileName) { + Entry entry = new Entry(); + entry.setKey(fileName); + entry.setData(item(fileName)); + return entry; + } + + /** + * Returns an item representing a file. + * + * @param fileName + * @return + */ + private static Item item(String fileName) { + Item item = new Item(); + item.setTitle(fileName); + item.setLink("/files/" + fileName); + return item; + } +} diff --git a/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/FileServiceImpl.java b/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/FileServiceImpl.java new file mode 100644 index 0000000000..7881217436 --- /dev/null +++ b/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/FileServiceImpl.java @@ -0,0 +1,153 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.domain.manager.impl; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.net.URLConnection; +import java.net.URLDecoder; +import java.util.List; +import java.util.logging.Logger; + +import javax.servlet.Servlet; +import javax.servlet.ServletException; +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.fileupload.FileItem; +import org.apache.commons.fileupload.disk.DiskFileItemFactory; +import org.apache.commons.fileupload.servlet.ServletFileUpload; +import org.oasisopen.sca.annotation.Init; +import org.oasisopen.sca.annotation.Property; +import org.oasisopen.sca.annotation.Reference; +import org.oasisopen.sca.annotation.Scope; +import org.oasisopen.sca.annotation.Service; + +/** + * Implementation of a servlet component supporting file upload/download. + * + * @version $Rev$ $Date$ + */ +@Scope("COMPOSITE") +@Service(Servlet.class) +public class FileServiceImpl extends HttpServlet { + private static final long serialVersionUID = -4560385595481971616L; + + private static final Logger logger = Logger.getLogger(FileServiceImpl.class.getName()); + + @Property + public String directoryName; + + @Reference + public DomainManagerConfiguration domainManagerConfiguration; + + private ServletFileUpload upload; + + /** + * Initialize the component. + */ + @Init + public void initialize() throws IOException { + upload = new ServletFileUpload(new DiskFileItemFactory()); + } + + @Override + public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { + + // Upload files + String rootDirectory = domainManagerConfiguration.getRootDirectory(); + try { + for (FileItem item: (List)upload.parseRequest(request)) { + if (!item.isFormField()) { + File directory = new File(rootDirectory + "/" + directoryName); + if (!directory.exists()) { + directory.mkdirs(); + } + logger.fine("post " + item.getName()); + item.write(new File(directory, item.getName())); + } + } + + // Redirect to the admin page + response.sendRedirect("/ui/files"); + } + catch (Exception e) { + throw new IOException(e.toString()); + } + } + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + // Download a file + String requestURI = URLDecoder.decode(request.getRequestURI(), "UTF-8"); + String path = requestURI.substring(request.getServletPath().length()); + if (path.startsWith("/")) { + path = path.substring(1); + } + logger.fine("get " + path); + + try { + + // Analyze the given path + URI uri = URI.create(path); + String scheme = uri.getScheme(); + if (scheme == null) { + + // If no scheme is specified then the path identifies file + // inside our directory + String rootDirectory = domainManagerConfiguration.getRootDirectory(); + uri = new File(rootDirectory + "/" + directoryName, path).toURI(); + + } else if (!scheme.equals("file")) { + + // If the scheme does not identify a local file, just redirect to the server + // hosting the file + response.sendRedirect(path); + } + + // Read the file and write to response + URLConnection connection = uri.toURL().openConnection(); + connection.setUseCaches(false); + connection.connect(); + InputStream is = connection.getInputStream(); + ServletOutputStream os = response.getOutputStream(); + byte[] buffer = new byte[4096]; + for (;;) { + int n = is.read(buffer); + if (n < 0) { + break; + } + os.write(buffer, 0, n); + } + is.close(); + os.flush(); + + } catch (FileNotFoundException e) { + response.sendError(HttpServletResponse.SC_NOT_FOUND); + } + } + +} diff --git a/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/NodeConfigurationServiceImpl.java b/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/NodeConfigurationServiceImpl.java new file mode 100644 index 0000000000..695f25f480 --- /dev/null +++ b/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/NodeConfigurationServiceImpl.java @@ -0,0 +1,96 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.domain.manager.impl; + +import static org.apache.tuscany.sca.domain.manager.impl.DomainManagerUtil.compositeQName; + +import java.io.IOException; +import java.net.URLDecoder; +import java.util.logging.Logger; + +import javax.servlet.Servlet; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.data.collection.Entry; +import org.apache.tuscany.sca.data.collection.Item; +import org.apache.tuscany.sca.data.collection.LocalItemCollection; +import org.oasisopen.sca.annotation.Reference; +import org.oasisopen.sca.annotation.Scope; +import org.oasisopen.sca.annotation.Service; + +/** + * Implementation of a service that returns a node configuration. + * + * @version $Rev$ $Date$ + */ +@Scope("COMPOSITE") +@Service(Servlet.class) +public class NodeConfigurationServiceImpl extends HttpServlet implements Servlet { + private static final long serialVersionUID = 6913769467386954463L; + + private static final Logger logger = Logger.getLogger(NodeConfigurationServiceImpl.class.getName()); + + @Reference + public LocalItemCollection contributionCollection; + + @Reference + public LocalItemCollection cloudCollection; + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + // Get the request path + String path = URLDecoder.decode(request.getRequestURI().substring(request.getServletPath().length()), "UTF-8"); + String key = path.startsWith("/")? path.substring(1) : path; + logger.fine("get " + key); + + // The key contains a node name, redirect + // to the corresponding composite config + + // Get the collection of cloud composites + Entry[] cloudEntries = cloudCollection.getAll(); + + // Find the specified node + for (Entry cloudEntry: cloudEntries) { + QName qname = compositeQName(cloudEntry.getKey()); + if (qname.getLocalPart().equals(key)) { + + // Found the specified node + String related = cloudEntry.getData().getRelated(); + int i = related.indexOf("composite:"); + if (i != -1) { + + // Redirect to its composite config + String compositeConfiguration = "/composite-config/?composite=" + related.substring(i); + response.sendRedirect(compositeConfiguration); + return; + } + } + } + + // Node not found + response.sendError(HttpServletResponse.SC_NOT_FOUND, key); + return; + } +} diff --git a/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/NodeProcessCollectionFacadeImpl.java b/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/NodeProcessCollectionFacadeImpl.java new file mode 100644 index 0000000000..9ab86ec2fc --- /dev/null +++ b/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/NodeProcessCollectionFacadeImpl.java @@ -0,0 +1,251 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.domain.manager.impl; + +import static org.apache.tuscany.sca.domain.manager.impl.DomainManagerUtil.compositeQName; +import static org.apache.tuscany.sca.domain.manager.impl.DomainManagerUtil.nodeURI; + +import java.net.URI; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Logger; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.assembly.AssemblyFactory; +import org.apache.tuscany.sca.binding.atom.AtomBindingFactory; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.core.FactoryExtensionPoint; +import org.apache.tuscany.sca.core.assembly.CompositeActivator; +import org.apache.tuscany.sca.data.collection.Entry; +import org.apache.tuscany.sca.data.collection.Item; +import org.apache.tuscany.sca.data.collection.ItemCollection; +import org.apache.tuscany.sca.data.collection.LocalItemCollection; +import org.apache.tuscany.sca.data.collection.NotFoundException; +import org.oasisopen.sca.ServiceRuntimeException; +import org.oasisopen.sca.annotation.Init; +import org.oasisopen.sca.annotation.Reference; +import org.oasisopen.sca.annotation.Scope; +import org.oasisopen.sca.annotation.Service; + +/** + * Implementation of a node process collection service. + * + * @version $Rev$ $Date$ + */ +@Scope("COMPOSITE") +@Service(interfaces={ItemCollection.class, LocalItemCollection.class}) +public class NodeProcessCollectionFacadeImpl implements ItemCollection, LocalItemCollection { + + private static final Logger logger = Logger.getLogger(NodeProcessCollectionFacadeImpl.class.getName()); + + @Reference + public LocalItemCollection cloudCollection; + + @Reference + public ItemCollection processCollection; + + @Reference + public DomainManagerConfiguration domainManagerConfiguration; + + private AssemblyFactory assemblyFactory; + private AtomBindingFactory atomBindingFactory; + private CompositeActivator compositeActivator; + + /** + * Initialize the component. + */ + @Init + public void initialize() { + + // Get its composite activator + //FIXME + //compositeActivator = runtime.getCompositeActivator(); + + // Get the model factories + ExtensionPointRegistry extensionPoints = domainManagerConfiguration.getExtensionPoints(); + FactoryExtensionPoint modelFactories = extensionPoints.getExtensionPoint(FactoryExtensionPoint.class); + assemblyFactory = modelFactories.getFactory(AssemblyFactory.class); + atomBindingFactory = modelFactories.getFactory(AtomBindingFactory.class); + } + + public Entry[] getAll() { + logger.fine("getAll"); + + // Get the collection of nodes + Entry[] nodeEntries = cloudCollection.getAll(); + + // Dispatch to the hosts hosting these nodes + List> entries = new ArrayList>(); + for (String host: hosts(nodeEntries)) { + ItemCollection processCollection = processCollection(host); + for (Entry remoteEntry: processCollection.getAll()) { + entries.add(remoteEntry); + } + break; + } + + return entries.toArray(new Entry[entries.size()]); + } + + public Item get(String key) throws NotFoundException { + logger.fine("get " + key); + + // Get the host hosting the given node + String host = host(key); + + // Dispatch the request to that host + ItemCollection processCollection = processCollection(host); + return processCollection.get(key); + } + + public String post(String key, Item item) { + logger.fine("post " + key); + + // Get the host hosting the given node + String host; + try { + host = host(key); + } catch (NotFoundException e) { + throw new ServiceRuntimeException(e); + } + + // Dispatch the request to that host + ItemCollection processCollection = processCollection(host); + return processCollection.post(key, item); + } + + public void put(String key, Item item) throws NotFoundException { + throw new UnsupportedOperationException(); + } + + public void delete(String key) throws NotFoundException { + logger.fine("delete " + key); + + // Get the host hosting the given node + String host = host(key); + + // Dispatch the request to that host + ItemCollection processCollection = processCollection(host); + processCollection.delete(key); + } + + public Entry[] query(String queryString) { + logger.fine("query " + queryString); + + if (queryString.startsWith("node=")) { + String key = queryString.substring(queryString.indexOf('=') + 1); + + // Get the host hosting the given node + String host; + try { + host = host(key); + } catch (NotFoundException e) { + return new Entry[0]; + } + + // Dispatch the request to that host + ItemCollection processCollection = processCollection(host); + return processCollection.query(queryString); + + } else { + throw new UnsupportedOperationException(); + } + } + + private String host(String nodeName) throws NotFoundException { + + // Get the entry representing the given node + Entry nodeEntry = nodeEntry(cloudCollection.getAll(), nodeName); + if (nodeEntry == null) { + throw new NotFoundException(nodeName); + } + + // Get the host hosting it + return host(nodeEntry.getData()); + } + + /** + * Returns the entry representing the given node. + * + * @param entries + * @param name + * @return + */ + private static Entry nodeEntry(Entry[] entries, String name) { + for (Entry entry: entries) { + QName qname = compositeQName(entry.getKey()); + if (qname.getLocalPart().equals(name)) { + return entry; + } + } + return null; + } + + /** + * Returns the lists of hosts hosting the nodes in the given entries. + * + * @param entries + * @return + */ + private static List hosts(Entry[] entries) { + List hosts = new ArrayList(); + for (Entry entry: entries) { + String host = host(entry.getData()); + if (!hosts.contains(host)) { + hosts.add(host); + } + } + return hosts; + } + + /** + * Returns the host of the node represented by the given item. + * + * @param item + * @return + */ + private static String host(Item item) { + String uri = nodeURI(item.getContents()); + if (uri != null) { + return URI.create(uri).getHost(); + } else { + return null; + } + } + + /** + * Returns a proxy to the process collection service on the specified + * host. + * + * @param host + * @return + */ + private ItemCollection processCollection(String host) { + return processCollection; + +//FIXME +// AtomBinding binding = atomBindingFactory.createAtomBinding(); +// binding.setURI("http://" + host + ":9990/node/processes"); +// ServiceReference reference = dynamicReference(ItemCollection.class, binding, assemblyFactory, compositeActivator); +// return reference.getService(); + } + +} diff --git a/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/QuickStartServiceImpl.java b/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/QuickStartServiceImpl.java new file mode 100644 index 0000000000..f7ae597c52 --- /dev/null +++ b/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/impl/QuickStartServiceImpl.java @@ -0,0 +1,236 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.domain.manager.impl; + +import static org.apache.tuscany.sca.domain.manager.impl.DomainManagerUtil.compositeKey; +import static org.apache.tuscany.sca.domain.manager.impl.DomainManagerUtil.compositeQName; +import static org.apache.tuscany.sca.domain.manager.impl.DomainManagerUtil.contributionURI; +import static org.apache.tuscany.sca.domain.manager.impl.DomainManagerUtil.nodeURI; + +import java.io.IOException; +import java.net.URI; +import java.net.URLDecoder; +import java.util.HashSet; +import java.util.Set; +import java.util.logging.Level; +import java.util.logging.Logger; + +import javax.servlet.Servlet; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.xml.namespace.QName; +import javax.xml.parsers.ParserConfigurationException; + +import org.apache.tuscany.sca.data.collection.Entry; +import org.apache.tuscany.sca.data.collection.Item; +import org.apache.tuscany.sca.data.collection.LocalItemCollection; +import org.apache.tuscany.sca.data.collection.NotFoundException; +import org.oasisopen.sca.annotation.Init; +import org.oasisopen.sca.annotation.Reference; +import org.oasisopen.sca.annotation.Scope; +import org.oasisopen.sca.annotation.Service; + +/** + * Implementation of a component that provides a quick start path for a + * composite in a contribution. + * + * @version $Rev$ $Date$ + */ +@Scope("COMPOSITE") +@Service(interfaces={Servlet.class}) +public class QuickStartServiceImpl extends HttpServlet { + private static final long serialVersionUID = -3477992129462720901L; + + private static final Logger logger = Logger.getLogger(QuickStartServiceImpl.class.getName()); + + @Reference + public LocalItemCollection contributionCollection; + + @Reference + public LocalItemCollection deployableCollection; + + @Reference + public LocalItemCollection domainCompositeCollection; + + @Reference + public LocalItemCollection cloudCollection; + + @Reference + public LocalItemCollection processCollection; + + /** + * Initialize the component. + */ + @Init + public void initialize() throws ParserConfigurationException { + } + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + try { + + // Get the request path + String path = URLDecoder.decode(request.getRequestURI().substring(request.getServletPath().length()), "UTF-8"); + if (path.startsWith("/")) { + path = path.substring(1); + } + + // Get the request parameters + String contributionURI = request.getParameter("contribution"); + String contributionLocation = request.getParameter("location"); + String compositeURI = request.getParameter("composite"); + String start = request.getParameter("start"); + + logger.fine("Composite Quick Start."); + logger.fine("Contribution URI: " + contributionURI); + logger.fine("Contribution location: " + contributionLocation); + logger.fine("Composite URI: " + compositeURI); + + // Look for the contribution in the workspace + Entry[] contributionEntries = contributionCollection.getAll(); + Entry contributionEntry = null; + for (Entry entry: contributionEntries) { + if (contributionURI.equals(entry.getKey())) { + contributionEntry = entry; + break; + } + } + + // Add the contribution if necessary + if (contributionEntry == null) { + Item item = new Item(); + item.setLink(contributionLocation); + contributionCollection.post(contributionURI, item); + } + + // Look for the specified deployable composite in the contribution + String compositeKey = null; + Entry[] deployableEntries = deployableCollection.query("contribution=" + contributionURI); + for (Entry entry: deployableEntries) { + Item item = entry.getData(); + if (contributionURI.equals(contributionURI(entry.getKey())) && item.getAlternate().endsWith(compositeURI)) { + compositeKey = entry.getKey(); + break; + } + } + + if (compositeKey == null) { + response.sendError(HttpServletResponse.SC_NOT_FOUND, compositeURI); + return; + } + + // Look for the deployable composite in the domain composite + try { + domainCompositeCollection.get(compositeKey); + } catch (NotFoundException e) { + + // Add the deployable composite to the domain composite + Item item = new Item(); + domainCompositeCollection.post(compositeKey, item); + } + + // Check if the deployable composite is already assigned a node + Entry[] nodeEntries = cloudCollection.getAll(); + String nodeName = null; + for (Entry entry: nodeEntries) { + Item item = entry.getData(); + String related = item.getRelated(); + if (related != null) { + int c = related.indexOf("composite:"); + related = related.substring(c); + if (compositeKey.equals(related)) { + nodeName = compositeQName(entry.getKey()).getLocalPart(); + } + } + } + + // Create a new node for the composite if necessary + if (nodeName == null) { + + // Construct node name and key + QName compositeName = compositeQName(compositeKey); + nodeName = compositeName.getLocalPart() + "Node"; + String nodeKey = compositeKey("http://tuscany.apache.org/cloud", new QName("http://tuscany.apache.org/cloud", nodeName)); + + // Find a free node port + Set nodePorts = new HashSet(); + for (Entry entry: nodeEntries) { + Item item = entry.getData(); + String uri = nodeURI(item.getContents()); + if (uri != null) { + URI u = URI.create(uri); + int port = u.getPort(); + if (port != -1) { + nodePorts.add(port); + } + } + } + String nodeURI = null; + for (int port = 8100; port<8200; port++) { + if (!nodePorts.contains(port)) { + nodeURI = "http://localhost:" + port; + break; + } + } + if (nodeURI == null) { + throw new RuntimeException("Couldn't find a free port for new node: " + nodeName); + } + + // Build the entry describing the node + Item item = new Item(); + String content = + "\n" + + "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + ""; + item.setContents(content); + + // Create the new node + cloudCollection.post(nodeKey, item); + } + + // Finally, start the node + if ("true".equals(start)) { + processCollection.post(nodeName, new Item()); + } + + response.getWriter().print("Node " + nodeName + " OK."); + + } catch (Exception e) { + logger.log(Level.SEVERE, "Could not start composite", e); + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); + } + } + +} diff --git a/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/launcher/DomainManagerLauncherBootstrap.java b/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/launcher/DomainManagerLauncherBootstrap.java new file mode 100644 index 0000000000..c0afcc6efd --- /dev/null +++ b/java/sca/contrib/modules/domain-manager/src/main/java/org/apache/tuscany/sca/domain/manager/launcher/DomainManagerLauncherBootstrap.java @@ -0,0 +1,121 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.domain.manager.launcher; + +import org.apache.tuscany.sca.domain.manager.impl.DomainManagerConfiguration; +import org.apache.tuscany.sca.node.Contribution; +import org.apache.tuscany.sca.node.ContributionLocationHelper; +import org.apache.tuscany.sca.node.Node; +import org.apache.tuscany.sca.node.NodeFactory; +import org.oasisopen.sca.CallableReference; +import org.oasisopen.sca.ServiceReference; + +/** + * Bootstrap class for the SCA domain manager. + * + * @version $Rev$ $Date$ + */ +public class DomainManagerLauncherBootstrap { + private Node node; + + /** + * A node wrappering an instance of a domain manager. + */ + public static class NodeFacade implements Node { + private ClassLoader threadContextClassLoader; + private ClassLoader runtimeClassLoader; + private Node node; + private String rootDirectory; + + private NodeFacade(String rootDirectory) { + this.rootDirectory = rootDirectory; + runtimeClassLoader = Thread.currentThread().getContextClassLoader(); + } + + public void start() { + threadContextClassLoader = Thread.currentThread().getContextClassLoader(); + boolean started = false; + try { + Thread.currentThread().setContextClassLoader(runtimeClassLoader); + NodeFactory factory = NodeFactory.newInstance(); + String contribution = ContributionLocationHelper.getContributionLocation(getClass()); + node = factory.createNode("DomainManager.composite", new Contribution("domain-manager", contribution)); + node.start(); + + // Set the domain manager's root directory + DomainManagerConfiguration domainManagerConfiguration = node.getService(DomainManagerConfiguration.class, "DomainManagerConfigurationComponent"); + domainManagerConfiguration.setRootDirectory(rootDirectory); + + started = true; + } finally { + if (!started) { + Thread.currentThread().setContextClassLoader(threadContextClassLoader); + } + } + } + + public void stop() { + try { + Thread.currentThread().setContextClassLoader(runtimeClassLoader); + node.stop(); + } finally { + Thread.currentThread().setContextClassLoader(threadContextClassLoader); + } + } + + public void destroy() { + try { + Thread.currentThread().setContextClassLoader(runtimeClassLoader); + node.destroy(); + } finally { + Thread.currentThread().setContextClassLoader(threadContextClassLoader); + } + } + + public > R cast(B target) throws IllegalArgumentException { + throw new UnsupportedOperationException(); + } + + public B getService(Class businessInterface, String serviceName) { + throw new UnsupportedOperationException(); + } + + public ServiceReference getServiceReference(Class businessInterface, String serviceName) { + throw new UnsupportedOperationException(); + } + + } + + /** + * Constructs a new domain manager bootstrap. + */ + public DomainManagerLauncherBootstrap(String rootDirectory) throws Exception { + node = new NodeFacade(rootDirectory); + } + + /** + * Returns the node representing the domain manager. + * @return + */ + public Node getNode() { + return node; + } + +} diff --git a/java/sca/contrib/modules/domain-manager/src/main/resources/DomainManager.composite b/java/sca/contrib/modules/domain-manager/src/main/resources/DomainManager.composite new file mode 100644 index 0000000000..ba57ea45d1 --- /dev/null +++ b/java/sca/contrib/modules/domain-manager/src/main/resources/DomainManager.composite @@ -0,0 +1,281 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + workspace.xml + cloud + + + + + + + + + + + + + + + + + files + + + + + + + + + files + + + + + + + + + domain.composite + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + cloud.composite + cloud + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/java/sca/contrib/modules/domain-manager/src/main/resources/cloud-gadget.html b/java/sca/contrib/modules/domain-manager/src/main/resources/cloud-gadget.html new file mode 100644 index 0000000000..619df54ede --- /dev/null +++ b/java/sca/contrib/modules/domain-manager/src/main/resources/cloud-gadget.html @@ -0,0 +1,408 @@ + + + +SCA Domain - Cloud + + + + + + + + +
      + +
      +
      +
      + >Add +  Delete +    + Start +  Stop +
      + + + +
      + + + + diff --git a/java/sca/contrib/modules/domain-manager/src/main/resources/cloud.html b/java/sca/contrib/modules/domain-manager/src/main/resources/cloud.html new file mode 100644 index 0000000000..d661d5d38b --- /dev/null +++ b/java/sca/contrib/modules/domain-manager/src/main/resources/cloud.html @@ -0,0 +1,68 @@ + + + +SCA Domain - Cloud + + + + + + + +
      +
      + + + SCA Domain

      + Cloud
        +
      +
      + Here is the list of SCA nodes configured in your SCA domain cloud. +

      + +
      + + + + + + + diff --git a/java/sca/contrib/modules/domain-manager/src/main/resources/composite-gadget.html b/java/sca/contrib/modules/domain-manager/src/main/resources/composite-gadget.html new file mode 100644 index 0000000000..82855a410a --- /dev/null +++ b/java/sca/contrib/modules/domain-manager/src/main/resources/composite-gadget.html @@ -0,0 +1,277 @@ + + + +SCA Domain - Domain Composite + + + + + + + + +
      + +
      +
      +
      + >Add +  Delete +
      + + + +
      + + + + diff --git a/java/sca/contrib/modules/domain-manager/src/main/resources/composite.html b/java/sca/contrib/modules/domain-manager/src/main/resources/composite.html new file mode 100644 index 0000000000..b0631e1d66 --- /dev/null +++ b/java/sca/contrib/modules/domain-manager/src/main/resources/composite.html @@ -0,0 +1,66 @@ + + + +SCA Domain - Domain Composite + + + + + + + +
      +
      + + + SCA Domain

      + Domain Composite  +
      +
      + Here is the list of SCA composites currently included as top-level composites in your SCA domain. +

      + +
      + + + + + + + diff --git a/java/sca/contrib/modules/domain-manager/src/main/resources/files-gadget.html b/java/sca/contrib/modules/domain-manager/src/main/resources/files-gadget.html new file mode 100644 index 0000000000..83315a1957 --- /dev/null +++ b/java/sca/contrib/modules/domain-manager/src/main/resources/files-gadget.html @@ -0,0 +1,124 @@ + + + +SCA Domain - Contribution File Server + + + + + + + + +
      + +
      +
      +
      + >Upload +  Delete +
      + + + +
      + + + + diff --git a/java/sca/contrib/modules/domain-manager/src/main/resources/files.html b/java/sca/contrib/modules/domain-manager/src/main/resources/files.html new file mode 100644 index 0000000000..37d89e7665 --- /dev/null +++ b/java/sca/contrib/modules/domain-manager/src/main/resources/files.html @@ -0,0 +1,64 @@ + + + +SCA Domain - Contribution File Server + + + + + + + +
      +
      + + + SCA Domain

      + File Server  +
      +
      + This is a simple ATOM-based file server useful to share files if you don't have an FTP, SVN or Maven repository. +

      + +
      + + + + + + + diff --git a/java/sca/contrib/modules/domain-manager/src/main/resources/home-gadget.html b/java/sca/contrib/modules/domain-manager/src/main/resources/home-gadget.html new file mode 100644 index 0000000000..05e262e4df --- /dev/null +++ b/java/sca/contrib/modules/domain-manager/src/main/resources/home-gadget.html @@ -0,0 +1,45 @@ + + + +SCA Domain - Home + + + + + + + + +
      + +
      + + + +
      Search:
      +
      + +
      + + + + diff --git a/java/sca/contrib/modules/domain-manager/src/main/resources/home.html b/java/sca/contrib/modules/domain-manager/src/main/resources/home.html new file mode 100644 index 0000000000..aad1856621 --- /dev/null +++ b/java/sca/contrib/modules/domain-manager/src/main/resources/home.html @@ -0,0 +1,65 @@ + + + +SCA Domain - Home + + + + + + + +
      +
      + + + SCA Domain + +





      + +
      + +






      +
      This page is under construction, searching the domain is not implemented yet.
      + + + + + + + + diff --git a/java/sca/contrib/modules/domain-manager/src/main/resources/icons/feed-icon.png b/java/sca/contrib/modules/domain-manager/src/main/resources/icons/feed-icon.png new file mode 100644 index 0000000000..a59728b2ad Binary files /dev/null and b/java/sca/contrib/modules/domain-manager/src/main/resources/icons/feed-icon.png differ diff --git a/java/sca/contrib/modules/domain-manager/src/main/resources/manager.css b/java/sca/contrib/modules/domain-manager/src/main/resources/manager.css new file mode 100644 index 0000000000..e080ff1d87 --- /dev/null +++ b/java/sca/contrib/modules/domain-manager/src/main/resources/manager.css @@ -0,0 +1,104 @@ +/* + * 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. + */ + +body { + white-space: nowrap; margin: 2px; +} + +table { + border: 1px; border-collapse: separate +} + +th { + font-weight: bold; white-space: nowrap; background-color: #e5ecf9; color: #598edd; + text-align: left; padding-left: 2px; padding-right: 20px; padding-top: 2px; padding-bottom: 2px; vertical-align: text-top; + border-top: 1px; border-bottom: 1px; border-left: 0px; border-right: 0px; + border-style: solid; border-top-color: #a2bae7; border-bottom-color: #d1d3d4 +} + +td { + padding-left: 2px; padding-top: 2px; padding-right: 20px; white-space: nowrap; vertical-align: text-top +} + +iframe { + visibility: hidden; +} + +input { + vertical-align: middle +} + +a:link { + color: blue +} + +a:visited { + color: blue +} + +.tdw { + padding-left: 2px; padding-top: 2px; padding-right: 20px; white-space: normal; vertical-align: text-top +} + +.hd1 { + font-size:150%; font-weight: bold +} + +.tbar { + margin: 0px; + padding-top: 0px; padding-left: 0px; padding-right: 0px; padding-bottom: 3px; + border-bottom: 1px solid #a2bae7 +} + +.ltbar { + padding-left: 0px; padding-top: 0px; padding-right: 20px; white-space: nowrap; vertical-align: top +} + +.rtbar { + padding-left: 0px; padding-right: 0px; padding-top: 0px; white-space: nowrap; vertical-align: top; + text-align: right +} + +.suggest { + background-color: #e5ecf9; color: #598edd; + border-top: 1px; border-bottom: 1px; border-left: 1px; border-right: 1px; + border-style: solid; border-top-color: #a2bae7; border-bottom-color: #d1d3d4; + border-left-color: #d1d3d4; border-right-color: #d1d3d4; + position: absolute; + overflow: auto; overflow-x: hidden; + cursor: default; + padding: 0px; margin: 0px; +} + +suggestTable { + border: 0px; border-collapse: separate; + padding-left: 5px; padding-right: 5px; padding-top: 2px; padding-bottom: 2px; + margin: 0px; +} + +.suggestItem { + padding-left: 2px; padding-top: 0px; padding-bottom: 0px; padding-right: 2px; white-space: nowrap; vertical-align: text-top; + background-color: #e5ecf9; color: #598edd; +} + +.suggestHilighted { + padding-left: 2px; padding-top: 0px; padding-bottom: 0px; padding-right: 2px; white-space: nowrap; vertical-align: text-top; + background-color: #598edd; color: #e5ecf9; +} + diff --git a/java/sca/contrib/modules/domain-manager/src/main/resources/toolbar-gadget.html b/java/sca/contrib/modules/domain-manager/src/main/resources/toolbar-gadget.html new file mode 100644 index 0000000000..c9389affc3 --- /dev/null +++ b/java/sca/contrib/modules/domain-manager/src/main/resources/toolbar-gadget.html @@ -0,0 +1,47 @@ + + + +SCA Domain - Toolbar + + + + + + + +
      + + + + diff --git a/java/sca/contrib/modules/domain-manager/src/main/resources/utils.js b/java/sca/contrib/modules/domain-manager/src/main/resources/utils.js new file mode 100644 index 0000000000..77ed807e85 --- /dev/null +++ b/java/sca/contrib/modules/domain-manager/src/main/resources/utils.js @@ -0,0 +1,246 @@ +/* + * 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. + */ + +/** + * Autocomplete / suggest support for input fields + * + * To use it declare a 'suggest' function as follows: + * function suggestItems() { + * return new Array('abc', 'def', 'ghi'); + * } + * + * then hook it to an input field as follows: + * suggest(document.yourForm.yourInputField, suggestItems); + */ +function selectSuggestion(node, value) { + for (;;) { + node = node.parentNode; + if (node.tagName.toLowerCase() == 'div') { + break; + } + } + node.selectSuggestion(value); +} + +function hilightSuggestion(node, over) { + if (over) { + node.className = 'suggestHilighted'; + } else { + node.className = 'suggestItem'; + } +} + +function suggest(input, suggestFunction) { + + input.suggest = suggestFunction; + + input.selectSuggestion = function(value) { + this.hideSuggestDiv(); + this.value = value; + } + + input.hideSuggestDiv = function() { + if (this.suggestDiv != null) { + this.suggestDiv.style.visibility = 'hidden'; + } + } + + input.showSuggestDiv = function() { + if (this.suggestDiv == null) { + this.suggestDiv = document.createElement('div'); + this.suggestDiv.input = this; + this.suggestDiv.className = 'suggest'; + input.parentNode.insertBefore(this.suggestDiv, input); + this.suggestDiv.style.visibility = 'hidden'; + this.suggestDiv.style.zIndex = '99'; + + this.suggestDiv.selectSuggestion = function(value) { + this.input.selectSuggestion(value); + } + } + + var values = this.suggest(); + var items = ""; + for (var i = 0; i < values.length; i++) { + if (values[i].indexOf(this.value) == -1) { + continue; + } + if (items.length == 0) { + items += ''; + } + items += ''; + } + if (items.length != 0) { + items += '
      ' + values[i] + '
      '; + } + this.suggestDiv.innerHTML = items; + + if (items.length != 0) { + var node = input; + var left = 0; + var top = 0; + for (;;) { + left += node.offsetLeft; + top += node.offsetTop; + node = node.offsetParent; + if (node.tagName.toLowerCase() == 'body') { + break; + } + } + this.suggestDiv.style.left = left; + this.suggestDiv.style.top = top + input.offsetHeight; + this.suggestDiv.style.visibility = 'visible'; + } else { + this.suggestDiv.style.visibility = 'hidden'; + } + } + + input.onkeydown = function(event) { + this.showSuggestDiv(); + }; + + input.onkeyup = function(event) { + this.showSuggestDiv(); + }; + + input.onmousedown = function(event) { + this.showSuggestDiv(); + }; + + input.onblur = function(event) { + setTimeout(function() { input.hideSuggestDiv(); }, 50); + }; +} + +/** + * A Toolbar class + */ +function Tool(name, href) { + this.name = name; + this.href = href; +} + +Tool.prototype.print = function() { + var loc = '' + location; + if (loc.match(this.href) == null) { + return '' + this.name + ''; + } else { + return '' + this.name + ''; + } +} + +/** + * Initialize the toolbar + */ +function toolbar(home, tools) { + var toolbar = '' + + '' + + '' + + '
      '; + + for (var i = 0; i < tools.length; i++) { + toolbar = toolbar + '' + } + + toolbar = toolbar + '
      ' +tools[i].print() + '
      ' + + '
      ' + home.print() + '
      '; + + return toolbar; +} + +/** + * Return an non-sparse array from an array or an object. + */ +function array(obj) { + if (obj.length == undefined) { + var a = new Array(); + a[0] = obj; + return a; + } + else { + var a = new Array(); + var n = 0; + for (var i in obj) { + a[n++] = obj[i]; + } + return a; + } +} + +/** + * Dump a Javascript object to the console + */ +function dump(o) { + for (f in o) { + try { + console.log(f + '=' + o[f]); + } catch (e) {} + } +} + +/** + * Return the content document of the given window. + */ +function content(win) { + if (win.document != 'undefined' && win.document != null) { + return win.document; + } else if (win.contentDocument != 'undefined' && win.contentDocument != null) { + return win.contentDocument; + } else { + return null; + } +} + +/** + * Returns a child element with the given id. + */ +function elementByID(node, id) { + for (var i in node.childNodes) { + var child = node.childNodes[i]; + if (child.id == id) { + return child; + } else { + child = elementByID(child, id); + if (child != null) { + return child; + } + } + } + return null; +} + +/** + * Install a gadget. + */ +function gadget(win, doc) { + var ongadget = null; + try { + if (win.parent.ongadget != null && win.parent.ongadget != 'undefined') { + ongadget = win.parent.ongadget; + } + } catch (e) { + } + if (ongadget != null) { + return ongadget(win, doc); + } else { + return doc; + } +} diff --git a/java/sca/contrib/modules/domain-manager/src/main/resources/workspace-gadget.html b/java/sca/contrib/modules/domain-manager/src/main/resources/workspace-gadget.html new file mode 100644 index 0000000000..a4589b42e6 --- /dev/null +++ b/java/sca/contrib/modules/domain-manager/src/main/resources/workspace-gadget.html @@ -0,0 +1,232 @@ + + + +SCA Domain - Contributions + + + + + + + + +
      + +
      +
      +
      + >Add +  Delete +
      + + + +
      + + + + diff --git a/java/sca/contrib/modules/domain-manager/src/main/resources/workspace.html b/java/sca/contrib/modules/domain-manager/src/main/resources/workspace.html new file mode 100644 index 0000000000..36c02ab1e6 --- /dev/null +++ b/java/sca/contrib/modules/domain-manager/src/main/resources/workspace.html @@ -0,0 +1,65 @@ + + + +SCA Domain - Contributions + + + + + + + +
      +
      + + + SCA Domain

      + Contributions
        +
      + Here is the list of SCA contributions currently available in your SCA domain. +

      + +
      + + + + + + + diff --git a/java/sca/contrib/modules/domain-manager/src/test/java/org/apache/tuscany/sca/domain/manager/impl/DomainManagerTestCase.java b/java/sca/contrib/modules/domain-manager/src/test/java/org/apache/tuscany/sca/domain/manager/impl/DomainManagerTestCase.java new file mode 100644 index 0000000000..5e76556a14 --- /dev/null +++ b/java/sca/contrib/modules/domain-manager/src/test/java/org/apache/tuscany/sca/domain/manager/impl/DomainManagerTestCase.java @@ -0,0 +1,117 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.domain.manager.impl; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.net.URL; + +import junit.framework.TestCase; + +import org.apache.tuscany.sca.data.collection.Entry; +import org.apache.tuscany.sca.data.collection.Item; +import org.apache.tuscany.sca.data.collection.NotFoundException; + +/** + * Test case for the workspace admin services. + * + * @version $Rev$ $Date$ + */ +public class DomainManagerTestCase extends TestCase { + + private ContributionCollectionImpl contributionCollection; + private DeployableCompositeCollectionImpl deployableCollection; + private DomainManagerConfigurationImpl domainManagerConfiguration; + + private static final String WORKSPACE_XML = + "\n" + + "\n" + + ""; + + @Override + protected void setUp() throws Exception { + ClassLoader cl = getClass().getClassLoader(); + + // Make sure we start with a clean workspace.xml file + URL url = cl.getResource("workspace.xml"); + FileOutputStream os = new FileOutputStream(new File(url.toURI())); + Writer writer = new OutputStreamWriter(os); + writer.write(WORKSPACE_XML); + writer.flush(); + writer.close(); + + // Create a workspace collection component + domainManagerConfiguration = new DomainManagerConfigurationImpl(); + domainManagerConfiguration.initialize(); + String root = url.getFile(); + root = root.substring(0, root.lastIndexOf('/')); + domainManagerConfiguration.setRootDirectory(root); + + contributionCollection = new ContributionCollectionImpl(); + contributionCollection.domainManagerConfiguration = domainManagerConfiguration; + contributionCollection.workspaceFile = "workspace.xml"; + contributionCollection.deploymentContributionDirectory = "cloud"; + contributionCollection.domainManagerConfiguration = domainManagerConfiguration; + deployableCollection = new DeployableCompositeCollectionImpl(); + deployableCollection.domainManagerConfiguration = domainManagerConfiguration; + deployableCollection.contributionCollection = contributionCollection; + contributionCollection.initialize(); + deployableCollection.initialize(); + + // Populate the workspace with test data + Item item = new Item(); + item.setLink(cl.getResource("contributions/store").toString()); + contributionCollection.post("store", item); + item.setLink(cl.getResource("contributions/assets").toString()); + contributionCollection.post("assets", item); + } + + public void testGetAll() { + Entry[] entries = contributionCollection.getAll(); + assertEquals(2, entries.length); + assertEquals(entries[0].getKey(), "store"); + } + + public void testGet() throws NotFoundException { + Item item = contributionCollection.get("assets"); + assertTrue(item.getAlternate().endsWith("contributions/assets/")); + } + + public void testDependencies1() { + Entry[] entries = contributionCollection.query("alldependencies=store"); + assertEquals(2, entries.length); + } + + public void testDependencies2() { + Entry[] entries = contributionCollection.query("alldependencies=assets"); + assertEquals(1, entries.length); + assertEquals("assets", entries[0].getKey()); + } + + public void testDeployables() throws NotFoundException { + Entry[] entries = deployableCollection.getAll(); + assertEquals(1, entries.length); + assertEquals("composite:store;http://store;store", entries[0].getKey()); + } + +} diff --git a/java/sca/contrib/modules/domain-manager/src/test/resources/contributions/assets/META-INF/sca-contribution.xml b/java/sca/contrib/modules/domain-manager/src/test/resources/contributions/assets/META-INF/sca-contribution.xml new file mode 100644 index 0000000000..4eab6dd5e7 --- /dev/null +++ b/java/sca/contrib/modules/domain-manager/src/test/resources/contributions/assets/META-INF/sca-contribution.xml @@ -0,0 +1,27 @@ + + + + + + + + + \ No newline at end of file diff --git a/java/sca/contrib/modules/domain-manager/src/test/resources/contributions/store/META-INF/sca-contribution.xml b/java/sca/contrib/modules/domain-manager/src/test/resources/contributions/store/META-INF/sca-contribution.xml new file mode 100644 index 0000000000..48d4be2d6e --- /dev/null +++ b/java/sca/contrib/modules/domain-manager/src/test/resources/contributions/store/META-INF/sca-contribution.xml @@ -0,0 +1,25 @@ + + + + + + \ No newline at end of file diff --git a/java/sca/contrib/modules/domain-manager/src/test/resources/workspace.xml b/java/sca/contrib/modules/domain-manager/src/test/resources/workspace.xml new file mode 100644 index 0000000000..e6ac7d7701 --- /dev/null +++ b/java/sca/contrib/modules/domain-manager/src/test/resources/workspace.xml @@ -0,0 +1,21 @@ + + + + diff --git a/java/sca/contrib/modules/host-corba-jee/LICENSE b/java/sca/contrib/modules/host-corba-jee/LICENSE new file mode 100644 index 0000000000..6e529a25c4 --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jee/LICENSE @@ -0,0 +1,205 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + + diff --git a/java/sca/contrib/modules/host-corba-jee/META-INF/MANIFEST.MF b/java/sca/contrib/modules/host-corba-jee/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..71fbb7e6a9 --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jee/META-INF/MANIFEST.MF @@ -0,0 +1,23 @@ +Manifest-Version: 1.0 +Private-Package: org.apache.tuscany.sca.host.corba.jee;version="2.0.0" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA JEE environment CORBA Host +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397427890 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA JEE environment CORBA Host +Import-Package: javax.naming, + javax.naming.spi;resolution:=optional, + javax.rmi, + org.apache.tuscany.sca.core;version="2.0.0", + org.apache.tuscany.sca.host.corba;version="2.0.0", + org.omg.CORBA, + org.omg.CORBA.portable;resolution:=optional, + org.omg.CosNaming, + org.omg.CosNaming.NamingContextPackage +Bundle-SymbolicName: org.apache.tuscany.sca.host.corba.jee +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/host-corba-jee/NOTICE b/java/sca/contrib/modules/host-corba-jee/NOTICE new file mode 100644 index 0000000000..51042eab05 --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jee/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/host-corba-jee/pom.xml b/java/sca/contrib/modules/host-corba-jee/pom.xml new file mode 100644 index 0000000000..29cd6209ae --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jee/pom.xml @@ -0,0 +1,44 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + + tuscany-host-corba-jee + Apache Tuscany SCA JEE environment CORBA Host + + + + org.apache.tuscany.sca + tuscany-host-corba + 2.0-SNAPSHOT + + + org.apache.tuscany.sca + tuscany-host-corba-jse + 2.0-SNAPSHOT + test + + + + diff --git a/java/sca/contrib/modules/host-corba-jee/src/main/java/org/apache/tuscany/sca/host/corba/jee/CorbaRuntimeModuleActivator.java b/java/sca/contrib/modules/host-corba-jee/src/main/java/org/apache/tuscany/sca/host/corba/jee/CorbaRuntimeModuleActivator.java new file mode 100644 index 0000000000..b5fe9f5d0f --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jee/src/main/java/org/apache/tuscany/sca/host/corba/jee/CorbaRuntimeModuleActivator.java @@ -0,0 +1,52 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.host.corba.jee; + +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.core.ModuleActivator; +import org.apache.tuscany.sca.host.corba.CorbaHostExtensionPoint; + +/** + * @version $Rev$ $Date$ + */ +public class CorbaRuntimeModuleActivator implements ModuleActivator { + + private JEECorbaHost server; + + public void start(ExtensionPointRegistry extensionPointRegistry) { + + // Register our Corba host + CorbaHostExtensionPoint corbaHosts = extensionPointRegistry.getExtensionPoint(CorbaHostExtensionPoint.class); + + server = new JEECorbaHost(); + try { + server.start(); + corbaHosts.addCorbaHost(server); + } catch (Exception e) { + + } + } + + public void stop(ExtensionPointRegistry registry) { + if (server != null) { + server.stop(); + } + } + +} diff --git a/java/sca/contrib/modules/host-corba-jee/src/main/java/org/apache/tuscany/sca/host/corba/jee/JEECorbaHost.java b/java/sca/contrib/modules/host-corba-jee/src/main/java/org/apache/tuscany/sca/host/corba/jee/JEECorbaHost.java new file mode 100644 index 0000000000..7e714c1ca5 --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jee/src/main/java/org/apache/tuscany/sca/host/corba/jee/JEECorbaHost.java @@ -0,0 +1,162 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.host.corba.jee; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.rmi.PortableRemoteObject; + +import org.apache.tuscany.sca.host.corba.CorbaHost; +import org.apache.tuscany.sca.host.corba.CorbaHostException; +import org.apache.tuscany.sca.host.corba.CorbaHostUtils; +import org.apache.tuscany.sca.host.corba.CorbanameURL; +import org.omg.CORBA.ORB; +import org.omg.CORBA.Object; +import org.omg.CosNaming.NameComponent; +import org.omg.CosNaming.NamingContext; +import org.omg.CosNaming.NamingContextExt; +import org.omg.CosNaming.NamingContextExtHelper; +import org.omg.CosNaming.NamingContextHelper; +import org.omg.CosNaming.NamingContextPackage.InvalidName; +import org.omg.CosNaming.NamingContextPackage.NotFound; + +/** + * @version $Rev$ $Date$ + * Implementation of JEE CORBA host + */ +public class JEECorbaHost implements CorbaHost { + + public static final String ORB_NAME = "java:comp/ORB"; + + private List registeredServants = Collections.synchronizedList(new ArrayList()); + private ORB orb; + + private void registerURI(String uri) { + registeredServants.add(uri); + } + + private void removeURI(String uri) { + registeredServants.remove(uri); + } + + private NamingContextExt getNamingContext(String nameService) throws Exception { + org.omg.CORBA.Object objRef = orb.resolve_initial_references(nameService); + return NamingContextExtHelper.narrow(objRef); + } + + private void handleException(Exception e) throws CorbaHostException { + // The cause of the Exception is JDK specific + if (e instanceof NotFound) { + throw new CorbaHostException(CorbaHostException.NO_SUCH_OBJECT, e); + } else if (e instanceof InvalidName) { + throw new CorbaHostException(e); + } else { + throw new CorbaHostException(e); + } + } + + public void registerServant(String uri, Object servantObject) throws CorbaHostException { + CorbanameURL details = CorbaHostUtils.getServiceDetails(uri); + try { + NamingContext namingCtx = getNamingContext(details.getNameService()); + for (int i = 0; i < details.getNamePath().size() - 1; i++) { + NameComponent nc = new NameComponent(details.getNamePath().get(i), ""); + NameComponent[] path = new NameComponent[] {nc}; + try { + namingCtx = NamingContextHelper.narrow(namingCtx.resolve(path)); + } catch (Exception e) { + namingCtx = namingCtx.bind_new_context(path); + } + } + NameComponent finalName = + new NameComponent(details.getNamePath().get(details.getNamePath().size() - 1), ""); + try { + namingCtx.resolve(new NameComponent[] {finalName}); + // no exception means that some object is already registered + // under this name, we need to crash here + throw new CorbaHostException(CorbaHostException.BINDING_IN_USE); + } catch (NotFound e) { + namingCtx.bind(new NameComponent[] {finalName}, servantObject); + registerURI(uri); + } + } catch (CorbaHostException e) { + throw e; + } catch (Exception e) { + handleException(e); + } + } + + public void unregisterServant(String uri) throws CorbaHostException { + CorbanameURL details = CorbaHostUtils.getServiceDetails(uri); + try { + NamingContextExt namingCtx = getNamingContext(details.getNameService()); + namingCtx.unbind(namingCtx.to_name(details.getName())); + removeURI(uri); + } catch (Exception e) { + handleException(e); + } + } + + public Object lookup(String uri) throws CorbaHostException { + Object result = null; + try { + CorbanameURL url = new CorbanameURL(uri); + NamingContextExt context = getNamingContext(url.getNameService()); + result = context.resolve_str(url.getName()); + } catch (Exception e) { + // e.printStackTrace(); + handleException(e); + } + if (result == null) { + throw new CorbaHostException(CorbaHostException.NO_SUCH_OBJECT); + } + return result; + } + + // obtain ORB from environment + public void start() throws CorbaHostException { + Context ctx; + try { + ctx = new InitialContext(); + orb = (ORB)PortableRemoteObject.narrow(ctx.lookup(ORB_NAME), org.omg.CORBA.ORB.class); + } catch (Exception e) { + throw new CorbaHostException(e); + } + } + + // unregister registered servants + public void stop() { + // use copy because unregisterServant(...) method removes from + // registeredServants collection + List rsCopy = new ArrayList(registeredServants); + for (String servantURI : rsCopy) { + try { + unregisterServant(servantURI); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + +} diff --git a/java/sca/contrib/modules/host-corba-jee/src/main/resources/META-INF/services/org.apache.tuscany.sca.core.ModuleActivator b/java/sca/contrib/modules/host-corba-jee/src/main/resources/META-INF/services/org.apache.tuscany.sca.core.ModuleActivator new file mode 100644 index 0000000000..3762550c01 --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jee/src/main/resources/META-INF/services/org.apache.tuscany.sca.core.ModuleActivator @@ -0,0 +1,18 @@ +# 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. + +org.apache.tuscany.sca.host.corba.jee.CorbaRuntimeModuleActivator diff --git a/java/sca/contrib/modules/host-corba-jee/src/test/java/org/apache/tuscany/sca/host/corba/jee/testing/JEECorbaHostTestCase.java b/java/sca/contrib/modules/host-corba-jee/src/test/java/org/apache/tuscany/sca/host/corba/jee/testing/JEECorbaHostTestCase.java new file mode 100644 index 0000000000..fd952a02c7 --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jee/src/test/java/org/apache/tuscany/sca/host/corba/jee/testing/JEECorbaHostTestCase.java @@ -0,0 +1,208 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.host.corba.jee.testing; + +import static junit.framework.Assert.assertEquals; +import static junit.framework.Assert.assertTrue; +import static junit.framework.Assert.fail; + +import javax.naming.Context; + +import org.apache.tuscany.sca.host.corba.CorbaHostException; +import org.apache.tuscany.sca.host.corba.jee.JEECorbaHost; +import org.apache.tuscany.sca.host.corba.jee.testing.general.TestInterface; +import org.apache.tuscany.sca.host.corba.jee.testing.general.TestInterfaceHelper; +import org.apache.tuscany.sca.host.corba.jee.testing.servants.TestInterfaceServant; +import org.apache.tuscany.sca.host.corba.naming.TransientNameServer; +import org.apache.tuscany.sca.host.corba.naming.TransientNameService; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * General tests for JEECorbaHost. Uses host-corba-jdk as mock for JEE + * environment ORB. + */ +public class JEECorbaHostTestCase { + + public static final String LOCALHOST = "localhost"; + public static final int DEFAULT_PORT = 11100; + private static JEECorbaHost host; + private static TransientNameServer server; + private static String factoryClassName; + + private String createCorbanameURI(String name) { + return "corbaname:#" + name; + } + + @BeforeClass + public static void start() { + try { + server = new TransientNameServer(LOCALHOST, DEFAULT_PORT, TransientNameService.DEFAULT_SERVICE_NAME); + Thread t = server.start(); + if (t == null) { + fail("The naming server cannot be started"); + } + factoryClassName = System.getProperty(Context.INITIAL_CONTEXT_FACTORY); + System.setProperty(Context.INITIAL_CONTEXT_FACTORY, TestInitialContextFactory.class.getName()); + host = new JEECorbaHost(); + host.start(); + } catch (Throwable e) { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + @AfterClass + public static void stop() { + server.stop(); + if (factoryClassName != null) { + System.setProperty(Context.INITIAL_CONTEXT_FACTORY, factoryClassName); + } else { + System.clearProperty(Context.INITIAL_CONTEXT_FACTORY); + } + } + + /** + * Tests registering and lookup CORBA services + */ + @Test + public void test_registerServant() { + try { + String uri = createCorbanameURI("Nested/Test"); + TestInterface servant = new TestInterfaceServant(); + host.registerServant(uri, servant); + TestInterface ref = TestInterfaceHelper.narrow(host.lookup(uri)); + assertEquals(2, ref.getInt(2)); + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + } + + /** + * Tests unregistering servants + */ + @Test + public void test_unregisterServant() { + try { + String uri = createCorbanameURI("Unregistering/Test"); + TestInterface servant = new TestInterfaceServant(); + + // creating and releasing using corbaname URI + host.registerServant(uri, servant); + host.unregisterServant(uri); + host.registerServant(uri, servant); + host.unregisterServant(uri); + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + } + + /** + * Tests situation when name is already registered + */ + @Test + public void test_nameAlreadyRegistered() { + // test using URI + try { + TestInterface servant = new TestInterfaceServant(); + String uri = createCorbanameURI("AlreadyRegisteredTest2"); + host.registerServant(uri, servant); + host.registerServant(uri, servant); + fail(); + } catch (CorbaHostException e) { + assertTrue(e.getMessage().equals(CorbaHostException.BINDING_IN_USE)); + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + } + + /** + * Tests getting non existing reference + */ + @Test + public void test_getNonExistingObject() { + // try to fetch object with corbaname URI + try { + host.lookup(createCorbanameURI("NonExistingOne")); + fail(); + } catch (CorbaHostException e) { + // The message is JDK-specific + // assertTrue(e.getMessage().equals(CorbaHostException.NO_SUCH_OBJECT)); + } catch (Exception e) { + // e.printStackTrace(); + fail(); + } + } + + /** + * Tests unregistering non existing reference + */ + @Test + public void test_unregisterNonExistentObject() { + // test using URI + try { + String uri = createCorbanameURI("NonExistingReference1"); + host.unregisterServant(uri); + fail(); + } catch (CorbaHostException e) { + assertTrue(e.getMessage().equals(CorbaHostException.NO_SUCH_OBJECT)); + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + } + + /** + * Tests unregistering servants on host stop + */ + @Test + public void test_unregisterOnStop() { + try { + String uri1 = createCorbanameURI("TempService1"); + String uri2 = createCorbanameURI("TempService2"); + JEECorbaHost innerHost = new JEECorbaHost(); + innerHost.start(); + TestInterfaceServant servant = new TestInterfaceServant(); + innerHost.registerServant(uri1, servant); + innerHost.registerServant(uri2, servant); + innerHost.stop(); + try { + innerHost.lookup(uri1); + fail(); + } catch (CorbaHostException e) { + assertEquals(CorbaHostException.NO_SUCH_OBJECT, e.getMessage()); + } + try { + innerHost.lookup(uri2); + fail(); + } catch (CorbaHostException e) { + assertEquals(CorbaHostException.NO_SUCH_OBJECT, e.getMessage()); + } + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + } + +} diff --git a/java/sca/contrib/modules/host-corba-jee/src/test/java/org/apache/tuscany/sca/host/corba/jee/testing/TestContext.java b/java/sca/contrib/modules/host-corba-jee/src/test/java/org/apache/tuscany/sca/host/corba/jee/testing/TestContext.java new file mode 100644 index 0000000000..a0b9b7c514 --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jee/src/test/java/org/apache/tuscany/sca/host/corba/jee/testing/TestContext.java @@ -0,0 +1,174 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.host.corba.jee.testing; + +import java.util.Hashtable; + +import javax.naming.Binding; +import javax.naming.Context; +import javax.naming.Name; +import javax.naming.NameClassPair; +import javax.naming.NameParser; +import javax.naming.NamingEnumeration; +import javax.naming.NamingException; + +import org.apache.tuscany.sca.host.corba.jee.JEECorbaHost; +import org.omg.CORBA.ORB; + +/** + * Mock implementation of javax.naming.Context interface. + */ +public class TestContext implements Context { + + private ORB orb; + + public Object addToEnvironment(String propName, Object propVal) throws NamingException { + return null; + } + + public void bind(Name name, Object obj) throws NamingException { + + } + + public void bind(String name, Object obj) throws NamingException { + + } + + public void close() throws NamingException { + + } + + public Name composeName(Name name, Name prefix) throws NamingException { + return null; + } + + public String composeName(String name, String prefix) throws NamingException { + return null; + } + + public Context createSubcontext(Name name) throws NamingException { + return null; + } + + public Context createSubcontext(String name) throws NamingException { + return null; + } + + public void destroySubcontext(Name name) throws NamingException { + + } + + public void destroySubcontext(String name) throws NamingException { + + } + + public Hashtable getEnvironment() throws NamingException { + return null; + } + + public String getNameInNamespace() throws NamingException { + return null; + } + + public NameParser getNameParser(Name name) throws NamingException { + return null; + } + + public NameParser getNameParser(String name) throws NamingException { + return null; + } + + public NamingEnumeration list(Name name) throws NamingException { + return null; + } + + public NamingEnumeration list(String name) throws NamingException { + return null; + } + + public NamingEnumeration listBindings(Name name) throws NamingException { + return null; + } + + public NamingEnumeration listBindings(String name) throws NamingException { + return null; + } + + public Object lookup(Name name) throws NamingException { + return null; + } + + public Object lookup(String name) throws NamingException { + try { + if (name.equals(JEECorbaHost.ORB_NAME)) { + if (orb == null) { + // get ORB which was spawned under host and port declared in + // test class + String[] args = + {"-ORBInitialHost", JEECorbaHostTestCase.LOCALHOST, "-ORBInitialPort", + "" + JEECorbaHostTestCase.DEFAULT_PORT}; + orb = ORB.init(args, null); + } + } else { + throw new NamingException("Unknown name: " + name); + } + } catch (Exception e) { + throw new NamingException(e.getMessage()); + } + return orb; + } + + public Object lookupLink(Name name) throws NamingException { + return null; + } + + public Object lookupLink(String name) throws NamingException { + return null; + } + + public void rebind(Name name, Object obj) throws NamingException { + + } + + public void rebind(String name, Object obj) throws NamingException { + + } + + public Object removeFromEnvironment(String propName) throws NamingException { + return null; + } + + public void rename(Name oldName, Name newName) throws NamingException { + + } + + public void rename(String oldName, String newName) throws NamingException { + + } + + public void unbind(Name name) throws NamingException { + + } + + public void unbind(String name) throws NamingException { + + } + +} diff --git a/java/sca/contrib/modules/host-corba-jee/src/test/java/org/apache/tuscany/sca/host/corba/jee/testing/TestInitialContextFactory.java b/java/sca/contrib/modules/host-corba-jee/src/test/java/org/apache/tuscany/sca/host/corba/jee/testing/TestInitialContextFactory.java new file mode 100644 index 0000000000..f480235fa8 --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jee/src/test/java/org/apache/tuscany/sca/host/corba/jee/testing/TestInitialContextFactory.java @@ -0,0 +1,37 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.host.corba.jee.testing; + +import java.util.Hashtable; + +import javax.naming.Context; +import javax.naming.NamingException; +import javax.naming.spi.InitialContextFactory; + +/** + * Factory for mock implementation of javax.naming.Context interface. + */ +public class TestInitialContextFactory implements InitialContextFactory { + + public Context getInitialContext(Hashtable environment) throws NamingException { + return new TestContext(); + } + +} diff --git a/java/sca/contrib/modules/host-corba-jee/src/test/java/org/apache/tuscany/sca/host/corba/jee/testing/general/TestInterface.java b/java/sca/contrib/modules/host-corba-jee/src/test/java/org/apache/tuscany/sca/host/corba/jee/testing/general/TestInterface.java new file mode 100644 index 0000000000..f9f3d4789e --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jee/src/test/java/org/apache/tuscany/sca/host/corba/jee/testing/general/TestInterface.java @@ -0,0 +1,30 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.host.corba.jee.testing.general; + +/** +* org/apache/tuscany/sca/host/corba/testing/general/TestInterface.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* ¶roda, 25 czerwiec 2008 16:19:44 CEST +*/ + +public interface TestInterface extends TestInterfaceOperations, org.omg.CORBA.Object, org.omg.CORBA.portable.IDLEntity { +} // interface TestInterface diff --git a/java/sca/contrib/modules/host-corba-jee/src/test/java/org/apache/tuscany/sca/host/corba/jee/testing/general/TestInterfaceHelper.java b/java/sca/contrib/modules/host-corba-jee/src/test/java/org/apache/tuscany/sca/host/corba/jee/testing/general/TestInterfaceHelper.java new file mode 100644 index 0000000000..9ed4c81248 --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jee/src/test/java/org/apache/tuscany/sca/host/corba/jee/testing/general/TestInterfaceHelper.java @@ -0,0 +1,100 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.host.corba.jee.testing.general; + +/** +* org/apache/tuscany/sca/host/corba/testing/general/TestInterfaceHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* ¶roda, 25 czerwiec 2008 16:19:44 CEST +*/ + +abstract public class TestInterfaceHelper { + private static String _id = "IDL:org/apache/tuscany/sca/host/corba/testing/general/TestInterface:1.0"; + + public static void insert(org.omg.CORBA.Any a, + org.apache.tuscany.sca.host.corba.jee.testing.general.TestInterface that) { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream(); + a.type(type()); + write(out, that); + a.read_value(out.create_input_stream(), type()); + } + + public static org.apache.tuscany.sca.host.corba.jee.testing.general.TestInterface extract(org.omg.CORBA.Any a) { + return read(a.create_input_stream()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + + synchronized public static org.omg.CORBA.TypeCode type() { + if (__typeCode == null) { + __typeCode = + org.omg.CORBA.ORB + .init() + .create_interface_tc(org.apache.tuscany.sca.host.corba.jee.testing.general.TestInterfaceHelper.id(), + "TestInterface"); + } + return __typeCode; + } + + public static String id() { + return _id; + } + + public static org.apache.tuscany.sca.host.corba.jee.testing.general.TestInterface read(org.omg.CORBA.portable.InputStream istream) { + return narrow(istream.read_Object(_TestInterfaceStub.class)); + } + + public static void write(org.omg.CORBA.portable.OutputStream ostream, + org.apache.tuscany.sca.host.corba.jee.testing.general.TestInterface value) { + ostream.write_Object((org.omg.CORBA.Object)value); + } + + public static org.apache.tuscany.sca.host.corba.jee.testing.general.TestInterface narrow(org.omg.CORBA.Object obj) { + if (obj == null) + return null; + else if (obj instanceof org.apache.tuscany.sca.host.corba.jee.testing.general.TestInterface) + return (org.apache.tuscany.sca.host.corba.jee.testing.general.TestInterface)obj; + else if (!obj._is_a(id())) + throw new org.omg.CORBA.BAD_PARAM(); + else { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate(); + org.apache.tuscany.sca.host.corba.jee.testing.general._TestInterfaceStub stub = + new org.apache.tuscany.sca.host.corba.jee.testing.general._TestInterfaceStub(); + stub._set_delegate(delegate); + return stub; + } + } + + public static org.apache.tuscany.sca.host.corba.jee.testing.general.TestInterface unchecked_narrow(org.omg.CORBA.Object obj) { + if (obj == null) + return null; + else if (obj instanceof org.apache.tuscany.sca.host.corba.jee.testing.general.TestInterface) + return (org.apache.tuscany.sca.host.corba.jee.testing.general.TestInterface)obj; + else { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate(); + org.apache.tuscany.sca.host.corba.jee.testing.general._TestInterfaceStub stub = + new org.apache.tuscany.sca.host.corba.jee.testing.general._TestInterfaceStub(); + stub._set_delegate(delegate); + return stub; + } + } + +} diff --git a/java/sca/contrib/modules/host-corba-jee/src/test/java/org/apache/tuscany/sca/host/corba/jee/testing/general/TestInterfaceHolder.java b/java/sca/contrib/modules/host-corba-jee/src/test/java/org/apache/tuscany/sca/host/corba/jee/testing/general/TestInterfaceHolder.java new file mode 100644 index 0000000000..357c1eddb0 --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jee/src/test/java/org/apache/tuscany/sca/host/corba/jee/testing/general/TestInterfaceHolder.java @@ -0,0 +1,51 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.host.corba.jee.testing.general; + +/** +* org/apache/tuscany/sca/host/corba/testing/general/TestInterfaceHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* ¶roda, 25 czerwiec 2008 16:19:44 CEST +*/ + +public final class TestInterfaceHolder implements org.omg.CORBA.portable.Streamable { + public org.apache.tuscany.sca.host.corba.jee.testing.general.TestInterface value = null; + + public TestInterfaceHolder() { + } + + public TestInterfaceHolder(org.apache.tuscany.sca.host.corba.jee.testing.general.TestInterface initialValue) { + value = initialValue; + } + + public void _read(org.omg.CORBA.portable.InputStream i) { + value = org.apache.tuscany.sca.host.corba.jee.testing.general.TestInterfaceHelper.read(i); + } + + public void _write(org.omg.CORBA.portable.OutputStream o) { + org.apache.tuscany.sca.host.corba.jee.testing.general.TestInterfaceHelper.write(o, value); + } + + public org.omg.CORBA.TypeCode _type() { + return org.apache.tuscany.sca.host.corba.jee.testing.general.TestInterfaceHelper.type(); + } + +} diff --git a/java/sca/contrib/modules/host-corba-jee/src/test/java/org/apache/tuscany/sca/host/corba/jee/testing/general/TestInterfaceOperations.java b/java/sca/contrib/modules/host-corba-jee/src/test/java/org/apache/tuscany/sca/host/corba/jee/testing/general/TestInterfaceOperations.java new file mode 100644 index 0000000000..c2d4877791 --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jee/src/test/java/org/apache/tuscany/sca/host/corba/jee/testing/general/TestInterfaceOperations.java @@ -0,0 +1,31 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.host.corba.jee.testing.general; + +/** +* org/apache/tuscany/sca/host/corba/testing/general/TestInterfaceOperations.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* ¶roda, 25 czerwiec 2008 16:19:44 CEST +*/ + +public interface TestInterfaceOperations { + int getInt(int arg); +} // interface TestInterfaceOperations diff --git a/java/sca/contrib/modules/host-corba-jee/src/test/java/org/apache/tuscany/sca/host/corba/jee/testing/general/_TestInterfaceImplBase.java b/java/sca/contrib/modules/host-corba-jee/src/test/java/org/apache/tuscany/sca/host/corba/jee/testing/general/_TestInterfaceImplBase.java new file mode 100644 index 0000000000..9846748775 --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jee/src/test/java/org/apache/tuscany/sca/host/corba/jee/testing/general/_TestInterfaceImplBase.java @@ -0,0 +1,74 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.host.corba.jee.testing.general; + +/** +* org/apache/tuscany/sca/host/corba/testing/general/_TestInterfaceImplBase.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* ¶roda, 25 czerwiec 2008 16:19:44 CEST +*/ + +public abstract class _TestInterfaceImplBase extends org.omg.CORBA.portable.ObjectImpl implements + org.apache.tuscany.sca.host.corba.jee.testing.general.TestInterface, org.omg.CORBA.portable.InvokeHandler { + + // Constructors + public _TestInterfaceImplBase() { + } + + private static java.util.Hashtable _methods = new java.util.Hashtable(); + static { + _methods.put("getInt", new java.lang.Integer(0)); + } + + public org.omg.CORBA.portable.OutputStream _invoke(String $method, + org.omg.CORBA.portable.InputStream in, + org.omg.CORBA.portable.ResponseHandler $rh) { + org.omg.CORBA.portable.OutputStream out = null; + java.lang.Integer __method = (java.lang.Integer)_methods.get($method); + if (__method == null) + throw new org.omg.CORBA.BAD_OPERATION(0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE); + + switch (__method.intValue()) { + case 0: // org/apache/tuscany/sca/host/corba/testing/general/TestInterface/getInt + { + int arg = in.read_long(); + int $result = (int)0; + $result = this.getInt(arg); + out = $rh.createReply(); + out.write_long($result); + break; + } + + default: + throw new org.omg.CORBA.BAD_OPERATION(0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE); + } + + return out; + } // _invoke + + // Type-specific CORBA::Object operations + private static String[] __ids = {"IDL:org/apache/tuscany/sca/host/corba/testing/general/TestInterface:1.0"}; + + public String[] _ids() { + return (String[])__ids.clone(); + } + +} // class _TestInterfaceImplBase diff --git a/java/sca/contrib/modules/host-corba-jee/src/test/java/org/apache/tuscany/sca/host/corba/jee/testing/general/_TestInterfaceStub.java b/java/sca/contrib/modules/host-corba-jee/src/test/java/org/apache/tuscany/sca/host/corba/jee/testing/general/_TestInterfaceStub.java new file mode 100644 index 0000000000..cd722214ed --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jee/src/test/java/org/apache/tuscany/sca/host/corba/jee/testing/general/_TestInterfaceStub.java @@ -0,0 +1,73 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.host.corba.jee.testing.general; + +/** +* org/apache/tuscany/sca/host/corba/testing/general/_TestInterfaceStub.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* ¶roda, 25 czerwiec 2008 16:19:44 CEST +*/ + +public class _TestInterfaceStub extends org.omg.CORBA.portable.ObjectImpl implements + org.apache.tuscany.sca.host.corba.jee.testing.general.TestInterface { + + public int getInt(int arg) { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("getInt", true); + $out.write_long(arg); + $in = _invoke($out); + int $result = $in.read_long(); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return getInt(arg); + } finally { + _releaseReply($in); + } + } // getInt + + // Type-specific CORBA::Object operations + private static String[] __ids = {"IDL:org/apache/tuscany/sca/host/corba/testing/general/TestInterface:1.0"}; + + public String[] _ids() { + return (String[])__ids.clone(); + } + + private void readObject(java.io.ObjectInputStream s) throws java.io.IOException { + String str = s.readUTF(); + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.Object obj = org.omg.CORBA.ORB.init(args, props).string_to_object(str); + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate(); + _set_delegate(delegate); + } + + private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { + String[] args = null; + java.util.Properties props = null; + String str = org.omg.CORBA.ORB.init(args, props).object_to_string(this); + s.writeUTF(str); + } +} // class _TestInterfaceStub diff --git a/java/sca/contrib/modules/host-corba-jee/src/test/java/org/apache/tuscany/sca/host/corba/jee/testing/servants/TestInterfaceServant.java b/java/sca/contrib/modules/host-corba-jee/src/test/java/org/apache/tuscany/sca/host/corba/jee/testing/servants/TestInterfaceServant.java new file mode 100644 index 0000000000..6195f3af9c --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jee/src/test/java/org/apache/tuscany/sca/host/corba/jee/testing/servants/TestInterfaceServant.java @@ -0,0 +1,35 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.host.corba.jee.testing.servants; + +import org.apache.tuscany.sca.host.corba.jee.testing.general._TestInterfaceImplBase; + +/** + * Testing servant + */ +public class TestInterfaceServant extends _TestInterfaceImplBase { + + private static final long serialVersionUID = 1L; + + public int getInt(int arg) { + return arg; + } + +} diff --git a/java/sca/contrib/modules/host-corba-jee/src/test/resources/general.idl b/java/sca/contrib/modules/host-corba-jee/src/test/resources/general.idl new file mode 100644 index 0000000000..9194a37334 --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jee/src/test/resources/general.idl @@ -0,0 +1,45 @@ +/* + * 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. + */ + +/* + * compile by + * idlj -fall -oldImplBase general.idl + */ + +module org { + module apache { + module tuscany { + module sca { + module host { + module corba { + module jee { + module testing { + module general { + interface TestInterface { + long getInt(in long arg); + }; + }; + }; + }; + }; + }; + }; + }; + }; +}; diff --git a/java/sca/contrib/modules/host-corba-jse-tns/LICENSE b/java/sca/contrib/modules/host-corba-jse-tns/LICENSE new file mode 100644 index 0000000000..6e529a25c4 --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jse-tns/LICENSE @@ -0,0 +1,205 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + + diff --git a/java/sca/contrib/modules/host-corba-jse-tns/META-INF/MANIFEST.MF b/java/sca/contrib/modules/host-corba-jse-tns/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..8edf701bf7 --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jse-tns/META-INF/MANIFEST.MF @@ -0,0 +1,21 @@ +Manifest-Version: 1.0 +Private-Package: org.apache.tuscany.sca.host.corba.jse.tns;version="1. + 4" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA Transient Name Server CORBA Host +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397430015 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA Transient Name Server CORBA Hos + t +Import-Package: org.apache.tuscany.sca.core;version="2.0.0", + org.apache.tuscany.sca.host.corba;version="2.0.0", + org.apache.tuscany.sca.host.corba.jse;version="2.0.0", + org.apache.tuscany.sca.host.corba.naming;version="2.0.0", + org.omg.CORBA +Bundle-SymbolicName: org.apache.tuscany.sca.host.corba.jse.tns +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/host-corba-jse-tns/NOTICE b/java/sca/contrib/modules/host-corba-jse-tns/NOTICE new file mode 100644 index 0000000000..51042eab05 --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jse-tns/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/host-corba-jse-tns/pom.xml b/java/sca/contrib/modules/host-corba-jse-tns/pom.xml new file mode 100644 index 0000000000..5014507384 --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jse-tns/pom.xml @@ -0,0 +1,53 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + + tuscany-host-corba-jse-tns + Apache Tuscany SCA Transient Name Server CORBA Host + + + + + org.apache.tuscany.sca + tuscany-host-corba + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-host-corba-jse + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-binding-corba-runtime + 2.0-SNAPSHOT + test + + + + + diff --git a/java/sca/contrib/modules/host-corba-jse-tns/src/main/java/org/apache/tuscany/sca/host/corba/jse/tns/CorbaRuntimeModuleActivator.java b/java/sca/contrib/modules/host-corba-jse-tns/src/main/java/org/apache/tuscany/sca/host/corba/jse/tns/CorbaRuntimeModuleActivator.java new file mode 100644 index 0000000000..312d739c53 --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jse-tns/src/main/java/org/apache/tuscany/sca/host/corba/jse/tns/CorbaRuntimeModuleActivator.java @@ -0,0 +1,53 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.host.corba.jse.tns; + +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.core.ModuleActivator; +import org.apache.tuscany.sca.host.corba.CorbaHostExtensionPoint; +import org.apache.tuscany.sca.host.corba.jse.DefaultCorbaHost; + +/** + * @version $Rev: 683329 $ $Date: 2008-08-06 19:06:39 +0200 (Å›ro, 06 sie 2008) $ + */ +public class CorbaRuntimeModuleActivator implements ModuleActivator { + // private static final Logger logger = + // Logger.getLogger(CorbaRuntimeModuleActivator.class.getName()); + + private TnsDefaultCorbaHost server; + + public void start(ExtensionPointRegistry extensionPointRegistry) { + // Register our Corba host + CorbaHostExtensionPoint corbaHosts = extensionPointRegistry.getExtensionPoint(CorbaHostExtensionPoint.class); + server = new TnsDefaultCorbaHost(); + if (corbaHosts.getCorbaHosts().size() > 0 && corbaHosts.getCorbaHosts().get(0) instanceof DefaultCorbaHost) { + // Set TnsDefaultCorbaHost as default when DefaultCorbaHost was registered before + corbaHosts.getCorbaHosts().add(0, server); + } else { + corbaHosts.getCorbaHosts().add(server); + } + } + + public void stop(ExtensionPointRegistry registry) { + if (server != null) { + server.stop(); + } + } + +} diff --git a/java/sca/contrib/modules/host-corba-jse-tns/src/main/java/org/apache/tuscany/sca/host/corba/jse/tns/TnsDefaultCorbaHost.java b/java/sca/contrib/modules/host-corba-jse-tns/src/main/java/org/apache/tuscany/sca/host/corba/jse/tns/TnsDefaultCorbaHost.java new file mode 100644 index 0000000000..2dc2c7ddd4 --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jse-tns/src/main/java/org/apache/tuscany/sca/host/corba/jse/tns/TnsDefaultCorbaHost.java @@ -0,0 +1,116 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.host.corba.jse.tns; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.logging.Logger; + +import org.apache.tuscany.sca.host.corba.CorbaHost; +import org.apache.tuscany.sca.host.corba.CorbaHostException; +import org.apache.tuscany.sca.host.corba.CorbanameURL; +import org.apache.tuscany.sca.host.corba.SocketUtil; +import org.apache.tuscany.sca.host.corba.jse.DefaultCorbaHost; +import org.apache.tuscany.sca.host.corba.naming.TransientNameServer; +import org.apache.tuscany.sca.host.corba.naming.TransientNameService; +import org.omg.CORBA.Object; + +/** + * @version $Rev$ $Date$ + * Default implementation of CORBA host + */ +public class TnsDefaultCorbaHost implements CorbaHost { + + private static final Logger logger = Logger.getLogger(TnsDefaultCorbaHost.class.getName()); + private Map localServers = new ConcurrentHashMap(); + private Map clientsCount = new ConcurrentHashMap(); + private CorbaHost targetHost = new DefaultCorbaHost(); + + public void registerServant(String uri, Object servantObject) throws CorbaHostException { + CorbanameURL details = new CorbanameURL(uri); + if (SocketUtil.isLocalhost(details.getHost())) { + createLocalNameServer(details.getPort()); + } + targetHost.registerServant(uri, servantObject); + } + + public void unregisterServant(String uri) throws CorbaHostException { + targetHost.unregisterServant(uri); + CorbanameURL details = new CorbanameURL(uri); + if (SocketUtil.isLocalhost(details.getHost())) { + releaseLocalNameServer(details.getPort()); + } + } + + public Object lookup(String uri) throws CorbaHostException { + return targetHost.lookup(uri); + } + + /** + * Starts transient name server under given port. If TNS was previously + * spawned it increments clients counter. + */ + synchronized private void createLocalNameServer(int port) throws CorbaHostException { + int useCount = clientsCount.containsKey(port) ? clientsCount.get(port) : 0; + // no server previously spawned + if (useCount == 0) { + TransientNameServer server = + new TransientNameServer("localhost", port, TransientNameService.DEFAULT_SERVICE_NAME); + Thread thread = server.start(); + if (thread == null) { + throw new CorbaHostException("TransientNameServer couldn't be started"); + } else { + localServers.put(port, server); + } + } + clientsCount.put(port, ++useCount); + } + + /** + * Stops transient name server if there is only one client left using such + * TNS. Decrements clients counter if TNS is used by 2 or more clients. + */ + synchronized private void releaseLocalNameServer(int port) throws CorbaHostException { + int useCount = clientsCount.containsKey(port) ? clientsCount.get(port) : 0; + if (useCount == 1) { + // last client executed stop, cleaning up + TransientNameServer server = localServers.get(port); + if (server != null) { + server.stop(); + clientsCount.remove(port); + localServers.remove(port); + } else { + logger.warning("Local name server on port " + port + " was null!"); + } + } else if (useCount > 1) { + clientsCount.put(port, --useCount); + } else { + logger.warning("Tried to release non existing local name server on port " + port); + } + + } + + public void stop() { + for (TransientNameServer tns : localServers.values()) { + tns.stop(); + } + } + +} diff --git a/java/sca/contrib/modules/host-corba-jse-tns/src/main/resources/META-INF/services/org.apache.tuscany.sca.core.ModuleActivator b/java/sca/contrib/modules/host-corba-jse-tns/src/main/resources/META-INF/services/org.apache.tuscany.sca.core.ModuleActivator new file mode 100644 index 0000000000..906ec4efce --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jse-tns/src/main/resources/META-INF/services/org.apache.tuscany.sca.core.ModuleActivator @@ -0,0 +1,18 @@ +# 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. + +org.apache.tuscany.sca.host.corba.jse.tns.CorbaRuntimeModuleActivator diff --git a/java/sca/contrib/modules/host-corba-jse-tns/src/test/java/org/apache/tuscany/sca/host/corba/testing/TnsDefaultCorbaHostTestCase.java b/java/sca/contrib/modules/host-corba-jse-tns/src/test/java/org/apache/tuscany/sca/host/corba/testing/TnsDefaultCorbaHostTestCase.java new file mode 100644 index 0000000000..39d9191f80 --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jse-tns/src/test/java/org/apache/tuscany/sca/host/corba/testing/TnsDefaultCorbaHostTestCase.java @@ -0,0 +1,97 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.host.corba.testing; + +import static junit.framework.Assert.assertTrue; +import static junit.framework.Assert.fail; + +import java.net.Socket; +import java.net.SocketException; + +import org.apache.tuscany.sca.binding.corba.provider.service.DynaCorbaServant; +import org.apache.tuscany.sca.host.corba.jse.tns.TnsDefaultCorbaHost; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * @version $Rev$ $Date$ + * General tests + */ +public class TnsDefaultCorbaHostTestCase { + + private static TnsDefaultCorbaHost host; + + @BeforeClass + public static void start() { + try { + host = new TnsDefaultCorbaHost(); + } catch (Throwable e) { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + @AfterClass + public static void stop() { + host.stop(); + } + + /** + * Test for creating and releasing local name server + */ + @Test + public void test_localNameServer() { + int testPort = 5070; + try { + String testUri1 = "corbaname::localhost:" + testPort + "#Test1"; + String testUri2 = "corbaname::localhost:" + testPort + "#Test2"; + String testUri3 = "corbaname::localhost:" + testPort + "#Test3"; + DynaCorbaServant servant = new DynaCorbaServant(null, "IDL:org/apache/tuscany:1.0"); + host.registerServant(testUri1, servant); + host.registerServant(testUri2, servant); + host.registerServant(testUri3, servant); + Thread.sleep(1000); + // make test connection to name server + Socket socket = new Socket("localhost", testPort); + socket.close(); + // and stop server + host.unregisterServant(testUri1); + host.unregisterServant(testUri2); + // after releasing 2 clients 3rd should still hold the server + socket = new Socket("localhost", testPort); + socket.close(); + host.unregisterServant(testUri3); + Thread.sleep(1000); + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + try { + // previously made 3rd stop so there should be no name server under + // this port + new Socket("localhost", testPort); + fail(); + } catch (Exception e) { + assertTrue(e instanceof SocketException); + } + } +} + diff --git a/java/sca/contrib/modules/host-corba-jse/LICENSE b/java/sca/contrib/modules/host-corba-jse/LICENSE new file mode 100644 index 0000000000..6e529a25c4 --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jse/LICENSE @@ -0,0 +1,205 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + + diff --git a/java/sca/contrib/modules/host-corba-jse/META-INF/MANIFEST.MF b/java/sca/contrib/modules/host-corba-jse/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..060baa69b9 --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jse/META-INF/MANIFEST.MF @@ -0,0 +1,26 @@ +Manifest-Version: 1.0 +Export-Package: org.apache.tuscany.sca.host.corba.naming;uses:="org.om + g.CosNaming.NamingContextPackage,org.omg.CosNaming,org.omg.CosNaming. + NamingContextExtPackage,org.omg.CORBA,org.omg.PortableServer";version + ="1.4",org.apache.tuscany.sca.host.corba.jse;uses:="org.omg.CosNaming + .NamingContextPackage,org.omg.CosNaming,org.apache.tuscany.sca.host.c + orba,org.omg.CORBA,org.apache.tuscany.sca.core";version="2.0.0" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA JSE built-in CORBA Host +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397133187 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA JSE built-in CORBA Host +Import-Package: org.apache.tuscany.sca.core;version="2.0.0",org.apache.t + uscany.sca.host.corba;version="2.0.0",org.apache.tuscany.sca.host.corba + .jse;version="2.0.0",org.apache.tuscany.sca.host.corba.naming;version=" + 1.4",org.omg.CORBA,org.omg.CosNaming,org.omg.CosNaming.NamingContextE + xtPackage,org.omg.CosNaming.NamingContextPackage,org.omg.PortableServ + er,org.omg.CORBA.portable;resolu + tion:=optional +Bundle-SymbolicName: org.apache.tuscany.sca.host.corba.jse +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/host-corba-jse/NOTICE b/java/sca/contrib/modules/host-corba-jse/NOTICE new file mode 100644 index 0000000000..51042eab05 --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jse/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/host-corba-jse/pom.xml b/java/sca/contrib/modules/host-corba-jse/pom.xml new file mode 100644 index 0000000000..72cb65f5b4 --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jse/pom.xml @@ -0,0 +1,38 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + + tuscany-host-corba-jse + Apache Tuscany SCA JSE built-in CORBA Host + + + + org.apache.tuscany.sca + tuscany-host-corba + 2.0-SNAPSHOT + + + + diff --git a/java/sca/contrib/modules/host-corba-jse/src/main/java/org/apache/tuscany/sca/host/corba/jse/CorbaRuntimeModuleActivator.java b/java/sca/contrib/modules/host-corba-jse/src/main/java/org/apache/tuscany/sca/host/corba/jse/CorbaRuntimeModuleActivator.java new file mode 100644 index 0000000000..252a1512e4 --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jse/src/main/java/org/apache/tuscany/sca/host/corba/jse/CorbaRuntimeModuleActivator.java @@ -0,0 +1,48 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.host.corba.jse; + +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.core.ModuleActivator; +import org.apache.tuscany.sca.host.corba.CorbaHostExtensionPoint; + +/** + * @version $Rev$ $Date$ + */ +public class CorbaRuntimeModuleActivator implements ModuleActivator { + // private static final Logger logger = + // Logger.getLogger(CorbaRuntimeModuleActivator.class.getName()); + + private DefaultCorbaHost server; + + public void start(ExtensionPointRegistry extensionPointRegistry) { + + // Register our Corba host + CorbaHostExtensionPoint corbaHosts = extensionPointRegistry.getExtensionPoint(CorbaHostExtensionPoint.class); + server = new DefaultCorbaHost(); + corbaHosts.addCorbaHost(server); + } + + public void stop(ExtensionPointRegistry registry) { + if (server != null) { + server.stop(); + } + } + +} diff --git a/java/sca/contrib/modules/host-corba-jse/src/main/java/org/apache/tuscany/sca/host/corba/jse/DefaultCorbaHost.java b/java/sca/contrib/modules/host-corba-jse/src/main/java/org/apache/tuscany/sca/host/corba/jse/DefaultCorbaHost.java new file mode 100644 index 0000000000..015644e19d --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jse/src/main/java/org/apache/tuscany/sca/host/corba/jse/DefaultCorbaHost.java @@ -0,0 +1,181 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.host.corba.jse; + +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.ConcurrentHashMap; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.apache.tuscany.sca.host.corba.CorbaHost; +import org.apache.tuscany.sca.host.corba.CorbaHostException; +import org.apache.tuscany.sca.host.corba.CorbaHostUtils; +import org.apache.tuscany.sca.host.corba.CorbanameURL; +import org.omg.CORBA.ORB; +import org.omg.CORBA.Object; +import org.omg.CosNaming.NameComponent; +import org.omg.CosNaming.NamingContext; +import org.omg.CosNaming.NamingContextExt; +import org.omg.CosNaming.NamingContextExtHelper; +import org.omg.CosNaming.NamingContextHelper; +import org.omg.CosNaming.NamingContextPackage.InvalidName; +import org.omg.CosNaming.NamingContextPackage.NotFound; + +/** + * @version $Rev$ $Date$ + * Default implementation of JSE CORBA host + */ +public class DefaultCorbaHost implements CorbaHost { + private static final Logger logger = Logger.getLogger(DefaultCorbaHost.class.getName()); + + private Map orbs = new ConcurrentHashMap(); + + private void validatePort(int port) throws IllegalArgumentException { + if (port < 1) { + throw new IllegalArgumentException("Port value should be > 0"); + } + } + + private NamingContextExt getNamingContext(ORB orb, String nameService) throws Exception { + org.omg.CORBA.Object objRef = orb.resolve_initial_references(nameService); + return NamingContextExtHelper.narrow(objRef); + } + + private void handleException(Exception e) throws CorbaHostException { + // The cause of the Exception is JDK specific + if (e instanceof NotFound) { + throw new CorbaHostException(CorbaHostException.NO_SUCH_OBJECT, e); + } else if (e instanceof InvalidName) { + throw new CorbaHostException(e); + } else { + throw new CorbaHostException(e); + } + } + + public void registerServant(String uri, Object servantObject) throws CorbaHostException { + CorbanameURL details = CorbaHostUtils.getServiceDetails(uri); + ORB orb = createORB(details.getHost(), details.getPort(), false); + try { + NamingContext namingCtx = getNamingContext(orb, details.getNameService()); + for (int i = 0; i < details.getNamePath().size() - 1; i++) { + NameComponent nc = new NameComponent(details.getNamePath().get(i), ""); + NameComponent[] path = new NameComponent[] {nc}; + try { + namingCtx = NamingContextHelper.narrow(namingCtx.resolve(path)); + } catch (Exception e) { + namingCtx = namingCtx.bind_new_context(path); + } + } + NameComponent finalName = + new NameComponent(details.getNamePath().get(details.getNamePath().size() - 1), ""); + try { + namingCtx.resolve(new NameComponent[] {finalName}); + // no exception means that some object is already registered + // under this name, we need to crash here + throw new CorbaHostException(CorbaHostException.BINDING_IN_USE); + } catch (NotFound e) { + namingCtx.bind(new NameComponent[] {finalName}, servantObject); + } + } catch (CorbaHostException e) { + throw e; + } catch (Exception e) { + handleException(e); + } + } + + public void unregisterServant(String uri) throws CorbaHostException { + CorbanameURL details = CorbaHostUtils.getServiceDetails(uri); + ORB orb = createORB(details.getHost(), details.getPort(), false); + try { + NamingContextExt namingCtx = getNamingContext(orb, details.getNameService()); + namingCtx.unbind(namingCtx.to_name(details.getName())); + } catch (Exception e) { + handleException(e); + } + } + + public Object lookup(String uri) throws CorbaHostException { + Object result = null; + try { + CorbanameURL url = new CorbanameURL(uri); + ORB orb = createORB(url.getHost(), url.getPort(), false); + NamingContextExt context = getNamingContext(orb, url.getNameService()); + result = context.resolve_str(url.getName()); + } catch (Exception e) { + handleException(e); + } + if (result == null) { + throw new CorbaHostException(CorbaHostException.NO_SUCH_OBJECT); + } + return result; + } + + public ORB createORB(String host, int port, boolean server) throws CorbaHostException { + validatePort(port); + + String key = host + ":" + port; + ORB orb = orbs.get(key); + if (orb != null) { + return orb; + } + // Create an ORB object + Properties props = new Properties(); + props.putAll(System.getProperties()); + + String portStr = String.valueOf(port); + props.put("org.omg.CORBA.ORBServerId", "1000000"); + props.put("org.omg.CORBA.ORBInitialHost", host); + props.put("org.omg.CORBA.ORBInitialPort", portStr); + + // STEP 1: Set ORBPeristentServerPort property + // Set the proprietary property to open up a port to listen to + // INS requests. + + if (server) { + props.put("com.sun.CORBA.POA.ORBPersistentServerPort", portStr); + props.put("com.ibm.CORBA.ListenerPort", portStr); + props.put("gnu.CORBA.ListenerPort", portStr); + // props.put("org.omg.CORBA.ORBClass", + // "org.apache.yoko.orb.CORBA.ORB"); + // props.put("org.omg.CORBA.ORBSingletonClass", + // "org.apache.yoko.orb.CORBA.ORBSingleton"); + props.put("yoko.orb.oa.endpoint", "iiop --host " + host + " --port " + port); + props.put("yoko.orb.poamanager.TNameService.endpoint", "iiop --host " + host); + } + + String[] args = {"-ORBInitialHost", host, "-ORBInitialPort", "" + port}; + orb = ORB.init(args, props); + orbs.put(key, orb); + return orb; + } + + public void stop() { + for (ORB orb : orbs.values()) { + try { + orb.shutdown(true); + orb.destroy(); + } catch (Throwable e) { + logger.log(Level.SEVERE, e.getMessage(), e); + } + } + } + +} diff --git a/java/sca/contrib/modules/host-corba-jse/src/main/java/org/apache/tuscany/sca/host/corba/naming/NamingContextBase.java b/java/sca/contrib/modules/host-corba-jse/src/main/java/org/apache/tuscany/sca/host/corba/naming/NamingContextBase.java new file mode 100644 index 0000000000..59f0ce9a53 --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jse/src/main/java/org/apache/tuscany/sca/host/corba/naming/NamingContextBase.java @@ -0,0 +1,863 @@ +/* + * 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. + */ +/** + * @version $Rev$ $Date$ + */ + +package org.apache.tuscany.sca.host.corba.naming; + +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.omg.CORBA.BAD_PARAM; +import org.omg.CORBA.CompletionStatus; +import org.omg.CORBA.ORB; +import org.omg.CORBA.SystemException; +import org.omg.CosNaming.BindingType; +import org.omg.CosNaming.BindingTypeHolder; +import org.omg.CosNaming.NameComponent; +import org.omg.CosNaming.NamingContext; +import org.omg.CosNaming.NamingContextExtPOA; +import org.omg.CosNaming.NamingContextHelper; +import org.omg.CosNaming.NamingContextExtPackage.InvalidAddress; +import org.omg.CosNaming.NamingContextPackage.AlreadyBound; +import org.omg.CosNaming.NamingContextPackage.InvalidName; +import org.omg.CosNaming.NamingContextPackage.NotFound; +import org.omg.CosNaming.NamingContextPackage.NotFoundReason; +import org.omg.PortableServer.POA; + +public abstract class NamingContextBase extends NamingContextExtPOA { + // the real logger backing instance. We use the interface class as the locator + protected static final Logger logger = Logger.getLogger(NamingContext.class.getName()); + + // set of URL characters that don't require escaping when encoded. + protected final String nonEscaped = ";/?:@&=+$;-_.!~* ()"; + // the orb we're attached to + protected ORB orb; + // the poa we're associated with + protected POA poa; + + /** + * Create a new base NamingContext (super class constructor + * for the derived classes). + * + * @param orb The ORB this is hosted on. + * + * @exception java.lang.Exception + */ + public NamingContextBase(ORB orb, POA poa) throws java.lang.Exception { + super(); + this.orb = orb; + this.poa = poa; + } + + /** + * Bind an object to a given name. + * + * @param n An array of NameComponents that are the target name. + * The last element in the array is binding name for the + * object. The remainder of the array is the path + * for resolving the naming context, relative to the + * current context. All path contexts must already be + * bound in the context tree. + * @param obj The object to be bound. + * + * @exception org.omg.CosNaming.NamingContextPackage.NotFound + * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed + * @exception org.omg.CosNaming.NamingContextPackage.InvalidName + * @exception org.omg.CosNaming.NamingContextPackage.AlreadyBound + */ + public void bind(org.omg.CosNaming.NameComponent[] n, org.omg.CORBA.Object obj) + throws org.omg.CosNaming.NamingContextPackage.NotFound, org.omg.CosNaming.NamingContextPackage.CannotProceed, + org.omg.CosNaming.NamingContextPackage.InvalidName, org.omg.CosNaming.NamingContextPackage.AlreadyBound { + // perform various name validations + validateName(n); + + logNameComponent("bind() name", n); + + // do we need to push through to a deeper naming context first? + if (n.length > 1) { + // resolve the top level name to a context, and have that context + // resolve the rest. + NamingContext context = resolveContext(n[0]); + NameComponent[] subName = extractSubName(n); + + // now pass this along to the next context for the real bind operation. + context.bind(subName, obj); + } else { + NameComponent name = n[0]; + // we need the resolveObject() and bindObject() calls to be consistent, so + // synchronize on this + synchronized (this) { + // see if we have this bound already...can't replace these. + BindingTypeHolder type = new BindingTypeHolder(); + if (resolveObject(name, type) != null) { + throw new AlreadyBound(); + } + type.value = BindingType.nobject; + // ok, this is a new binding, go do it. + bindObject(name, obj, type); + } + } + } + + /** + * Rebind an object to a given name. If an object is + * already bound with this name, the new object replaces + * the bound object's value. If no object has been + * bound already, this is the same as a bind operation. + * + * @param n An array of NameComponents that are the target name. + * The last element in the array is binding name for the + * object. The remainder of the array is the path + * for resolving the naming context, relative to the + * current context. All path contexts must already be + * bound in the context tree. + * @param obj The new value for this binding. + * + * @exception org.omg.CosNaming.NamingContextPackage.NotFound + * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed + * @exception org.omg.CosNaming.NamingContextPackage.InvalidName + * @exception org.omg.CosNaming.NamingContextPackage.AlreadyBound + */ + public void rebind(org.omg.CosNaming.NameComponent[] n, org.omg.CORBA.Object obj) + throws org.omg.CosNaming.NamingContextPackage.NotFound, org.omg.CosNaming.NamingContextPackage.CannotProceed, + org.omg.CosNaming.NamingContextPackage.InvalidName { + // perform various name validations + validateName(n); + + logNameComponent("rebind() name", n); + + // do we need to push through to a deeper naming context first? + if (n.length > 1) { + // resolve the top level name to a context, and have that context + // resolve the rest. + NamingContext context = resolveContext(n[0]); + NameComponent[] subName = extractSubName(n); + + // now pass this along to the next context for the real bind operation. + context.rebind(subName, obj); + } else { + NameComponent name = n[0]; + // we need the resolveObject() and bindObject() calls to be consistent, so + // synchronize on this + synchronized (this) { + // see if we have this bound already...can't replace these. + BindingTypeHolder type = new BindingTypeHolder(); + // for a rebind, we must have an object, and it must be a real object + if (resolveObject(name, type) != null) { + // it has to resolve to a real object. If it is a naming context, + // then this is the wrong binding operation. + if (type.value.value() == BindingType._ncontext) { + throw new NotFound(NotFoundReason.not_object, n); + } + // safe to unbind + unbindObject(name); + } + type.value = BindingType.nobject; + // now bind this object + bindObject(name, obj, type); + } + } + } + + /** + * Bind a new context to a given name. + * + * @param n An array of NameComponents that are the target name. + * The last element in the array is binding name for the + * object. The remainder of the array is the path + * for resolving the naming context, relative to the + * current context. All path contexts must already be + * bound in the context tree. + * @param nc The new naming context added to the tree. + * + * @exception org.omg.CosNaming.NamingContextPackage.NotFound + * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed + * @exception org.omg.CosNaming.NamingContextPackage.InvalidName + * @exception org.omg.CosNaming.NamingContextPackage.AlreadyBound + */ + public void bind_context(org.omg.CosNaming.NameComponent[] n, org.omg.CosNaming.NamingContext nc) + throws org.omg.CosNaming.NamingContextPackage.NotFound, org.omg.CosNaming.NamingContextPackage.CannotProceed, + org.omg.CosNaming.NamingContextPackage.InvalidName, org.omg.CosNaming.NamingContextPackage.AlreadyBound { + // perform various name validations + validateName(n); + + logNameComponent("bind_context() name", n); + + // do we need to push through to a deeper naming context first? + if (n.length > 1) { + // resolve the top level name to a context, and have that context + // resolve the rest. + NamingContext context = resolveContext(n[0]); + NameComponent[] subName = extractSubName(n); + + // now pass this along to the next context for the real bind operation. + context.bind_context(subName, nc); + } else { + NameComponent name = n[0]; + // we need the resolveObject() and bindObject() calls to be consistent, so + // synchronize on this + synchronized (this) { + // see if we have this bound already...can't replace these. + BindingTypeHolder type = new BindingTypeHolder(); + if (resolveObject(name, type) != null) { + throw new AlreadyBound(); + } + type.value = BindingType.ncontext; + // ok, this is a new binding, go do it. + bindObject(name, nc, type); + } + } + } + + /** + * Rebind a context to a given name. If a context is + * already bound with this name, the new context replaces + * the existing context. If no context has been + * bound already, this is the same as a bind operation. + * + * @param n An array of NameComponents that are the target name. + * The last element in the array is binding name for the + * object. The remainder of the array is the path + * for resolving the naming context, relative to the + * current context. All path contexts must already be + * bound in the context tree. + * @param nc The new context to be bound with the name. + * + * @exception org.omg.CosNaming.NamingContextPackage.NotFound + * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed + * @exception org.omg.CosNaming.NamingContextPackage.InvalidName + * @exception org.omg.CosNaming.NamingContextPackage.AlreadyBound + */ + public void rebind_context(org.omg.CosNaming.NameComponent[] n, org.omg.CosNaming.NamingContext nc) + throws org.omg.CosNaming.NamingContextPackage.NotFound, org.omg.CosNaming.NamingContextPackage.CannotProceed, + org.omg.CosNaming.NamingContextPackage.InvalidName { + // perform various name validations + validateName(n); + + logNameComponent("rebind_context() name", n); + + // do we need to push through to a deeper naming context first? + if (n.length > 1) { + // resolve the top level name to a context, and have that context + // resolve the rest. + NamingContext context = resolveContext(n[0]); + NameComponent[] subName = extractSubName(n); + + // now pass this along to the next context for the real bind operation. + context.rebind_context(subName, nc); + } else { + NameComponent name = n[0]; + // we need the resolveObject() and bindObject() calls to be consistent, so + // synchronize on this + synchronized (this) { + // see if we have this bound already...can't replace these. + BindingTypeHolder type = new BindingTypeHolder(); + // for a rebind, we must have an object, and it must be a real object + if (resolveObject(name, type) != null) { + // it has to resolve to a real object. If it is a naming context, + // then this is the wrong binding operation. + if (type.value.value() != BindingType._ncontext) { + throw new NotFound(NotFoundReason.not_context, n); + } + // safe to unbind + unbindObject(name); + } + type.value = BindingType.ncontext; + // now bind this object + bindObject(name, nc, type); + } + } + } + + /** + * Resolve an an entry in the context tree. The + * resolved object may be a bound object or another + * NamingContext. If the named entry is not found, + * a NotFound exception is thrown. + * + * @param n An array of NameComponents that are the target name. + * The last element in the array is binding name for the + * object. The remainder of the array is the path + * for resolving the naming context, relative to the + * current context. All path contexts must already be + * bound in the context tree. + * + * @return The object bound at the indicated location. + * @exception org.omg.CosNaming.NamingContextPackage.NotFound + * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed + * @exception org.omg.CosNaming.NamingContextPackage.InvalidName + * @exception org.omg.CosNaming.NamingContextPackage.AlreadyBound + */ + public org.omg.CORBA.Object resolve(org.omg.CosNaming.NameComponent[] n) + throws org.omg.CosNaming.NamingContextPackage.NotFound, org.omg.CosNaming.NamingContextPackage.CannotProceed, + org.omg.CosNaming.NamingContextPackage.InvalidName { + // perform various name validations + validateName(n); + + logNameComponent("resolve() name", n); + + // do we need to push through to a deeper naming context first? + if (n.length > 1) { + // resolve the top level name to a context, and have that context + // resolve the rest. + NamingContext context = resolveContext(n[0]); + NameComponent[] subName = extractSubName(n); + + // now pass this along to the next context for the real bind operation. + return context.resolve(subName); + } else { + NameComponent name = n[0]; + // see if we have this bound already...can't replace these. + BindingTypeHolder type = new BindingTypeHolder(); + org.omg.CORBA.Object obj = resolveObject(name, type); + if (obj == null) { + // Object was not found + throw new NotFound(NotFoundReason.missing_node, n); + } + return obj; + } + } + + /** + * Remove an entry from the context tree. The + * target object may be a bound object or another + * NamingContext. If the named entry is not found, + * a NotFound exception is thrown. + * + * @param n An array of NameComponents that are the target name. + * The last element in the array is binding name for the + * object. The remainder of the array is the path + * for resolving the naming context, relative to the + * current context. All path contexts must already be + * bound in the context tree. + * + * @exception org.omg.CosNaming.NamingContextPackage.NotFound + * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed + * @exception org.omg.CosNaming.NamingContextPackage.InvalidName + * @exception org.omg.CosNaming.NamingContextPackage.AlreadyBound + */ + public void unbind(org.omg.CosNaming.NameComponent[] n) throws org.omg.CosNaming.NamingContextPackage.NotFound, + org.omg.CosNaming.NamingContextPackage.CannotProceed, org.omg.CosNaming.NamingContextPackage.InvalidName { + // perform various name validations + validateName(n); + + logNameComponent("unbind() name", n); + + // do we need to push through to a deeper naming context first? + if (n.length > 1) { + // resolve the top level name to a context, and have that context + // resolve the rest. + NamingContext context = resolveContext(n[0]); + NameComponent[] subName = extractSubName(n); + + // now pass this along to the next context for the real bind operation. + context.unbind(subName); + } else { + NameComponent name = n[0]; + synchronized (this) { + // see if we have this bound already...can't replace these. + BindingTypeHolder type = new BindingTypeHolder(); + org.omg.CORBA.Object obj = unbindObject(name); + if (obj == null) { + // Object was not found + throw new NotFound(NotFoundReason.missing_node, n); + } + } + } + } + + /** + * Create a new context and bind it in at the target + * location. + * + * @param n An array of NameComponents that are the target name. + * The last element in the array is binding name for the + * object. The remainder of the array is the path + * for resolving the naming context, relative to the + * current context. All path contexts must already be + * bound in the context tree. + * + * @return The newly created context. + * @exception org.omg.CosNaming.NamingContextPackage.NotFound + * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed + * @exception org.omg.CosNaming.NamingContextPackage.InvalidName + * @exception org.omg.CosNaming.NamingContextPackage.AlreadyBound + */ + public synchronized org.omg.CosNaming.NamingContext bind_new_context(org.omg.CosNaming.NameComponent[] n) + throws org.omg.CosNaming.NamingContextPackage.NotFound, org.omg.CosNaming.NamingContextPackage.AlreadyBound, + org.omg.CosNaming.NamingContextPackage.CannotProceed, org.omg.CosNaming.NamingContextPackage.InvalidName { + logNameComponent("bind_new_context() name", n); + + NamingContext context = new_context(); + try { + bind_context(n, context); + NamingContext returnContext = context; + // transfer this to another variable so the finally block doesn't try to destroy this. + context = null; + return returnContext; + } finally { + // if there is a bind failure on this, we need to ensure the context has + // an opportunity to clean up any of its resources. + if (context != null) { + try { + context.destroy(); + } catch (org.omg.CosNaming.NamingContextPackage.NotEmpty e) { + // new contexts should be empty. + } + } + } + } + + /** + * Convert an array of NameComponents into the string + * form of a context name. + * + * @param n The array of NameComponents to convert. + * + * @return The context name, in string form. + * @exception org.omg.CosNaming.NamingContextPackage.InvalidName + */ + public String to_string(org.omg.CosNaming.NameComponent[] n) + throws org.omg.CosNaming.NamingContextPackage.InvalidName { + validateName(n); + + logNameComponent("to_string() name", n); + + // convert the first part of the name + StringBuffer value = new StringBuffer(); + ; + // convert the first component, then build up from there. + nameToString(n[0], value); + + // the remainder need to get a separator + for (int i = 1; i < n.length; i++) { + value.append('/'); + nameToString(n[i], value); + } + return value.toString(); + } + + /** + * Perform the reverse operation of the to_string() method, + * parsing a String context name into an array of + * NameComponents. + * + * @param sn The string form of the name. + * + * @return An array of NameComponents parsed from the String name. + * @exception org.omg.CosNaming.NamingContextPackage.InvalidName + */ + public org.omg.CosNaming.NameComponent[] to_name(String sn) + throws org.omg.CosNaming.NamingContextPackage.InvalidName { + // must have a argument to parse + if (sn == null || sn.length() == 0) { + throw new InvalidName(); + } + + List components = new ArrayList(); + + StringBuffer component = new StringBuffer(); + + int index = 0; + String id = null; + String kind = null; + while (index < sn.length()) { + char ch = sn.charAt(index++); + + // found an escape character or a delimiter? + if (ch == '\\') { + // nothing after the escape? Trouble + if (index >= sn.length()) { + throw new InvalidName(); + } + // get the next character + ch = sn.charAt(index++); + component.append(ch); + } + // we need to process the periods here, to avoid getting + // mixed up with unescaped periods. + else if (ch == '.') { + // already seen a period while scanning? That's not allowed + if (id != null) { + throw new InvalidName(); + } + // pull off the id piece and reset the buffer + id = component.toString(); + component.setLength(0); + } + // found a component delimiter? + else if (ch == '/') { + // not seen a id/kind separator yet? This is an id with no kind + if (id == null) { + id = component.toString(); + kind = ""; + } else { + // we have an id already, pull off the kind + kind = component.toString(); + } + // add the parsed name component + components.add(new NameComponent(id, kind)); + // make sure these are all reset after pulling off a component + component.setLength(0); + id = null; + kind = null; + } else { + component.append(ch); + } + } + + // parse the last section + // not seen a id/kind separator yet? This is an id with no kind + if (id == null) { + id = component.toString(); + kind = ""; + } else { + // we have an id already, pull off the kind + kind = component.toString(); + } + // add the parsed name component + components.add(new NameComponent(id, kind)); + + // and turn this into a component array + return (NameComponent[])components.toArray(new NameComponent[components.size()]); + } + + /** + * Create a URL name for accessing a component by name. The + * URL will have a corbaname: protocol. + * + * @param addr The address location for the naming service used + * to resolve the object. This is in "host:port" form, + * just line a corbaloc: URL. + * @param sn The string mae of the target object. + * + * @return A URL for accessing this object, in String form. + * @exception org.omg.CosNaming.NamingContextExtPackage.InvalidAddress + * @exception org.omg.CosNaming.NamingContextPackage.InvalidName + */ + public String to_url(String addr, String sn) throws org.omg.CosNaming.NamingContextExtPackage.InvalidAddress, + org.omg.CosNaming.NamingContextPackage.InvalidName { + // basic validation + if (addr == null || addr.length() == 0) { + throw new InvalidAddress(); + } + + if (sn == null || sn.length() == 0) { + throw new InvalidName(); + } + + // TODO: What validation, if any, needs to be done here? + return "corbaname:" + addr + "#" + encodeRFC2396Name(sn); + } + + /** + * Resolve a bound object or context using a name + * in String form. + * + * @param n The string name of the object context. This must + * be a form parseable by to_name(). + * + * @return The bound object or context. + * @exception org.omg.CosNaming.NamingContextPackage.NotFound + * @exception org.omg.CosNaming.NamingContextPackage.CannotProceed + * @exception org.omg.CosNaming.NamingContextPackage.InvalidName + */ + public org.omg.CORBA.Object resolve_str(String n) throws org.omg.CosNaming.NamingContextPackage.NotFound, + org.omg.CosNaming.NamingContextPackage.CannotProceed, org.omg.CosNaming.NamingContextPackage.InvalidName { + // this is just a simple convenience method + return resolve(to_name(n)); + } + + // abstract methods that are part of the NamingContext interface that need to be + // implemented by the subclasses. + + /** + * Create a new context of the same type as the + * calling context. + * + * @return A new NamingContext item. + * @exception org.omg.CosNaming.NamingContextPackage.NotFound + * @exception SystemException + */ + public abstract org.omg.CosNaming.NamingContext new_context() throws SystemException; + + /** + * Destroy a context. This method should clean up + * any backing resources associated with the context. + * + * @exception org.omg.CosNaming.NamingContextPackage.NotEmpty + */ + public abstract void destroy() throws org.omg.CosNaming.NamingContextPackage.NotEmpty; + + /** + * Create a list of bound objects an contexts contained + * within this context. + * + * @param how_many The count of elements to return as a BindingList. + * @param bl A holder element for returning the source binding list. + * @param bi A holder for returning a BindingIterator. Any extra + * elements not returned in the BindingList are returned + * in the BindingIterator. + * + * @exception SystemException + */ + public abstract void list(int how_many, + org.omg.CosNaming.BindingListHolder bl, + org.omg.CosNaming.BindingIteratorHolder bi) throws SystemException; + + // abstract methods for the sub class to implement + + /** + * Resolve an object in this context (single level + * resolution). + * + * @param n The name of the target object. + * @param type A type holder for returning the bound object type + * information. + * + * @return The bound object. Returns null if the object does not + * exist in the context. + * @exception SystemException + */ + protected abstract org.omg.CORBA.Object resolveObject(NameComponent n, BindingTypeHolder type) + throws SystemException; + + /** + * Bind an object into the current context. This can + * be either an object or a naming context. + * + * @param n The single-level name of the target object. + * @param obj The object or context to be bound. + * @param type + * + * @exception SystemException + */ + protected abstract void bindObject(NameComponent n, org.omg.CORBA.Object obj, BindingTypeHolder type) + throws SystemException; + + /** + * Unbind an object from the current context. + * + * @param n The name of the target object (single level). + * + * @return The object associated with the binding. Returns null + * if there was no binding currently associated with this + * name. + * @exception SystemException + */ + protected abstract org.omg.CORBA.Object unbindObject(NameComponent n) throws SystemException; + + // implementation specific routines + + /** + * Resolve a name to a context object stored that has + * already been stored in this context. Throws an exception + * if the name cannot be resolved or if the resolved + * object is not a naming context. + * + * @param name The target name. + * + * @return The resolved NamingContext object. + * @exception org.omg.CosNaming.NamingContextPackage.NotFound + */ + protected synchronized NamingContext resolveContext(NameComponent name) + throws org.omg.CosNaming.NamingContextPackage.NotFound { + BindingTypeHolder type = new BindingTypeHolder(); + // Resolve this to an object. We must be able to resolve this. + org.omg.CORBA.Object resolvedReference = resolveObject(name, type); + if (resolvedReference == null) { + throw new NotFound(NotFoundReason.missing_node, new NameComponent[] {name}); + } + + // it has to resolve to a naming context + if (type.value.value() != BindingType._ncontext) { + throw new NotFound(NotFoundReason.not_context, new NameComponent[] {name}); + } + + // in theory, this is a naming context. Narrow it an return. Any + // errors just become a NotFound exception + try { + return NamingContextHelper.narrow(resolvedReference); + } catch (org.omg.CORBA.BAD_PARAM ex) { + throw new NotFound(NotFoundReason.not_context, new NameComponent[] {name}); + } + } + + /** + * Extract the tail portion of a name. This is used + * to strip off the first name element so we can recurse + * on the name resolutions with a resolved context. + * + * @param name The current name array (this MUST have 2 or more + * elements). + * + * @return An array of NameComponent items that is one element + * smaller than the argument array, with the elements + * shifted over. + */ + protected NameComponent[] extractSubName(NameComponent[] name) { + NameComponent[] subName = new NameComponent[name.length - 1]; + System.arraycopy(name, 1, subName, 0, name.length - 1); + return subName; + } + + /** + * Perform common name validity checking. + * + * @param n The NameComponent array to check. + * + * @exception InvalidName + */ + protected void validateName(NameComponent[] n) throws InvalidName { + // perform various name validations + if (n == null) { + throw new BAD_PARAM(27 | org.omg.CORBA.OMGVMCID.value, CompletionStatus.COMPLETED_NO); + } + + // Valid name? + if (n.length < 1) { + throw new InvalidName(); + } + + // we have at least one name, so validate the toplevel item + NameComponent name = n[0]; + + // more name validation + if (name.id.length() == 0 && name.kind.length() == 0) { + throw new InvalidName(); + } + } + + /** + * Convert a NameComponent item into a string form, + * appending it to a StringBuffer. + * + * @param name The source NameComponent. + * @param out The StringBuffer location used to store the name + * value (appended to the end). + */ + protected void nameToString(NameComponent name, StringBuffer out) { + // if the id is null, then we base off of the kind. + if (name.id == null || name.id.length() == 0) { + out.append("."); + // true null name element? That displays as a "." + if (name.kind != null && name.kind.length() != 0) { + escapeName(name.kind, out); + } + } else { + // escape the name + escapeName(name.id, out); + // have a kind qualifier to add on? + if (name.kind != null && name.kind.length() != 0) { + out.append("."); + escapeName(name.kind, out); + } + } + } + + /** + * Process a name or kind element of a NameComponent, + * adding escape characters for '.' or '/' characters + * that might appear in the name. + * + * @param name The name element to process. + * @param out The StringBuffer to copy the escaped name into. + */ + protected void escapeName(String name, StringBuffer out) { + // no characters requiring escapes (common)? + // use this directly + if (name.indexOf('.') == -1 && name.indexOf('/') == -1) { + out.append(name); + } else { + // scan the string adding the escapes + for (int i = 0; i < name.length(); i++) { + char ch = name.charAt(i); + if (ch == '.' || ch == '/') { + out.append('/'); + } + out.append(ch); + } + } + } + + /** + * Perform RFC 2396 escape encoding of a name value. + * + * @param name The input name value. + * + * @return An encoded name, with special characters converted + * into a hex encoded value. + */ + protected String encodeRFC2396Name(String name) { + StringBuffer value = new StringBuffer(); + + for (int i = 0; i < name.length(); i++) { + char ch = name.charAt(i); + + // Alphanumerics and the "acceptable" set of special characters just get copied + // without encoding. + if (Character.isLetterOrDigit(ch) || nonEscaped.indexOf(ch) != -1) { + value.append(ch); + } else { + // this gets converted into a hex value, marked by "%". + value.append('%'); + value.append(Integer.toHexString((int)ch)); + } + } + return value.toString(); + } + + /** + * Test if debug logging is currently available. + * + * @return True if debug level (FINE) logging is currently turned on. + */ + protected boolean isDebugEnabled() { + return logger.isLoggable(Level.FINE); + } + + /** + * Log a line of debug output + * + * @param message The message to log + */ + protected void debug(String message) { + logger.fine(message); + } + + /** + * Log the name components passed in for a request. + * + * @param message A message describing the request context. + * @param n The array of name components. + */ + protected void logNameComponent(String message, NameComponent[] n) { + if (isDebugEnabled()) { + debug(message); + for (int i = 0; i < n.length; i++) { + debug(" NameComponent " + i + " id=" + n[i].id + " kind=" + n[i].kind); + } + } + } + +} diff --git a/java/sca/contrib/modules/host-corba-jse/src/main/java/org/apache/tuscany/sca/host/corba/naming/TransientNameServer.java b/java/sca/contrib/modules/host-corba-jse/src/main/java/org/apache/tuscany/sca/host/corba/naming/TransientNameServer.java new file mode 100644 index 0000000000..599f5bca54 --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jse/src/main/java/org/apache/tuscany/sca/host/corba/naming/TransientNameServer.java @@ -0,0 +1,133 @@ +/* + * 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. + */ + +/** + * @version $Rev$ $Date$ + */ +package org.apache.tuscany.sca.host.corba.naming; + +import org.omg.CORBA.ORB; + +/** + * A stand-alone naming service launchable from a command line. + */ +public class TransientNameServer { + private final TransientNameService service; + private final Object flag = new Object(); + private Boolean started; + + public TransientNameServer(String host, int port, String serviceName) { + this.service = new TransientNameService(host, port, serviceName); + } + + public ORB getORB() { + return service.getORB(); + } + + public Thread start() { + Thread t = new Thread() { + public void run() { + ORB orb = null; + synchronized (flag) { + try { + service.run(); + orb = service.getORB(); + started = Boolean.TRUE; + } catch (Throwable e) { + started = Boolean.FALSE; + throw new IllegalStateException(e); + } finally { + flag.notifyAll(); + } + } + // Wait for requests + orb.run(); + } + }; + t.setDaemon(true); + t.start(); + checkState(); + return t.isAlive() ? t : null; + } + + private Boolean checkState() { + synchronized (flag) { + while (started == null) { + try { + flag.wait(); + } catch (InterruptedException e) { + return null; + } + } + return started; + } + } + + public void stop() { + if (started == Boolean.TRUE) { + service.destroy(); + } + } + + /** + * Launch a name service as a stand alone process. The + * Host, port, and service name are controlled using + * program arguments. + * + * @param args The array of arguments for tailoring the service. + * + * @exception Exception + */ + public static void main(String args[]) throws Exception { + int port = TransientNameService.DEFAULT_SERVICE_PORT; + String host = TransientNameService.DEFAULT_SERVICE_HOST; + String serviceName = TransientNameService.DEFAULT_SERVICE_NAME; + + // see if we have + for (int i = 0; i < args.length; i++) { + if (args[i].equals("-ORBInitialPort")) { + i++; + if (i < args.length) { + port = java.lang.Integer.parseInt(args[i]); + } else { + throw new IllegalArgumentException("Invalid -ORBInitialPort option"); + } + } else if (args[i].equals("-ORBInitialHost")) { + i++; + if (i < args.length) { + host = args[i]; + } else { + throw new IllegalArgumentException("Invalid -ORBInitialHost option"); + } + } else if (args[i].equals("-ORBServiceName")) { + i++; + if (i < args.length) { + serviceName = args[i]; + } else { + throw new IllegalArgumentException("Invalid -ORBServiceName option"); + } + } + + } + // create a services, and just spin it off. We wait forever after that. + TransientNameServer server = new TransientNameServer(host, port, serviceName); + server.start().join(); + } + +} diff --git a/java/sca/contrib/modules/host-corba-jse/src/main/java/org/apache/tuscany/sca/host/corba/naming/TransientNameService.java b/java/sca/contrib/modules/host-corba-jse/src/main/java/org/apache/tuscany/sca/host/corba/naming/TransientNameService.java new file mode 100644 index 0000000000..77617a6c5c --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jse/src/main/java/org/apache/tuscany/sca/host/corba/naming/TransientNameService.java @@ -0,0 +1,200 @@ +/* + * 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. + */ + +/** + * @version $Rev$ $Date$ + */ +package org.apache.tuscany.sca.host.corba.naming; + +import java.lang.reflect.Method; +import java.util.Collection; +import java.util.Properties; + +import org.omg.CORBA.ORB; +import org.omg.CORBA.Policy; +import org.omg.PortableServer.IdAssignmentPolicyValue; +import org.omg.PortableServer.LifespanPolicyValue; +import org.omg.PortableServer.POA; +import org.omg.PortableServer.ServantRetentionPolicyValue; + +/** + * A transient name service attached to an ORB. This + * class manages all of the housekeeping for creating a + * TransientNamingContext and a exposing it using an + * ORB. + */ +public class TransientNameService { + // the default registered name service + static public final String DEFAULT_SERVICE_NAME = "TNameService"; + // the default listening port + static public final int DEFAULT_SERVICE_PORT = 900; + // the default host name + static public final String DEFAULT_SERVICE_HOST = "localhost"; + + // the service root context + protected TransientNamingContext initialContext; + // initial listening port + protected int port; + // initial listening host + protected String host; + // the service name (used for registing for the corbaloc:: URL name + protected String serviceName; + // the orb instance we're running on + protected ORB createdOrb; + + /** + * Create a new TransientNameService, using all default + * attributes. + */ + public TransientNameService() { + this(DEFAULT_SERVICE_HOST, DEFAULT_SERVICE_PORT, DEFAULT_SERVICE_NAME); + } + + /** + * Create a default-named name service using the specified + * host and port parameters. + * + * @param host The host to expose this under. + * @param port The initial listening port. + */ + public TransientNameService(String host, int port) { + this(host, port, DEFAULT_SERVICE_NAME); + } + + /** + * Create a specifically-named name service using the specified + * host and port parameters. + * + * @param host The host to expose this under. + * @param port The initial listening port. + * @param name The name to register this service under using the + * BootManager. + */ + public TransientNameService(String host, int port, String name) { + this.port = port; + this.host = host; + this.serviceName = name; + } + + /** + * Start up the name service, including creating an + * ORB instance to expose it under. + * + * @exception TransientServiceException + */ + public void run() throws TransientServiceException { + // Create an ORB object + Properties props = new Properties(); + props.putAll(System.getProperties()); + + String portStr = String.valueOf(port); + props.put("org.omg.CORBA.ORBServerId", "1000000"); + props.put("org.omg.CORBA.ORBInitialHost", host); + props.put("org.omg.CORBA.ORBInitialPort", portStr); + + // STEP 1: Set ORBPeristentServerPort property + // Set the proprietary property to open up a port to listen to + // INS requests. + + props.put("com.sun.CORBA.POA.ORBPersistentServerPort", portStr); + props.put("com.ibm.CORBA.ListenerPort", portStr); + props.put("gnu.CORBA.ListenerPort", portStr); + // props.put("org.omg.CORBA.ORBClass", "org.apache.yoko.orb.CORBA.ORB"); + // props.put("org.omg.CORBA.ORBSingletonClass", "org.apache.yoko.orb.CORBA.ORBSingleton"); + props.put("yoko.orb.oa.endpoint", "iiop --host " + host + " --port " + port); + props.put("yoko.orb.poamanager.TNameService.endpoint", "iiop --host " + host); + + String[] args = {"-ORBInitialHost", host, "-ORBInitialPort", "" + port}; + createdOrb = ORB.init(args, props); + + // now initialize the service + initialize(createdOrb); + + } + + /** + * Initialize a transient name service on a specific + * ORB. + * + * @param orb The ORB hosting the service. + * + * @exception TransientServiceException + */ + public void initialize(ORB orb) throws TransientServiceException { + try { + // get the root POA. We're going to re + POA rootPOA = (POA)orb.resolve_initial_references("RootPOA"); + rootPOA.the_POAManager().activate(); + + // we need to create a POA to manage this named instance, and then activate + // a context on it. + Policy[] policy = new Policy[3]; + policy[0] = rootPOA.create_lifespan_policy(LifespanPolicyValue.TRANSIENT); + policy[1] = rootPOA.create_id_assignment_policy(IdAssignmentPolicyValue.SYSTEM_ID); + policy[2] = rootPOA.create_servant_retention_policy(ServantRetentionPolicyValue.RETAIN); + + POA nameServicePOA = rootPOA.create_POA("TNameService", null, policy); + nameServicePOA.the_POAManager().activate(); + + // create our initial context, and register that with the ORB as the name service + initialContext = new TransientNamingContext(orb, nameServicePOA); + org.omg.CORBA.Object context = initialContext.getRootContext(); + Method method = + orb.getClass().getMethod("register_initial_reference", String.class, org.omg.CORBA.Object.class); + method.invoke(orb, serviceName, context); + method.invoke(orb, "NamingService", context); + method.invoke(orb, "NameService", context); + } catch (Exception e) { + throw new TransientServiceException("Unable to initialize name service", e); + } + } + + /** + * Destroy the created service. + */ + public void destroy() { + // only destroy this if we created the orb instance. + if (createdOrb != null) { + createdOrb.shutdown(false); + createdOrb.destroy(); + + try { + // This is a workaround to close the sockets for SUN ORB + Method m = createdOrb.getClass().getMethod("getTransportManager"); + Object tm = m.invoke(createdOrb); + m = tm.getClass().getMethod("close"); + m.invoke(tm); + m = tm.getClass().getMethod("getAcceptors"); + Collection acceptors = (Collection) m.invoke(tm); + for(Object a: acceptors) { + m = a.getClass().getMethod("close"); + m.invoke(a); + } + } catch (Throwable e) { + // Ignore + } + createdOrb = null; + } + } + + public ORB getORB() { + return createdOrb; + } + +} diff --git a/java/sca/contrib/modules/host-corba-jse/src/main/java/org/apache/tuscany/sca/host/corba/naming/TransientNamingContext.java b/java/sca/contrib/modules/host-corba-jse/src/main/java/org/apache/tuscany/sca/host/corba/naming/TransientNamingContext.java new file mode 100644 index 0000000000..a7164e9ef3 --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jse/src/main/java/org/apache/tuscany/sca/host/corba/naming/TransientNamingContext.java @@ -0,0 +1,440 @@ +/* + * 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. + */ +/** + * @version $Rev$ $Date$ + */ + +package org.apache.tuscany.sca.host.corba.naming; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +import org.omg.CORBA.INTERNAL; +import org.omg.CORBA.ORB; +import org.omg.CORBA.SystemException; +import org.omg.CosNaming.Binding; +import org.omg.CosNaming.BindingHolder; +import org.omg.CosNaming.BindingIteratorHelper; +import org.omg.CosNaming.BindingIteratorPOA; +import org.omg.CosNaming.BindingType; +import org.omg.CosNaming.BindingTypeHolder; +import org.omg.CosNaming.NameComponent; +import org.omg.CosNaming.NamingContext; +import org.omg.CosNaming.NamingContextHelper; +import org.omg.CosNaming.NamingContextPackage.NotEmpty; +import org.omg.PortableServer.POA; + +public class TransientNamingContext extends NamingContextBase { + // the bindings maintained by this context + protected HashMap bindings = new HashMap(); + // the root context object + protected org.omg.CORBA.Object rootContext = null; + + /** + * Create a top-level naming context. + * + * @param orb The orb hosting this context. + * @param poa The POA used to activate the object. + * + * @exception Exception + */ + public TransientNamingContext(ORB orb, POA poa) throws Exception { + this(orb, poa, null); + // now get the initial root context as a corba object. + + byte[] objectId = poa.activate_object(this); + rootContext = poa.id_to_reference(objectId); + + } + + /** + * Construct a TransientNamingContext subcontext. + * + * @param orb The orb this context is associated with. + * @param poa The POA the root context is activated under. + * @param root The root context. + * + * @exception Exception + */ + public TransientNamingContext(ORB orb, POA poa, org.omg.CORBA.Object root) throws Exception { + super(orb, poa); + // save the root context link. + rootContext = root; + } + + // abstract methods part of the interface contract that the implementation is required + // to supply. + + /** + * Create a new context of the same type as the + * calling context. + * + * @return A new NamingContext item. + * @exception org.omg.CosNaming.NamingContextPackage.NotFound + * @exception SystemException + */ + public NamingContext new_context() throws SystemException { + try { + // create a new context. Then we need to register this with the POA and activate it. + TransientNamingContext newContext = new TransientNamingContext(orb, poa, rootContext); + + byte[] objectId = poa.activate_object(newContext); + org.omg.CORBA.Object obj = poa.id_to_reference(objectId); + return NamingContextHelper.narrow(obj); + } catch (SystemException e) { + // just propagate system exceptions + throw e; + } catch (Exception e) { + throw (INTERNAL)(new INTERNAL("Unable to create new naming context").initCause(e)); + } + } + + /** + * Destroy a context. This method should clean up + * any backing resources associated with the context. + * + * @exception org.omg.CosNaming.NamingContextPackage.NotEmpty + */ + public synchronized void destroy() throws org.omg.CosNaming.NamingContextPackage.NotEmpty { + // still holding bound objects? Not allowed to destroy + if (!bindings.isEmpty()) { + throw new NotEmpty(); + } + + try { + // now detach ourselves from the POA + byte[] objectId = poa.servant_to_id(this); + if (objectId != null) { + poa.deactivate_object(objectId); + } + } catch (Exception e) { + // ignore + } + } + + /** + * Create a list of bound objects an contexts contained + * within this context. + * + * @param how_many The count of elements to return as a BindingList. + * @param bl A holder element for returning the source binding list. + * @param bi A holder for returning a BindingIterator. Any extra + * elements not returned in the BindingList are returned + * in the BindingIterator. + * + * @exception SystemException + */ + public synchronized void list(int how_many, + org.omg.CosNaming.BindingListHolder bl, + org.omg.CosNaming.BindingIteratorHolder bi) throws SystemException { + TransientBindingIterator iterator = new TransientBindingIterator(poa, (HashMap)bindings.clone()); + // have the iterator fill in the entries here + iterator.next_n(how_many, bl); + + // now it's necessary to activate this iterator with the poa. The value we pass + // back is the narrowed activated object + try { + byte[] objectId = poa.activate_object(iterator); + org.omg.CORBA.Object obj = poa.id_to_reference(objectId); + + bi.value = BindingIteratorHelper.narrow(obj); + } catch (SystemException e) { + // just propagate system exceptions + throw e; + } catch (Exception e) { + throw (INTERNAL)(new INTERNAL("Unable to activate BindingIterator").initCause(e)); + } + } + + // lower level functions that are used by the base class + + /** + * Resolve an object in this context (single level + * resolution). + * + * @param n The name of the target object. + * @param type A type holder for returning the bound object type + * information. + * + * @return The bound object. Returns null if the object does not + * exist in the context. + * @exception SystemException + */ + protected org.omg.CORBA.Object resolveObject(NameComponent n, BindingTypeHolder type) throws SystemException { + // special call to resolve the root context. This is the only one that goes backwards. + if (n.id.length() == 0 && n.kind.length() == 0) { + // this is a name context item, so set it properly. + type.value = BindingType.ncontext; + return rootContext; + } + + BindingKey key = new BindingKey(n); + BoundObject obj = (BoundObject)bindings.get(key); + // if not in the table, just return null + if (obj == null) { + return null; + } + // update the type information and return the bound object reference. + type.value = obj.type; + return obj.boundObject; + } + + /** + * Bind an object into the current context. This can + * be either an object or a naming context. + * + * @param n The single-level name of the target object. + * @param obj The object or context to be bound. + * @param type + * + * @exception SystemException + */ + protected void bindObject(NameComponent n, org.omg.CORBA.Object obj, BindingTypeHolder type) throws SystemException { + // fairly simple table put... + bindings.put(new BindingKey(n), new BoundObject(n, obj, type.value)); + } + + /** + * Unbind an object from the current context. + * + * @param n The name of the target object (single level). + * + * @return The object associated with the binding. Returns null + * if there was no binding currently associated with this + * name. + * @exception SystemException + */ + protected org.omg.CORBA.Object unbindObject(NameComponent n) throws SystemException { + //remove the object from the hash table, returning the bound object if it exists. + BindingKey key = new BindingKey(n); + BoundObject obj = (BoundObject)bindings.remove(key); + + if (obj != null) { + return obj.boundObject; + } + return null; + } + + /** + * Retrieve the rootContext for this NamingContext. + * + * @return The rootContext CORBA object associated with this context. + */ + public org.omg.CORBA.Object getRootContext() { + return rootContext; + } + + /** + * Internal class used for HashMap lookup keys. + */ + class BindingKey { + // the name component this is a HashMap key for. + public NameComponent name; + private int hashval = 0; + + /** + * Create a new BindingKey for a NameComponent. + * + * @param n The lookup name. + */ + public BindingKey(NameComponent n) { + name = n; + // create a hash value used for lookups + if (name.id != null) { + hashval += name.id.hashCode(); + } + if (name.kind != null) { + hashval += name.kind.hashCode(); + } + } + + /** + * Return the hashcode associated with this binding key. The + * hashcode is created using the NameComponent id and + * kind fields. + * + * @return The lookup hashvalue associated with this key. + */ + public int hashCode() { + return hashval; + } + + /** + * Compare two BindingKeys for equality (used for HashMap + * lookups). + * + * @param other The comparison partner. + * + * @return True if the keys are equivalent, false otherwise. + */ + public boolean equals(Object other) { + // if not given or the wrong type, this is false. + if (other == null || !(other instanceof BindingKey)) { + return false; + } + + BindingKey otherKey = (BindingKey)other; + + // verify first on the id name. + if (name.id != null) { + if (otherKey.name.id == null) { + return false; + } + if (!name.id.equals(otherKey.name.id)) { + return false; + } + } else { + if (otherKey.name.id != null) { + return false; + } + } + // this is a match so far...now compare the kinds + if (name.kind != null) { + if (otherKey.name.kind == null) { + return false; + } + if (!name.kind.equals(otherKey.name.kind)) { + return false; + } + } else { + if (otherKey.name.kind != null) { + return false; + } + } + return true; + } + } + + /** + * Internal class used to store bound objects in the HashMap. + */ + public class BoundObject { + // the name this object is bound under. + public NameComponent name; + // the type of binding (either nobject or ncontext). + public BindingType type; + // the actual bound object. + public org.omg.CORBA.Object boundObject; + + /** + * Create a new object binding for our HashMap. + * + * @param name The bound object's name. + * @param boundObject + * The bound object (real object or NamingContext). + * @param type The type information associated with this binding. + */ + public BoundObject(NameComponent name, org.omg.CORBA.Object boundObject, BindingType type) { + this.name = name; + this.boundObject = boundObject; + this.type = type; + } + } + + /** + * Context implementation version of the BindingIterator + * object used to return list items. + */ + public class TransientBindingIterator extends BindingIteratorPOA { + // the POA used to activate this object (required for destroy(); + private POA poa; + // the binding set we're iterating over (this must be a snapshot copy) + private HashMap bindings; + // the iterator use to access the bindings + private Iterator iterator; + + /** + * Create a new BindingIterator hosted by the given POA and + * iterating over the map of items. + * + * @param poa The hosting POA. + * @param bindings The HashMap of bound objects. + */ + public TransientBindingIterator(POA poa, HashMap bindings) { + this.poa = poa; + this.bindings = bindings; + this.iterator = bindings.values().iterator(); + } + + /** + * Return the next object in the iteration sequence. + * + * @param b The BindingHolder used to return the next item. If + * we've reached the end of the sequence, an item + * with an empty name is returned. + * + * @return true if there is another item, false otherwise. + */ + public boolean next_one(org.omg.CosNaming.BindingHolder b) { + if (iterator.hasNext()) { + // return this as a Binding value. + BoundObject obj = (BoundObject)iterator.next(); + b.value = new Binding(new NameComponent[] {obj.name}, obj.type); + return true; + } else { + // return an empty element + b.value = new Binding(new NameComponent[0], BindingType.nobject); + return false; + } + } + + /** + * Retrieve the next "n" items from the list, returned + * as a BindingList. + * + * @param how_many The count of items to retrieve. + * @param bl A holder for returning an array of Bindings for + * the returned items. + * + * @return true if any items were returned, false if there's + * nothing left to return. + */ + public boolean next_n(int how_many, org.omg.CosNaming.BindingListHolder bl) { + List accum = new ArrayList(); + BindingHolder holder = new BindingHolder(); + int i = 0; + // Keep iterating as long as there are entries + while (i < how_many && next_one(holder)) { + accum.add(holder.value); + i++; + } + + // convert to an array and return whether we found anything. + bl.value = (Binding[])accum.toArray(new Binding[accum.size()]); + return accum.isEmpty(); + } + + /** + * Destory this BindingIterator instance, which deativates + * it from the hosting POA. + */ + public void destroy() { + try { + // we need to deactivate this from the POA. + byte[] objectId = poa.servant_to_id(this); + if (objectId != null) { + poa.deactivate_object(objectId); + } + } catch (Exception e) { + } + } + } +} diff --git a/java/sca/contrib/modules/host-corba-jse/src/main/java/org/apache/tuscany/sca/host/corba/naming/TransientServiceException.java b/java/sca/contrib/modules/host-corba-jse/src/main/java/org/apache/tuscany/sca/host/corba/naming/TransientServiceException.java new file mode 100644 index 0000000000..444143f173 --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jse/src/main/java/org/apache/tuscany/sca/host/corba/naming/TransientServiceException.java @@ -0,0 +1,44 @@ +/* + * 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. + */ + +/** + * @version $Rev$ $Date$ + */ +package org.apache.tuscany.sca.host.corba.naming; + +public class TransientServiceException extends Exception { + + /** + * + */ + private static final long serialVersionUID = -2611596914331994827L; + + public TransientServiceException() { + super(); + } + + public TransientServiceException(String reason) { + super(reason); + } + + public TransientServiceException(String reason, Exception cause) { + super(reason, cause); + } + +} diff --git a/java/sca/contrib/modules/host-corba-jse/src/main/resources/META-INF/services/org.apache.tuscany.sca.core.ModuleActivator b/java/sca/contrib/modules/host-corba-jse/src/main/resources/META-INF/services/org.apache.tuscany.sca.core.ModuleActivator new file mode 100644 index 0000000000..a96baed33e --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jse/src/main/resources/META-INF/services/org.apache.tuscany.sca.core.ModuleActivator @@ -0,0 +1,18 @@ +# 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. + +org.apache.tuscany.sca.host.corba.jse.CorbaRuntimeModuleActivator \ No newline at end of file diff --git a/java/sca/contrib/modules/host-corba-jse/src/test/java/org/apache/tuscany/sca/host/corba/testing/DefaultCorbaHostTestCase.java b/java/sca/contrib/modules/host-corba-jse/src/test/java/org/apache/tuscany/sca/host/corba/testing/DefaultCorbaHostTestCase.java new file mode 100644 index 0000000000..8084e39956 --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jse/src/test/java/org/apache/tuscany/sca/host/corba/testing/DefaultCorbaHostTestCase.java @@ -0,0 +1,250 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.host.corba.testing; + +import static junit.framework.Assert.assertEquals; +import static junit.framework.Assert.assertTrue; +import static junit.framework.Assert.fail; + +import java.net.ConnectException; +import java.net.Socket; +import java.net.SocketException; + +import org.apache.tuscany.sca.host.corba.CorbaHost; +import org.apache.tuscany.sca.host.corba.CorbaHostException; +import org.apache.tuscany.sca.host.corba.CorbaHostUtils; +import org.apache.tuscany.sca.host.corba.jse.DefaultCorbaHost; +import org.apache.tuscany.sca.host.corba.naming.TransientNameServer; +import org.apache.tuscany.sca.host.corba.naming.TransientNameService; +import org.apache.tuscany.sca.host.corba.testing.general.TestInterface; +import org.apache.tuscany.sca.host.corba.testing.general.TestInterfaceHelper; +import org.apache.tuscany.sca.host.corba.testing.servants.TestInterfaceServant; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; + +/** + * General tests + */ +public class DefaultCorbaHostTestCase { + + private static final String LOCALHOST = "localhost"; + private static final int DEFAULT_PORT = 11100; // 1050; + + private static CorbaHost host; + + private static TransientNameServer server; + + @BeforeClass + public static void start() { + try { + server = new TransientNameServer(LOCALHOST, DEFAULT_PORT, TransientNameService.DEFAULT_SERVICE_NAME); + Thread t = server.start(); + if (t == null) { + fail("The naming server cannot be started"); + } + host = new DefaultCorbaHost(); + } catch (Throwable e) { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + @AfterClass + public static void stop() { + server.stop(); + } + + /** + * Tests registering and lookup CORBA services + */ + @Test + public void test_registerServant() { + try { + String uri = CorbaHostUtils.createCorbanameURI(LOCALHOST, DEFAULT_PORT, "Nested/Test"); + TestInterface servant = new TestInterfaceServant(); + host.registerServant(uri, servant); + TestInterface ref = TestInterfaceHelper.narrow(host.lookup(uri)); + assertEquals(2, ref.getInt(2)); + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + } + + /** + * Tests unregistering servants + */ + @Test + public void test_unregisterServant() { + try { + String objName = "Unregistering/Test"; + String uri = CorbaHostUtils.createCorbanameURI(LOCALHOST, DEFAULT_PORT, objName); + TestInterface servant = new TestInterfaceServant(); + + // creating and releasing using corbaname URI + host.registerServant(uri, servant); + host.unregisterServant(uri); + host.registerServant(uri, servant); + host.unregisterServant(uri); + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + } + + /** + * Tests situation when name is already registered + */ + @Test + public void test_nameAlreadyRegistered() { + // test using URI + try { + TestInterface servant = new TestInterfaceServant(); + String uri = CorbaHostUtils.createCorbanameURI(LOCALHOST, DEFAULT_PORT, "AlreadyRegisteredTest2"); + host.registerServant(uri, servant); + host.registerServant(uri, servant); + fail(); + } catch (CorbaHostException e) { + assertTrue(e.getMessage().equals(CorbaHostException.BINDING_IN_USE)); + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + } + + /** + * Tests getting non existing reference + */ + @Test + public void test_getNonExistingObject() { + // try to fetch object with corbaname URI + try { + host.lookup(CorbaHostUtils.createCorbanameURI("NonExistingOne", DEFAULT_PORT, LOCALHOST)); + fail(); + } catch (CorbaHostException e) { + // The message is JDK-specific + // assertTrue(e.getMessage().equals(CorbaHostException.NO_SUCH_OBJECT)); + } catch (Exception e) { + // e.printStackTrace(); + fail(); + } + } + + /** + * Tests unregistering non existing reference + */ + @Test + public void test_unregisterNonExistentObject() { + // test using URI + try { + String uri = CorbaHostUtils.createCorbanameURI(LOCALHOST, DEFAULT_PORT, "NonExistingReference1"); + host.unregisterServant(uri); + fail(); + } catch (CorbaHostException e) { + assertTrue(e.getMessage().equals(CorbaHostException.NO_SUCH_OBJECT)); + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + } + + /** + * Tests registering under invalid host + */ + @Test + public void test_invalidHost() { + try { + String url = CorbaHostUtils.createCorbanameURI("not_" + LOCALHOST, DEFAULT_PORT, "Name"); + TestInterface servant = new TestInterfaceServant(); + host.registerServant(url, servant); + fail(); + } catch (CorbaHostException e) { + // Expected + } catch (Exception e) { + // e.printStackTrace(); + fail(e.getMessage()); + } + } + + /** + * Tests registering under invalid port + */ + @Test + public void test_invalidPort() { + try { + String url = CorbaHostUtils.createCorbanameURI(LOCALHOST, DEFAULT_PORT + 1, "Name"); + TestInterface servant = new TestInterfaceServant(); + host.registerServant(url, servant); + fail(); + } catch (CorbaHostException e) { + // Expected + } catch (Exception e) { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + /** + * Tests registering under invalid name + */ + @Test + @Ignore("SUN JDK 6 is happy with all kind of names") + public void test_invalidBindingName() { + try { + TestInterface servant = new TestInterfaceServant(); + host.registerServant("---", servant); + fail(); + } catch (CorbaHostException e) { + assertTrue(e.getMessage().equals(CorbaHostException.WRONG_NAME)); + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + } + + /** + * + */ + @Test + public void test_ensureORBStopped() { + try { + int innerORBPort = 11102; + TransientNameServer innerServer = + new TransientNameServer(LOCALHOST, innerORBPort, TransientNameService.DEFAULT_SERVICE_NAME); + innerServer.start(); + innerServer.stop(); + try { + Thread.sleep(500); + } catch (Exception e) { + } + new Socket(LOCALHOST, innerORBPort); + fail(); + } catch (Exception e) { + if (e instanceof ConnectException) { + assertTrue(true); + } else { + e.printStackTrace(); + } + } + } + +} diff --git a/java/sca/contrib/modules/host-corba-jse/src/test/java/org/apache/tuscany/sca/host/corba/testing/general/TestInterface.java b/java/sca/contrib/modules/host-corba-jse/src/test/java/org/apache/tuscany/sca/host/corba/testing/general/TestInterface.java new file mode 100644 index 0000000000..8d1a9db9e9 --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jse/src/test/java/org/apache/tuscany/sca/host/corba/testing/general/TestInterface.java @@ -0,0 +1,30 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.host.corba.testing.general; + +/** +* org/apache/tuscany/sca/host/corba/testing/general/TestInterface.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* ¶roda, 25 czerwiec 2008 16:19:44 CEST +*/ + +public interface TestInterface extends TestInterfaceOperations, org.omg.CORBA.Object, org.omg.CORBA.portable.IDLEntity { +} // interface TestInterface diff --git a/java/sca/contrib/modules/host-corba-jse/src/test/java/org/apache/tuscany/sca/host/corba/testing/general/TestInterfaceHelper.java b/java/sca/contrib/modules/host-corba-jse/src/test/java/org/apache/tuscany/sca/host/corba/testing/general/TestInterfaceHelper.java new file mode 100644 index 0000000000..fe85dc7743 --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jse/src/test/java/org/apache/tuscany/sca/host/corba/testing/general/TestInterfaceHelper.java @@ -0,0 +1,98 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.host.corba.testing.general; + +/** +* org/apache/tuscany/sca/host/corba/testing/general/TestInterfaceHelper.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* ¶roda, 25 czerwiec 2008 16:19:44 CEST +*/ + +abstract public class TestInterfaceHelper { + private static String _id = "IDL:org/apache/tuscany/sca/host/corba/testing/general/TestInterface:1.0"; + + public static void insert(org.omg.CORBA.Any a, org.apache.tuscany.sca.host.corba.testing.general.TestInterface that) { + org.omg.CORBA.portable.OutputStream out = a.create_output_stream(); + a.type(type()); + write(out, that); + a.read_value(out.create_input_stream(), type()); + } + + public static org.apache.tuscany.sca.host.corba.testing.general.TestInterface extract(org.omg.CORBA.Any a) { + return read(a.create_input_stream()); + } + + private static org.omg.CORBA.TypeCode __typeCode = null; + + synchronized public static org.omg.CORBA.TypeCode type() { + if (__typeCode == null) { + __typeCode = + org.omg.CORBA.ORB.init() + .create_interface_tc(org.apache.tuscany.sca.host.corba.testing.general.TestInterfaceHelper.id(), + "TestInterface"); + } + return __typeCode; + } + + public static String id() { + return _id; + } + + public static org.apache.tuscany.sca.host.corba.testing.general.TestInterface read(org.omg.CORBA.portable.InputStream istream) { + return narrow(istream.read_Object(_TestInterfaceStub.class)); + } + + public static void write(org.omg.CORBA.portable.OutputStream ostream, + org.apache.tuscany.sca.host.corba.testing.general.TestInterface value) { + ostream.write_Object((org.omg.CORBA.Object)value); + } + + public static org.apache.tuscany.sca.host.corba.testing.general.TestInterface narrow(org.omg.CORBA.Object obj) { + if (obj == null) + return null; + else if (obj instanceof org.apache.tuscany.sca.host.corba.testing.general.TestInterface) + return (org.apache.tuscany.sca.host.corba.testing.general.TestInterface)obj; + else if (!obj._is_a(id())) + throw new org.omg.CORBA.BAD_PARAM(); + else { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate(); + org.apache.tuscany.sca.host.corba.testing.general._TestInterfaceStub stub = + new org.apache.tuscany.sca.host.corba.testing.general._TestInterfaceStub(); + stub._set_delegate(delegate); + return stub; + } + } + + public static org.apache.tuscany.sca.host.corba.testing.general.TestInterface unchecked_narrow(org.omg.CORBA.Object obj) { + if (obj == null) + return null; + else if (obj instanceof org.apache.tuscany.sca.host.corba.testing.general.TestInterface) + return (org.apache.tuscany.sca.host.corba.testing.general.TestInterface)obj; + else { + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate(); + org.apache.tuscany.sca.host.corba.testing.general._TestInterfaceStub stub = + new org.apache.tuscany.sca.host.corba.testing.general._TestInterfaceStub(); + stub._set_delegate(delegate); + return stub; + } + } + +} diff --git a/java/sca/contrib/modules/host-corba-jse/src/test/java/org/apache/tuscany/sca/host/corba/testing/general/TestInterfaceHolder.java b/java/sca/contrib/modules/host-corba-jse/src/test/java/org/apache/tuscany/sca/host/corba/testing/general/TestInterfaceHolder.java new file mode 100644 index 0000000000..305a4d7b97 --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jse/src/test/java/org/apache/tuscany/sca/host/corba/testing/general/TestInterfaceHolder.java @@ -0,0 +1,51 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.host.corba.testing.general; + +/** +* org/apache/tuscany/sca/host/corba/testing/general/TestInterfaceHolder.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* ¶roda, 25 czerwiec 2008 16:19:44 CEST +*/ + +public final class TestInterfaceHolder implements org.omg.CORBA.portable.Streamable { + public org.apache.tuscany.sca.host.corba.testing.general.TestInterface value = null; + + public TestInterfaceHolder() { + } + + public TestInterfaceHolder(org.apache.tuscany.sca.host.corba.testing.general.TestInterface initialValue) { + value = initialValue; + } + + public void _read(org.omg.CORBA.portable.InputStream i) { + value = org.apache.tuscany.sca.host.corba.testing.general.TestInterfaceHelper.read(i); + } + + public void _write(org.omg.CORBA.portable.OutputStream o) { + org.apache.tuscany.sca.host.corba.testing.general.TestInterfaceHelper.write(o, value); + } + + public org.omg.CORBA.TypeCode _type() { + return org.apache.tuscany.sca.host.corba.testing.general.TestInterfaceHelper.type(); + } + +} diff --git a/java/sca/contrib/modules/host-corba-jse/src/test/java/org/apache/tuscany/sca/host/corba/testing/general/TestInterfaceOperations.java b/java/sca/contrib/modules/host-corba-jse/src/test/java/org/apache/tuscany/sca/host/corba/testing/general/TestInterfaceOperations.java new file mode 100644 index 0000000000..f557d3e020 --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jse/src/test/java/org/apache/tuscany/sca/host/corba/testing/general/TestInterfaceOperations.java @@ -0,0 +1,31 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.host.corba.testing.general; + +/** +* org/apache/tuscany/sca/host/corba/testing/general/TestInterfaceOperations.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* ¶roda, 25 czerwiec 2008 16:19:44 CEST +*/ + +public interface TestInterfaceOperations { + int getInt(int arg); +} // interface TestInterfaceOperations diff --git a/java/sca/contrib/modules/host-corba-jse/src/test/java/org/apache/tuscany/sca/host/corba/testing/general/_TestInterfaceImplBase.java b/java/sca/contrib/modules/host-corba-jse/src/test/java/org/apache/tuscany/sca/host/corba/testing/general/_TestInterfaceImplBase.java new file mode 100644 index 0000000000..f993066dab --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jse/src/test/java/org/apache/tuscany/sca/host/corba/testing/general/_TestInterfaceImplBase.java @@ -0,0 +1,74 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.host.corba.testing.general; + +/** +* org/apache/tuscany/sca/host/corba/testing/general/_TestInterfaceImplBase.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* ¶roda, 25 czerwiec 2008 16:19:44 CEST +*/ + +public abstract class _TestInterfaceImplBase extends org.omg.CORBA.portable.ObjectImpl implements + org.apache.tuscany.sca.host.corba.testing.general.TestInterface, org.omg.CORBA.portable.InvokeHandler { + + // Constructors + public _TestInterfaceImplBase() { + } + + private static java.util.Hashtable _methods = new java.util.Hashtable(); + static { + _methods.put("getInt", new java.lang.Integer(0)); + } + + public org.omg.CORBA.portable.OutputStream _invoke(String $method, + org.omg.CORBA.portable.InputStream in, + org.omg.CORBA.portable.ResponseHandler $rh) { + org.omg.CORBA.portable.OutputStream out = null; + java.lang.Integer __method = (java.lang.Integer)_methods.get($method); + if (__method == null) + throw new org.omg.CORBA.BAD_OPERATION(0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE); + + switch (__method.intValue()) { + case 0: // org/apache/tuscany/sca/host/corba/testing/general/TestInterface/getInt + { + int arg = in.read_long(); + int $result = (int)0; + $result = this.getInt(arg); + out = $rh.createReply(); + out.write_long($result); + break; + } + + default: + throw new org.omg.CORBA.BAD_OPERATION(0, org.omg.CORBA.CompletionStatus.COMPLETED_MAYBE); + } + + return out; + } // _invoke + + // Type-specific CORBA::Object operations + private static String[] __ids = {"IDL:org/apache/tuscany/sca/host/corba/testing/general/TestInterface:1.0"}; + + public String[] _ids() { + return (String[])__ids.clone(); + } + +} // class _TestInterfaceImplBase diff --git a/java/sca/contrib/modules/host-corba-jse/src/test/java/org/apache/tuscany/sca/host/corba/testing/general/_TestInterfaceStub.java b/java/sca/contrib/modules/host-corba-jse/src/test/java/org/apache/tuscany/sca/host/corba/testing/general/_TestInterfaceStub.java new file mode 100644 index 0000000000..30a77deaf5 --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jse/src/test/java/org/apache/tuscany/sca/host/corba/testing/general/_TestInterfaceStub.java @@ -0,0 +1,73 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.host.corba.testing.general; + +/** +* org/apache/tuscany/sca/host/corba/testing/general/_TestInterfaceStub.java . +* Generated by the IDL-to-Java compiler (portable), version "3.2" +* from general_tests.idl +* ¶roda, 25 czerwiec 2008 16:19:44 CEST +*/ + +public class _TestInterfaceStub extends org.omg.CORBA.portable.ObjectImpl implements + org.apache.tuscany.sca.host.corba.testing.general.TestInterface { + + public int getInt(int arg) { + org.omg.CORBA.portable.InputStream $in = null; + try { + org.omg.CORBA.portable.OutputStream $out = _request("getInt", true); + $out.write_long(arg); + $in = _invoke($out); + int $result = $in.read_long(); + return $result; + } catch (org.omg.CORBA.portable.ApplicationException $ex) { + $in = $ex.getInputStream(); + String _id = $ex.getId(); + throw new org.omg.CORBA.MARSHAL(_id); + } catch (org.omg.CORBA.portable.RemarshalException $rm) { + return getInt(arg); + } finally { + _releaseReply($in); + } + } // getInt + + // Type-specific CORBA::Object operations + private static String[] __ids = {"IDL:org/apache/tuscany/sca/host/corba/testing/general/TestInterface:1.0"}; + + public String[] _ids() { + return (String[])__ids.clone(); + } + + private void readObject(java.io.ObjectInputStream s) throws java.io.IOException { + String str = s.readUTF(); + String[] args = null; + java.util.Properties props = null; + org.omg.CORBA.Object obj = org.omg.CORBA.ORB.init(args, props).string_to_object(str); + org.omg.CORBA.portable.Delegate delegate = ((org.omg.CORBA.portable.ObjectImpl)obj)._get_delegate(); + _set_delegate(delegate); + } + + private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { + String[] args = null; + java.util.Properties props = null; + String str = org.omg.CORBA.ORB.init(args, props).object_to_string(this); + s.writeUTF(str); + } +} // class _TestInterfaceStub diff --git a/java/sca/contrib/modules/host-corba-jse/src/test/java/org/apache/tuscany/sca/host/corba/testing/servants/TestInterfaceServant.java b/java/sca/contrib/modules/host-corba-jse/src/test/java/org/apache/tuscany/sca/host/corba/testing/servants/TestInterfaceServant.java new file mode 100644 index 0000000000..0ebde8ef0d --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jse/src/test/java/org/apache/tuscany/sca/host/corba/testing/servants/TestInterfaceServant.java @@ -0,0 +1,35 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.host.corba.testing.servants; + +import org.apache.tuscany.sca.host.corba.testing.general._TestInterfaceImplBase; + +/** + * Testing servant + */ +public class TestInterfaceServant extends _TestInterfaceImplBase { + + private static final long serialVersionUID = 1L; + + public int getInt(int arg) { + return arg; + } + +} diff --git a/java/sca/contrib/modules/host-corba-jse/src/test/resources/general.idl b/java/sca/contrib/modules/host-corba-jse/src/test/resources/general.idl new file mode 100644 index 0000000000..f67566deb8 --- /dev/null +++ b/java/sca/contrib/modules/host-corba-jse/src/test/resources/general.idl @@ -0,0 +1,43 @@ +/* + * 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. + */ + +/* + * compile by + * idlj -fall -oldImplBase genera.idl + */ + +module org { + module apache { + module tuscany { + module sca { + module host { + module corba { + module testing { + module general { + interface TestInterface { + long getInt(in long arg); + }; + }; + }; + }; + }; + }; + }; + }; +}; diff --git a/java/sca/contrib/modules/host-corba/LICENSE b/java/sca/contrib/modules/host-corba/LICENSE new file mode 100644 index 0000000000..6e529a25c4 --- /dev/null +++ b/java/sca/contrib/modules/host-corba/LICENSE @@ -0,0 +1,205 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + + diff --git a/java/sca/contrib/modules/host-corba/META-INF/MANIFEST.MF b/java/sca/contrib/modules/host-corba/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..2b38d299c0 --- /dev/null +++ b/java/sca/contrib/modules/host-corba/META-INF/MANIFEST.MF @@ -0,0 +1,17 @@ +Manifest-Version: 1.0 +Export-Package: org.apache.tuscany.sca.host.corba;uses:="org.omg.CORBA + ";version="2.0.0" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA CORBA Host Extension Point +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397126578 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA CORBA Host Extension Point +Import-Package: org.apache.tuscany.sca.host.corba;version="2.0.0",org.om + g.CORBA +Bundle-SymbolicName: org.apache.tuscany.sca.host.corba +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/host-corba/NOTICE b/java/sca/contrib/modules/host-corba/NOTICE new file mode 100644 index 0000000000..51042eab05 --- /dev/null +++ b/java/sca/contrib/modules/host-corba/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/host-corba/pom.xml b/java/sca/contrib/modules/host-corba/pom.xml new file mode 100644 index 0000000000..b1e1281e17 --- /dev/null +++ b/java/sca/contrib/modules/host-corba/pom.xml @@ -0,0 +1,38 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + + tuscany-host-corba + Apache Tuscany SCA CORBA Host Extension Point + + + + org.apache.tuscany.sca + tuscany-core-spi + 2.0-SNAPSHOT + + + + diff --git a/java/sca/contrib/modules/host-corba/src/main/java/org/apache/tuscany/sca/host/corba/CorbaHost.java b/java/sca/contrib/modules/host-corba/src/main/java/org/apache/tuscany/sca/host/corba/CorbaHost.java new file mode 100644 index 0000000000..eb49f3f841 --- /dev/null +++ b/java/sca/contrib/modules/host-corba/src/main/java/org/apache/tuscany/sca/host/corba/CorbaHost.java @@ -0,0 +1,56 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.host.corba; + +import org.omg.CORBA.Object; + +/** + * @version $Rev$ $Date$ + * CORBA Service hosting interface + */ +public interface CorbaHost { + + /** + * Registers servant in name server. + * + * @param uri corbaname URI + * @param serviceObject + * @throws CorbaHostException + */ + void registerServant(String uri, Object serviceObject) throws CorbaHostException; + + /** + * Removes servant from name server + * + * @param orb The ORB instance + * @param name binding name + * @throws CorbaHostException + */ + void unregisterServant(String uri) throws CorbaHostException; + + /** + * Gets reference to object + * + * @param name binding name + * @return objects reference + * @throws CorbaHostException + */ + Object lookup(String uri) throws CorbaHostException; +} diff --git a/java/sca/contrib/modules/host-corba/src/main/java/org/apache/tuscany/sca/host/corba/CorbaHostException.java b/java/sca/contrib/modules/host-corba/src/main/java/org/apache/tuscany/sca/host/corba/CorbaHostException.java new file mode 100644 index 0000000000..049bfdb6cd --- /dev/null +++ b/java/sca/contrib/modules/host-corba/src/main/java/org/apache/tuscany/sca/host/corba/CorbaHostException.java @@ -0,0 +1,47 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.host.corba; + +/** + * @version $Rev$ $Date$ + * General exception for corba hosts operations + */ +public class CorbaHostException extends Exception { + + private static final long serialVersionUID = 1L; + + public static final String BINDING_IN_USE = "Binding name is already in use"; + public static final String NO_SUCH_OBJECT = "There is no object under given location"; + public static final String NO_SUCH_HOST = "Couldn't find specified host"; + public static final String NO_SUCH_PORT = "Couldn't connect to specified port"; + public static final String WRONG_NAME = "Characters used in binding name are illegal"; + + public CorbaHostException(String message) { + super(message); + } + + public CorbaHostException(Exception cause) { + super(cause); + } + + public CorbaHostException(String message, Exception cause) { + super(message, cause); + } +} diff --git a/java/sca/contrib/modules/host-corba/src/main/java/org/apache/tuscany/sca/host/corba/CorbaHostExtensionPoint.java b/java/sca/contrib/modules/host-corba/src/main/java/org/apache/tuscany/sca/host/corba/CorbaHostExtensionPoint.java new file mode 100644 index 0000000000..067b9193c5 --- /dev/null +++ b/java/sca/contrib/modules/host-corba/src/main/java/org/apache/tuscany/sca/host/corba/CorbaHostExtensionPoint.java @@ -0,0 +1,51 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.host.corba; + +import java.util.List; + +/** + * @version $Rev$ $Date$ + * An extension point for CORBA hostst + */ +public interface CorbaHostExtensionPoint { + + /** + * Removes CORBA host extension + * + * @param corbaHost + */ + void addCorbaHost(CorbaHost corbaHost); + + /** + * Removes CORBA host extension + * + * @param corbaHost + */ + void removeCorbaHost(CorbaHost corbaHost); + + /** + * Gets all CORBA host extensions + * + * @return + */ + List getCorbaHosts(); + +} diff --git a/java/sca/contrib/modules/host-corba/src/main/java/org/apache/tuscany/sca/host/corba/CorbaHostUtils.java b/java/sca/contrib/modules/host-corba/src/main/java/org/apache/tuscany/sca/host/corba/CorbaHostUtils.java new file mode 100644 index 0000000000..b90fe9c78b --- /dev/null +++ b/java/sca/contrib/modules/host-corba/src/main/java/org/apache/tuscany/sca/host/corba/CorbaHostUtils.java @@ -0,0 +1,61 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.host.corba; + + +/** + * @version $Rev$ $Date$ + * Various utilities for host-corba + */ +public class CorbaHostUtils { + + /** + * Tests if given URI is valid corbaname string + * @param uri + * @return + */ + public static boolean isValidCorbanameURI(String uri) { + return uri != null && uri.startsWith("corbaname:") && uri.contains("#") && uri.indexOf('#') < uri.length() - 1; + } + + /** + * Creates corbaname URI basing on given parameters + * @param host + * @param port + * @param name + * + * @return + */ + public static String createCorbanameURI(String host, int port, String name) { + return new CorbanameURL(host, port, name).toString(); + } + + /** + * Translates corbaname URI to CorbanameDetails instances + * + * @param uri + * @return + */ + public static CorbanameURL getServiceDetails(String uri) { + CorbanameURL details = new CorbanameURL(uri); + return details; + } + +} diff --git a/java/sca/contrib/modules/host-corba/src/main/java/org/apache/tuscany/sca/host/corba/CorbanameURL.java b/java/sca/contrib/modules/host-corba/src/main/java/org/apache/tuscany/sca/host/corba/CorbanameURL.java new file mode 100644 index 0000000000..a380fd6d79 --- /dev/null +++ b/java/sca/contrib/modules/host-corba/src/main/java/org/apache/tuscany/sca/host/corba/CorbanameURL.java @@ -0,0 +1,202 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.host.corba; + +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.util.Arrays; +import java.util.List; + +/** + * @version $Rev$ $Date$ + * Holds corbaname URI details + */ +public class CorbanameURL { + public static String DEFAULT_PROTOCOL = "iiop"; + public static String DEFAULT_VERSION = ""; + public static String DEFAULT_NAME_SERVICE = "NameService"; + public static String DEFAULT_HOST = "localhost"; + public static int DEFAULT_PORT = 2809; + + private String protocol = ""; + private String version = ""; + private String host; + private int port; + private String nameService; + private List namePath; + + public CorbanameURL(String host, int port, String namePath, String nameService) { + super(); + this.host = host == null ? DEFAULT_HOST : host; + this.port = port <= 0 ? DEFAULT_PORT : port; + this.namePath = parseName(namePath); + this.nameService = nameService == null ? DEFAULT_NAME_SERVICE : nameService; + } + + public CorbanameURL(String host, int port, String namePath) { + this(host, port, namePath, DEFAULT_NAME_SERVICE); + } + + public CorbanameURL(String url) { + if (url == null || (!url.startsWith("corbaname"))) { + throw new IllegalArgumentException("Malformed corbaname URL: " + url); + } + try { + url = URLDecoder.decode(url, "UTF-8"); + } catch (UnsupportedEncodingException e) { + throw new IllegalArgumentException(e); + } + String[] parts = url.split("#"); + if (parts.length == 2) { + String serviceLocation = parts[0]; + String servicePath = parts[1]; + namePath = parseName(servicePath); + + parts = serviceLocation.split("/"); + if (parts.length == 2) { + nameService = parts[1]; + } else { + nameService = DEFAULT_NAME_SERVICE; + } + + parts = parts[0].split(":"); + + if (parts.length >= 2) { + protocol = parts[1]; + } + if (parts.length >= 3) { + version = parts[2]; + String[] strs = version.split("@"); + if (strs.length == 2) { + version = strs[0]; + host = strs[1]; + } else { + version = ""; + host = strs[0]; + } + } + if (host == null || "".equals(host)) { + host = DEFAULT_HOST; + } + if (parts.length >= 4 && !"".equals(parts[3])) { + port = Integer.parseInt(parts[3]); + } else { + port = DEFAULT_PORT; + } + } else { + throw new IllegalArgumentException("Malformed corbaname URL: " + url); + } + } + + private static List parseName(String name) { + try { + name = URLDecoder.decode(name, "UTF-8"); + } catch (UnsupportedEncodingException e) { + throw new IllegalArgumentException(e); + } + String[] names = name.split("/"); + return Arrays.asList(names); + } + + public String getProtocol() { + return protocol; + } + + public void setProtocol(String protocol) { + this.protocol = protocol; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public int getPort() { + return port; + } + + public void setPort(int port) { + this.port = port; + } + + public String getNameService() { + return nameService; + } + + public void setNameService(String nameService) { + this.nameService = nameService; + } + + public List getNamePath() { + return namePath; + } + + public String getName() { + if (namePath != null) { + StringBuffer buf = new StringBuffer(); + for (int i = 0; i < namePath.size(); i++) { + buf.append(namePath.get(i)); + if (i < namePath.size() - 1) { + buf.append("/"); + } + } + return buf.toString(); + } + return null; + } + + public void setNamePath(List namePath) { + this.namePath = namePath; + } + + @Override + public String toString() { + StringBuffer buf = new StringBuffer(); + buf.append("corbaname:"); + buf.append(protocol).append(":"); + if (version != null && !"".equals(version)) { + buf.append(version).append("@"); + } + buf.append(host).append(":").append(port); + buf.append("/").append(nameService); + buf.append("#"); + if (namePath != null) { + for (int i = 0; i < namePath.size(); i++) { + buf.append(namePath.get(i)); + if (i < namePath.size() - 1) { + buf.append("/"); + } + } + } + return buf.toString(); + } + +} diff --git a/java/sca/contrib/modules/host-corba/src/main/java/org/apache/tuscany/sca/host/corba/DefaultCorbaHostExtensionPoint.java b/java/sca/contrib/modules/host-corba/src/main/java/org/apache/tuscany/sca/host/corba/DefaultCorbaHostExtensionPoint.java new file mode 100644 index 0000000000..438734086d --- /dev/null +++ b/java/sca/contrib/modules/host-corba/src/main/java/org/apache/tuscany/sca/host/corba/DefaultCorbaHostExtensionPoint.java @@ -0,0 +1,48 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.host.corba; + +import java.util.ArrayList; +import java.util.List; + +/** + * @version $Rev$ $Date$ + * Default implementation of CorbaHostExtensionPoint + */ +public class DefaultCorbaHostExtensionPoint implements CorbaHostExtensionPoint { + + private List corbaHosts = new ArrayList(); + + public DefaultCorbaHostExtensionPoint() { + } + + public void addCorbaHost(CorbaHost host) { + corbaHosts.add(host); + } + + public void removeCorbaHost(CorbaHost host) { + corbaHosts.remove(host); + } + + public List getCorbaHosts() { + return corbaHosts; + } + +} diff --git a/java/sca/contrib/modules/host-corba/src/main/java/org/apache/tuscany/sca/host/corba/ExtensibleCorbaHost.java b/java/sca/contrib/modules/host-corba/src/main/java/org/apache/tuscany/sca/host/corba/ExtensibleCorbaHost.java new file mode 100644 index 0000000000..7e043667a9 --- /dev/null +++ b/java/sca/contrib/modules/host-corba/src/main/java/org/apache/tuscany/sca/host/corba/ExtensibleCorbaHost.java @@ -0,0 +1,55 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.host.corba; + +import org.omg.CORBA.Object; + +/** + * @version $Rev$ $Date$ + * Default implementation of extensible CORBA host + */ +public class ExtensibleCorbaHost implements CorbaHost { + + private CorbaHostExtensionPoint hosts; + + public ExtensibleCorbaHost(CorbaHostExtensionPoint chep) { + this.hosts = chep; + } + + public Object lookup(String uri) throws CorbaHostException { + return getCorbaHost().lookup(uri); + } + + public void registerServant(String uri, Object serviceObject) throws CorbaHostException { + getCorbaHost().registerServant(uri, serviceObject); + } + + public void unregisterServant(String uri) throws CorbaHostException { + getCorbaHost().unregisterServant(uri); + } + + protected CorbaHost getCorbaHost() throws CorbaHostException { + if (hosts.getCorbaHosts().isEmpty()) { + throw new CorbaHostException("No registered CORBA hosts"); + } + return hosts.getCorbaHosts().get(0); + } + +} diff --git a/java/sca/contrib/modules/host-corba/src/main/java/org/apache/tuscany/sca/host/corba/SocketUtil.java b/java/sca/contrib/modules/host-corba/src/main/java/org/apache/tuscany/sca/host/corba/SocketUtil.java new file mode 100755 index 0000000000..6989b3ad06 --- /dev/null +++ b/java/sca/contrib/modules/host-corba/src/main/java/org/apache/tuscany/sca/host/corba/SocketUtil.java @@ -0,0 +1,226 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.host.corba; + +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.net.UnknownHostException; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +/** + * @version $Rev$ $Date$ + * Class partially copied from eclipse wst project + * (http://repo1.maven.org/maven2/org/eclipse/wst/server/core/1.0.205-v20070829b/). + * Finally we should use jar from maven dependency. Problem described in + * http://www.fornax-platform.org/cp/display/fornax/2.+Hello+World+Tutorial+(CSC)?replyToComment=2098#comment-2098 + * needs to be fixed. + */ +public class SocketUtil { + + protected static final Object lock = new Object(); + + private static Set localHostCache; + private static Set notLocalHostCache = new HashSet(); + private static Map threadMap = new HashMap(); + + private static Set addressCache; + + static class CacheThread extends Thread { + private Set currentAddresses; + private Set addressList; + private String host; + private Set nonAddressList; + private Map threadMap2; + + public CacheThread(String host, + Set currentAddresses, + Set addressList, + Set nonAddressList, + Map threadMap2) { + super("Caching localhost information"); + this.host = host; + this.currentAddresses = currentAddresses; + this.addressList = addressList; + this.nonAddressList = nonAddressList; + this.threadMap2 = threadMap2; + } + + public void run() { + if (currentAddresses != null) { + Iterator iter2 = currentAddresses.iterator(); + while (iter2.hasNext()) { + InetAddress addr = iter2.next(); + String hostname = addr.getHostName(); + String hostname2 = addr.getCanonicalHostName(); + synchronized (lock) { + if (hostname != null && !addressList.contains(hostname)) + addressList.add(hostname); + if (hostname2 != null && !addressList.contains(hostname2)) + addressList.add(hostname2); + } + } + } + + try { + InetAddress[] addrs = InetAddress.getAllByName(host); + int length = addrs.length; + for (int j = 0; j < length; j++) { + InetAddress addr = addrs[0]; + String hostname = addr.getHostName(); + String hostname2 = addr.getCanonicalHostName(); + synchronized (lock) { + if (addr.isLoopbackAddress()) { + if (hostname != null && !addressList.contains(hostname)) + addressList.add(hostname); + if (hostname2 != null && !addressList.contains(hostname2)) + addressList.add(hostname2); + } else { + if (hostname != null && !nonAddressList.contains(hostname)) + nonAddressList.add(hostname); + if (hostname2 != null && !nonAddressList.contains(hostname2)) + nonAddressList.add(hostname2); + } + } + } + } catch (UnknownHostException e) { + synchronized (lock) { + if (host != null && !nonAddressList.contains(host)) + nonAddressList.add(host); + } + } + synchronized (lock) { + threadMap2.remove(host); + } + } + } + + public static boolean isLocalhost(final String host) { + if (host == null || host.equals("")) + return false; + + if ("localhost".equals(host) || "127.0.0.1".equals(host)) + return true; + + // check simple cases + try { + InetAddress localHostaddr = InetAddress.getLocalHost(); + if (localHostaddr.getHostName().equals(host) || host.equals(localHostaddr.getCanonicalHostName()) + || localHostaddr.getHostAddress().equals(host)) + return true; + } catch (Exception e) { + + } + + // check for current thread and wait if necessary + boolean currentThread = false; + try { + Thread t = null; + synchronized (lock) { + t = threadMap.get(host); + } + if (t != null && t.isAlive()) { + currentThread = true; + t.join(30); + } + } catch (Exception e) { + + } + + // check if cache is still ok + boolean refreshedCache = false; + try { + // get network interfaces + final Set currentAddresses = new HashSet(); + currentAddresses.add(InetAddress.getLocalHost()); + Enumeration nis = NetworkInterface.getNetworkInterfaces(); + while (nis.hasMoreElements()) { + NetworkInterface inter = (NetworkInterface)nis.nextElement(); + Enumeration ias = inter.getInetAddresses(); + while (ias.hasMoreElements()) + currentAddresses.add(ias.nextElement()); + } + + // check if cache is empty or old and refill it if necessary + if (addressCache == null || !addressCache.containsAll(currentAddresses) + || !currentAddresses.containsAll(addressCache)) { + CacheThread cacheThread = null; + refreshedCache = true; + + synchronized (lock) { + addressCache = currentAddresses; + notLocalHostCache = new HashSet(); + localHostCache = new HashSet(currentAddresses.size() * 3); + + Iterator iter = currentAddresses.iterator(); + while (iter.hasNext()) { + InetAddress addr = iter.next(); + String a = addr.getHostAddress(); + if (a != null && !localHostCache.contains(a)) + localHostCache.add(a); + } + + cacheThread = new CacheThread(host, currentAddresses, localHostCache, notLocalHostCache, threadMap); + threadMap.put(host, cacheThread); + cacheThread.setDaemon(true); + cacheThread.setPriority(Thread.NORM_PRIORITY - 1); + cacheThread.start(); + } + cacheThread.join(200); + } + } catch (Exception e) { + } + + synchronized (lock) { + if (localHostCache.contains(host)) + return true; + if (notLocalHostCache.contains(host)) + return false; + } + + // if the cache hasn't been cleared, maybe we still need to lookup the + // host + if (!refreshedCache && !currentThread) { + try { + CacheThread cacheThread = null; + synchronized (lock) { + cacheThread = new CacheThread(host, null, localHostCache, notLocalHostCache, threadMap); + threadMap.put(host, cacheThread); + cacheThread.setDaemon(true); + cacheThread.setPriority(Thread.NORM_PRIORITY - 1); + cacheThread.start(); + } + cacheThread.join(75); + + synchronized (lock) { + if (localHostCache.contains(host)) + return true; + } + } catch (Exception e) { + } + } + return false; + } + +} diff --git a/java/sca/contrib/modules/host-corba/src/main/resources/META-INF/services/org.apache.tuscany.sca.host.corba.CorbaHostExtensionPoint b/java/sca/contrib/modules/host-corba/src/main/resources/META-INF/services/org.apache.tuscany.sca.host.corba.CorbaHostExtensionPoint new file mode 100644 index 0000000000..a72bed4ea8 --- /dev/null +++ b/java/sca/contrib/modules/host-corba/src/main/resources/META-INF/services/org.apache.tuscany.sca.host.corba.CorbaHostExtensionPoint @@ -0,0 +1,18 @@ +# 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. + +org.apache.tuscany.sca.host.corba.DefaultCorbaHostExtensionPoint diff --git a/java/sca/contrib/modules/host-corba/src/test/java/org/apache/tuscany/sca/host/corba/UtilsTestCase.java b/java/sca/contrib/modules/host-corba/src/test/java/org/apache/tuscany/sca/host/corba/UtilsTestCase.java new file mode 100644 index 0000000000..4e076f9342 --- /dev/null +++ b/java/sca/contrib/modules/host-corba/src/test/java/org/apache/tuscany/sca/host/corba/UtilsTestCase.java @@ -0,0 +1,145 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.host.corba; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; + +/** + * @version $Rev$ $Date$ + * Tests for host utils + */ +public class UtilsTestCase { + + private void assertDetailsAreOk(CorbanameURL details, String host, int port, String nameService, List namePath) { + assertTrue(details.getHost().equals(host)); + assertTrue(details.getNameService().equals(nameService)); + assertTrue(details.getPort() == port); + assertTrue(details.getNamePath().size() == namePath.size()); + for (int i = 0; i < namePath.size(); i++) { + assertTrue(details.getNamePath().get(i).equals(namePath.get(i))); + } + } + + /** + * Tests if corbaname url is beeing processes properly + */ + @Test + public void test_validCorbaname() { + String testUri = null; + CorbanameURL details = null; + List namePath = null; + + testUri = "corbaname:ignore:host:1234/Service#Reference"; + details = CorbaHostUtils.getServiceDetails(testUri); + namePath = new ArrayList(); + namePath.add("Reference"); + assertDetailsAreOk(details, "host", 1234, "Service", namePath); + + testUri = "corbaname:ignore:host:/Service#Reference"; + details = CorbaHostUtils.getServiceDetails(testUri); + namePath = new ArrayList(); + namePath.add("Reference"); + assertDetailsAreOk(details, "host", CorbanameURL.DEFAULT_PORT, "Service", namePath); + + testUri = "corbaname:ignore:host/Service#Reference"; + details = CorbaHostUtils.getServiceDetails(testUri); + namePath = new ArrayList(); + namePath.add("Reference"); + assertDetailsAreOk(details, "host", CorbanameURL.DEFAULT_PORT, "Service", namePath); + + testUri = "corbaname:ignore:/Service#Reference"; + details = CorbaHostUtils.getServiceDetails(testUri); + namePath = new ArrayList(); + namePath.add("Reference"); + assertDetailsAreOk(details, CorbanameURL.DEFAULT_HOST, CorbanameURL.DEFAULT_PORT, "Service", namePath); + + testUri = "corbaname:ignore/Service#Reference"; + details = CorbaHostUtils.getServiceDetails(testUri); + namePath = new ArrayList(); + namePath.add("Reference"); + assertDetailsAreOk(details, CorbanameURL.DEFAULT_HOST, CorbanameURL.DEFAULT_PORT, "Service", namePath); + + testUri = "corbaname:/Service#Reference"; + details = CorbaHostUtils.getServiceDetails(testUri); + namePath = new ArrayList(); + namePath.add("Reference"); + assertDetailsAreOk(details, CorbanameURL.DEFAULT_HOST, CorbanameURL.DEFAULT_PORT, "Service", namePath); + + testUri = "corbaname/Service#Reference"; + details = CorbaHostUtils.getServiceDetails(testUri); + namePath = new ArrayList(); + namePath.add("Reference"); + assertDetailsAreOk(details, CorbanameURL.DEFAULT_HOST, CorbanameURL.DEFAULT_PORT, "Service", namePath); + + testUri = "corbaname#Reference"; + details = CorbaHostUtils.getServiceDetails(testUri); + namePath = new ArrayList(); + namePath.add("Reference"); + assertDetailsAreOk(details, CorbanameURL.DEFAULT_HOST, CorbanameURL.DEFAULT_PORT, CorbanameURL.DEFAULT_NAME_SERVICE, namePath); + + testUri = "corbaname#Parent/Mid/Reference"; + details = CorbaHostUtils.getServiceDetails(testUri); + namePath = new ArrayList(); + namePath.add("Parent"); + namePath.add("Mid"); + namePath.add("Reference"); + assertDetailsAreOk(details, CorbanameURL.DEFAULT_HOST, CorbanameURL.DEFAULT_PORT, CorbanameURL.DEFAULT_NAME_SERVICE, namePath); + } + + /** + * Test for invalid corbaname url + */ + @Test + public void test_invalidCorbaname() { + String testUri = null; + + try { + testUri = "this.string.should.not.appear.in.the.beggining:ignore:host:1234/Service#Reference"; + CorbaHostUtils.getServiceDetails(testUri); + fail(); + } catch (Exception e) { + assertTrue(e instanceof IllegalArgumentException); + } + + try { + testUri = "corbaname:ignore:host:1234/Service#"; + CorbaHostUtils.getServiceDetails(testUri); + fail(); + } catch (Exception e) { + assertTrue(e instanceof IllegalArgumentException); + } + } + + /** + * Test for creating corbaname url from host, port, name parameters + */ + @Test + public void test_creatingCorbanameURI() { + String uri = CorbaHostUtils.createCorbanameURI("SomeHost", 1000, "SomeName"); + assertEquals("corbaname::SomeHost:1000/NameService#SomeName", uri); + } +} diff --git a/java/sca/contrib/modules/host-tomcat/LICENSE b/java/sca/contrib/modules/host-tomcat/LICENSE new file mode 100644 index 0000000000..8aa906c321 --- /dev/null +++ b/java/sca/contrib/modules/host-tomcat/LICENSE @@ -0,0 +1,205 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + + diff --git a/java/sca/contrib/modules/host-tomcat/META-INF/MANIFEST.MF b/java/sca/contrib/modules/host-tomcat/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..d6a87c4ae8 --- /dev/null +++ b/java/sca/contrib/modules/host-tomcat/META-INF/MANIFEST.MF @@ -0,0 +1,23 @@ +Manifest-Version: 1.0 +Private-Package: org.apache.tuscany.sca.http.tomcat;version="2.0.0",org. + apache.tuscany.sca.http.tomcat.module;version="2.0.0" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA Tomcat Servlet Host Extension +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1222833663765 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA Tomcat Servlet Host Extension +Import-Package: javax.naming,javax.naming.directory,javax.servlet,java + x.servlet.http,org.apache.catalina,org.apache.catalina.connector,org. + apache.catalina.core,org.apache.catalina.servlets,org.apache.catalina + .startup,org.apache.coyote,org.apache.coyote.http11,org.apache.naming + .resources,org.apache.tomcat.util.buf,org.apache.tomcat.util.http.map + per,org.apache.tomcat.util.net,org.apache.tuscany.sca.core;version="1 + .4",org.apache.tuscany.sca.host.http;version="2.0.0",org.apache.tuscany + .sca.work;version="2.0.0" +Bundle-SymbolicName: org.apache.tuscany.sca.host.tomcat +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/host-tomcat/NOTICE b/java/sca/contrib/modules/host-tomcat/NOTICE new file mode 100644 index 0000000000..25bb89c9b2 --- /dev/null +++ b/java/sca/contrib/modules/host-tomcat/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/host-tomcat/pom.xml b/java/sca/contrib/modules/host-tomcat/pom.xml new file mode 100644 index 0000000000..826a58deee --- /dev/null +++ b/java/sca/contrib/modules/host-tomcat/pom.xml @@ -0,0 +1,69 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + tuscany-host-tomcat + Apache Tuscany SCA Tomcat Servlet Host Extension + + + + org.apache.tuscany.sca + tuscany-host-http + 2.0-SNAPSHOT + + + + javax.servlet + servlet-api + 2.5 + + + + org.apache.tomcat + catalina + 6.0.14 + + + org.apache.tomcat + servlet-api + + + + + + org.apache.tomcat + coyote + 6.0.14 + + + org.apache.tomcat + servlet-api + + + + + + diff --git a/java/sca/contrib/modules/host-tomcat/src/main/java/org/apache/tuscany/sca/http/tomcat/ServletWrapper.java b/java/sca/contrib/modules/host-tomcat/src/main/java/org/apache/tuscany/sca/http/tomcat/ServletWrapper.java new file mode 100644 index 0000000000..a0b384d554 --- /dev/null +++ b/java/sca/contrib/modules/host-tomcat/src/main/java/org/apache/tuscany/sca/http/tomcat/ServletWrapper.java @@ -0,0 +1,58 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.http.tomcat; + +import javax.servlet.Servlet; +import javax.servlet.ServletException; + +import org.apache.catalina.core.StandardWrapper; + +/** + * A Servlet wrapper. + * + * @version $Rev$ $Date$ + */ +public class ServletWrapper extends StandardWrapper { + private static final long serialVersionUID = 1L; + + private final Servlet servlet; + + public ServletWrapper(Servlet servlet) { + this.servlet = servlet; + } + + @Override + public synchronized Servlet loadServlet() { + return servlet; + } + + @Override + public Servlet getServlet() { + return servlet; + } + + public void initServlet() throws ServletException { + servlet.init(facade); + } + + public void destroyServlet() { + servlet.destroy(); + } + +} diff --git a/java/sca/contrib/modules/host-tomcat/src/main/java/org/apache/tuscany/sca/http/tomcat/TomcatDefaultServlet.java b/java/sca/contrib/modules/host-tomcat/src/main/java/org/apache/tuscany/sca/http/tomcat/TomcatDefaultServlet.java new file mode 100644 index 0000000000..5d9b65503a --- /dev/null +++ b/java/sca/contrib/modules/host-tomcat/src/main/java/org/apache/tuscany/sca/http/tomcat/TomcatDefaultServlet.java @@ -0,0 +1,114 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.http.tomcat; + +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URL; +import java.net.URLConnection; +import java.util.Hashtable; + +import javax.naming.NamingException; +import javax.naming.directory.Attributes; +import javax.naming.directory.BasicAttributes; +import javax.naming.directory.DirContext; +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; + +import org.apache.catalina.servlets.DefaultServlet; +import org.apache.naming.resources.FileDirContext; +import org.apache.naming.resources.ProxyDirContext; +import org.apache.naming.resources.Resource; + +/** + * DefaultServlet implementation for Tomcat. + * + * @version $Rev$ $Date$ + */ +public class TomcatDefaultServlet extends DefaultServlet { + private static final long serialVersionUID = -7503581551326796573L; + + private String documentRoot; + private ProxyDirContext proxyDirContext; + + public TomcatDefaultServlet(String servletPath, String documentRoot) { + this.documentRoot = documentRoot; + + DirContext dirContext; + URI uri = URI.create(documentRoot); + if (!"file".equals(uri.getScheme())) { + + dirContext = new FileDirContext() { + @Override + public Attributes getAttributes(String name) throws NamingException { + return new BasicAttributes(); + } + + @Override + public Object lookup(String name) throws NamingException { + + try { + final URL url = new URL(TomcatDefaultServlet.this.documentRoot + name); + return new Resource() { + @Override + public InputStream streamContent() throws IOException { + URLConnection connection = url.openConnection(); + connection.setUseCaches(false); + return connection.getInputStream(); + } + }; + } catch (MalformedURLException e) { + throw new NamingException(e.toString()); + } + } + }; + + } else { + dirContext = new FileDirContext(); + ((FileDirContext)dirContext).setDocBase(uri.getPath()); + } + proxyDirContext = new ProxyDirContext(new Hashtable(), dirContext); + resources = proxyDirContext; + } + + @Override + public void init() throws ServletException { + super.init(); + resources = proxyDirContext; + } + + @Override + public void init(ServletConfig servletConfig) throws ServletException { + super.init(servletConfig); + resources = proxyDirContext; + } + + @Override + protected String getRelativePath(HttpServletRequest request) { + String path = request.getPathInfo(); + if (path == null || path.length() == 0) { + path = "/"; + } + return path; + } +} diff --git a/java/sca/contrib/modules/host-tomcat/src/main/java/org/apache/tuscany/sca/http/tomcat/TomcatServer.java b/java/sca/contrib/modules/host-tomcat/src/main/java/org/apache/tuscany/sca/http/tomcat/TomcatServer.java new file mode 100644 index 0000000000..5ea1701c05 --- /dev/null +++ b/java/sca/contrib/modules/host-tomcat/src/main/java/org/apache/tuscany/sca/http/tomcat/TomcatServer.java @@ -0,0 +1,653 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.http.tomcat; + +import java.beans.PropertyChangeListener; +import java.net.InetAddress; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URL; +import java.net.UnknownHostException; +import java.security.AccessController; +import java.security.KeyStore; +import java.security.PrivilegedAction; +import java.security.PrivilegedActionException; +import java.security.PrivilegedExceptionAction; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.Map.Entry; +import java.util.concurrent.Executor; +import java.util.logging.Logger; + +import javax.servlet.RequestDispatcher; +import javax.servlet.Servlet; +import javax.servlet.ServletException; + +import org.apache.catalina.Container; +import org.apache.catalina.Context; +import org.apache.catalina.Lifecycle; +import org.apache.catalina.LifecycleException; +import org.apache.catalina.Loader; +import org.apache.catalina.connector.Connector; +import org.apache.catalina.core.StandardContext; +import org.apache.catalina.core.StandardEngine; +import org.apache.catalina.core.StandardHost; +import org.apache.catalina.startup.ContextConfig; +import org.apache.coyote.http11.Http11Protocol; +import org.apache.tomcat.util.buf.MessageBytes; +import org.apache.tomcat.util.http.mapper.MappingData; +import org.apache.tomcat.util.net.JIoEndpoint; +import org.apache.tuscany.sca.host.http.DefaultResourceServlet; +import org.apache.tuscany.sca.host.http.ServletHost; +import org.apache.tuscany.sca.host.http.ServletMappingException; +import org.apache.tuscany.sca.work.WorkScheduler; + +/** + * A Tomcat based implementation of ServletHost. + * + * @version $Rev$ $Date$ + */ +@SuppressWarnings("deprecation") +public class TomcatServer implements ServletHost { + private static final Logger logger = Logger.getLogger(TomcatServer.class.getName()); + + private int defaultPortNumber = 8080; + + private final class TuscanyLoader implements Loader { + private final ClassLoader tccl; + private boolean delegate; + private boolean reloadable; + private Container container; + private List repos = new ArrayList(); + private List listeners = new ArrayList(); + + private TuscanyLoader(ClassLoader tccl) { + this.tccl = tccl; + } + + public void addPropertyChangeListener(PropertyChangeListener listener) { + listeners.add(listener); + } + + public void addRepository(String repository) { + repos.add(repository); + } + + public void backgroundProcess() { + } + + public String[] findRepositories() { + return repos.toArray(new String[repos.size()]); + } + + public Container getContainer() { + return container; + } + + public boolean getDelegate() { + return delegate; + } + + public String getInfo() { + return "Tuscany Loader for Embedded Tomcat"; + } + + public boolean getReloadable() { + return reloadable; + } + + public boolean modified() { + return false; + } + + public void removePropertyChangeListener(PropertyChangeListener listener) { + listeners.remove(listener); + } + + public void setContainer(Container container) { + this.container = container; + } + + public void setDelegate(boolean delegate) { + this.delegate = delegate; + } + + public void setReloadable(boolean reloadable) { + this.reloadable = reloadable; + } + + public ClassLoader getClassLoader() { + return tccl; + } + } + + /** + * Represents a port and the server that serves it. + */ + private class Port { + private StandardEngine engine; + private StandardHost host; + private Connector connector; + + private Port(StandardEngine engine, StandardHost host, Connector connector) { + this.engine = engine; + this.host = host; + this.connector = connector; + } + + public StandardEngine getEngine() { + return engine; + } + + public StandardHost getHost() { + return host; + } + + public Connector getConnector() { + return connector; + } + } + + private Map ports = new HashMap(); + + private WorkScheduler workScheduler; + + private String contextPath = "/"; + + /** + * Constructs a new embedded Tomcat server. + * + * @param workScheduler the WorkScheduler to use to process requests. + */ + public TomcatServer(WorkScheduler workScheduler) { + this.workScheduler = workScheduler; + } + + public void setDefaultPort(int port) { + defaultPortNumber = port; + } + + public int getDefaultPort() { + return defaultPortNumber; + } + + /** + * Stop all the started servers. + */ + public void stop() throws ServletMappingException { + if (!ports.isEmpty()) { + try { + Set> entries = new HashSet>(ports.entrySet()); + for (Entry entry : entries) { + Port port = entry.getValue(); + port.getConnector().stop(); + port.getEngine().stop(); + ports.remove(entry.getKey()); + } + } catch (Exception e) { + throw new ServletMappingException(e); + } + } + } + + public void addServletMapping(String suri, Servlet servlet) { + URI uri = URI.create(suri); + + // Get the URI scheme and port + String scheme = uri.getScheme(); + if (scheme == null) { + scheme = "http"; + } + final int portNumber = (uri.getPort() == -1 ? defaultPortNumber : uri.getPort()); + + // Get the port object associated with the given port number + Port port = ports.get(portNumber); + if (port == null) { + + // Create an engine + // Allow privileged access to read properties. Requires PropertiesPermission read in + // security policy. + final StandardEngine engine = AccessController.doPrivileged(new PrivilegedAction() { + public StandardEngine run() { + return new StandardEngine(); + } + }); + + engine.setBaseDir(""); + engine.setDefaultHost("localhost"); + engine.setName("engine/" + portNumber); + + // Create a host + final StandardHost host = new StandardHost(); + host.setAppBase(""); + host.setName("localhost"); + // Allow privileged access to read properties. Requires PropertiesPermission read in + // security policy. + AccessController.doPrivileged(new PrivilegedAction() { + public Object run() { + engine.addChild(host); + return null; + } + }); + + // Create the root context + StandardContext context = new StandardContext(); + final ClassLoader tccl = Thread.currentThread().getContextClassLoader(); + context.setLoader(new TuscanyLoader(tccl)); + // context.setParentClassLoader(tccl.getParent()); + context.setDocBase(""); + context.setPath(""); + ContextConfig config = new ContextConfig(); + ((Lifecycle)context).addLifecycleListener(config); + host.addChild(context); + + // Install an HTTP connector + // Allow privileged access to read properties. Requires PropertiesPermission read in + // security policy. + try { + AccessController.doPrivileged(new PrivilegedExceptionAction() { + public Object run() throws LifecycleException { + engine.start(); + return null; + } + }); + } catch (PrivilegedActionException e) { + // throw (LifecycleException)e.getException(); + throw new ServletMappingException(e); + } + Connector connector; + // Allow privileged access to read properties. Requires PropertiesPermission read in + // security policy. + try { + final String protocol = scheme; + connector = AccessController.doPrivileged(new PrivilegedExceptionAction() { + public CustomConnector run() throws Exception { + CustomConnector customConnector = new CustomConnector(); + customConnector.setPort(portNumber); + customConnector.setContainer(engine); + + if ("https".equalsIgnoreCase(protocol)) { + configureSSL(customConnector); + ((Http11Protocol) customConnector.getProtocolHandler()).setSSLEnabled(true); + } + customConnector.initialize(); + customConnector.start(); + return customConnector; + } + + private void configureSSL(CustomConnector customConnector) { + String trustStore = System.getProperty("javax.net.ssl.trustStore"); + String trustStorePass = System.getProperty("javax.net.ssl.trustStorePassword"); + String keyStore = System.getProperty("javax.net.ssl.keyStore"); + String keyStorePass = System.getProperty("javax.net.ssl.keyStorePassword"); + + customConnector.setProperty("protocol", "TLS"); + + customConnector.setProperty("keystore", keyStore); + customConnector.setProperty("keypass", keyStorePass); + String keyStoreType = + System.getProperty("javax.net.ssl.keyStoreType", KeyStore.getDefaultType()); + String trustStoreType = + System.getProperty("javax.net.ssl.trustStoreType", KeyStore.getDefaultType()); + customConnector.setProperty("keytype", keyStoreType); + customConnector.setProperty("trusttype", trustStoreType); + customConnector.setProperty("truststore", trustStore); + customConnector.setProperty("trustpass", trustStorePass); + + customConnector.setProperty("clientauth", "false"); + customConnector.setProtocol("HTTP/1.1"); + customConnector.setScheme(protocol); + customConnector.setProperty("backlog", "10"); + customConnector.setSecure(true); + } + }); + } catch (Exception e) { + throw new ServletMappingException(e); + } + // Keep track of the running server + port = new Port(engine, host, connector); + ports.put(portNumber, port); + } + + // Register the Servlet mapping + String path = uri.getPath(); + + if (!path.startsWith("/")) { + path = '/' + path; + } + + if (!path.startsWith(contextPath)) { + path = contextPath + path; + } + + ServletWrapper wrapper; + if (servlet instanceof DefaultResourceServlet) { + String defaultServletPath = path; + + // Optimize the handling of resource requests, use the Tomcat default Servlet + // instead of our default resource Servlet + if (defaultServletPath.endsWith("*")) { + defaultServletPath = defaultServletPath.substring(0, defaultServletPath.length() - 1); + } + if (defaultServletPath.endsWith("/")) { + defaultServletPath = defaultServletPath.substring(0, defaultServletPath.length() - 1); + } + DefaultResourceServlet resourceServlet = (DefaultResourceServlet)servlet; + TomcatDefaultServlet defaultServlet = + new TomcatDefaultServlet(defaultServletPath, resourceServlet.getDocumentRoot()); + wrapper = new ServletWrapper(defaultServlet); + + } else { + wrapper = new ServletWrapper(servlet); + } + Context context = port.getHost().map(path); + wrapper.setName(path); + wrapper.addMapping(path); + context.addChild(wrapper); + context.addServletMapping(path, path); + port.getConnector().getMapper().addWrapper("localhost", "", path, wrapper); + + // Initialize the Servlet + try { + wrapper.initServlet(); + } catch (ServletException e) { + throw new ServletMappingException(e); + } + + // Compute the complete URL + String host; + try { + host = InetAddress.getLocalHost().getHostName(); + } catch (UnknownHostException e) { + host = "localhost"; + } + URL addedURL; + try { + addedURL = new URL(scheme, host, portNumber, path); + } catch (MalformedURLException e) { + throw new ServletMappingException(e); + } + logger.info("Added Servlet mapping: " + addedURL); + } + + public URL getURLMapping(String suri) throws ServletMappingException { + URI uri = URI.create(suri); + + // Get the URI scheme and port + String scheme = uri.getScheme(); + if (scheme == null) { + scheme = "http"; + } + int portNumber = uri.getPort(); + if (portNumber == -1) { + portNumber = defaultPortNumber; + } + + // Get the host + String host; + try { + host = InetAddress.getLocalHost().getHostName(); + } catch (UnknownHostException e) { + host = "localhost"; + } + + // Construct the URL + String path = uri.getPath(); + + if (!path.startsWith("/")) { + path = '/' + path; + } + + if (!path.startsWith(contextPath)) { + path = contextPath + path; + } + URL url; + try { + url = new URL(scheme, host, portNumber, path); + } catch (MalformedURLException e) { + throw new ServletMappingException(e); + } + return url; + } + + public Servlet getServletMapping(String suri) throws ServletMappingException { + + if (suri == null) { + return null; + } + + URI uri = URI.create(suri); + + // Get the URI port + int portNumber = uri.getPort(); + if (portNumber == -1) { + portNumber = defaultPortNumber; + } + + // Get the port object associated with the given port number + Port port = ports.get(portNumber); + if (port == null) { + return null; + } + + String mapping = uri.getPath(); + + if (!mapping.startsWith("/")) { + mapping = '/' + mapping; + } + + if (!mapping.startsWith(contextPath)) { + mapping = contextPath + mapping; + } + + final Context context = port.getHost().map(mapping); + final MappingData md = new MappingData(); + final MessageBytes mb = MessageBytes.newInstance(); + mb.setString(mapping); + try { + // Allow privileged access to read properties. Requires PropertiesPermission read in + // security policy. + AccessController.doPrivileged(new PrivilegedExceptionAction() { + public Object run() throws Exception { + context.getMapper().map(mb, md); + return null; + } + }); + } catch (Exception e) { + return null; + } + if (md.wrapper instanceof ServletWrapper) { + ServletWrapper servletWrapper = (ServletWrapper)md.wrapper; + return servletWrapper.getServlet(); + } else { + return null; + } + } + + public Servlet removeServletMapping(String suri) { + URI uri = URI.create(suri); + + // Get the URI port + int portNumber = uri.getPort(); + if (portNumber == -1) { + portNumber = defaultPortNumber; + } + + // Get the port object associated with the given port number + Port port = ports.get(portNumber); + if (port == null) { + throw new IllegalStateException("No servlet registered at this URI: " + suri); + } + + String mapping = uri.getPath(); + + if (!mapping.startsWith("/")) { + mapping = '/' + mapping; + } + + if (!mapping.startsWith(contextPath)) { + mapping = contextPath + mapping; + } + + final Context context = port.getHost().map(mapping); + final MappingData md = new MappingData(); + final MessageBytes mb = MessageBytes.newInstance(); + mb.setString(mapping); + try { + // Allow privileged access to read properties. Requires PropertiesPermission read in + // security policy. + AccessController.doPrivileged(new PrivilegedExceptionAction() { + public Object run() throws Exception { + context.getMapper().map(mb, md); + return null; + } + }); + } catch (Exception e) { + return null; + } + if (md.wrapper instanceof ServletWrapper) { + ServletWrapper servletWrapper = (ServletWrapper)md.wrapper; + + port.getConnector().getMapper().removeWrapper("localhost", "", mapping); + + try { + context.removeServletMapping(mapping); + } catch (NegativeArraySizeException e) { + // JIRA TUSCANY-1599 + // FIXME Looks like a bug in Tomcat when removing the last + // Servlet in the list, catch the exception for now as it doesn't + // seem harmful, will find a better solution for the next release + } + context.removeChild(servletWrapper); + try { + servletWrapper.destroyServlet(); + } catch (Exception ex) { + // Hack to handle destruction of Servlets without Servlet context + } + + logger.info("Removed Servlet mapping: " + suri); + + // Stop the port if there's no servlets on it anymore + String[] contextNames = port.getConnector().getMapper().getContextNames(); + if (contextNames == null || contextNames.length == 0) { + try { + port.getConnector().stop(); + port.getEngine().stop(); + ports.remove(portNumber); + } catch (LifecycleException e) { + throw new IllegalStateException(e); + } + } + + return servletWrapper.getServlet(); + } else { + logger.warning("Trying to Remove servlet mapping: " + mapping + " where mapping is not registered"); + return null; + } + } + + public RequestDispatcher getRequestDispatcher(String suri) throws ServletMappingException { + //FIXME implement this later + return null; + } + + public String getContextPath() { + return contextPath; + } + + /** + * A custom connector that uses our WorkScheduler to schedule + * worker threads. + */ + private class CustomConnector extends Connector { + + private class CustomHttpProtocolHandler extends Http11Protocol { + + /** + * An Executor wrapping our WorkScheduler + */ + private class WorkSchedulerExecutor implements Executor { + public void execute(Runnable command) { + workScheduler.scheduleWork(command); + } + } + + /** + * A custom Endpoint that waits for its acceptor thread to + * terminate before stopping. + */ + private class CustomEndpoint extends JIoEndpoint { + private Thread acceptorThread; + + private class CustomAcceptor extends Acceptor { + CustomAcceptor() { + super(); + } + } + + @Override + public void start() throws Exception { + if (!initialized) + init(); + if (!running) { + running = true; + paused = false; + acceptorThread = new Thread(new CustomAcceptor(), getName() + "-Acceptor-" + 0); + acceptorThread.setPriority(threadPriority); + acceptorThread.setDaemon(daemon); + acceptorThread.start(); + } + } + + @Override + public void stop() { + super.stop(); + try { + acceptorThread.join(); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } + + @Override + public int getCurrentThreadsBusy() { + return 0; + } + } + + CustomHttpProtocolHandler() { + endpoint = new CustomEndpoint(); + endpoint.setExecutor(new WorkSchedulerExecutor()); + } + } + + CustomConnector() throws Exception { + protocolHandler = new CustomHttpProtocolHandler(); + } + } + + public void setContextPath(String path) { + this.contextPath = path; + } + +} diff --git a/java/sca/contrib/modules/host-tomcat/src/main/java/org/apache/tuscany/sca/http/tomcat/module/TomcatRuntimeModuleActivator.java b/java/sca/contrib/modules/host-tomcat/src/main/java/org/apache/tuscany/sca/http/tomcat/module/TomcatRuntimeModuleActivator.java new file mode 100644 index 0000000000..070dffdce6 --- /dev/null +++ b/java/sca/contrib/modules/host-tomcat/src/main/java/org/apache/tuscany/sca/http/tomcat/module/TomcatRuntimeModuleActivator.java @@ -0,0 +1,69 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.http.tomcat.module; + +import java.security.AccessController; +import java.security.PrivilegedAction; + +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.core.ModuleActivator; +import org.apache.tuscany.sca.core.UtilityExtensionPoint; +import org.apache.tuscany.sca.host.http.ServletHostExtensionPoint; +import org.apache.tuscany.sca.http.tomcat.TomcatServer; +import org.apache.tuscany.sca.work.WorkScheduler; + +/** + * @version $Rev$ $Date$ + */ +public class TomcatRuntimeModuleActivator implements ModuleActivator { + + private TomcatServer server; + + public void start(ExtensionPointRegistry extensionPointRegistry) { + + // Register a Tomcat Servlet host + ServletHostExtensionPoint servletHosts = + extensionPointRegistry.getExtensionPoint(ServletHostExtensionPoint.class); + + if (servletHosts.getServletHosts().size() < 1) { + UtilityExtensionPoint utilities = extensionPointRegistry.getExtensionPoint(UtilityExtensionPoint.class); + final WorkScheduler workScheduler = utilities.getUtility(WorkScheduler.class); + // Allow privileged access to start MBeans. Requires MBeanPermission in security policy. + server = AccessController.doPrivileged(new PrivilegedAction() { + public TomcatServer run() { + return new TomcatServer(workScheduler); + } + }); + servletHosts.addServletHost(server); + } + } + + public void stop(ExtensionPointRegistry registry) { + // Allow privileged access to stop MBeans. Requires MBeanPermission in security policy. + AccessController.doPrivileged(new PrivilegedAction() { + public Object run() { + if (server != null) { + server.stop(); + } + return null; + } + }); + } +} diff --git a/java/sca/contrib/modules/host-tomcat/src/main/resources/META-INF/services/org.apache.tuscany.sca.core.ModuleActivator b/java/sca/contrib/modules/host-tomcat/src/main/resources/META-INF/services/org.apache.tuscany.sca.core.ModuleActivator new file mode 100644 index 0000000000..f0f4e17507 --- /dev/null +++ b/java/sca/contrib/modules/host-tomcat/src/main/resources/META-INF/services/org.apache.tuscany.sca.core.ModuleActivator @@ -0,0 +1,18 @@ +# 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. +# Implementation class for the ModuleActivator +org.apache.tuscany.sca.http.tomcat.module.TomcatRuntimeModuleActivator diff --git a/java/sca/contrib/modules/host-tomcat/src/test/java/org/apache/tuscany/sca/http/tomcat/TomcatServerTestCase.java b/java/sca/contrib/modules/host-tomcat/src/test/java/org/apache/tuscany/sca/http/tomcat/TomcatServerTestCase.java new file mode 100644 index 0000000000..afbec52cd9 --- /dev/null +++ b/java/sca/contrib/modules/host-tomcat/src/test/java/org/apache/tuscany/sca/http/tomcat/TomcatServerTestCase.java @@ -0,0 +1,353 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.http.tomcat; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.net.Socket; +import java.net.URL; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLSession; +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import junit.framework.TestCase; + +import org.apache.tuscany.sca.host.http.DefaultResourceServlet; +import org.apache.tuscany.sca.work.NotificationListener; +import org.apache.tuscany.sca.work.WorkScheduler; + +/** + * @version $Rev$ $Date$ + */ +public class TomcatServerTestCase extends TestCase { + + private static final String REQUEST1_HEADER = + "GET /foo HTTP/1.0\n" + "Host: localhost\n" + + "Content-Type: text/xml\n" + + "Connection: close\n" + + "Content-Length: "; + private static final String REQUEST1_CONTENT = ""; + private static final String REQUEST1 = + REQUEST1_HEADER + REQUEST1_CONTENT.getBytes().length + "\n\n" + REQUEST1_CONTENT; + + private static final String REQUEST2_HEADER = + "GET /webcontent/test.html HTTP/1.0\n" + "Host: localhost\n" + + "Content-Type: text/xml\n" + + "Connection: close\n" + + "Content-Length: "; + private static final String REQUEST2_CONTENT = ""; + private static final String REQUEST2 = + REQUEST2_HEADER + REQUEST2_CONTENT.getBytes().length + "\n\n" + REQUEST2_CONTENT; + + private static final int HTTP_PORT = 8085; + + private WorkScheduler workScheduler = new WorkScheduler() { + + public void scheduleWork(T work) { + Thread thread = new Thread(work); + thread.start(); + } + + public void scheduleWork(T work, NotificationListener listener) { + scheduleWork(work); + } + + public void destroy() { + } + }; + + /** + * Verifies requests are properly routed according to the Servlet mapping + */ + public void testRegisterServletMapping() throws Exception { + TomcatServer service = new TomcatServer(workScheduler); + TestServlet servlet = new TestServlet(); + service.addServletMapping("http://127.0.0.1:" + HTTP_PORT + "/foo", servlet); + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + os.write(REQUEST1.getBytes()); + os.flush(); + read(client); + service.stop(); + assertTrue(servlet.invoked); + } + + /** + * Verifies requests are properly routed according to the Servlet mapping + */ + public void testRegisterServletMappingSSL() throws Exception { + System.setProperty("javax.net.ssl.keyStore", "target/test-classes/tuscany.keyStore"); + System.setProperty("javax.net.ssl.keyStorePassword", "apache"); + TomcatServer service = new TomcatServer(workScheduler); + TestServlet servlet = new TestServlet(); + try { + service.addServletMapping("https://127.0.0.1:" + HTTP_PORT + "/foo", servlet); + } finally { + System.clearProperty("javax.net.ssl.keyStore"); + System.clearProperty("javax.net.ssl.keyStorePassword"); + } + System.setProperty("javax.net.ssl.trustStore", "target/test-classes/tuscany.keyStore"); + System.setProperty("javax.net.ssl.trustStorePassword", "apache"); + URL url = new URL("https://127.0.0.1:8085/foo"); + HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); + conn.setHostnameVerifier(new HostnameVerifier() { + public boolean verify(String hostname, SSLSession session) { + return true; + }} + ); + + conn.connect(); + read(conn.getInputStream()); + + service.stop(); + assertTrue(servlet.invoked); + + } + /** + * Verifies that Servlets can be registered with multiple ports + */ + public void testRegisterMultiplePorts() throws Exception { + TomcatServer service = new TomcatServer(workScheduler); + TestServlet servlet = new TestServlet(); + service.addServletMapping("http://127.0.0.1:" + HTTP_PORT + "/", servlet); + TestServlet servlet2 = new TestServlet(); + service.addServletMapping("http://127.0.0.1:" + (HTTP_PORT + 1) + "/", servlet2); + { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + os.write(REQUEST1.getBytes()); + os.flush(); + read(client); + } + { + Socket client = new Socket("127.0.0.1", HTTP_PORT + 1); + OutputStream os = client.getOutputStream(); + os.write(REQUEST1.getBytes()); + os.flush(); + read(client); + } + + service.stop(); + assertTrue(servlet.invoked); + assertTrue(servlet2.invoked); + } + + public void testUnregisterMapping() throws Exception { + TomcatServer service = new TomcatServer(workScheduler); + TestServlet servlet = new TestServlet(); + service.addServletMapping("http://127.0.0.1:" + HTTP_PORT + "/foo", servlet); + service.removeServletMapping("http://127.0.0.1:" + HTTP_PORT + "/foo"); + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + os.write(REQUEST1.getBytes()); + os.flush(); + read(client); + service.stop(); + assertFalse(servlet.invoked); + + } + + public void testRegisterUnregisterMapping() throws Exception { + TomcatServer service = new TomcatServer(workScheduler); + TestServlet servlet = new TestServlet(); + service.addServletMapping("http://127.0.0.1:" + HTTP_PORT + "/foo", servlet); + { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + os.write(REQUEST1.getBytes()); + os.flush(); + read(client); + } + assertTrue(servlet.invoked); + service.removeServletMapping("http://127.0.0.1:" + HTTP_PORT + "/foo"); + { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + os.write(REQUEST1.getBytes()); + os.flush(); + read(client); + } + servlet = new TestServlet(); + service.addServletMapping("http://127.0.0.1:" + HTTP_PORT + "/foo", servlet); + { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + os.write(REQUEST1.getBytes()); + os.flush(); + read(client); + } + assertTrue(servlet.invoked); + service.stop(); + } + + public void testRequestSession() throws Exception { + TomcatServer service = new TomcatServer(workScheduler); + TestServlet servlet = new TestServlet(); + service.addServletMapping("http://127.0.0.1:" + HTTP_PORT + "/foo", servlet); + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + os.write(REQUEST1.getBytes()); + os.flush(); + read(client); + service.stop(); + assertTrue(servlet.invoked); + assertNotNull(servlet.sessionId); + } + + public void testRestart() throws Exception { + TomcatServer service = new TomcatServer(workScheduler); + service.stop(); + service.stop(); + } + + public void testNoMappings() throws Exception { + TomcatServer service = new TomcatServer(workScheduler); + Exception ex = null; + try { + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + os.write(REQUEST1.getBytes()); + os.flush(); + } catch (Exception e) { + ex = e; + } + assertNotNull(ex); + service.stop(); + } + + public void testResourceServlet() throws Exception { + TomcatServer service = new TomcatServer(workScheduler); + + String documentRoot = getClass().getClassLoader().getResource("content/test.html").toString(); + documentRoot = documentRoot.substring(0, documentRoot.lastIndexOf('/')); + DefaultResourceServlet resourceServlet = new DefaultResourceServlet(documentRoot); + TestResourceServlet servlet = new TestResourceServlet(resourceServlet); + service.addServletMapping("http://127.0.0.1:" + HTTP_PORT + "/webcontent/*", servlet); + + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + os.write(REQUEST2.getBytes()); + os.flush(); + + String document = read(client); + assertTrue(document.indexOf("

      hello") != -1); + + service.stop(); + } + + public void testDefaultServlet() throws Exception { + TomcatServer service = new TomcatServer(workScheduler); + + String documentRoot = getClass().getClassLoader().getResource("content/test.html").toString(); + documentRoot = documentRoot.substring(0, documentRoot.lastIndexOf('/')); + DefaultResourceServlet resourceServlet = new DefaultResourceServlet(documentRoot); + service.addServletMapping("http://127.0.0.1:" + HTTP_PORT + "/webcontent/*", resourceServlet); + + Socket client = new Socket("127.0.0.1", HTTP_PORT); + OutputStream os = client.getOutputStream(); + os.write(REQUEST2.getBytes()); + os.flush(); + + String document = read(client); + assertTrue(document.indexOf("

      hello") != -1); + + service.stop(); + } + + private static String read(Socket socket) throws IOException { + InputStream is = socket.getInputStream(); + return read(is); + } + + private static String read(InputStream is) throws IOException { + BufferedReader reader = null; + try { + reader = new BufferedReader(new InputStreamReader(is)); + StringBuffer sb = new StringBuffer(); + String str; + while ((str = reader.readLine()) != null) { + sb.append(str); + } + return sb.toString(); + } finally { + if (reader != null) { + reader.close(); + } + } + } + private class TestServlet extends HttpServlet { + private static final long serialVersionUID = 1L; + boolean invoked; + String sessionId; + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + invoked = true; + sessionId = req.getSession().getId(); + OutputStream writer = resp.getOutputStream(); + try { + writer.write("result".getBytes()); + } finally { + writer.close(); + } + } + + } + + private class TestResourceServlet extends HttpServlet { + private static final long serialVersionUID = 1L; + private HttpServlet delegate; + + public TestResourceServlet(HttpServlet delegate) { + this.delegate = delegate; + } + + @Override + public void init() throws ServletException { + super.init(); + delegate.init(); + } + + @Override + public void init(ServletConfig config) throws ServletException { + super.init(); + delegate.init(config); + } + + @Override + protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + delegate.service(req, resp); + } + + @Override + public void destroy() { + super.destroy(); + delegate.destroy(); + } + } +} diff --git a/java/sca/contrib/modules/host-tomcat/src/test/resources/content/test.html b/java/sca/contrib/modules/host-tomcat/src/test/resources/content/test.html new file mode 100644 index 0000000000..f4b79d7f01 --- /dev/null +++ b/java/sca/contrib/modules/host-tomcat/src/test/resources/content/test.html @@ -0,0 +1,21 @@ + + +

      hello + \ No newline at end of file diff --git a/java/sca/contrib/modules/host-tomcat/src/test/resources/tuscany.keyStore b/java/sca/contrib/modules/host-tomcat/src/test/resources/tuscany.keyStore new file mode 100644 index 0000000000..7ea23f7ff4 Binary files /dev/null and b/java/sca/contrib/modules/host-tomcat/src/test/resources/tuscany.keyStore differ diff --git a/java/sca/contrib/modules/host-webapp-junit/LICENSE b/java/sca/contrib/modules/host-webapp-junit/LICENSE new file mode 100644 index 0000000000..8aa906c321 --- /dev/null +++ b/java/sca/contrib/modules/host-webapp-junit/LICENSE @@ -0,0 +1,205 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + + diff --git a/java/sca/contrib/modules/host-webapp-junit/META-INF/MANIFEST.MF b/java/sca/contrib/modules/host-webapp-junit/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..56b597c164 --- /dev/null +++ b/java/sca/contrib/modules/host-webapp-junit/META-INF/MANIFEST.MF @@ -0,0 +1,19 @@ +Manifest-Version: 1.0 +Export-Package: org.apache.tuscany.sca.host.webapp.junit;uses:="org.ju + nit.runner.notification,javax.servlet,junit.framework,org.junit.runne + r,javax.servlet.http";version="2.0.0" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA Webapp JUnit Host +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397431421 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA Webapp JUnit Host +Import-Package: javax.servlet,javax.servlet.http,junit.framework,org.a + pache.tuscany.sca.host.webapp.junit;version="2.0.0",org.junit.runner,or + g.junit.runner.notification +Bundle-SymbolicName: org.apache.tuscany.sca.host.webapp.junit +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/host-webapp-junit/NOTICE b/java/sca/contrib/modules/host-webapp-junit/NOTICE new file mode 100644 index 0000000000..51042eab05 --- /dev/null +++ b/java/sca/contrib/modules/host-webapp-junit/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/host-webapp-junit/pom.xml b/java/sca/contrib/modules/host-webapp-junit/pom.xml new file mode 100644 index 0000000000..443b55b8a9 --- /dev/null +++ b/java/sca/contrib/modules/host-webapp-junit/pom.xml @@ -0,0 +1,48 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + + tuscany-host-webapp-junit + Apache Tuscany SCA Webapp JUnit Host + + + + + junit + junit + 4.5 + + + + javax.servlet + servlet-api + 2.5 + + + + + diff --git a/java/sca/contrib/modules/host-webapp-junit/src/main/java/org/apache/tuscany/sca/host/webapp/junit/JUnitServletFilter.java b/java/sca/contrib/modules/host-webapp-junit/src/main/java/org/apache/tuscany/sca/host/webapp/junit/JUnitServletFilter.java new file mode 100644 index 0000000000..b2d3d0abf1 --- /dev/null +++ b/java/sca/contrib/modules/host-webapp-junit/src/main/java/org/apache/tuscany/sca/host/webapp/junit/JUnitServletFilter.java @@ -0,0 +1,355 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.host.webapp.junit; + +import java.io.EOFException; +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintStream; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.jar.JarEntry; +import java.util.jar.JarInputStream; +import java.util.logging.Logger; +import java.util.regex.Pattern; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import junit.framework.AssertionFailedError; + +import org.junit.runner.JUnitCore; +import org.junit.runner.Request; +import org.junit.runner.Result; +import org.junit.runner.notification.Failure; + +/** + * @version $Rev$ $Date$ + */ +public class JUnitServletFilter implements Filter { + private static final Logger logger = Logger.getLogger(JUnitServletFilter.class.getName()); + + private static final String JUNIT_TESTS_PATTERN = "junit.tests.pattern"; + private static final String JUNIT_TESTS_PATH = "junit.tests.path"; + private static final String JUNIT_ENABLED = "junit.enabled"; + private static final String TESTCASE_PATTERN = ".*TestCase"; + private static final String TESTS_JAR = "/WEB-INF/test-lib/junit-tests.jar"; + + private FilterConfig config; + private boolean junitEnabled = true; + private Set allTestCases; + private ClassLoader testClassLoader; + + private Set findTestCases(String testJarPath) throws IOException { + Pattern pattern = getTestCasePattern(); + if (testJarPath.endsWith(".jar")) { + return findTestCasesInJar(testJarPath, pattern); + } else { + return findTestCasesInDir(testJarPath, pattern); + } + } + + /** + * Search test cases in a JAR + * @param testJarPath + * @param pattern + * @return + * @throws IOException + */ + private Set findTestCasesInJar(String testJarPath, Pattern pattern) throws IOException { + InputStream in = config.getServletContext().getResourceAsStream(testJarPath); + Set tests = new HashSet(); + if (in != null) { + JarInputStream jar = new JarInputStream(in); + try { + JarEntry entry = null; + + while ((entry = jar.getNextJarEntry()) != null) { + String name = entry.getName(); + + if (name.endsWith(".class")) { + String className = name.substring(0, name.length() - 6).replace('/', '.'); + if (pattern.matcher(className).matches()) { + tests.add(className); + } + } + } + } catch (EOFException e) { + } finally { + if (jar != null) { + try { + jar.close(); + } catch (IOException e) { + } + } + } + + } + return tests; + } + + private Pattern getTestCasePattern() { + String filter = config.getInitParameter(JUNIT_TESTS_PATTERN); + if (filter == null) { + filter = TESTCASE_PATTERN; + } + Pattern pattern = Pattern.compile(filter); + return pattern; + } + + public void destroy() { + } + + private void init() throws IOException { + testClassLoader = Thread.currentThread().getContextClassLoader(); + allTestCases = new HashSet(); + String testsPath = config.getInitParameter(JUNIT_TESTS_PATH); + if (testsPath == null) { + testsPath = TESTS_JAR; + } + URL url = config.getServletContext().getResource(testsPath); + if (url != null) { + allTestCases = findTestCases(testsPath); + if (!(testsPath.startsWith("/WEB-INF/lib/") || testsPath.startsWith("/WEB-INF/classes/"))) { + // Create a new ClassLoader to load the test jar + testClassLoader = new URLClassLoader(new URL[] {url}, testClassLoader); + } + } + } + + /** + * Search test cases in a directory + * @param classesPath + * @param pattern + * @return + */ + private Set findTestCasesInDir(String classesPath, Pattern pattern) { + ServletContext context = config.getServletContext(); + Set tests = new HashSet(); + String dir = classesPath; + findResources(context, pattern, tests, classesPath, dir); + return tests; + } + + @SuppressWarnings("unchecked") + private void findResources(ServletContext context, Pattern pattern, Set tests, String root, String dir) { + Set paths = context.getResourcePaths(dir); + if (paths != null) { + for (String name : paths) { + if (name.endsWith("/")) { + findResources(context, pattern, tests, root, name); + } + if (name.endsWith(".class")) { + String className = name.substring(root.length(), name.length() - 6).replace('/', '.'); + if (pattern.matcher(className).matches()) { + tests.add(className); + } + } + } + } + } + + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, + ServletException { + + if (!junitEnabled) { + chain.doFilter(request, response); + return; + } + + HttpServletRequest req = (HttpServletRequest)request; + HttpServletResponse resp = (HttpServletResponse)response; + + if (!req.getRequestURI().equals(req.getContextPath() + "/junit")) { + // Intercept the /junit call + chain.doFilter(request, response); + return; + } + + String query = req.getQueryString(); + PrintStream ps = new PrintStream(response.getOutputStream()); + + Set testCases = null; + // ClassLoader cl = Thread.currentThread().getContextClassLoader(); + String op = req.getParameter("op"); + if (query == null || op == null || "list".equalsIgnoreCase(op)) { + response.setContentType("text/html"); + resp.setStatus(HttpServletResponse.SC_OK); + ps.println(""); + ps.println("

      Available Test Cases

      "); + ps.println("

      "); + ps.println(""); + for (String s : this.allTestCases) { + ps.print(""); + } + ps.println("
      "); + ps.print("" + + s + + ""); + ps.println("
      "); + ps.println("

      "); + ps.println(""); + ps.println("

      "); + resp.flushBuffer(); + return; + } else { + if ("runAll".equalsIgnoreCase(op)) { + testCases = this.allTestCases; + } else { + String[] tests = req.getParameterValues("test"); + if (tests == null) { + tests = new String[0]; + } + testCases = new HashSet(Arrays.asList(tests)); + } + } + + response.setContentType("application/xml"); + ps.println(""); + + ServletContext context = config.getServletContext(); + Object domain = context.getAttribute("org.apache.tuscany.sca.SCADomain"); + URL contribution = context.getResource("/META-INF/sca-contribution.xml"); + + long duration = 0L; + int errors = 0; + int failures = 0; + int runs = 0; + List> testClasses = new ArrayList>(); + List results = new ArrayList(); + for (String testClass : testCases) { + Class test = null; + try { + test = Class.forName(testClass, false, testClassLoader); + if (domain != null && contribution != null) { + // Inject the SCADomain + inject(test, domain); + } + testClasses.add(test); + } catch (ClassNotFoundException e) { + String st = XMLFormatter.exceptionToString(e); + st = XMLFormatter.escape(st); + ps.println(st); + // ps.close(); + throw new ServletException(e); + } + + JUnitCore core = new JUnitCore(); + Result result = core.run(Request.aClass(test)); + results.add(result); + + duration += result.getRunTime(); + runs += result.getRunCount(); + + for (Failure f : result.getFailures()) { + if (f.getException() instanceof AssertionFailedError) { + failures++; + } else { + errors++; + } + } + } + + ps.println("<" + XMLFormatter.TESTSUITE + + " " + + XMLFormatter.ATTR_TESTS + + "=\"" + + runs + + "\" " + + XMLFormatter.ATTR_FAILURES + + "=\"" + + failures + + "\" " + + XMLFormatter.ATTR_ERRORS + + "=\"" + + errors + + "\" " + + XMLFormatter.ATTR_TIME + + "=\"" + + XMLFormatter.getDurationAsString(duration) + + "\">"); + for (int i = 0; i < testClasses.size(); i++) { + ps.println(XMLFormatter.toXML(results.get(i), testClasses.get(i))); + } + ps.println(""); + + resp.addIntHeader("junit.errors", errors); + resp.addIntHeader("junit.failures", failures); + resp.addIntHeader("junit.runs", runs); + resp.setStatus(HttpServletResponse.SC_OK); + resp.flushBuffer(); + + ps.close(); + } + + private boolean inject(Class cls, Object target) { + for (Field f : cls.getDeclaredFields()) { + if (Modifier.isStatic(f.getModifiers()) && f.getType().isInstance(target)) { + f.setAccessible(true); + try { + f.set(null, target); + return true; + } catch (IllegalArgumentException e) { + return false; + } catch (IllegalAccessException e) { + return false; + } + } + } + return false; + } + + public void init(FilterConfig config) throws ServletException { + this.config = config; + // Check if the /junit path should be allowed + String param = config.getInitParameter(JUNIT_ENABLED); + if (param != null && param.trim().equals("false")) { + junitEnabled = false; + return; + } + try { + init(); + } catch (IOException e) { + throw new ServletException(e); + } + } + + public boolean isJunitEnabled() { + return junitEnabled; + } + +} diff --git a/java/sca/contrib/modules/host-webapp-junit/src/main/java/org/apache/tuscany/sca/host/webapp/junit/XMLFormatter.java b/java/sca/contrib/modules/host-webapp-junit/src/main/java/org/apache/tuscany/sca/host/webapp/junit/XMLFormatter.java new file mode 100644 index 0000000000..72ec478cd6 --- /dev/null +++ b/java/sca/contrib/modules/host-webapp-junit/src/main/java/org/apache/tuscany/sca/host/webapp/junit/XMLFormatter.java @@ -0,0 +1,286 @@ +/* + * ======================================================================== + * + * Copyright 2001-2005 The Apache Software Foundation. + * + * 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.apache.tuscany.sca.host.webapp.junit; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringReader; +import java.io.StringWriter; +import java.text.NumberFormat; +import java.util.Locale; + +import junit.framework.AssertionFailedError; + +import org.junit.runner.Result; +import org.junit.runner.notification.Failure; + +/** + * Format the test results in XML. + * + * @version $Id: XMLFormatter.java 239169 2005-05-05 09:21:54Z vmassol $ + */ +public class XMLFormatter { + /** + * Errors attribute for TestSuite elements + */ + public static final String ATTR_ERRORS = "errors"; + + /** + * Failures attribute for TestSuite elements + */ + public static final String ATTR_FAILURES = "failures"; + + /** + * Message attribute for failure elements (message of the exception) + */ + public static final String ATTR_MESSAGE = "message"; + + /** + * Name attribute for property, TestCase and TestSuite elements + */ + public static final String ATTR_NAME = "name"; + + /** + * Tests attribute for TestSuite elements (number of tests executed) + */ + public static final String ATTR_TESTS = "tests"; + + /** + * Time attribute for TestCase and TestSuite elements + */ + public static final String ATTR_TIME = "time"; + + /** + * Type attribute for failure and error elements + */ + public static final String ATTR_TYPE = "type"; + + /** + * Default stack filter patterns. + */ + private static final String[] DEFAULT_STACK_FILTER_PATTERNS = + new String[] {"junit.framework.TestCase", "junit.framework.TestResult", "junit.framework.TestSuite", + "junit.framework.Assert.", // don't filter AssertionFailure + "java.lang.reflect.Method.invoke("}; + + /** + * The number format used to convert durations into strings. Don't use the + * default locale for that, because the resulting string needs to use + * dotted decimal notation for an XSLT transformation to work correctly. + */ + private static NumberFormat durationFormat = NumberFormat.getInstance(Locale.US); + + /** + * The error element (for a test case) + */ + public static final String ERROR = "error"; + + /** + * The failure element (for a test case) + */ + public static final String FAILURE = "failure"; + + /** + * A single TestCase element + */ + public static final String TESTCASE = "testcase"; + + /** + * A single test suite results. + */ + public static final String TESTSUITE = "testsuite"; + + /** + * Escapes reserved XML characters. + * + * @param theString the string to escape + * @return the escaped string + */ + public static String escape(String theString) { + String newString; + + // It is important to replace the "&" first as the other replacements + // also introduces "&" chars ... + newString = theString.replace("&", "&"); + + newString = newString.replace("<", "<"); + newString = newString.replace(">", ">"); + newString = newString.replace("\"", """); + + return newString; + } + + /** + * Returns the stack trace of an exception as String. + * + * @param theThrowable the exception from which to extract the stack trace + * as a String + * @return the exception stack trace as a String + */ + public static String exceptionToString(Throwable theThrowable) { + return exceptionToString(theThrowable, null); + } + + /** + * Returns the stack trace of an exception as String, optionally filtering + * out line from the stack trace + * + * @param theThrowable the exception from which to extract the stack trace + * as a String + * @param theFilterPatterns Array containing a list of patterns to filter + * out from the stack trace + * @return the exception stack trace as a String + */ + public static String exceptionToString(Throwable theThrowable, String[] theFilterPatterns) { + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + + theThrowable.printStackTrace(pw); + String stackTrace = sw.toString(); + return filterStackTrace(stackTrace, theFilterPatterns); + } + + /** + * + * + * @param theLine The line to check + * @param theFilterPatterns The patterns to filter out + * @return boolean Whether the specified line should be filtered from the + * stack trace + */ + public static boolean filterLine(String theLine, String[] theFilterPatterns) { + for (int i = 0; i < theFilterPatterns.length; i++) { + if (theLine.indexOf(theFilterPatterns[i]) > 0) { + return true; + } + } + return false; + } + + /** + * + * + * @param theStackTrace The original, unfiltered stack trace + * @param theFilterPatterns The patterns to filter out + * @return The filtered stack trace + */ + static String filterStackTrace(String theStackTrace, String[] theFilterPatterns) { + if ((theFilterPatterns == null) || (theFilterPatterns.length == 0) || (theStackTrace == null)) { + return theStackTrace; + } + + StringWriter stringWriter = new StringWriter(); + PrintWriter printWriter = new PrintWriter(stringWriter); + StringReader stringReader = new StringReader(theStackTrace); + BufferedReader bufferedReader = new BufferedReader(stringReader); + + String line; + try { + while ((line = bufferedReader.readLine()) != null) { + if (!filterLine(line, theFilterPatterns)) { + printWriter.println(line); + } + } + } catch (IOException e) { + return theStackTrace; + } + return stringWriter.toString(); + } + + /** + * Convert a duration expressed as a long into a string. + * + * @param theDuration the duration to convert to string + * @return the total duration as a string + */ + public static String getDurationAsString(long theDuration) { + return durationFormat.format((double)theDuration / 1000); + } + + public static String toXML(Failure failure) { + StringBuffer xml = new StringBuffer(); + Throwable ex = failure.getException(); + String tag = (ex instanceof AssertionFailedError) ? FAILURE : ERROR; + xml.append("<" + tag + + " " + + ATTR_MESSAGE + + "=\"" + + escape(ex.getMessage()) + + "\" " + + ATTR_TYPE + + "=\"" + + ex.getClass().getName() + + "\">"); + xml.append(escape(exceptionToString(ex, DEFAULT_STACK_FILTER_PATTERNS))); + xml.append(""); + + return xml.toString(); + } + + /** + * Formats the test result as an XML string. + * + * @param result the test result object + * @return the XML string representation of the test results + */ + public static String toXML(Result result, Class cls) { + int failures = 0, errors = 0; + for (Failure f : result.getFailures()) { + if (f.getException() instanceof AssertionFailedError) { + failures++; + } else { + errors++; + } + } + StringBuffer xml = new StringBuffer(); + + xml.append("<" + TESTCASE + + " " + + ATTR_NAME + + "=\"" + + cls.getName() + + "\" " + + ATTR_TESTS + + "=\"" + + result.getRunCount() + + "\" " + + ATTR_FAILURES + + "=\"" + + failures + + "\" " + + ATTR_ERRORS + + "=\"" + + errors + + "\" " + + ATTR_TIME + + "=\"" + + getDurationAsString(result.getRunTime()) + + "\">"); + + for (Failure f : result.getFailures()) { + xml.append(toXML(f)); + } + + xml.append(""); + + return xml.toString(); + } +} diff --git a/java/sca/contrib/modules/implementation-bpel-ode/LICENSE b/java/sca/contrib/modules/implementation-bpel-ode/LICENSE new file mode 100644 index 0000000000..baba9ca048 --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel-ode/LICENSE @@ -0,0 +1,251 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + +=============================================================================================================== + +Apache Tuscany SCA for Java Subcomponents +=========================================: + +The Tuscany SCA for Java release includes a number of subcomponents with +separate copyright notices and license terms. Your use of the source +code for the these subcomponents is subject to the terms and +conditions of the following licenses. + +================================================================================================================= + +This module implementation-script temporarily includes one file under the following BSD license: + + Copyright (c) 2006, Sun Microsystems, Inc. + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + - Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + - Neither the name of the Sun Microsystems, Inc. nor the names of + contributors may be used to endorse or promote products derived from this + software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND + CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED + WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH + DAMAGE. + +================================================================================================================= diff --git a/java/sca/contrib/modules/implementation-bpel-ode/META-INF/MANIFEST.MF b/java/sca/contrib/modules/implementation-bpel-ode/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..552581efb6 --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel-ode/META-INF/MANIFEST.MF @@ -0,0 +1,47 @@ +Manifest-Version: 1.0 +Private-Package: org.apache.tuscany.sca.implementation.bpel.ode;versio + n="1.4",org.apache.tuscany.sca.implementation.bpel.ode.provider;versi + on="1.4" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA BPEL ODE Implementation Extension +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397447609 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA BPEL ODE Implementation Extensi + on +Import-Package: javax.resource.spi, + javax.sql, + javax.transaction;version="1.0.1", + javax.wsdl, + javax.xml.namespace, + + org.apache.commons.logging, + org.apache.geronimo.transaction.manager, + org.apache.ode.bpel.compiler, + org.apache.ode.bpel.dao, + org.apache.ode.bpel.engine, + org.apache.ode.bpel.evt, + org.apache.ode.bpel.iapi, + org.apache.ode.bpel.memdao, + org.apache.ode.il.config, + org.apache.ode.il.dbutil, + org.apache.ode.scheduler.simple, + org.apache.ode.utils, + org.apache.tuscany.sca.assembly;version="2.0.0", + org.apache.tuscany.sca.core;version="2.0.0", + org.apache.tuscany.sca.databinding.xml;version="2.0.0", + org.apache.tuscany.sca.implementation.bpel;version="2.0.0", + org.apache.tuscany.sca.interfacedef;version="2.0.0", + org.apache.tuscany.sca.interfacedef.wsdl;version="2.0.0", + org.apache.tuscany.sca.invocation;version="2.0.0", + org.apache.tuscany.sca.policy;version="2.0.0", + org.apache.tuscany.sca.provider;version="2.0.0", + org.apache.tuscany.sca.runtime;version="2.0.0", + org.oasisopen.sca.annotation;version="2.0.0", + org.w3c.dom +Bundle-SymbolicName: org.apache.tuscany.sca.implementation.bpel.ode +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/implementation-bpel-ode/NOTICE b/java/sca/contrib/modules/implementation-bpel-ode/NOTICE new file mode 100644 index 0000000000..61ea4111aa --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel-ode/NOTICE @@ -0,0 +1,17 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + +Unless otherwise indicated, all distribution made available by the Apache Software Foundation +is provided to you under the terms and conditions of the Apache License Version 2.0 ("AL"). +A copy of the AL is provided with this distribution as the LICENSE file present in the +root directory, and is also available at http://www.apache.org/licenses/. + +This product also includes software under the BSD license +(see the LICENSE file contained in this distribution), with +the following copyright: + +Copyright (c) 2006, Sun Microsystems, Inc. +All rights reserved. diff --git a/java/sca/contrib/modules/implementation-bpel-ode/pom.xml b/java/sca/contrib/modules/implementation-bpel-ode/pom.xml new file mode 100644 index 0000000000..02eccc899a --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel-ode/pom.xml @@ -0,0 +1,415 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + tuscany-implementation-bpel-ode + Apache Tuscany SCA BPEL ODE Implementation Extension + + + org.apache.tuscany.sca + tuscany-assembly + 2.0-SNAPSHOT + + + org.apache.tuscany.sca + tuscany-implementation-bpel + 2.0-SNAPSHOT + + + org.apache.tuscany.sca + tuscany-core + 2.0-SNAPSHOT + + + org.apache.tuscany.sca + tuscany-interface + 2.0-SNAPSHOT + + + org.apache.tuscany.sca + tuscany-assembly-xml + 2.0-SNAPSHOT + + + org.apache.tuscany.sca + tuscany-contribution + 2.0-SNAPSHOT + + + org.apache.tuscany.sca + tuscany-sca-api + 2.0-SNAPSHOT + + + org.apache.tuscany.sca + tuscany-databinding + 2.0-SNAPSHOT + + + org.apache.tuscany.sca + tuscany-databinding-sdo + 2.0-SNAPSHOT + + + org.apache.tuscany.sca + tuscany-implementation-java-runtime + 2.0-SNAPSHOT + + + org.apache.tuscany.sca + tuscany-node-impl + 2.0-SNAPSHOT + + + org.apache.tuscany.sca + tuscany-interface-wsdl + 2.0-SNAPSHOT + + + org.apache.tuscany.sca + tuscany-interface-wsdl-xml + 2.0-SNAPSHOT + + + org.apache.tuscany.sdo + tuscany-sdo-impl + 1.1.1 + compile + + + stax + stax-api + + + + + junit + junit + 4.5 + test + + + + + org.apache.ode + ode-bpel-epr + 1.1.1 + + + org.apache.ode + ode-bpel-store + 1.1.1 + + + org.apache.ode + ode-bpel-dao + 1.1.1 + + + org.apache.ode + ode-bpel-dao + 1.1.1 + + + org.apache.ode + ode-dao-jpa + 1.1.1 + + + org.apache.ode + ode-dao-jpa-ojpa-derby + 1.1.1 + zip + + + org.apache.ode + ode-bpel-runtime + 1.1.1 + + + org.apache.ode + ode-bpel-api + 1.1.1 + + + org.apache.ode + ode-scheduler-simple + 1.1.1 + + + org.apache.ode + ode-utils + 1.1.1 + + + org.apache.ode + ode-bpel-compiler + 1.1.1 + + + org.apache.ode + ode-bpel-schemas + 1.1.1 + + + org.apache.ode + ode-bpel-obj + 1.1.1 + + + org.apache.ode + ode-jacob + 1.1.1 + + + org.apache.ode + ode-jacob-ap + 1.1.1 + + + + + commons-lang + commons-lang + 2.1 + + + commons-collections + commons-collections + 3.1 + + + org.apache.geronimo.specs + geronimo-jta_1.0.1B_spec + 1.0 + + + org.apache.geronimo.modules + geronimo-kernel + 1.2-beta + + + mx4j + mx4j + + + xpp3 + xpp3 + + + xstream + xstream + + + + + org.apache.geronimo.modules + geronimo-transaction + 1.2-beta + + + org.apache.geronimo.specs + geronimo-ejb_2.1_spec + + + ognl + ognl + + + + + org.apache.geronimo.specs + geronimo-ejb_3.0_spec + 1.0 + + + org.apache.geronimo.modules + geronimo-connector + 1.2-beta + + + xmlbeans + xbean + + + stax + stax-api + + + + + org.apache.derby + derby + 10.3.1.4 + + + tranql + tranql-connector + 1.1 + + + org.apache.openjpa + openjpa-all + 0.9.7-incubating + + + org.apache.openjpa + openjpa-lib + + + org.apache.openjpa + openjpa-kernel + + + org.apache.openjpa + openjpa-kernel-5 + + + org.apache.openjpa + openjpa-jdbc + + + org.apache.openjpa + openjpa-jdbc-5 + + + org.apache.openjpa + openjpa-persistence-jdbc + + + org.apache.openjpa + openjpa-xmlstore + + + + + net.sourceforge.serp + serp + 1.12.0 + + + jaxen + jaxen + 1.1.1 + + + xom + xom + + + + + xalan + xalan + 2.7.0 + + + xerces + xercesImpl + 2.8.1 + + + org.apache.xmlbeans + xmlbeans + 2.3.0 + + + stax + stax-api + + + + + net.sf.saxon + saxon + 8.7 + + + + net.sf.saxon + saxon-dom + 8.7 + + + + net.sf.saxon + saxon-xpath + 8.7 + + + + commons-codec + commons-codec + 1.3 + + + commons-codec + commons-codec + + + + + log4j + log4j + 1.2.13 + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + 2.3.1 + + false + false + true + + + + org.apache.maven.plugins + maven-dependency-plugin + + + unpack + generate-sources + + unpack + + + + + org.apache.ode + ode-dao-jpa-ojpa-derby + 1.1.1 + zip + true + ${project.build.directory}/test-classes/ + + + + + + + + + + + diff --git a/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/BPELODEDeployFile.java b/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/BPELODEDeployFile.java new file mode 100644 index 0000000000..20373d0819 --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/BPELODEDeployFile.java @@ -0,0 +1,225 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.implementation.bpel.ode; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.net.URI; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.tuscany.sca.assembly.ComponentType; +import org.apache.tuscany.sca.assembly.Reference; +import org.apache.tuscany.sca.assembly.Service; +import org.apache.tuscany.sca.implementation.bpel.BPELImplementation; + +/** + * A class that handles the deploy.xml file required for each BPEL process by the ODE runtime + * @author Mike Edwards + * + * An explanation of the structure of the ODE deploy file: + * + * + * + * + * true + * + * + * + * + * + * + * + * + * + * For SCA purposes: + * + * a) Each partner link in the BPEL process is declared using either a + * (for a service) or using a (for a reference). + * + * b) Each and must use the partnerLink name, as declared in the + * BPEL process. + * + * c) The and elements each have a single child element. + * The elements have name and port attributes. The NAME attribute MUST be set + * to the same name as the partnerLink and MUST be prefixed by a prefix which references + * the namespace "http://tuscany.apache.org" ("tus" in the example above). + * The port attribute can be set to any name (it must be present but it is not actually + * used for anything significant). + * + * When SCA loads a BPEL process to the ODE server, this file is read by the ODE server to + * characterize the process. When SCA interacts with ODE at later points - either when a + * service is being invoked or the process invokes a reference - it is the service @name + * attribute that identifies the service or reference involved. + * + * @version + */ +public class BPELODEDeployFile { + private final Log __log = LogFactory.getLog(getClass()); + + static final String DEPLOY_ELEMENT_START = ""; + static final String PROCESS_ENDELEMENT = ""; + static final String ACTIVE_ELEMENT = "true"; + static final String PROVIDE_ELEMENT_START = ""; + static final String PROVIDE_ENDELEMENT = ""; + static final String SERVICE_ELEMENT_START = ""; + static final String INVOKE_ELEMENT_START = ""; + static final String INVOKE_ENDELEMENT = ""; + + static final String DEPLOY_FILENAME = "deploy.xml"; + + private BPELImplementation implementation; + + /** + * Constructor - requires a BPELImplementation as a parameter + * The ODE deploy.xml file is for this supplied BPELImplementation + * @param theImplementation + */ + public BPELODEDeployFile( BPELImplementation theImplementation ) { + + implementation = theImplementation; + + } // end BPELODEDeployFile constructor + + /** + * Writes the deploy file into the same directory as the BPEL process file, with the name + * "deploy.xml" + */ + public void writeDeployfile() throws IOException { + + File theDirectory = getDirectory(); + + File deployFile = new File( theDirectory, DEPLOY_FILENAME ); + new FileOutputStream( deployFile ); + //if( !deployFile.canWrite() ) throw new IOException( "Unable to write to deploy file" + + // deployFile.getPath() ); + + // Create a stream for the data and write the data to the file + PrintStream theStream = new PrintStream( new FileOutputStream( deployFile ) ); + try { + constructDeployXML( theStream ); + if( theStream.checkError() ) throw new IOException(); + } catch (Exception e) { + throw new IOException( "Unable to write data to deploy file" + + deployFile.getPath() ); + } finally { + theStream.close(); + } // end try + + } // end writeDeployFile + + /** + * Creates the deploy.xml data and writes it to a supplied PrintStream + * @param stream + */ + public void constructDeployXML( PrintStream stream ) { + + // " ); + + // element + stream.println( PROCESS_ELEMENT_START + process.getLocalPart() + + PROCESS_ELEMENT_END ); + + // element + stream.println( ACTIVE_ELEMENT ); + + ComponentType componentType = implementation.getComponentType(); + List theServices = componentType.getServices(); + // Loop over the elements - one per service + for ( Service service : theServices ) { + String serviceName = service.getName(); + // Provide element... + stream.println( PROVIDE_ELEMENT_START + serviceName + PROVIDE_ELEMENT_END ); + // Child service element... + stream.println( SERVICE_ELEMENT_START + serviceName + + SERVICE_ELEMENT_PORT + serviceName + SERVICE_ELEMENT_END ); + stream.println( PROVIDE_ENDELEMENT ); + } // end for + + // Loop over the elements - one per reference + List theReferences = componentType.getReferences(); + for ( Reference reference : theReferences ) { + String referenceName = reference.getName(); + stream.println( INVOKE_ELEMENT_START + referenceName + INVOKE_ELEMENT_END ); + // Child service element... + stream.println( SERVICE_ELEMENT_START + referenceName + + SERVICE_ELEMENT_PORT + referenceName + SERVICE_ELEMENT_END ); + stream.println( INVOKE_ENDELEMENT ); + + } // end for + + // element + stream.println( PROCESS_ENDELEMENT ); + + // + stream.println( DEPLOY_ENDELEMENT ); + + } // end constructDeployXML + + /** + * Gets the directory containing the BPEL process + * @return + */ + private File getDirectory() { + File theDir = getBPELFile().getParentFile(); + return theDir; + } // end getDirectory + + /** + * Gets the File containing the BPEL process definition + * @return - the File object containing the BPEL process + */ + private File getBPELFile() { + try { + File theProcess = new File(URI.create(implementation.getProcessDefinition().getLocation())); + return theProcess; + } catch( Exception e ) { + if(__log.isDebugEnabled()) { + __log.debug("Exception converting BPEL file URL to an URI: " + e ); + } + } // end try + return null; + } // end getBPELFile + + + +} // end class BPELODEDeployFile diff --git a/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/EmbeddedODEServer.java b/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/EmbeddedODEServer.java new file mode 100644 index 0000000000..ed327331db --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/EmbeddedODEServer.java @@ -0,0 +1,261 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.implementation.bpel.ode; + +import java.io.File; +import java.net.URL; +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import javax.transaction.TransactionManager; +import javax.xml.namespace.QName; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.ode.bpel.dao.BpelDAOConnectionFactoryJDBC; +import org.apache.ode.bpel.engine.BpelServerImpl; +import org.apache.ode.bpel.engine.CountLRUDehydrationPolicy; +import org.apache.ode.bpel.iapi.Scheduler; +import org.apache.ode.bpel.memdao.BpelDAOConnectionFactoryImpl; +import org.apache.ode.il.config.OdeConfigProperties; +import org.apache.ode.il.dbutil.Database; +import org.apache.ode.scheduler.simple.JdbcDelegate; +import org.apache.ode.scheduler.simple.SimpleScheduler; +import org.apache.ode.utils.GUID; +import org.apache.tuscany.sca.implementation.bpel.BPELImplementation; +import org.apache.tuscany.sca.runtime.RuntimeComponent; + +/** + * Embedded ODE process server + * + * @version $Rev$ $Date$ + */ +public class EmbeddedODEServer { + protected final Log __log = LogFactory.getLog(getClass()); + + private boolean _initialized; + + private OdeConfigProperties _config; + + private TransactionManager _txMgr; + + private Database _db; + + private File _workRoot; + + private BpelDAOConnectionFactoryJDBC _daoCF; + + private BpelServerImpl _bpelServer; + + private Scheduler _scheduler; + + protected ExecutorService _executorService; + + private Map tuscanyRuntimeComponents = new ConcurrentHashMap(); + + public EmbeddedODEServer(TransactionManager txMgr) { + _txMgr = txMgr; + } + + public void init() throws ODEInitializationException { + Properties p = System.getProperties(); + p.put("derby.system.home", "target"); + + Properties confProps = new Properties(); + confProps.put("openjpa.jdbc.SynchronizeMappings", "buildSchema(ForeignKeys=false)"); + _config = new OdeConfigProperties(confProps, "ode-sca"); + + // Setting work root as the directory containing our database (wherever in the classpath) + URL dbLocation = getClass().getClassLoader().getResource("jpadb"); + if (dbLocation == null) + throw new ODEInitializationException("Couldn't find database in the classpath"); + _workRoot = new File(dbLocation.getFile()).getParentFile(); + + initTxMgr(); + initPersistence(); + initBpelServer(); + + try { + _bpelServer.start(); + } catch (Exception ex) { + String errmsg = "An error occured during the ODE BPEL server startup."; + __log.error(errmsg, ex); + throw new ODEInitializationException(errmsg, ex); + } + + __log.info("ODE BPEL server started."); + _initialized = true; + } + + private void initTxMgr() { + if(_txMgr == null) { + try { + GeronimoTxFactory txFactory = new GeronimoTxFactory(); + _txMgr = txFactory.getTransactionManager(); + } catch (Exception e) { + __log.fatal("Couldn't initialize a transaction manager using Geronimo's transaction factory.", e); + throw new ODEInitializationException("Couldn't initialize a transaction manager using " + "Geronimo's transaction factory.", e); + } + } + } + + private void initPersistence() { + _db = new Database(_config); + _db.setTransactionManager(_txMgr); + _db.setWorkRoot(_workRoot); + + try { + _db.start(); + _daoCF = _db.createDaoCF(); + } catch (Exception ex) { + String errmsg = "Error while configuring ODE persistence."; + __log.error(errmsg, ex); + throw new ODEInitializationException(errmsg, ex); + } + } + + private void initBpelServer() { + if (__log.isDebugEnabled()) { + __log.debug("ODE initializing"); + } + + //FIXME: externalize the configuration for ThreadPoolMaxSize + _executorService = Executors.newCachedThreadPool(); + + _bpelServer = new BpelServerImpl(); + _scheduler = createScheduler(); + _scheduler.setJobProcessor(_bpelServer); + + _bpelServer.setDaoConnectionFactory(_daoCF); + _bpelServer.setInMemDaoConnectionFactory(new BpelDAOConnectionFactoryImpl(_scheduler)); + // _bpelServer.setEndpointReferenceContext(new EndpointReferenceContextImpl(this)); + _bpelServer.setMessageExchangeContext(new ODEMessageExchangeContext(this)); + _bpelServer.setBindingContext(new ODEBindingContext()); + _bpelServer.setScheduler(_scheduler); + if (_config.isDehydrationEnabled()) { + CountLRUDehydrationPolicy dehy = new CountLRUDehydrationPolicy(); + _bpelServer.setDehydrationPolicy(dehy); + } + + _bpelServer.init(); + } // end InitBpelServer + + public void stop() throws ODEShutdownException { + if(_bpelServer != null) { + try { + __log.debug("Stopping BPEL Embedded server"); + _bpelServer.shutdown(); + _bpelServer = null; + } catch (Exception ex) { + __log.debug("Error stopping BPEL server"); + } + } + + if(_scheduler != null) { + try { + __log.debug("Stopping scheduler"); + _scheduler.shutdown(); + _scheduler = null; + } catch (Exception ex) { + __log.debug("Error stopping scheduler"); + } + } + + if(_daoCF != null) { + try { + __log.debug("Stopping DAO"); + _daoCF.shutdown(); + _daoCF = null; + } catch (Exception ex) { + __log.debug("Error stopping DAO"); + } + } + + if(_db != null) { + try { + __log.debug("Stopping DB"); + _db.shutdown(); + _db = null; + } catch (Exception ex) { + __log.debug("Error stopping DB"); + } + } + + if(_txMgr != null) { + try { + __log.debug("Stopping Transaction Manager"); + _txMgr = null; + } catch (Exception ex) { + __log.debug("Error stopping Transaction Manager"); + } + } + } + + protected Scheduler createScheduler() { + SimpleScheduler scheduler = new SimpleScheduler(new GUID().toString(),new JdbcDelegate(_db.getDataSource())); + scheduler.setTransactionManager(_txMgr); + + return scheduler; + } + + public boolean isInitialized() { + return _initialized; + } + + public BpelServerImpl getBpelServer() { + return _bpelServer; + } + + public Scheduler getScheduler() { + return _scheduler; + } + + public ExecutorService getExecutor() { + return _executorService; + } + + // Updated by Mike Edwards, 23/05/2008 + public void deploy(ODEDeployment d, BPELImplementation implementation) { + try { + TuscanyProcessConfImpl processConf = new TuscanyProcessConfImpl( implementation ); + _bpelServer.register(processConf); + System.out.println("Completed calling new Process deployment code..."); + } catch (Exception ex) { + String errMsg = ">>> DEPLOY: Unexpected exception: " + ex.getMessage(); + __log.debug(errMsg, ex); + throw new ODEDeploymentException(errMsg,ex); + } + } + + public void undeploy(ODEDeployment d) { + //TODO + } + + public void registerTuscanyRuntimeComponent(QName processName,RuntimeComponent componentContext) { + tuscanyRuntimeComponents.put(processName, componentContext); + } + + public RuntimeComponent getTuscanyRuntimeComponent(QName processName) { + return tuscanyRuntimeComponents.get(processName); + } +} diff --git a/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/GeronimoTxFactory.java b/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/GeronimoTxFactory.java new file mode 100644 index 0000000000..11af0f8b50 --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/GeronimoTxFactory.java @@ -0,0 +1,48 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.implementation.bpel.ode; + +import javax.transaction.TransactionManager; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** + * Geronimo transaction factory + * + * @version $Rev$ $Date$ + */ +public class GeronimoTxFactory { + private static final Log __log = LogFactory.getLog(GeronimoTxFactory.class); + + /* Public no-arg constructor is required */ + public GeronimoTxFactory() { + } + + public TransactionManager getTransactionManager() { + __log.info("Using embedded Geronimo transaction manager"); + try { + Object obj = new org.apache.geronimo.transaction.manager.GeronimoTransactionManager(); + return (TransactionManager) obj; + } catch (Exception except) { + throw new IllegalStateException("Unable to instantiate Geronimo Transaction Manager", except); + } + } +} diff --git a/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/ODEBindingContext.java b/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/ODEBindingContext.java new file mode 100644 index 0000000000..3f2db7b244 --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/ODEBindingContext.java @@ -0,0 +1,79 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.implementation.bpel.ode; + +import javax.wsdl.PortType; +import javax.xml.namespace.QName; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.ode.bpel.iapi.BindingContext; +import org.apache.ode.bpel.iapi.Endpoint; +import org.apache.ode.bpel.iapi.EndpointReference; +import org.apache.ode.bpel.iapi.PartnerRoleChannel; + +/** + * Binding Context information + * + * @version $Rev$ $Date$ + */ +public class ODEBindingContext implements BindingContext { + protected final Log __log = LogFactory.getLog(getClass()); + + public ODEBindingContext() { + + } + + public EndpointReference activateMyRoleEndpoint(QName pid, Endpoint endpoint) { + // This will be needed when we support callBacks + if (__log.isDebugEnabled()) { + __log.debug("Activating MyRole Endpoint : " + pid + " - " + endpoint.serviceName); + } + + QName processName = getProcessName(pid); + + return new TuscanyEPR(processName, endpoint); + } + + public void deactivateMyRoleEndpoint(Endpoint endpoint) { + if (__log.isDebugEnabled()) { + __log.debug("Deactivate MyRole Endpoint : " + endpoint.serviceName); + } + + } + + public PartnerRoleChannel createPartnerRoleChannel(QName pid, PortType portType, Endpoint endpoint) { + if (__log.isDebugEnabled()) { + __log.debug("Create PartnerRole channel : " + pid + " - " + portType.getQName() + " - "+ endpoint.serviceName); + } + + QName processName = getProcessName(pid); + return new TuscanyPRC(processName, pid, portType, endpoint); + } + + /** + * Helper method to retrieve the BPEL process name from a processID (where processID have version concatenated to it) + * @param pid + * @return QName the BPEL process name + */ + private static QName getProcessName(QName pid) { + String processName = pid.getLocalPart().substring(0, pid.getLocalPart().lastIndexOf("-")); + return new QName(pid.getNamespaceURI(), processName); + } +} diff --git a/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/ODEDeployment.java b/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/ODEDeployment.java new file mode 100644 index 0000000000..a6428f6984 --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/ODEDeployment.java @@ -0,0 +1,44 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.implementation.bpel.ode; + +import java.io.File; + +/** + * Deployment information + * + * @version $Rev$ $Date$ + */ +public class ODEDeployment { + /** The directory containing the deploy.xml and artifacts. */ + public File deployDir; + + /** If non-null the type of exception we expect to get when we deploy. */ + public Class expectedException = null; + + public ODEDeployment(File deployDir) { + this.deployDir = deployDir; + } + + @Override + public String toString() { + return "Deployment#" + deployDir; + } +} \ No newline at end of file diff --git a/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/ODEDeploymentException.java b/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/ODEDeploymentException.java new file mode 100644 index 0000000000..b03f69d9aa --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/ODEDeploymentException.java @@ -0,0 +1,41 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.implementation.bpel.ode; + +/** + * Thrown when ODE failed to shutdown. + * + * @version $Rev$ $Date$ + */ +public class ODEDeploymentException extends RuntimeException { + private static final long serialVersionUID = -2869674556330744215L; + + public ODEDeploymentException(Throwable cause) { + super(cause); + } + + public ODEDeploymentException(String message) { + super(message); + } + + public ODEDeploymentException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/ODEExternalService.java b/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/ODEExternalService.java new file mode 100644 index 0000000000..15e9229601 --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/ODEExternalService.java @@ -0,0 +1,285 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.implementation.bpel.ode; + +import java.util.concurrent.Callable; + +import javax.wsdl.Part; +import javax.xml.namespace.QName; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.ode.bpel.iapi.Message; +import org.apache.ode.bpel.iapi.MessageExchange; +import org.apache.ode.bpel.iapi.PartnerRoleMessageExchange; +import org.apache.ode.bpel.iapi.Scheduler; +import org.apache.ode.utils.DOMUtils; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.interfacedef.wsdl.WSDLInterface; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeWire; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * Helper Class to handle invocation to Tuscany Component References + * + * @version $Rev$ $Date$ + */ +public class ODEExternalService { + protected final Log __log = LogFactory.getLog(getClass()); + + private EmbeddedODEServer _server; + private Scheduler _sched; + + public ODEExternalService(EmbeddedODEServer server) { + this._server = server; + this._sched = _server.getScheduler(); + } + + + public void invoke(final PartnerRoleMessageExchange partnerRoleMessageExchange) { + boolean isTwoWay = + partnerRoleMessageExchange.getMessageExchangePattern() == org.apache.ode.bpel.iapi.MessageExchange.MessageExchangePattern.REQUEST_RESPONSE; + + if (isTwoWay) { + // Defer the invoke until the transaction commits. + _sched.registerSynchronizer(new Scheduler.Synchronizer() { + public void beforeCompletion() { + + } + + public void afterCompletion(boolean success) { + // If the TX is rolled back, then we don't send the request. + if (!success) + return; + + // The invocation must happen in a separate thread, holding + // on the afterCompletion + // blocks other operations that could have been listed there + // as well. + _server.getExecutor().submit(new Callable() { + public Object call() throws Exception { + try { + // do execution + if(! (partnerRoleMessageExchange.getChannel() instanceof TuscanyPRC)) { + throw new IllegalArgumentException("Channel should be an instance of TuscanyPRC"); + } + + TuscanyPRC channel = (TuscanyPRC) partnerRoleMessageExchange.getChannel(); + RuntimeComponent tuscanyRuntimeComponent = _server.getTuscanyRuntimeComponent(channel.getProcessName()); + + RuntimeComponentReference runtimeComponentReference = + (RuntimeComponentReference)tuscanyRuntimeComponent.getReferences().get(0); + RuntimeWire runtimeWire = + runtimeComponentReference.getRuntimeWire(runtimeComponentReference.getBindings().get(0)); + + // convert operations + Operation operation = + findOperation(partnerRoleMessageExchange.getOperation().getName(), runtimeComponentReference); + + + /* + This is how a request looks like (payload is wrapped with extra info) + + + + + Luciano + + + + */ + Element msg = partnerRoleMessageExchange.getRequest().getMessage(); + if (msg != null) { + String xml = DOMUtils.domToString(msg); + + String payload = + DOMUtils.domToString(getPayload(partnerRoleMessageExchange.getRequest())); + + if(__log.isDebugEnabled()) { + __log.debug("Starting invocation of SCA Reference"); + __log.debug(">>> Original message: " + xml); + __log.debug(">>> Payload: " + payload); + } + + Object[] args = new Object[] {getPayload(partnerRoleMessageExchange.getRequest())}; + + Object result = null; + boolean success = false; + + try { + result = runtimeWire.invoke(operation, args); + success = true; + } catch (Exception e) { + partnerRoleMessageExchange.replyWithFailure(MessageExchange.FailureType.OTHER, + e.getMessage(), + null); + } + + + if(__log.isDebugEnabled()) { + __log.debug("SCA Reference invocation finished"); + __log.debug(">>> Result : " + DOMUtils.domToString((Element)result)); + } + + if (!success) { + return null; + } + + // two way invocation + // process results based on type of message + // invocation + + // Message response = + // createResponseMessage(partnerRoleMessageExchange, + // (Element) result); + // partnerRoleMessageExchange.reply(response); + replyTwoWayInvocation(partnerRoleMessageExchange.getMessageExchangeId(), + operation, + (Element)result); + } + + } catch (Throwable t) { + // some error + String errmsg = + "Error sending message (mex=" + partnerRoleMessageExchange + "): " + t.getMessage(); + __log.error(errmsg, t); + /*replyWithFailure(partnerRoleMessageExchange.getMessageExchangeId(), + MessageExchange.FailureType.COMMUNICATION_ERROR, + errmsg, + null);*/ + } + return null; + } + }); + + } + }); + partnerRoleMessageExchange.replyAsync(); + + } else { + /** one-way case * */ + _server.getExecutor().submit(new Callable() { + public Object call() throws Exception { + // do reply + // operationClient.execute(false); + return null; + } + }); + partnerRoleMessageExchange.replyOneWayOk(); + } + } + + + /** + * Find the SCA Reference operation + * + * @param operationName + * @param runtimeComponentReference + * @return + */ + private Operation findOperation(String operationName, RuntimeComponentReference runtimeComponentReference) { + Operation reseultOperation = null; + + for(Operation operation : runtimeComponentReference.getInterfaceContract().getInterface().getOperations()) { + if (operationName.equalsIgnoreCase(operation.getName())) { + reseultOperation = operation; + break; + } + } + return reseultOperation; + } + + /** + * Get paylod from a given ODEMessage + * @param odeMessage + * @return + */ + private Element getPayload(Message odeMessage) { + Element payload = null; + Element parameters = odeMessage.getPart("parameters"); + + if (parameters != null && parameters.hasChildNodes()) { + payload = (Element)parameters.getFirstChild(); + } + + return payload; + } + + + private void replyTwoWayInvocation(final String odeMexId, final Operation operation, final Element result) { + // ODE MEX needs to be invoked in a TX. + try { + _server.getScheduler().execIsolatedTransaction(new Callable() { + public Void call() throws Exception { + PartnerRoleMessageExchange odeMex = null; + try { + odeMex = (PartnerRoleMessageExchange)_server.getBpelServer().getEngine().getMessageExchange(odeMexId); + if (odeMex != null) { + Message response = createResponseMessage(odeMex, operation, (Element)result); + odeMex.reply(response); + } + } catch (Exception ex) { + String errmsg = "Unable to process response: " + ex.getMessage(); + if (odeMex != null) { + odeMex.replyWithFailure(MessageExchange.FailureType.OTHER, errmsg, null); + } + } + + return null; + } + }); + } catch (Exception ex) { + ex.printStackTrace(); + } + + } + + private Message createResponseMessage(PartnerRoleMessageExchange partnerRoleMessageExchange, + Operation operation, + Element invocationResult) { + Document dom = DOMUtils.newDocument(); + + String operationName = operation.getName(); + Part bpelOperationOutputPart = + (Part)((WSDLInterface)operation.getInterface()).getPortType().getOperation(operationName, null, null) + .getOutput().getMessage().getParts().values().iterator().next(); + + Element contentMessage = dom.createElement("message"); + Element contentPart = dom.createElement(bpelOperationOutputPart.getName()); + + contentPart.appendChild(dom.importNode(invocationResult, true)); + contentMessage.appendChild(contentPart); + dom.appendChild(contentMessage); + + if(__log.isDebugEnabled()) { + __log.debug("Creating result message:"); + __log.debug(">>>" + DOMUtils.domToString(dom.getDocumentElement())); + } + + QName id = partnerRoleMessageExchange.getOperation().getOutput().getMessage().getQName(); + Message response = partnerRoleMessageExchange.createMessage(id); + response.setMessage(dom.getDocumentElement()); + + return response; + } + +} diff --git a/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/ODEInitializationException.java b/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/ODEInitializationException.java new file mode 100644 index 0000000000..2fa91e4e86 --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/ODEInitializationException.java @@ -0,0 +1,41 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.implementation.bpel.ode; + +/** + * Thrown when ODE failed to initialize one if its needed resources. + * + * @version $Rev$ $Date$ + */ +public class ODEInitializationException extends RuntimeException { + private static final long serialVersionUID = -2869674556330744215L; + + public ODEInitializationException(Throwable cause) { + super(cause); + } + + public ODEInitializationException(String message) { + super(message); + } + + public ODEInitializationException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/ODEMessageExchangeContext.java b/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/ODEMessageExchangeContext.java new file mode 100644 index 0000000000..1ec82390cf --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/ODEMessageExchangeContext.java @@ -0,0 +1,57 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.implementation.bpel.ode; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.ode.bpel.iapi.BpelEngineException; +import org.apache.ode.bpel.iapi.ContextException; +import org.apache.ode.bpel.iapi.MessageExchangeContext; +import org.apache.ode.bpel.iapi.MyRoleMessageExchange; +import org.apache.ode.bpel.iapi.PartnerRoleMessageExchange; + +/** + * Message Exchange Context information + * + * @version $Rev$ $Date$ + */ +public class ODEMessageExchangeContext implements MessageExchangeContext { + private static final Log __log = LogFactory.getLog(ODEMessageExchangeContext.class); + + private EmbeddedODEServer _server; + + public ODEMessageExchangeContext(EmbeddedODEServer _server) { + this._server = _server; + } + + public void invokePartner(PartnerRoleMessageExchange partnerRoleMessageExchange) throws ContextException { + if (__log.isDebugEnabled()) { + __log.debug("Invoking a partner operation: " + partnerRoleMessageExchange.getOperationName()); + } + + ODEExternalService scaService = new ODEExternalService(_server); + scaService.invoke(partnerRoleMessageExchange); + } + + public void onAsyncReply(MyRoleMessageExchange myRoleMessageExchange) throws BpelEngineException { + if (__log.isDebugEnabled()) { + __log.debug("Processing an async reply from service " + myRoleMessageExchange.getServiceName()); + } + } + } diff --git a/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/ODEShutdownException.java b/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/ODEShutdownException.java new file mode 100644 index 0000000000..a928379ba9 --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/ODEShutdownException.java @@ -0,0 +1,41 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.implementation.bpel.ode; + +/** + * Thrown when ODE failed to shutdown. + * + * @version $Rev$ $Date$ + */ +public class ODEShutdownException extends RuntimeException { + private static final long serialVersionUID = -2869674556330744215L; + + public ODEShutdownException(Throwable cause) { + super(cause); + } + + public ODEShutdownException(String message) { + super(message); + } + + public ODEShutdownException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/TuscanyEPR.java b/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/TuscanyEPR.java new file mode 100644 index 0000000000..328403e626 --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/TuscanyEPR.java @@ -0,0 +1,54 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.implementation.bpel.ode; + +import javax.xml.namespace.QName; + +import org.apache.ode.bpel.iapi.Endpoint; +import org.apache.ode.bpel.iapi.EndpointReference; +import org.apache.ode.utils.DOMUtils; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * This should hold something that makes sense for Tuscany so that the + * process has an address that makes sense from the outside world perspective + * + * @version $Rev$ $Date$ + */ +public class TuscanyEPR implements EndpointReference { + private final QName prcessName; + private final Endpoint endpoint; + private final Document doc = DOMUtils.newDocument(); + + public TuscanyEPR(QName processName, Endpoint endpoint) { + this.prcessName = processName; + this.endpoint = endpoint; + + Element serviceref = doc.createElementNS(EndpointReference.SERVICE_REF_QNAME.getNamespaceURI(), + EndpointReference.SERVICE_REF_QNAME.getLocalPart()); + serviceref.setNodeValue(endpoint.serviceName + ":" + endpoint.portName); + doc.appendChild(serviceref); + } + + public Document toXML() { + return doc; + } +} diff --git a/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/TuscanyPRC.java b/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/TuscanyPRC.java new file mode 100644 index 0000000000..8f8f608217 --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/TuscanyPRC.java @@ -0,0 +1,71 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.implementation.bpel.ode; + +import javax.wsdl.PortType; +import javax.xml.namespace.QName; + +import org.apache.ode.bpel.iapi.Endpoint; +import org.apache.ode.bpel.iapi.EndpointReference; +import org.apache.ode.bpel.iapi.PartnerRoleChannel; +import org.apache.ode.utils.DOMUtils; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * Tuscany Partner Role Channel for ODE Integration + * + * @version $Rev$ $Date$ + */ +public class TuscanyPRC implements PartnerRoleChannel { + private final QName processName; + private final QName pid; + private final PortType portType; + private final Endpoint endpoint; + + public TuscanyPRC(QName processName, QName pid, PortType portType, Endpoint endpoint){ + this.processName = processName; + this.pid = pid; + this.portType = portType; + this.endpoint = endpoint; + } + + public QName getProcessName() { + return this.processName; + } + + public void close() { + + } + + public EndpointReference getInitialEndpointReference() { + final Document doc = DOMUtils.newDocument(); + Element serviceref = doc.createElementNS(EndpointReference.SERVICE_REF_QNAME.getNamespaceURI(), + EndpointReference.SERVICE_REF_QNAME.getLocalPart()); + doc.appendChild(serviceref); + + return new EndpointReference() { + public Document toXML() { + return doc; + } + }; + } + +} diff --git a/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/TuscanyProcessConfImpl.java b/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/TuscanyProcessConfImpl.java new file mode 100644 index 0000000000..c626e6a8e3 --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/TuscanyProcessConfImpl.java @@ -0,0 +1,433 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.implementation.bpel.ode; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.wsdl.Definition; +import javax.xml.namespace.QName; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.ode.bpel.compiler.BpelC; +import org.apache.ode.bpel.evt.BpelEvent.TYPE; +import org.apache.ode.bpel.iapi.Endpoint; +import org.apache.ode.bpel.iapi.ProcessConf; +import org.apache.ode.bpel.iapi.ProcessState; +import org.apache.tuscany.sca.assembly.Reference; +import org.apache.tuscany.sca.assembly.Service; +import org.apache.tuscany.sca.implementation.bpel.BPELImplementation; +import org.apache.tuscany.sca.interfacedef.wsdl.WSDLInterface; +import org.w3c.dom.Element; +import org.w3c.dom.Node; + +/** + * A Tuscany implementation of the ODE Process Conf + * + * @version $Rev$ $Date$ + */ +public class TuscanyProcessConfImpl implements ProcessConf { + private final Log __log = LogFactory.getLog(getClass()); + + private BPELImplementation implementation; + private Map invokeEndpoints = null; + private Map provideEndpoints = null; + private Map properties = null; + private ProcessState processState; + private Date deployDate; + + private final String TUSCANY_NAMESPACE = "http://tuscany.apache.org"; + + /** + * Constructor for the ProcessConf implementation + * @param theImplementation the BPEL implementation for which this is the ProcessConf + */ + public TuscanyProcessConfImpl( BPELImplementation theImplementation ) { + //System.out.println("New TuscanyProcessConfImpl..."); + this.implementation = theImplementation; + + processState = ProcessState.ACTIVE; + deployDate = new Date(); + + // Compile the process + compile( getBPELFile() ); + } // end TuscanyProcessConfImpl constructor + + /** + * Returns the URI for the directory containing the BPEL process + */ + public URI getBaseURI() { + //System.out.println("getBaseURI called"); + File theDir = getDirectory(); + return theDir.toURI(); + } + + /** + * Returns a String containing the (local) name of the file containing the BPEL process + */ + public String getBpelDocument() { + //System.out.println("getBPELDocument called"); + try { + File processFile = new File(URI.create(implementation.getProcessDefinition().getLocation())); + return getRelativePath( getDirectory(), processFile); + } catch (Exception e) { + if(__log.isWarnEnabled()) { + __log.warn("Unable to resolve relative path of BPEL process" + implementation.getProcessDefinition().getLocation(), e ); + } + return null; + } // end try + } // end getBpelDocument + + /** + * Returns an InputStream containing the Compiled BPEL Process (CBP) + */ + public InputStream getCBPInputStream() { + //System.out.println("getCBPInputStream called"); + // Find the CBP file - it has the same name as the BPEL process and lives in the same + // directory as the process file + String cbpFileName = null; + try { + String fileName = getRelativePath( getDirectory(), getBPELFile() ); + cbpFileName = fileName.substring(0, fileName.lastIndexOf(".")) + ".cbp"; + } catch (Exception e ) { + // IOException trying to fetch the BPEL file name + if(__log.isDebugEnabled()) { + __log.debug("Unable to calculate the file name for BPEL process: " + + implementation.getProcessDefinition().getName(), e); + return null; + } // end if + } // end try + File cbpFile = new File( getDirectory(), cbpFileName ); + if( cbpFile.exists() ) { + // Create an InputStream from the cbp file... + try { + return new FileInputStream( cbpFile ); + } catch ( Exception e ) { + if(__log.isDebugEnabled()) { + __log.debug("Unable to open the cbp file for BPEL process: " + + implementation.getProcessDefinition().getName(), e); + } + } // end try + } else { + // Cannot find the cbp file + if(__log.isWarnEnabled()){ + __log.warn("Cannot find the cbp file for process: " + + implementation.getProcessDefinition().getName()); + } + } // end if + // TODO - need better exception handling if we can't open the cbp file for any reason + return null; + } // end getCBPInputStream + + /** + * Return the WSDL Definition for a given PortType + * @param portTypeName - the QName of the PortType + */ + public Definition getDefinitionForPortType( QName portTypeName ) { + //System.out.println("getDefinitionForPortType called for portType: " + portTypeName ); + // Find the named PortType in the list of WSDL interfaces associated with this BPEL Process + Collection theInterfaces = implementation.getProcessDefinition().getInterfaces(); + for( WSDLInterface wsdlInterface : theInterfaces ) { + if ( wsdlInterface.getPortType().getQName().equals( portTypeName ) ) { + // Extract and return the Definition associated with the WSDLDefinition... + return wsdlInterface.getWsdlDefinition().getDefinition(); + } // end if + } // end for + return null; + } // end getDefinitionforPortType + + /** + * Returns a WSDL Definition for a given Service QName + * + * 22/05/2008 - it is very unclear what this service QName is really meant to be. + * From the handling of the deploy.xml file by the current ODE code, it seems that the key link + * is from the Service QName to the PartnerLink name (done in the deploy.xml file). + * + * The curious part about this is that the QName for the service is ONLY defined in deploy.xml file + * and does not appear to relate to anything else, except for the QName of the PartnerLink + * + * The PartnerLink name is the same as the name of the SCA service (or reference) which in turn points + * at the PartnerLinkType which in turn points at an (WSDL) interface definition. + */ + public Definition getDefinitionForService(QName serviceQName ) { + //System.out.println("getDefinitionForService called for Service: " + serviceQName ); + if(__log.isDebugEnabled()){ + __log.debug("getDefinitionforService called for service: " + serviceQName ); + } + // TODO Auto-generated method stub + return null; + } + + /** + * Returns the date of deployment of the process + * - for SCA returns the date at which this object was created + */ + public Date getDeployDate() { + //System.out.println("getDeployDate called"); + return deployDate; + } + + /** + * Returns userid of deployer + * - always "SCA Tuscany" for Tuscany... + */ + public String getDeployer() { + //System.out.println("getDeployer called"); + return "SCA Tuscany"; + } // end getDeployer + + /** + * Returns a list of the files in the directory containing the BPEL Process + */ + public List getFiles() { + //System.out.println("getFiles called"); + File theDir = getDirectory(); + List theFiles = Arrays.asList( (File[]) theDir.listFiles() ); + // TODO recurse into subdirectories + return theFiles; + } // end getFiles + + /** + * Returns a Map containing all the "invoke endpoints" - for which read "SCA references" + * The map is keyed by partnerLink name and holds Endpoint objects + * + * TODO deal with service callbacks on bidirectional services + */ + public Map getInvokeEndpoints() { + //System.out.println("getInvokeEndpoints called"); + if( invokeEndpoints == null ) { + invokeEndpoints = new HashMap(); + // Get a collection of the references + List theReferences = implementation.getReferences(); + // Create an endpoint for each reference, using the reference name as the "service" + // name, combined with http://tuscany.apache.org to make a QName + for( Reference reference : theReferences ) { + invokeEndpoints.put( reference.getName(), + new Endpoint( new QName( TUSCANY_NAMESPACE, reference.getName() ), "ReferencePort")); + } // end for + } // end if + return invokeEndpoints; + } // end getInvokeEndpoints + + /** + * Returns the name of the directory containing the BPEL files + */ + public String getPackage() { + //System.out.println("getPackage called"); + File theDir = getDirectory(); + return theDir.getName(); + } // end getPackage + + /** + * Return the BPEL Process ID - which is the Process QName appended "-versionnumber" + */ + public QName getProcessId() { + //System.out.println("getProcessId called"); + QName processType = getType(); + QName processID = new QName( processType.getNamespaceURI(), + processType.getLocalPart() + "-" + getVersion() ); + return processID; + } // end getProcessID + + /** + * TODO - What are properties? + */ + public Map getProperties() { + //System.out.println("getProperties called"); + if ( properties == null ) { + properties = new HashMap(); + } // end if + return properties; + } // end getProperties + + /** + * Returns a Map containing all the "provide endpoints" - for which read "SCA services" + * The map is keyed by partnerLink name and holds Endpoint objects + * + * TODO deal with reference callbacks on bidirectional references + */ + public Map getProvideEndpoints() { + //System.out.println("getProvideEndpoints called"); + if( provideEndpoints == null ) { + provideEndpoints = new HashMap(); + // Get a collection of the references + List theServices = implementation.getServices(); + // Create an endpoint for each reference, using the reference name as the "service" + // name, combined with http://tuscany.apache.org to make a QName + for( Service service : theServices ) { + provideEndpoints.put( service.getName(), + new Endpoint( new QName( TUSCANY_NAMESPACE, service.getName() ), "ServicePort")); + } // end for + } // end if + return provideEndpoints; + } // end getProvideEndpoints + + /** + * Return the process state + */ + public ProcessState getState() { + //System.out.println("getState called"); + return processState; + } + + /** + * Returns the QName of the BPEL process + */ + public QName getType() { + //System.out.println("getType called"); + return implementation.getProcess(); + } + + /** + * Gets the process Version number + * - current code does not have versions for BPEL processes and always returns "1" + */ + public long getVersion() { + //System.out.println("getVersion called"); + return 1; + } + + /** + * Returns true if the supplied event type is enabled for any of the scopes in the provided + * List. These events are "ODE Execution Events" and there is a definition of them on this + * page: http://ode.apache.org/user-guide.html#UserGuide-ProcessDeployment + * + * For the present Tuscany does not support manipulating the event enablement and always + * returns that the event is not enabled + * @param scopeNames - list of BPEL process Scope names + * @param type - the event type + */ + public boolean isEventEnabled(List scopeNames, TYPE type) { + //System.out.println("isEventEnabled called with scopeNames: " + + // scopeNames + " and type: " + type ); + return false; + } // end isEventEnabled + + /** + * Returns whether the process is persisted in the store + * + * Returns false for SCA configuration + * - returning true causes problems in communicating with the BPEL process + */ + public boolean isTransient() { + //System.out.println("isTransient called"); + return false; + } // end isTransient + + /** + * Compiles a BPEL process file into a compiled form CBP file in the main directory + * (ie same directory as the BPEL process file) + * @param bpelFile - the BPEL process file + */ + private void compile( File bpelFile ) { + // Set up the compiler + BpelC compiler = BpelC.newBpelCompiler(); + // Provide a null set of initial properties for now + Map processProps = new HashMap(); + Map compileProps = new HashMap(); + compileProps.put( BpelC.PROCESS_CUSTOM_PROPERTIES, processProps ); + compiler.setCompileProperties( compileProps ); + compiler.setBaseDirectory( getDirectory() ); + + // Run the compiler and generate the CBP file into the given directory + try { + compiler.compile( bpelFile ); + } catch (IOException e) { + if(__log.isDebugEnabled()) { + __log.debug("Compile error in " + bpelFile, e); + } + // TODO - need better exception handling here + } // end try + } // end compile + + /** + * Gets the directory containing the BPEL process + * @return + */ + private File getDirectory() { + File theDir = getBPELFile().getParentFile(); + return theDir; + } // end getDirectory + + /** + * Gets the File containing the BPEL process definition + * @return - the File object containing the BPEL process + */ + private File getBPELFile() { + try { + File theProcess = new File(URI.create(implementation.getProcessDefinition().getLocation())); + return theProcess; + } catch( Exception e ) { + if(__log.isDebugEnabled()) { + __log.debug("Exception converting BPEL file URL to an URI: " + e ); + } + } // end try + return null; + } // end getBPELFile + + /** + * Gets the relative path of a file against a directory in its hierarchy + * @param base - the base directory + * @param path - the file + * @return + * @throws IOException + */ + private String getRelativePath(File base, File path) throws IOException { + String basePath = base.getCanonicalPath(); + String filePath = path.getCanonicalPath(); + if (!filePath.startsWith(basePath)) { + throw new IOException("Invalid relative path: base=" + base + " path=" + path); + } + String relative = filePath.substring(basePath.length()); + if (relative.startsWith(File.separator)) { + relative = relative.substring(1); + } + return relative; + } // end getRelativePath + + //----------------------------------------------------------------------------- + // other public APIs which ProcessConfImpl displays which are not in ProcessConf interface + + public List getMexInterceptors(QName processId) { + System.out.println("getMexInterceptors for processID: " + processId ); + return null; + } + + public void setTransient(boolean t) { + System.out.println("setTransient called with boolean: " + t ); + } + + public List getExtensionElement(QName arg0) { + return Collections.emptyList(); + } + // end of other public APIs + //----------------------------------------------------------------------------- + +} // end class TuscanyProcessConfImpl diff --git a/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/provider/BPELImplementationProvider.java b/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/provider/BPELImplementationProvider.java new file mode 100644 index 0000000000..c644b6a965 --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/provider/BPELImplementationProvider.java @@ -0,0 +1,145 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.implementation.bpel.ode.provider; + +import java.io.File; +import java.net.URI; + +import javax.transaction.TransactionManager; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.tuscany.sca.assembly.Reference; +import org.apache.tuscany.sca.assembly.Service; +import org.apache.tuscany.sca.databinding.xml.DOMDataBinding; +import org.apache.tuscany.sca.implementation.bpel.BPELImplementation; +import org.apache.tuscany.sca.implementation.bpel.ode.EmbeddedODEServer; +import org.apache.tuscany.sca.implementation.bpel.ode.ODEDeployment; +import org.apache.tuscany.sca.implementation.bpel.ode.ODEInitializationException; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.provider.ImplementationProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; + +/** + * BPEL Implementation provider + * + * @version $Rev$ $Date$ + */ +public class BPELImplementationProvider implements ImplementationProvider { + private final Log __log = LogFactory.getLog(getClass()); + + private RuntimeComponent component; + private BPELImplementation implementation; + + private EmbeddedODEServer odeServer; + private TransactionManager txMgr; + + /** + * Constructs a new BPEL Implementation. + */ + public BPELImplementationProvider(RuntimeComponent component, + BPELImplementation implementation, + EmbeddedODEServer odeServer, + TransactionManager txMgr) { + this.component = component; + this.implementation = implementation; + this.odeServer = odeServer; + this.txMgr = txMgr; + + // Configure the service and reference interfaces to use a DOM databinding + // as it's what ODE expects + for (Service service: implementation.getServices()) { + service.getInterfaceContract().getInterface().resetDataBinding(DOMDataBinding.NAME); + } + for (Reference reference: implementation.getReferences()) { + reference.getInterfaceContract().getInterface().resetDataBinding(DOMDataBinding.NAME); + } + + } + + public Invoker createInvoker(RuntimeComponentService service, Operation operation) { + BPELInvoker invoker = new BPELInvoker(component, service, operation, odeServer, txMgr); + return invoker; + } + + public boolean supportsOneWayInvocation() { + return false; + } + + public void start() { + if(__log.isInfoEnabled()) { + __log.info("Starting " + component.getName()); + } + + try { + if (!odeServer.isInitialized()) { + // start ode server + odeServer.init(); + } + + URI deployURI = URI.create(this.implementation.getProcessDefinition().getLocation()); + + File deploymentDir = new File(deployURI).getParentFile(); + + if(__log.isInfoEnabled()) { + __log.info(">>> Deploying : " + deploymentDir.toString()); + } + + // deploy the process + if (odeServer.isInitialized()) { + try { + //txMgr.begin(); + odeServer.registerTuscanyRuntimeComponent(implementation.getProcess(), component); + // Replaced by Mike Edwards 23/05/2008 + //odeServer.deploy(new ODEDeployment(deploymentDir)); + odeServer.deploy(new ODEDeployment(deploymentDir), implementation ); + //txMgr.commit(); + } catch (Exception e) { + e.printStackTrace(); + //txMgr.rollback(); + } + } + + } catch (ODEInitializationException inite) { + throw new RuntimeException("BPEL Component Type Implementation : Error initializing embedded ODE server " + inite.getMessage(), inite); + } catch(Exception e) { + throw new RuntimeException("BPEl Component Type Implementation initialization failure : " + e.getMessage(), e); + } + } + + public void stop() { + if(__log.isInfoEnabled()) { + __log.info("Stopping " + component.getName()); + } + + if (odeServer.isInitialized()) { + // start ode server + odeServer.stop(); + } + + txMgr = null; + + if(__log.isInfoEnabled()) { + __log.info("Stopped !!!"); + } + } + +} diff --git a/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/provider/BPELImplementationProviderFactory.java b/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/provider/BPELImplementationProviderFactory.java new file mode 100644 index 0000000000..ed327e237b --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/provider/BPELImplementationProviderFactory.java @@ -0,0 +1,69 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.implementation.bpel.ode.provider; + +import javax.transaction.TransactionManager; + +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.implementation.bpel.BPELImplementation; +import org.apache.tuscany.sca.implementation.bpel.ode.EmbeddedODEServer; +import org.apache.tuscany.sca.implementation.bpel.ode.GeronimoTxFactory; +import org.apache.tuscany.sca.provider.ImplementationProvider; +import org.apache.tuscany.sca.provider.ImplementationProviderFactory; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.oasisopen.sca.annotation.Destroy; + +/** + * BPEL Implementation provider factory + * + * We use the provider factory to instantiate a ODE server that is going to be injected in all BPEL components + * + * @version $Rev$ $Date$ + */ +public class BPELImplementationProviderFactory implements ImplementationProviderFactory { + + private EmbeddedODEServer odeServer; + private TransactionManager txMgr; + + /** + * Default constructor receiving an extension point + * @param extensionPoints + */ + public BPELImplementationProviderFactory(ExtensionPointRegistry extensionPoints) { + GeronimoTxFactory txFactory = new GeronimoTxFactory(); + txMgr = txFactory.getTransactionManager(); + this.odeServer = new EmbeddedODEServer(txMgr); + } + + /** + * Creates a new BPEL Implementation and inject the EmbeddedODEServer + */ + public ImplementationProvider createImplementationProvider(RuntimeComponent component, BPELImplementation implementation) { + return new BPELImplementationProvider(component, implementation, odeServer, txMgr); + } + + public Class getModelType() { + return BPELImplementation.class; + } + + @Destroy + public void destroy() { + txMgr = null; + } +} diff --git a/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/provider/BPELInvoker.java b/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/provider/BPELInvoker.java new file mode 100644 index 0000000000..f301082d59 --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel-ode/src/main/java/org/apache/tuscany/sca/implementation/bpel/ode/provider/BPELInvoker.java @@ -0,0 +1,251 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.implementation.bpel.ode.provider; + +import java.lang.reflect.InvocationTargetException; +import java.util.concurrent.Future; + +import javax.transaction.SystemException; +import javax.transaction.TransactionManager; +import javax.wsdl.Part; +import javax.xml.namespace.QName; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.ode.bpel.iapi.MyRoleMessageExchange; +import org.apache.ode.bpel.iapi.MessageExchange.Status; +import org.apache.ode.utils.DOMUtils; +import org.apache.ode.utils.GUID; +import org.apache.tuscany.sca.implementation.bpel.ode.EmbeddedODEServer; +import org.apache.tuscany.sca.interfacedef.Interface; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.interfacedef.wsdl.WSDLInterface; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * Implements a target invoker for BPEL component implementations. + * + * The target invoker is responsible for dispatching invocations to the particular + * component implementation logic. In this example we are simply delegating the + * CRUD operation invocations to the corresponding methods on our fake + * resource manager. + * + * @version $Rev$ $Date$ + */ +public class BPELInvoker implements Invoker { + protected final Log __log = LogFactory.getLog(getClass()); + + private EmbeddedODEServer odeServer; + private TransactionManager txMgr; + + private RuntimeComponent component; + private RuntimeComponentService service; + private Operation operation; + private QName bpelServiceName; + private String bpelOperationName; + private Part bpelOperationInputPart; + private Part bpelOperationOutputPart; + + public BPELInvoker(RuntimeComponent component, RuntimeComponentService service, Operation operation, EmbeddedODEServer odeServer, TransactionManager txMgr) { + this.component = component; + this.service = service; + this.operation = operation; + this.bpelOperationName = operation.getName(); + this.odeServer = odeServer; + this.txMgr = txMgr; + + initializeInvocation(); + } + + + private void initializeInvocation() { + + if(true){ + __log.debug("Initializing BPELInvoker"); + } + Interface interfaze = operation.getInterface(); + if(interfaze instanceof WSDLInterface){ + WSDLInterface wsdlInterface = null; + wsdlInterface = (WSDLInterface) interfaze; + + // The following commented out code is bogus and is replaced by what follows - Mike Edwards + // Service serviceDefinition = (Service) wsdlInterface.getWsdlDefinition().getDefinition().getAllServices().values().iterator().next(); + // bpelServiceName = serviceDefinition.getQName(); + // + // Fetch the service name from the service object + bpelServiceName = new QName( "http://tuscany.apache.org", service.getName() ); + //System.out.println("Actual service QName: " + bpelServiceName ); + + bpelOperationInputPart = (Part) wsdlInterface.getPortType().getOperation(bpelOperationName,null,null).getInput().getMessage().getParts().values().iterator().next(); + bpelOperationOutputPart = (Part) wsdlInterface.getPortType().getOperation(bpelOperationName,null,null).getOutput().getMessage().getParts().values().iterator().next(); + } + } + + public Message invoke(Message msg) { + try { + Object[] args = msg.getBody(); + Object resp = doTheWork(args); + msg.setBody(resp); + } catch (InvocationTargetException e) { + msg.setFaultBody(e.getCause()); + } + return msg; + } + + public Object doTheWork(Object[] args) throws InvocationTargetException { + Element response = null; + + if(! (operation.getInterface() instanceof WSDLInterface)) { + throw new InvocationTargetException(null,"Unsupported service contract"); + } + + if(true) { + System.out.println("Invoking bpel component : " + bpelServiceName + "#" + bpelOperationName); + } + + org.apache.ode.bpel.iapi.MyRoleMessageExchange mex = null; + Future onhold = null; + + //Process the BPEL process invocation + try { + txMgr.begin(); + mex = odeServer.getBpelServer().getEngine().createMessageExchange(new GUID().toString(), + bpelServiceName, + bpelOperationName); + + onhold = mex.invoke(createInvocationMessage(mex, args)); + + txMgr.commit(); + } catch (Exception e) { + try { + txMgr.rollback(); + } catch (SystemException se) { + + } + throw new InvocationTargetException(e, "Error invoking BPEL process : " + e.getMessage()); + } + + + // Waiting until the reply is ready in case the engine needs to continue in a different thread + if (onhold != null) { + try { + onhold.get(); + } catch (Exception e) { + throw new InvocationTargetException(e,"Error invoking BPEL process : " + e.getMessage()); + } + } + + //Process the BPEL invocation response + try { + txMgr.begin(); + // Reloading the mex in the current transaction, otherwise we can't + // be sure we have the "freshest" one. + mex = (MyRoleMessageExchange)odeServer.getBpelServer().getEngine().getMessageExchange(mex.getMessageExchangeId()); + + if(true) { + Status status = mex.getStatus(); + Element invocationResponse = mex.getResponse().getMessage(); + + System.out.println(">>>Invocation status:" + status.name()); + System.out.println(">>>Response:\n" + DOMUtils.domToString(invocationResponse)); + System.out.println(">>>Response:\n" + DOMUtils.domToString(invocationResponse)); + } + //process the method invocation result + response = processResponse(mex.getResponse().getMessage()); + + txMgr.commit(); + // end of transaction two + } catch (Exception e) { + try { + txMgr.rollback(); + } catch (SystemException se) { + + } + throw new InvocationTargetException(e, "Error retrieving BPEL process invocation status : " + e.getMessage()); + } + + + return response; + } + + /** + * Create BPEL Invocation message + * + * BPEL invocation message like : + * + * + * Hello + * + * + * @param args + * @return + */ + private org.apache.ode.bpel.iapi.Message createInvocationMessage(org.apache.ode.bpel.iapi.MyRoleMessageExchange mex, Object[] args) { + Document dom = DOMUtils.newDocument(); + + Element contentMessage = dom.createElement("message"); + Element contentPart = dom.createElement(bpelOperationInputPart.getName()); + Element payload = null; + + //TUSCANY-2321 - Properly handling Document or Element types + if(args[0] instanceof Document) { + payload = (Element) ((Document) args[0]).getFirstChild(); + } else { + payload = (Element) args[0]; + } + + contentPart.appendChild(dom.importNode(payload, true)); + contentMessage.appendChild(contentPart); + dom.appendChild(contentMessage); + + if(true) { + System.out.println("Creating invocation message:"); + System.out.println(">> args.....: " + DOMUtils.domToString(payload)); + System.out.println(">> message..:" + DOMUtils.domToString(dom.getDocumentElement())); + } + + org.apache.ode.bpel.iapi.Message request = mex.createMessage(new QName("", "")); + request.setMessage(dom.getDocumentElement()); + + return request; + } + + /** + * Process BPEL response + * + * + * + * World + * + * + * + * @param response + * @return + */ + private Element processResponse(Element response) { + // return (Element) DOMUtils.findChildByName(response, new QName("",bpelOperationOutputPart.getName())).getFirstChild(); + return (Element) DOMUtils.findChildByName(response, new QName("",bpelOperationOutputPart.getName())); + } +} diff --git a/java/sca/contrib/modules/implementation-bpel-ode/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.ImplementationProviderFactory b/java/sca/contrib/modules/implementation-bpel-ode/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.ImplementationProviderFactory new file mode 100644 index 0000000000..3bce8aa9ab --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel-ode/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.ImplementationProviderFactory @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for the implementation extension +org.apache.tuscany.sca.implementation.bpel.ode.provider.BPELImplementationProviderFactory;model=org.apache.tuscany.sca.implementation.bpel.BPELImplementation diff --git a/java/sca/contrib/modules/implementation-bpel-ode/src/test/java/org/apache/tuscany/sca/implementation/bpel/ode/EmbeddedODEServerTestCase.java b/java/sca/contrib/modules/implementation-bpel-ode/src/test/java/org/apache/tuscany/sca/implementation/bpel/ode/EmbeddedODEServerTestCase.java new file mode 100644 index 0000000000..0f59990377 --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel-ode/src/test/java/org/apache/tuscany/sca/implementation/bpel/ode/EmbeddedODEServerTestCase.java @@ -0,0 +1,124 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.implementation.bpel.ode; + +import javax.transaction.TransactionManager; + +import junit.framework.TestCase; + +/** + * Test to Deploy and Invoke a HelloWorld BPEL process using EmbeddedODEServer + * + * Major changes introduced to this testcase on 27/05/2008 associated with changes in the + * implementation of EmbeddedODEServer which remove the need for the ODE deploy.xml file - + * instead a Tuscany BPELImplementation object is passed to the EmbeddedODEServer and this is + * introspected to get all the necessary information about the BPEL process + * + * @version $Rev$ $Date$ + */ +public class EmbeddedODEServerTestCase extends TestCase { + + private EmbeddedODEServer odeServer; + + private TransactionManager txMgr; + + @Override + protected void setUp() throws Exception { + // Set up the ODE BPEL server... + GeronimoTxFactory txFactory = new GeronimoTxFactory(); + txMgr = txFactory.getTransactionManager(); + + this.odeServer = new EmbeddedODEServer(txMgr); + odeServer.init(); + + } // end setUp + + @Override + protected void tearDown() throws Exception { + odeServer.stop(); + } + + public void testProcessInvocation() throws Exception { + if (!odeServer.isInitialized()) { + fail("Server did not start !"); + } +// TODO - write effective testcase - made problematic by the need to supply a resolved +// BPELImplementation +/* + URL deployURL = getClass().getClassLoader().getResource("helloworld/deploy.xml"); + File deploymentDir = new File(deployURL.toURI().getPath()).getParentFile(); + System.out.println("Deploying : " + deploymentDir.toString()); + System.out.println(deploymentDir); + + if (odeServer.isInitialized()) { + try { + txMgr.begin(); + odeServer.deploy(new ODEDeployment(deploymentDir), implementation); + txMgr.commit(); + } catch (Exception e) { + e.printStackTrace(); + txMgr.rollback(); + } + + // transaction one + MyRoleMessageExchange mex = null; + Future onhold = null; + try { + // invoke the process + txMgr.begin(); + mex = odeServer.getBpelServer().getEngine().createMessageExchange(new GUID().toString(), + new QName("http://tuscany.apache.org/implementation/bpel/example/helloworld.wsdl", "HelloService"), "hello"); + + Message request = mex.createMessage(new QName("", "")); + request.setMessage(DOMUtils.stringToDOM("Hello")); + onhold = mex.invoke(request); + txMgr.commit(); + } catch (Exception e) { + e.printStackTrace(); + txMgr.rollback(); + } + // - end of transaction one + + // Waiting until the reply is ready in case the engine needs to continue in a different thread + if (onhold != null) + onhold.get(); + + // transaction two + try { + txMgr.begin(); + // Reloading the mex in the current transaction, otherwise we can't be sure we have + // the "freshest" one. + mex = (MyRoleMessageExchange) odeServer.getBpelServer().getEngine().getMessageExchange(mex.getMessageExchangeId()); + + Status status = mex.getStatus(); + System.out.println("Status: " + status.name()); + Element response = mex.getResponse().getMessage(); + System.out.println("Response: " + DOMUtils.domToString(response)); + txMgr.commit(); + // end of transaction two + } catch (Exception e) { + e.printStackTrace(); + txMgr.rollback(); + } // end try + } // end if +*/ + } // end testProcessInvocation + +} diff --git a/java/sca/contrib/modules/implementation-bpel-ode/src/test/resources/helloworld/deploy.xml b/java/sca/contrib/modules/implementation-bpel-ode/src/test/resources/helloworld/deploy.xml new file mode 100644 index 0000000000..571aa37d58 --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel-ode/src/test/resources/helloworld/deploy.xml @@ -0,0 +1,30 @@ + + + + + + true + + + + + diff --git a/java/sca/contrib/modules/implementation-bpel-ode/src/test/resources/helloworld/greetings.wsdl b/java/sca/contrib/modules/implementation-bpel-ode/src/test/resources/helloworld/greetings.wsdl new file mode 100644 index 0000000000..bcd3ea6afa --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel-ode/src/test/resources/helloworld/greetings.wsdl @@ -0,0 +1,87 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/java/sca/contrib/modules/implementation-bpel-ode/src/test/resources/helloworld/helloworld.bpel b/java/sca/contrib/modules/implementation-bpel-ode/src/test/resources/helloworld/helloworld.bpel new file mode 100644 index 0000000000..8cf91adc2c --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel-ode/src/test/resources/helloworld/helloworld.bpel @@ -0,0 +1,66 @@ + + + + + + + + + + + + + + + + + + + + + + + + concat($tmpVar,' World') + + + + + + diff --git a/java/sca/contrib/modules/implementation-bpel-ode/src/test/resources/helloworld/helloworld.wsdl b/java/sca/contrib/modules/implementation-bpel-ode/src/test/resources/helloworld/helloworld.wsdl new file mode 100644 index 0000000000..1d71727b2d --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel-ode/src/test/resources/helloworld/helloworld.wsdl @@ -0,0 +1,82 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/java/sca/contrib/modules/implementation-bpel-ode/src/test/resources/log4j.properties b/java/sca/contrib/modules/implementation-bpel-ode/src/test/resources/log4j.properties new file mode 100644 index 0000000000..82b3c09723 --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel-ode/src/test/resources/log4j.properties @@ -0,0 +1,36 @@ +# +# 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. +# + +# Set root logger level to WARN and its only appender to CONSOLE +log4j.rootLogger=OFF, CONSOLE + +# log4j properties to work with commandline tools. +log4j.category.org.mortbay=OFF +log4j.category.org.hibernate.type=OFF +log4j.category.org.objectweb=OFF +log4j.category.org.apache.ode.axis2=OFF +log4j.category.org.apache.ode.bpel.engine=OFF +log4j.category.org.apache.ode.daohib.bpel.CorrelatorDaoImpl=OFF +log4j.category.org.apache.ode.bpel.epr=OFF +log4j.category.org.apache.tuscany.sca.implementation.bpel=OFF +log4j.category.org.apache.tuscany.sca.implementation.bpel.ode=OFF +log4j.category.org.apache.tuscany.sca.implementation.bpel.ode.provider=OFF + +# Console appender +log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender +log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout +log4j.appender.CONSOLE.layout.ConversionPattern=[%p] - %C{1}.%M(%L) | %m%n diff --git a/java/sca/contrib/modules/implementation-bpel/LICENSE b/java/sca/contrib/modules/implementation-bpel/LICENSE new file mode 100644 index 0000000000..baba9ca048 --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel/LICENSE @@ -0,0 +1,251 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + +=============================================================================================================== + +Apache Tuscany SCA for Java Subcomponents +=========================================: + +The Tuscany SCA for Java release includes a number of subcomponents with +separate copyright notices and license terms. Your use of the source +code for the these subcomponents is subject to the terms and +conditions of the following licenses. + +================================================================================================================= + +This module implementation-script temporarily includes one file under the following BSD license: + + Copyright (c) 2006, Sun Microsystems, Inc. + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + - Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + - Neither the name of the Sun Microsystems, Inc. nor the names of + contributors may be used to endorse or promote products derived from this + software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND + CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED + WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH + DAMAGE. + +================================================================================================================= diff --git a/java/sca/contrib/modules/implementation-bpel/META-INF/MANIFEST.MF b/java/sca/contrib/modules/implementation-bpel/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..ba65f8632d --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel/META-INF/MANIFEST.MF @@ -0,0 +1,33 @@ +Manifest-Version: 1.0 +Export-Package: org.apache.tuscany.sca.implementation.bpel;uses:="org. + apache.tuscany.sca.assembly,org.apache.tuscany.sca.contribution.resol + ver,javax.xml.namespace";version="2.0.0" +Private-Package: org.apache.tuscany.sca.implementation.bpel.impl;versi + on="1.4",org.apache.tuscany.sca.implementation.bpel.xml;version="2.0.0" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA BPEL Implementation Extension +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397433843 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA BPEL Implementation Extension +Import-Package: javax.wsdl, + javax.wsdl.extensions, + javax.xml.namespace, + javax.xml.stream, + + org.apache.tuscany.sca.assembly;version="2.0.0", + org.apache.tuscany.sca.assembly.impl;version="2.0.0", + org.apache.tuscany.sca.contribution.processor;version="2.0.0", + org.apache.tuscany.sca.contribution.resolver;version="2.0.0", + org.apache.tuscany.sca.core;version="2.0.0", + org.apache.tuscany.sca.implementation.bpel;version="2.0.0", + org.apache.tuscany.sca.interfacedef;version="2.0.0", + org.apache.tuscany.sca.interfacedef.wsdl;version="2.0.0", + org.apache.tuscany.sca.monitor;version="2.0.0", + org.apache.tuscany.sca.policy;version="2.0.0" +Bundle-SymbolicName: org.apache.tuscany.sca.implementation.bpel +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/implementation-bpel/NOTICE b/java/sca/contrib/modules/implementation-bpel/NOTICE new file mode 100644 index 0000000000..61ea4111aa --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel/NOTICE @@ -0,0 +1,17 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + +Unless otherwise indicated, all distribution made available by the Apache Software Foundation +is provided to you under the terms and conditions of the Apache License Version 2.0 ("AL"). +A copy of the AL is provided with this distribution as the LICENSE file present in the +root directory, and is also available at http://www.apache.org/licenses/. + +This product also includes software under the BSD license +(see the LICENSE file contained in this distribution), with +the following copyright: + +Copyright (c) 2006, Sun Microsystems, Inc. +All rights reserved. diff --git a/java/sca/contrib/modules/implementation-bpel/pom.xml b/java/sca/contrib/modules/implementation-bpel/pom.xml new file mode 100644 index 0000000000..c0f92f1c1d --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel/pom.xml @@ -0,0 +1,82 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + tuscany-implementation-bpel + Apache Tuscany SCA BPEL Implementation Extension + + + + org.apache.tuscany.sca + tuscany-assembly + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-assembly-xml + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-interface + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-interface-wsdl + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-interface-java + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-interface-wsdl-xml + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-databinding + 2.0-SNAPSHOT + + + + junit + junit + 3.8.1 + test + + + + diff --git a/java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/BPELFactory.java b/java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/BPELFactory.java new file mode 100644 index 0000000000..9f8f9c0e9a --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/BPELFactory.java @@ -0,0 +1,42 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.implementation.bpel; + +/** + * A factory for the BPEL implementation model. + * + * @version $Rev$ $Date$ + */ +public interface BPELFactory { + + /** + * Creates a new BPEL implementation. + * + * @return + */ + BPELImplementation createBPELImplementation(); + + /** + * Creates a new BPEL Process Definition + * + * @return + */ + BPELProcessDefinition createBPELProcessDefinition(); +} diff --git a/java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/BPELImplementation.java b/java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/BPELImplementation.java new file mode 100644 index 0000000000..d54add5391 --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/BPELImplementation.java @@ -0,0 +1,91 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.implementation.bpel; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.assembly.ComponentType; +import org.apache.tuscany.sca.assembly.Implementation; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; + +/** + * The model representing the BPEL implementation in an SCA assembly model. + * + * @version $Rev$ $Date$ + */ +public interface BPELImplementation extends Implementation { + + /** + * Get the BPEL process Name + * + * @return + */ + QName getProcess(); + + /** + * Set the BPEL process Name + * + * @param processName process QName + */ + void setProcess(QName processName); + + /** + * Get the BPEL process definition + * + * @return + */ + BPELProcessDefinition getProcessDefinition(); + + /** + * Set the BPEL process definition + * + * @param processDefinition + */ + void setProcessDefinition(BPELProcessDefinition processDefinition); + + /** + * Returns the componentType for this implementation. + * + * @return + */ + public ComponentType getComponentType(); + + /** + * Sets the componentType for this implementation + * + * @param componentType the component type to set + */ + public void setComponentType(ComponentType componentType); + + /** + * Returns the model resolver that can be used to resolve WSDLs and XSDs + * referenced by the BPEL process. + * + * @return + */ + ModelResolver getModelResolver(); + + /** + * Sets the model resolver that can be used to resolve WSDLs and XSDs referenced + * by the BPEL process. + * + * @param modelResolver + */ + void setModelResolver(ModelResolver modelResolver); +} diff --git a/java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/BPELProcessDefinition.java b/java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/BPELProcessDefinition.java new file mode 100644 index 0000000000..a6518ed11b --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/BPELProcessDefinition.java @@ -0,0 +1,109 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.implementation.bpel; + +import java.net.URI; +import java.net.URL; +import java.util.List; + +import javax.wsdl.PortType; +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.assembly.Base; +import org.apache.tuscany.sca.implementation.bpel.xml.BPELImportElement; +import org.apache.tuscany.sca.implementation.bpel.xml.BPELPartnerLinkElement; +import org.apache.tuscany.sca.interfacedef.wsdl.WSDLInterface; + +/** + * The model representing a BPEL process definition. + * + * @version $Rev$ $Date$ + */ +public interface BPELProcessDefinition extends Base { + + /** + * Get the BPEL process Name + * + * @return + */ + QName getName(); + + /** + * Set the BPEL process Name + * + * @param processName process QName + */ + void setName(QName name); + + /** + * Get BPEL process URI + * + * @return URI for the process + */ + String getURI(); + + /** + * Set the BPEL process URI + * + * @param uri for the process + */ + void setURI(String uri); + + /** + * Get the URL for the process location + * + * @return + */ + String getLocation(); + + /** + * Set the URL for the process location + * + * @param url + */ + void setLocation(String location); + + /** + * Return the list of PartnerLinks for this process + * + * @return + */ + List getPartnerLinks(); + + /** + * Return the list of imports for this process + * + * @return + */ + List getImports(); + + /** + * Return the collection of associated port types + * + * @return + */ + public List getPortTypes() ; + + /** + * Return the collection of associated WSDL interfaces + * @return + */ + public List getInterfaces() ; +} diff --git a/java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/impl/BPELFactoryImpl.java b/java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/impl/BPELFactoryImpl.java new file mode 100644 index 0000000000..f9b95c7da8 --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/impl/BPELFactoryImpl.java @@ -0,0 +1,45 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.implementation.bpel.impl; + +import org.apache.tuscany.sca.core.FactoryExtensionPoint; +import org.apache.tuscany.sca.implementation.bpel.BPELFactory; +import org.apache.tuscany.sca.implementation.bpel.BPELImplementation; +import org.apache.tuscany.sca.implementation.bpel.BPELProcessDefinition; + +/** + * A factory for the BPEL implementation model. + * + * @version $Rev$ $Date$ + */ +public class BPELFactoryImpl implements BPELFactory { + + public BPELFactoryImpl(FactoryExtensionPoint modelFactories) { + } + + public BPELImplementation createBPELImplementation() { + return new BPELImplementationImpl(); + } + + public BPELProcessDefinition createBPELProcessDefinition() { + return new BPELProcessDefinitionImpl(); + } + +} diff --git a/java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/impl/BPELImplementationImpl.java b/java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/impl/BPELImplementationImpl.java new file mode 100644 index 0000000000..f1c943e49c --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/impl/BPELImplementationImpl.java @@ -0,0 +1,132 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.implementation.bpel.impl; + +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.assembly.ComponentType; +import org.apache.tuscany.sca.assembly.ConstrainingType; +import org.apache.tuscany.sca.assembly.Property; +import org.apache.tuscany.sca.assembly.Reference; +import org.apache.tuscany.sca.assembly.Service; +import org.apache.tuscany.sca.assembly.impl.ImplementationImpl; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.implementation.bpel.BPELImplementation; +import org.apache.tuscany.sca.implementation.bpel.BPELProcessDefinition; + +/** + * The model representing a BPEL implementation in an SCA assembly model. + * + * @version $Rev$ $Date$ + */ +class BPELImplementationImpl extends ImplementationImpl implements BPELImplementation { + + private QName processName; + private BPELProcessDefinition processDefinition; + private ComponentType componentType; + private ModelResolver modelResolver; + + public QName getProcess() { + return processName; + } + + public void setProcess(QName processName) { + this.processName = processName; + } + + public BPELProcessDefinition getProcessDefinition() { + return this.processDefinition; + } + + public void setProcessDefinition(BPELProcessDefinition processDefinition) { + this.processDefinition = processDefinition; + } + + @Override + public String getURI() { + // The BPEL implementation does not have a URI + return null; + } + + @Override + public void setURI(String uri) { + // The BPEL implementation does not have a URI + } + + @Override + public ConstrainingType getConstrainingType() { + // The BPEL implementation does not support constrainingTypes + return null; + } + + @Override + public List getProperties() { + // The BPEL implementation does not support properties + return Collections.emptyList(); + } + + public ComponentType getComponentType() { + return componentType; + } + + public void setComponentType(ComponentType componentType) { + this.componentType = componentType; + } + + public ModelResolver getModelResolver() { + return modelResolver; + } + + public void setModelResolver(ModelResolver modelResolver) { + this.modelResolver = modelResolver; + } + + @Override + public List getServices() { + return componentType.getServices(); + } + + @Override + public List getReferences() { + return componentType.getReferences(); + } + + @Override + public int hashCode() { + return String.valueOf(this.getProcess()).hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (obj == this) { + return true; + } else if (obj instanceof BPELImplementation) { + if (getProcess() != null) { + return getProcess().equals(((BPELImplementation)obj).getProcess()); + } else { + return ((BPELImplementation)obj).getProcess() == null; + } + } else { + return false; + } + } +} diff --git a/java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/impl/BPELProcessDefinitionImpl.java b/java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/impl/BPELProcessDefinitionImpl.java new file mode 100644 index 0000000000..5ce4f91376 --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/impl/BPELProcessDefinitionImpl.java @@ -0,0 +1,116 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.implementation.bpel.impl; + +import java.net.URL; +import java.util.ArrayList; +import java.util.List; + +import javax.wsdl.PortType; +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.implementation.bpel.BPELProcessDefinition; +import org.apache.tuscany.sca.implementation.bpel.xml.BPELImportElement; +import org.apache.tuscany.sca.implementation.bpel.xml.BPELPartnerLinkElement; +import org.apache.tuscany.sca.interfacedef.wsdl.WSDLInterface; + +/** + * The BPEL process definition implementation. + * + * @version $Rev$ $Date$ + */ +class BPELProcessDefinitionImpl implements BPELProcessDefinition { + private QName name; + private String uri; + private String location; + private boolean unresolved; + private List partnerLinks = new ArrayList(); + private List imports = new ArrayList(); + private List thePortTypes = new ArrayList(); + private List theInterfaces = new ArrayList(); + + public QName getName() { + return name; + } + + public void setName(QName name) { + this.name = name; + } + + public String getURI() { + return uri; + } + + public void setURI(String uri) { + this.uri = uri; + } + + public String getLocation() { + return location; + } + + public void setLocation(String location) { + this.location = location; + } + + public boolean isUnresolved() { + return unresolved; + } + + public void setUnresolved(boolean undefined) { + this.unresolved = undefined; + } + + public List getPartnerLinks() { + return partnerLinks; + } + + public List getImports() { + return imports; + } + + public List getPortTypes() { + return thePortTypes; + } + + public List getInterfaces() { + return theInterfaces; + } + + @Override + public int hashCode() { + return String.valueOf(getName()).hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (obj == this) { + return true; + } else if (obj instanceof BPELProcessDefinition) { + if (getName() != null) { + return getName().equals(((BPELProcessDefinition)obj).getName()); + } else { + return ((BPELProcessDefinition)obj).getName() == null; + } + } else { + return false; + } + } +} diff --git a/java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/xml/BPELDocumentProcessor.java b/java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/xml/BPELDocumentProcessor.java new file mode 100644 index 0000000000..43606cb216 --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/xml/BPELDocumentProcessor.java @@ -0,0 +1,532 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.implementation.bpel.xml; + +import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; +import static javax.xml.stream.XMLStreamConstants.START_ELEMENT; + +import java.io.InputStream; +import java.net.URI; +import java.net.URL; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; + +import javax.wsdl.Definition; +import javax.wsdl.PortType; +import javax.wsdl.extensions.ExtensibilityElement; +import javax.xml.namespace.QName; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sca.contribution.processor.BaseStAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.ContributionReadException; +import org.apache.tuscany.sca.contribution.processor.ContributionResolveException; +import org.apache.tuscany.sca.contribution.processor.URLArtifactProcessor; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.core.FactoryExtensionPoint; +import org.apache.tuscany.sca.implementation.bpel.BPELFactory; +import org.apache.tuscany.sca.implementation.bpel.BPELProcessDefinition; +import org.apache.tuscany.sca.interfacedef.InvalidInterfaceException; +import org.apache.tuscany.sca.interfacedef.wsdl.BPELPartnerLinkTypeExt; +import org.apache.tuscany.sca.interfacedef.wsdl.WSDLDefinition; +import org.apache.tuscany.sca.interfacedef.wsdl.WSDLFactory; +import org.apache.tuscany.sca.interfacedef.wsdl.WSDLInterface; +import org.apache.tuscany.sca.interfacedef.wsdl.WSDLObject; +import org.apache.tuscany.sca.monitor.Monitor; +import org.apache.tuscany.sca.monitor.Problem; +import org.apache.tuscany.sca.monitor.Problem.Severity; + +/** + * BPEL document processor responsible for reading a BPEL file and producing necessary model info about it + * + * TODO: The namespaces for WS-BPEL include 2 versions - only the earlier BPEL 1.1 versions are + * supported at present - the BPEL 2.0 namespaces also need support. This will require inspection + * of both BPEL process files and of WSDL files for their BPEL namespaces + * @version $Rev$ $Date$ + */ +public class BPELDocumentProcessor extends BaseStAXArtifactProcessor implements URLArtifactProcessor { + public final static QName BPEL_PROCESS_DEFINITION = new QName("http://schemas.xmlsoap.org/ws/2004/03/business-process/", "process"); + public final static QName BPEL_EXECUTABLE_DEFINITION = new QName("http://docs.oasis-open.org/wsbpel/2.0/process/executable", "process"); + private static final String SCA_BPEL_NS = "http://docs.oasis-open.org/ns/opencsa/sca-bpel/200801"; + private static final String BPEL_NS = "http://schemas.xmlsoap.org/ws/2004/03/business-process/"; + private static final String BPEL_PLINK_NS = "http://schemas.xmlsoap.org/ws/2004/03/partner-link/"; + private static final String WSDL_NS = "http://schemas.xmlsoap.org/wsdl/"; + private static final QName PROCESS_ELEMENT = new QName(BPEL_NS, "process"); + private static final QName PARTNERLINK_ELEMENT = new QName(BPEL_NS, "partnerLink"); + private static final QName ONEVENT_ELEMENT = new QName(BPEL_NS, "onEvent"); + private static final QName RECEIVE_ELEMENT = new QName(BPEL_NS, "receive"); + private static final QName ONMESSAGE_ELEMENT = new QName(BPEL_NS, "onMessage"); + private static final QName INVOKE_ELEMENT = new QName(BPEL_NS, "invoke"); + private static final QName IMPORT_ELEMENT = new QName(BPEL_NS, "import"); + private static final String LINKTYPE_NAME = "partnerLinkType"; + private static final QName LINKTYPE_ELEMENT = new QName(BPEL_PLINK_NS, LINKTYPE_NAME); + private final static String NAME_ELEMENT = "name"; + private final static String TARGET_NAMESPACE = "targetNamespace"; + + private final static XMLInputFactory inputFactory = XMLInputFactory.newInstance(); + + private final BPELFactory factory; + private WSDLFactory WSDLfactory; + private Monitor monitor; + + public BPELDocumentProcessor(FactoryExtensionPoint modelFactories, Monitor monitor) { + this.factory = modelFactories.getFactory(BPELFactory.class); + this.WSDLfactory = modelFactories.getFactory(WSDLFactory.class); + this.monitor = monitor; + } + + public String getArtifactType() { + return "*.bpel"; + } + + public Class getModelType() { + return BPELProcessDefinition.class; + } + + public BPELProcessDefinition read(URL contributionURL, URI artifactURI, URL artifactURL) throws ContributionReadException { + BPELProcessDefinition processDefinition = null; + try { + // for now we are just using process name + // and relying on componentType file for service definition + // so it's OK to set resolved for now + processDefinition = readProcessDefinition(artifactURL); + processDefinition.setURI(artifactURI.toString()); + processDefinition.setUnresolved(false); + } catch (Exception e) { + ContributionReadException ce = new ContributionReadException(e); + error("ContributionReadException", artifactURL, ce); + } + + return processDefinition; + } + + public void resolve(BPELProcessDefinition model, ModelResolver resolver) throws ContributionResolveException { + // FIXME - serious resolving needs to happen here + + // Step 1 is to resolve the WSDL files referenced from this BPEL process + // - one complexity here is that the WSDL definitions hold BPEL extension elements for + // the partnerLinkType declarations - and these must be used in later steps + // + // Step 2 is to take all the partnerLink definitions and establish the PortType being + // used, by tracing through the related partnerLinkType declarations - the PortType is + // effectively a definition of the interface used by the partnerLink. + // - another consideration here is that each partnerLink can involve 2 interfaces, one + // for the forward calls to the process, the other for calls from the process - depending + // on whether the partnerLink is a reference or a service, one of these interfaces is a + // callback interface. + + List theImports = model.getImports(); + for (BPELImportElement theImport : theImports) { + + // Deal with WSDL imports + if (theImport.getImportType().equals(WSDL_NS)) { + String wsdlLocation = theImport.getLocation(); + String wsdlNamespace = theImport.getNamespace(); + + // Resolve the WSDL definition + WSDLDefinition proxy = WSDLfactory.createWSDLDefinition(); + proxy.setUnresolved(true); + proxy.setNamespace(wsdlNamespace); + if (wsdlLocation != null) { + proxy.setLocation(URI.create(wsdlLocation)); + } + WSDLDefinition resolved = resolver.resolveModel(WSDLDefinition.class, proxy); + if (resolved != null && !resolved.isUnresolved()) { + theImport.setWSDLDefinition(resolved); + } else { + error("CannotResolveWSDLReference", resolver, wsdlLocation, wsdlNamespace); + return; + } // end if + } // end if + } // end for + + // Fetch the sets of partner links, port types and interfaces + List thePLinkTypes = getPartnerLinkTypes( theImports ); + Collection theInterfaces = (Collection)new ArrayList(); + Collection thePortTypes = getAllPortTypes( theImports, theInterfaces, resolver ); + + // Store the Port Types and the Interfaces for later calculation of the component type... + model.getPortTypes().addAll(thePortTypes); + model.getInterfaces().addAll(theInterfaces); + + // Now, for each partnerLink in the BPEL process, find the related partnerLinkType + // element + List thePartnerLinks = model.getPartnerLinks(); + for (BPELPartnerLinkElement thePartnerLink : thePartnerLinks) { + QName partnerLinkType = thePartnerLink.getPartnerLinkType(); + BPELPartnerLinkTypeElement pLinkType = findPartnerLinkType(partnerLinkType, thePLinkTypes); + if (pLinkType == null) { + error("PartnerLinkNoMatchingType", thePartnerLink, thePartnerLink.getName()); + } else + thePartnerLink.setPartnerLinkType(pLinkType); + } // end for + + } // end resolve + + /** + * Retrieve all the Partner Link types defined in the imported WSDL files + * + * @param theImports + */ + private List getPartnerLinkTypes( List theImports) throws ContributionResolveException { + + List thePLinks = new ArrayList(); + + // We must find the partner link type elements from amongst the imported + // WSDLs + for (BPELImportElement theImport : theImports) { + if (theImport.getImportType().equals(WSDL_NS)) { + + // Find all the WSDL definitions matching the imported namespace + List wsdlDefinitions = new ArrayList(); + WSDLDefinition theWSDL = theImport.getWSDLDefinition(); + wsdlDefinitions.add(theWSDL.getDefinition()); + for (WSDLDefinition importedWSDL: theWSDL.getImportedDefinitions()) { + wsdlDefinitions.add(importedWSDL.getDefinition()); + } + + // The BPEL partnerLinkType elements are extension elements within + // the WSDL definitions + for (Definition wsdlDefinition: wsdlDefinitions) { + for (ExtensibilityElement theElement : (List)wsdlDefinition.getExtensibilityElements()) { + QName elementType = theElement.getElementType(); + if (elementType.equals(LINKTYPE_ELEMENT)) { + BPELPartnerLinkTypeExt pLinkExt = (BPELPartnerLinkTypeExt)theElement; + + // Fetch the name of the partnerLinkType + String name = pLinkExt.getName(); + QName qName = new QName(wsdlDefinition.getTargetNamespace(), name); + BPELPartnerLinkTypeElement pLinkElement = new BPELPartnerLinkTypeElement(qName); + + // The partnerLinkType must have one and may have 2 role + // child elements + int count = 0; + for (int i = 0; i < 2; i++) { + if (pLinkExt.getRoleName(i) == null) + continue; + PortType pType = wsdlDefinition.getPortType(pLinkExt.getRolePortType(i)); + if (count == 0) { + pLinkElement.setRole1(pLinkExt.getRoleName(i), pLinkExt.getRolePortType(i), pType); + count++; + } else if (count == 1) { + pLinkElement.setRole2(pLinkExt.getRoleName(i), pLinkExt.getRolePortType(i), pType); + count++; + } else { + break; + } // end if + } // end for + + if (count == 0) { + error("PartnerLinkTypeNoRoles", theElement, pLinkElement.getName()); + throw new ContributionResolveException("partnerLinkType " + pLinkElement.getName() + " has no Roles defined"); + } else + thePLinks.add(pLinkElement); + } // end if + + } // end for + } + } + } // end for + return thePLinks; + } // end getPartnerLinkTypes + + /** + * Returns all the portTypes referenced by the process. + * + * @param theImports + * @param theInterfaces + * @param resolver + * @return + * @throws ContributionResolveException + */ + private Collection getAllPortTypes(List theImports, + Collection theInterfaces, ModelResolver resolver) throws ContributionResolveException { + + Collection thePortTypes = (Collection)new ArrayList(); + for (BPELImportElement theImport : theImports) { + if (theImport.getImportType().equals(WSDL_NS)) { + + // Find all the WSDL definitions matching the imported namespace + List wsdlDefinitions = new ArrayList(); + WSDLDefinition theWSDL = theImport.getWSDLDefinition(); + wsdlDefinitions.add(theWSDL.getDefinition()); + for (WSDLDefinition importedWSDL: theWSDL.getImportedDefinitions()) { + wsdlDefinitions.add(importedWSDL.getDefinition()); + } + for (Definition wsdlDefinition: wsdlDefinitions) { + + Collection portTypes = (Collection)wsdlDefinition.getPortTypes().values(); + thePortTypes.addAll(portTypes); + + // Create WSDLInterface elements for each PortType found + for (PortType portType : portTypes) { + WSDLObject wsdlPortType = theWSDL.getWSDLObject(PortType.class, portType.getQName()); + WSDLInterface wsdlInterface; + if (wsdlPortType != null) { + // Introspect the WSDL portType and add the resulting + // WSDLInterface to the resolver + try { + theWSDL.setDefinition(wsdlPortType.getDefinition()); + wsdlInterface = WSDLfactory.createWSDLInterface(wsdlPortType.getElement(), theWSDL, resolver); + wsdlInterface.setWsdlDefinition(theWSDL); + } catch (InvalidInterfaceException e) { + ContributionResolveException ce = new ContributionResolveException(e); + error("ContributionResolveException", resolver, ce); + throw ce; + } // end try + resolver.addModel(wsdlInterface); + theInterfaces.add(wsdlInterface); + } // end if + } // end for + } + } + } // end for + + return thePortTypes; + } // end getAllPortTypes + + /** + * Finds a partnerLinkType definition within the WSDLs imported by the BPEL + * process. + * + * @param partnerLinkTypeName - the name of the partnerLinkType + * @param theImports a list of the WSDL import declarations + * @return a BPELPartnerLinkTypeElement for the partnerLinkType or null if it cannot be + * found + */ + private BPELPartnerLinkTypeElement findPartnerLinkType( QName partnerLinkTypeName, + List thePLinkTypes) { + // We must find the partner link type element from amongst the imported WSDLs + for ( BPELPartnerLinkTypeElement thePLinkType : thePLinkTypes ){ + if( thePLinkType.getName().equals(partnerLinkTypeName) ) return thePLinkType; + } // end for + return null; + } // end findPartnerLinkType + + + /** + * Read a process definition. + * + * @param doc + * @return + * @throws Exception + */ + private BPELProcessDefinition readProcessDefinition(URL doc) throws Exception { + BPELProcessDefinition processDefinition = factory.createBPELProcessDefinition(); + processDefinition.setUnresolved(true); + processDefinition.setLocation(doc.toString()); + + InputStream is = doc.openStream(); + XMLStreamReader reader = null; + try { + reader = inputFactory.createXMLStreamReader(is); + + /* + * The principle here is to look for partnerLink elements, which + * form either services or references. A partnerLink can be EITHER - + * the algorithm for deciding is: 1) Explicit marking with + * sca:reference or sca:service attribute 2) "first use" of the + * partnerLink by specific BPEL activity elements: , + * or elements imply a service + * implies a reference + */ + + // TODO - need to handle elements as kind of "nested" processes + // - and scopes introduce the possibility of partnerLinks with the + // same name at different levels of scope.... (yuk!!) + boolean completed = false; + while (!completed) { + switch (reader.next()) { + case START_ELEMENT: + QName qname = reader.getName(); + if (BPEL_PROCESS_DEFINITION.equals(qname) || BPEL_EXECUTABLE_DEFINITION.equals(qname)) { + QName processName = new QName(getString(reader, TARGET_NAMESPACE), getString(reader, NAME_ELEMENT)); + processDefinition.setName(processName); + } else if (PARTNERLINK_ELEMENT.equals(qname)) { + processDefinition.getPartnerLinks().add(processPartnerLinkElement(reader)); + } else if (ONEVENT_ELEMENT.equals(qname) || RECEIVE_ELEMENT.equals(qname) || ONMESSAGE_ELEMENT.equals(qname)) { + processPartnerLinkAsService(reader.getAttributeValue(null, "partnerLink"), processDefinition.getPartnerLinks()); + } else if (INVOKE_ELEMENT.equals(qname)) { + processPartnerLinkAsReference(reader.getAttributeValue(null, "partnerLink"), processDefinition.getPartnerLinks()); + } else if (IMPORT_ELEMENT.equals(qname)) { + processDefinition.getImports().add(processImportElement(reader)); + } // end if + break; + case END_ELEMENT: + if (PROCESS_ELEMENT.equals(reader.getName())) { + completed = true; + break; + } // end if + } // end switch + } // end while + } finally { + if (reader != null) + reader.close(); + is.close(); + } // end try + + return processDefinition; + } // end readProcessDefinition + + /** + * Processes a partnerLink element from the BPEL process and creates a + * BPELPartnerLink object + * + * @param reader + */ + private BPELPartnerLinkElement processPartnerLinkElement(XMLStreamReader reader) throws ContributionReadException { + BPELPartnerLinkElement partnerLink = new BPELPartnerLinkElement( + reader.getAttributeValue(null, "name"), + getQNameValue(reader, reader.getAttributeValue(null, "partnerLinkType")), + reader.getAttributeValue(null, "myRole"), + reader.getAttributeValue(null, "partnerRole")); + + // See if there are any SCA extension attributes + String scaService = reader.getAttributeValue(SCA_BPEL_NS, "service"); + String scaReference = reader.getAttributeValue(SCA_BPEL_NS, "reference"); + if ((scaService != null) && (scaReference != null)) { + // It is incorrect to set both service & reference attributes + error("PartnerLinkHasBothAttr", partnerLink, reader.getAttributeValue(null, "name")); + throw new ContributionReadException("BPEL PartnerLink " + reader.getAttributeValue(null, "name") + " has both sca:reference and sca:service attributes set"); + } + + // Set the SCA type and the related name, if present + if (scaService != null) + partnerLink.setAsService(scaService); + else if (scaReference != null) + partnerLink.setAsReference(scaReference); + return partnerLink; + + } // end processPartnerLinkElement + + /** + * Processes an element from the BPEL process and creates a + * BPELImportElement object + * + * @param reader + */ + private BPELImportElement processImportElement(XMLStreamReader reader) { + return (new BPELImportElement(reader.getAttributeValue(null, "location"), + reader.getAttributeValue(null, "importType"), + reader.getAttributeValue(null, "namespace"))); + + } // end processImportElement + + /** + * Mark a named partnerLink as a Service, unless it is already marked as a + * Reference + * + * @param partnerLinkName + * @param partnerLinks + */ + private void processPartnerLinkAsService(String partnerLinkName, List partnerLinks) { + BPELPartnerLinkElement partnerLink = findPartnerLinkByName(partnerLinks, partnerLinkName); + if (partnerLink == null) { + warning("ReferencePartnerLinkNotInList", partnerLinkName, partnerLinkName); + } else { + // Set the type of the partnerLink to "service" if not already + // set... + if (!partnerLink.isSCATyped()) + partnerLink.setAsService(partnerLinkName); + } // endif + } // end processPartnerLinkAsReference + + /** + * Mark a named partnerLink as a Reference, unless it is already marked as a + * Service + * + * @param partnerLinkName + * @param partnerLinks + */ + private void processPartnerLinkAsReference(String partnerLinkName, List partnerLinks) { + BPELPartnerLinkElement partnerLink = findPartnerLinkByName(partnerLinks, partnerLinkName); + if (partnerLink == null) { + warning("ReferencePartnerLinkNotInList", partnerLinkName, partnerLinkName); + } else { + // Set the type of the partnerLink to "service" if not already + // set... + if (!partnerLink.isSCATyped()) + partnerLink.setAsReference(partnerLinkName); + } // endif + } // end processPartnerLinkAsReference + + /** + * Finds a PartnerLink by name from a List of PartnerLinks returns null if + * there is no partnerLink with a matching name - returns the PartnerLink + * with a matching name + * + * @param partnerLinks + * @param partnerLinkName + */ + private BPELPartnerLinkElement findPartnerLinkByName(List partnerLinks, String partnerLinkName) { + // Scan the list looking for a partner link with the supplied name + Iterator it = partnerLinks.iterator(); + while (it.hasNext()) { + BPELPartnerLinkElement thePartnerLink = it.next(); + if (thePartnerLink.getName().equals(partnerLinkName)) + return thePartnerLink; + } + return null; + } // end method findPartnerLinkByName + + /** + * Report a warning. + * + * @param problems + * @param message + * @param model + */ + private void warning(String message, Object model, Object... messageParameters) { + if (monitor != null) { + Problem problem = monitor.createProblem(this.getClass().getName(), "impl-bpel-validation-messages", Severity.WARNING, model, message, (Object[])messageParameters); + monitor.problem(problem); + } + } + + /** + * Report a error. + * + * @param problems + * @param message + * @param model + */ + private void error(String message, Object model, Object... messageParameters) { + if (monitor != null) { + Problem problem = monitor.createProblem(this.getClass().getName(), "impl-bpel-validation-messages", Severity.ERROR, model, message, (Object[])messageParameters); + monitor.problem(problem); + } + } + + /** + * Report a exception. + * + * @param problems + * @param message + * @param model + */ + private void error(String message, Object model, Exception ex) { + if (monitor != null) { + Problem problem = monitor.createProblem(this.getClass().getName(), "impl-bpel-validation-messages", Severity.ERROR, model, message, ex); + monitor.problem(problem); + } + } +} diff --git a/java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/xml/BPELImplementationProcessor.java b/java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/xml/BPELImplementationProcessor.java new file mode 100644 index 0000000000..92c38123a1 --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/xml/BPELImplementationProcessor.java @@ -0,0 +1,516 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.implementation.bpel.xml; + +import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; + +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.wsdl.PortType; +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; + +import org.apache.tuscany.sca.assembly.AssemblyFactory; +import org.apache.tuscany.sca.assembly.ComponentType; +import org.apache.tuscany.sca.assembly.Multiplicity; +import org.apache.tuscany.sca.assembly.Property; +import org.apache.tuscany.sca.assembly.Reference; +import org.apache.tuscany.sca.assembly.Service; +import org.apache.tuscany.sca.contribution.processor.BaseStAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.ContributionReadException; +import org.apache.tuscany.sca.contribution.processor.ContributionResolveException; +import org.apache.tuscany.sca.contribution.processor.ContributionWriteException; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.core.FactoryExtensionPoint; +import org.apache.tuscany.sca.implementation.bpel.BPELFactory; +import org.apache.tuscany.sca.implementation.bpel.BPELImplementation; +import org.apache.tuscany.sca.implementation.bpel.BPELProcessDefinition; +import org.apache.tuscany.sca.interfacedef.wsdl.WSDLFactory; +import org.apache.tuscany.sca.interfacedef.wsdl.WSDLInterface; +import org.apache.tuscany.sca.interfacedef.wsdl.WSDLInterfaceContract; +import org.apache.tuscany.sca.monitor.Monitor; +import org.apache.tuscany.sca.monitor.Problem; +import org.apache.tuscany.sca.monitor.Problem.Severity; + +/** + * Implements a StAX artifact processor for BPEL implementations. + * + * The artifact processor is responsible for processing + * elements in SCA assembly XML composite files and populating the BPEL + * implementation model, resolving its references to other artifacts in the SCA + * contribution, and optionally write the model back to SCA assembly XML. + * + * @version $Rev$ $Date$ + */ +public class BPELImplementationProcessor extends BaseStAXArtifactProcessor implements StAXArtifactProcessor { + private static final String SCA10_NS = "http://www.osoa.org/xmlns/sca/1.0"; + private static final String PROCESS = "process"; + private static final String IMPLEMENTATION_BPEL = "implementation.bpel"; + private static final QName IMPLEMENTATION_BPEL_QNAME = new QName(SCA10_NS, IMPLEMENTATION_BPEL); + + private AssemblyFactory assemblyFactory; + private BPELFactory bpelFactory; + private WSDLFactory wsdlFactory; + private Monitor monitor; + + public BPELImplementationProcessor(FactoryExtensionPoint modelFactories, Monitor monitor) { + this.assemblyFactory = modelFactories.getFactory(AssemblyFactory.class); + this.wsdlFactory = modelFactories.getFactory(WSDLFactory.class); + this.bpelFactory = modelFactories.getFactory(BPELFactory.class); + this.monitor = monitor; + } + + public QName getArtifactType() { + // Returns the QName of the XML element processed by this processor + return IMPLEMENTATION_BPEL_QNAME; + } + + public Class getModelType() { + // Returns the type of model processed by this processor + return BPELImplementation.class; + } + + public BPELImplementation read(XMLStreamReader reader) throws ContributionReadException, XMLStreamException { + assert IMPLEMENTATION_BPEL_QNAME.equals(reader.getName()); + + // Read an element + BPELImplementation implementation = null; + + // Read the process attribute. + QName process = getAttributeValueNS(reader, PROCESS); + if (process == null) { + return implementation; + } + + // Create and initialize the BPEL implementation model + implementation = bpelFactory.createBPELImplementation(); + implementation.setProcess(process); + implementation.setUnresolved(true); + + // Skip to end element + while (reader.hasNext()) { + if (reader.next() == END_ELEMENT && IMPLEMENTATION_BPEL_QNAME.equals(reader.getName())) { + break; + } + } + + return implementation; + } + + public void resolve(BPELImplementation implementation, ModelResolver resolver) throws ContributionResolveException { + + if( implementation != null && implementation.isUnresolved()) + { + implementation.setModelResolver(resolver); + + BPELProcessDefinition processDefinition = resolveBPELProcessDefinition(implementation, resolver); + if(processDefinition.isUnresolved()) { + error("BPELProcessNotFound", implementation, processDefinition.getName()); + } else { + implementation.setProcessDefinition(processDefinition); + + // Get the component type from the process definition + generateComponentType( implementation ); + + //resolve component type + mergeComponentType(resolver, implementation); + + //set current implementation resolved + implementation.setUnresolved(false); + } + } + + } // end resolve + + public void write( BPELImplementation bpelImplementation, + XMLStreamWriter writer ) throws ContributionWriteException, XMLStreamException { + //FIXME Deal with policy processing... + // Write + // policyProcessor.writePolicyPrefixes(bpelImplementation, writer); + writer.writeStartElement(SCA10_NS, IMPLEMENTATION_BPEL); + // policyProcessor.writePolicyAttributes(bpelImplementation, writer); + + if (bpelImplementation.getProcess() != null) { + writer.writeAttribute(PROCESS, bpelImplementation.getProcess().toString() ); + } + + writer.writeEndElement(); + + } // end write + + private BPELProcessDefinition resolveBPELProcessDefinition(BPELImplementation impl, ModelResolver resolver) throws ContributionResolveException { + QName processName = impl.getProcess(); + BPELProcessDefinition processDefinition = this.bpelFactory.createBPELProcessDefinition(); + processDefinition.setName(processName); + processDefinition.setUnresolved(true); + + return resolver.resolveModel(BPELProcessDefinition.class, processDefinition); + } // end resolveBPELProcessDefinition + + /** + * Calculates the component type of the supplied implementation and attaches it to the + * implementation. + * + * @param impl + * @throws ContributionResolveException + */ + private void generateComponentType(BPELImplementation impl) throws ContributionResolveException { + + // Create a ComponentType and mark it unresolved + ComponentType componentType = assemblyFactory.createComponentType(); + componentType.setUnresolved(true); + impl.setComponentType(componentType); + + // Each partner link in the process represents either a service or a + // reference + // - or both, in the sense of involving a callback + BPELProcessDefinition theProcess = impl.getProcessDefinition(); + List partnerLinks = theProcess.getPartnerLinks(); + + for (BPELPartnerLinkElement pLink : partnerLinks) { + + // check that the partner link has been designated as service or + // reference in SCA terms + if (pLink.isSCATyped()) { + String scaName = pLink.getSCAName(); + if (pLink.querySCAType().equals("reference")) { + componentType.getReferences().add(generateReference(scaName, pLink.getMyRolePortType(), pLink.getPartnerRolePortType(), theProcess.getInterfaces())); + } else { + componentType.getServices().add(generateService(scaName, pLink.getMyRolePortType(), pLink.getPartnerRolePortType(), theProcess.getInterfaces())); + } // end if + } // end if + } // end for + + } // end getComponentType + + /** + * Create an SCA reference for a partnerLink + * @param name - name of the reference + * @param myRolePT - partner link type of myRole + * @param partnerRolePT - partner link type of partnerRole + * @param theInterfaces - list of WSDL interfaces associated with the BPEL process + * @return + */ + private Reference generateReference( String name, PortType myRolePT, + PortType partnerRolePT, Collection theInterfaces) throws ContributionResolveException { + + Reference reference = assemblyFactory.createReference(); + WSDLInterfaceContract interfaceContract = wsdlFactory.createWSDLInterfaceContract(); + reference.setInterfaceContract(interfaceContract); + + // Establish whether there is just a call interface or a call + callback + // interface + PortType callPT = null; + PortType callbackPT = null; + if (myRolePT != null) { + callPT = myRolePT; + // If the 2 port types are not the same one, there is a callback... + if (partnerRolePT != null) { + if (!myRolePT.getQName().equals(partnerRolePT.getQName())) { + callbackPT = partnerRolePT; + } // end if + } // end if + } else if (partnerRolePT != null) { + callPT = partnerRolePT; + } // end if + + // No interfaces mean an error + if (callPT == null && callbackPT == null) { + error("MyRolePartnerRoleNull", theInterfaces); + } // end if + + // Set the name of the reference to the supplied name and the + // multiplicity of the reference + // to 1..1 + // TODO: support other multiplicities + reference.setName(name); + reference.setMultiplicity(Multiplicity.ONE_ONE); + + if (callPT != null) { + // Set the call interface and, if present, the callback interface + WSDLInterface callInterface = null; + for (WSDLInterface anInterface : theInterfaces) { + if (anInterface.getPortType().getQName().equals(callPT.getQName())) + callInterface = anInterface; + } // end for + if (callInterface == null) { + error("NoInterfaceForPortType", theInterfaces, callPT.getQName().toString()); + } else + reference.getInterfaceContract().setInterface(callInterface); + } + + // There is a callback if the partner role is not null and if the + // partner role port type + // is not the same as the port type for my role + if (callbackPT != null) { + WSDLInterface callbackInterface = null; + for (WSDLInterface anInterface : theInterfaces) { + if (anInterface.getPortType().getQName().equals(callbackPT.getQName())) + callbackInterface = anInterface; + } // end for + if (callbackInterface == null) { + error("NoInterfaceForPortType", theInterfaces, callbackPT.getQName().toString()); + } else + reference.getInterfaceContract().setCallbackInterface(callbackInterface); + } // end if + + return reference; + } // end generateReference + + /** + * Create an SCA service for a partnerLink + * @param name - name of the reference + * @param myRolePT - partner link type of myRole + * @param partnerRolePT - partner link type of partnerRole + * @param theInterfaces - list of WSDL interfaces associated with the BPEL process + * @return + */ + private Service generateService( String name, PortType myRolePT, + PortType partnerRolePT, Collection theInterfaces ) + throws ContributionResolveException { + Service service = assemblyFactory.createService(); + WSDLInterfaceContract interfaceContract = wsdlFactory.createWSDLInterfaceContract(); + service.setInterfaceContract(interfaceContract); + + // Set the name of the service to the supplied name + service.setName(name); + + // Establish whether there is just a call interface or a call + callback + // interface + PortType callPT = null; + PortType callbackPT = null; + if (myRolePT != null) { + callPT = myRolePT; + // If the 2 port types are not the same one, there is a callback... + if (partnerRolePT != null) { + if (!myRolePT.getQName().equals(partnerRolePT.getQName())) { + callbackPT = partnerRolePT; + } // end if + } // end if + } else if (partnerRolePT != null) { + callPT = partnerRolePT; + } // end if + + // No interfaces mean an error + if (callPT == null && callbackPT == null) { + error("MyRolePartnerRoleNull", theInterfaces); + } // end if + + if (callPT != null) { + // Set the call interface and, if present, the callback interface + WSDLInterface callInterface = null; + for (WSDLInterface anInterface : theInterfaces) { + if (anInterface.getPortType().getQName().equals(callPT.getQName())) + callInterface = anInterface; + } // end for + if (callInterface == null) { + error("NoInterfaceForPortType", theInterfaces, callPT.getQName().toString()); + } else + service.getInterfaceContract().setInterface(callInterface); + } // end if + + // There is a callback if the partner role is not null and if the + // partner role port type + // is not the same as the port type for my role + if (callbackPT != null) { + WSDLInterface callbackInterface = null; + for (WSDLInterface anInterface : theInterfaces) { + if (anInterface.getPortType().getQName().equals(callbackPT.getQName())) + callbackInterface = anInterface; + } // end for + if (callbackInterface == null) { + error("NoInterfaceForPortType", theInterfaces, callbackPT.getQName().toString()); + } else + service.getInterfaceContract().setCallbackInterface(callbackInterface); + } // end if + + return service; + } // end generateService + + /** + * Merge the componentType from introspection and from external file + * + * Note the setting of the DataBinding for both Services and References to DOM, since this is + * the data format expected by the ODE BPEL implementation code. + * + * @param resolver + * @param impl + */ + private void mergeComponentType(ModelResolver resolver, BPELImplementation impl) { + + // Load the component type from a component type file, if any + ComponentType componentType = getComponentType(resolver, impl); + if (componentType != null && !componentType.isUnresolved()) { + + // References... + Map refMap = new HashMap(); + for (Reference reference : componentType.getReferences()) { + refMap.put(reference.getName(), reference); + } // end for + + // For the present, overwrite anything arising from the component + // type sidefile if + // equivalent services are defined in the implementation. + // TODO - a more careful merge must be done, using the + // implementation introspection data + // as the master but adding any additional and non-conflicting + // information from the + // sidefile + for (Reference ref : impl.getReferences()) { + refMap.put(ref.getName(), ref); + } // end for + + impl.getReferences().clear(); + impl.getReferences().addAll(refMap.values()); + + // Services..... + Map serviceMap = new HashMap(); + for (Service service : componentType.getServices()) { + serviceMap.put(service.getName(), service); + } // end for + + // For the present, overwrite anything arising from the component + // type sidefile if + // equivalent services are defined in the implementation. + // TODO - a more careful merge must be done, using the + // implementation introspection data + // as the master but adding any additional and non-conflicting + // information from the + // sidefile + for (Service svc : impl.getServices()) { + serviceMap.put(svc.getName(), svc); + } // end for + + impl.getServices().clear(); + impl.getServices().addAll(serviceMap.values()); + + // Properties + Map propMap = new HashMap(); + for (Property property : componentType.getProperties()) { + propMap.put(property.getName(), property); + } // end for + + // A simple overwrite of any equivalent properties from the + // component type sidefile + for (Property prop : impl.getProperties()) { + propMap.put(prop.getName(), prop); + } + } + } + + + /** + * Find the componentType side file based on the BPEL implementation artifact + * @param resolver + * @param impl + * @return + */ + private ComponentType getComponentType(ModelResolver resolver, BPELImplementation impl) { + String bpelProcessURI = impl.getProcessDefinition().getURI().toString(); + + // Get the component type definition contained in the componentType file, if any + String componentTypeURI = bpelProcessURI.replace(".bpel", ".componentType"); + ComponentType componentType = assemblyFactory.createComponentType(); + componentType.setUnresolved(true); + componentType.setURI(componentTypeURI); + componentType = resolver.resolveModel(ComponentType.class, componentType); + if (!componentType.isUnresolved()) { + return componentType; + } + return null; + } // end getComponentType + + /** + * Returns a QName from its string representation in a named attribute of an XML element + * supplied in an XMLStreamReader + * + * QName attributes of an XML element (such as BPEL process) is presented in one of + * two alternative formats: + * 1) In the form of a local name with a prefix, with the prefix referencing a namespace + * URI declaration elsewhere in the composite (typically on the composite element) + * + * ie: nms:SomeName + * xmlns:nms="http://example.com/somenamespace" + * + * 2) In the XML Namespaces recommendation format (see http://jclark.com/xml/xmlns.htm ) + * where the namespace URI and the local name are encoded into a single string, with the + * namespace URI enclosed between a pair of braces {...} + * + * ie: {http://example.com/somenamespace}SomeName + */ + private QName getAttributeValueNS(XMLStreamReader reader, String attribute) { + String fullValue = reader.getAttributeValue(null, attribute); + if (fullValue == null) { + error("AttributeProcessMissing", reader); + return null; + } + + // Deal with the attribute in the XML Namespaces recommendation format + // - trim off any leading/trailing spaces and check that the first + // character is '{' + if (fullValue.trim().charAt(0) == '{') { + try { + // Attempt conversion to a QName object + QName theProcess = QName.valueOf(fullValue); + return theProcess; + } catch (IllegalArgumentException e) { + // This exception happens if the attribute begins with '{' but + // doesn't conform + // to the XML Namespaces recommendation format + error("AttributeWithoutNamespace", reader, attribute, fullValue); + return null; + } + } // endif + + // Deal with the attribute in the local name + prefix format + if (fullValue.indexOf(":") < 0) { + error("AttributeWithoutPrefix", reader, attribute, fullValue); + return null; + } + String prefix = fullValue.substring(0, fullValue.indexOf(":")); + String name = fullValue.substring(fullValue.indexOf(":") + 1); + String nsUri = reader.getNamespaceContext().getNamespaceURI(prefix); + if (nsUri == null) { + error("AttributeUnrecognizedNamespace", reader, attribute, fullValue); + return null; + } + return new QName(nsUri, name, prefix); + } + + /** + * Report a error. + * + * @param problems + * @param message + * @param model + */ + private void error(String message, Object model, Object... messageParameters) { + if (monitor != null) { + Problem problem = monitor.createProblem(this.getClass().getName(), "impl-bpel-validation-messages", Severity.ERROR, model, message, (Object[])messageParameters); + monitor.problem(problem); + } + } + +} diff --git a/java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/xml/BPELImportElement.java b/java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/xml/BPELImportElement.java new file mode 100644 index 0000000000..bf0020323c --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/xml/BPELImportElement.java @@ -0,0 +1,65 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.implementation.bpel.xml; + +import org.apache.tuscany.sca.interfacedef.wsdl.WSDLDefinition; + +/** + * Represents an element in a BPEL process + * - this has attributes: + * location + * importType + * namespace + * + * @version $Rev$ $Date$ + */ +public class BPELImportElement { + + private String location; + private String importType; + private String namespace; + private WSDLDefinition theWSDL = null; + + public BPELImportElement(String location, String importType, String namespace) { + this.location = location; + this.importType = importType; + this.namespace = namespace; + } + + public String getImportType() { + return importType; + } + + public String getLocation() { + return location; + } + + public String getNamespace() { + return namespace; + } + + public void setWSDLDefinition(WSDLDefinition theDefinition) { + theWSDL = theDefinition; + } + + public WSDLDefinition getWSDLDefinition() { + return theWSDL; + } + +} // end class BPELImportElement diff --git a/java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/xml/BPELPartnerLinkElement.java b/java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/xml/BPELPartnerLinkElement.java new file mode 100644 index 0000000000..b7f5d1d3f2 --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/xml/BPELPartnerLinkElement.java @@ -0,0 +1,130 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.implementation.bpel.xml; + +import javax.xml.namespace.QName; + +import javax.wsdl.PortType; + +/** + * Represents a element in a BPEL process + * - this has attributes: + * name + * partnerLinkType + * myRole + * partnerRole + * - plus zero or more property elements as children + * + * The partnerlink may also be given an SCA Type - either of service or of reference - this must + * generally be calculated and set on the partnerLink by inspecting the BPEL process + * + * @version $Rev$ $Date$ + */ +public class BPELPartnerLinkElement { + + private String REFERENCE_TYPE = "reference"; + private String SERVICE_TYPE = "service"; + private String name; + private QName partnerLinkType; + private BPELPartnerLinkTypeElement pLinkType = null; + private String myRole; + private String partnerRole; + private String scaName; // Holds the SCA reference or service name + private String scaType = null; // Holds the SCA type = null | service | reference + + public BPELPartnerLinkElement(String name, + QName partnerLinkType, + String myRole, + String partnerRole ) { + this.name = name; + this.partnerLinkType = partnerLinkType; + this.myRole = myRole; + this.partnerRole = partnerRole; + + scaName = null; + } + + public QName getPartnerLinkType() { + return partnerLinkType; + } + + public void setPartnerLinkType( BPELPartnerLinkTypeElement pLinkType ) { + this.pLinkType = pLinkType; + } + + + public PortType getMyRolePortType() { + return getRolePortType( myRole ); + } + + public PortType getPartnerRolePortType() { + return getRolePortType( partnerRole ); + } + + private PortType getRolePortType( String theRole ) { + if (theRole == null || theRole.length() == 0) { + return null; + } // end if + if (theRole.equals(pLinkType.getRole1Name())) { + return pLinkType.getRole1pType(); + } else if (theRole.equals(pLinkType.getRole2Name())) { + return pLinkType.getRole2pType(); + } // end if + return null; + } // end getRolePortType + + public String getName() { + return name; + } + + public String getMyRole() { + return myRole; + } + + public String getPartnerRole() { + return partnerRole; + } + + public void setSCAName( String name ) { + scaName = name; + } + + public String getSCAName() { + return scaName; + } + + public boolean isSCATyped() { + return ( !(scaType == null) ); + } + + public void setAsReference( String name ) { + scaType = REFERENCE_TYPE; + scaName = name; + } + + public void setAsService( String name ) { + scaType = SERVICE_TYPE; + scaName = name; + } + + public String querySCAType() { + return scaType; + } + +} // end class BPELPartnerLinkElement diff --git a/java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/xml/BPELPartnerLinkTypeElement.java b/java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/xml/BPELPartnerLinkTypeElement.java new file mode 100644 index 0000000000..fdaf98a97f --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel/src/main/java/org/apache/tuscany/sca/implementation/bpel/xml/BPELPartnerLinkTypeElement.java @@ -0,0 +1,112 @@ +/* + * 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. + */package org.apache.tuscany.sca.implementation.bpel.xml; + + import javax.xml.namespace.QName; + + import javax.wsdl.extensions.ExtensibilityElement; + import javax.wsdl.PortType; + +/** + * Represents a element related to a BPEL process + * - this has attributes: + * name + * Role1 name + * Role1 portType + * Role2 name + * Role2 portType + * + * - in the XML the 2 roles are child elements of the partnerLinkType element, but there + * seems little point in reflecting this back into this model - it is simpler to include + * both roles within the representation of the partnerLinkType itself + * + * @version $Rev$ $Date$ + */ +public class BPELPartnerLinkTypeElement implements ExtensibilityElement { + + private QName name; + private String Role1name = null; + private QName Role1porttype = null; + private PortType Role1pType = null; + private String Role2name = null; + private QName Role2porttype = null; + private PortType Role2pType = null; + private QName elementType = null; + private Boolean required = false; + + public BPELPartnerLinkTypeElement(QName name) { + this.name = name; + } + + public QName getName() { + return name; + } + + public void setRole1(String name, QName portType, PortType pType) { + Role1name = name; + Role1porttype = portType; + Role1pType = pType; + } + + public void setRole2(String name, QName portType, PortType pType) { + Role2name = name; + Role2porttype = portType; + Role2pType = pType; + } + + public String getRole1Name() { + return Role1name; + } + + public String getRole2Name() { + return Role2name; + } + + public QName getRole1PortType() { + return Role1porttype; + } + + public QName getRole2PortType() { + return Role2porttype; + } + + public PortType getRole1pType() { + return Role1pType; + } + + public PortType getRole2pType() { + return Role2pType; + } + + public QName getElementType() { + return elementType; + } + + public Boolean getRequired() { + return required; + } + + public void setElementType(QName elementType) { + this.elementType = elementType; + } + + public void setRequired(java.lang.Boolean required) { + this.required = required; + } + +} // end BPELPartnerLinkType diff --git a/java/sca/contrib/modules/implementation-bpel/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor b/java/sca/contrib/modules/implementation-bpel/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor new file mode 100644 index 0000000000..03ef3e3a7f --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for the artifact processor extension +org.apache.tuscany.sca.implementation.bpel.xml.BPELImplementationProcessor;qname=http://www.osoa.org/xmlns/sca/1.0#implementation.bpel,model=org.apache.tuscany.sca.implementation.bpel.BPELImplementation \ No newline at end of file diff --git a/java/sca/contrib/modules/implementation-bpel/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.URLArtifactProcessor b/java/sca/contrib/modules/implementation-bpel/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.URLArtifactProcessor new file mode 100644 index 0000000000..f6fd442f56 --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.URLArtifactProcessor @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for the artifact processor extension +org.apache.tuscany.sca.implementation.bpel.xml.BPELDocumentProcessor;type=.bpel,model=org.apache.tuscany.sca.implementation.bpel.BPELProcessDefinition \ No newline at end of file diff --git a/java/sca/contrib/modules/implementation-bpel/src/main/resources/META-INF/services/org.apache.tuscany.sca.implementation.bpel.BPELFactory b/java/sca/contrib/modules/implementation-bpel/src/main/resources/META-INF/services/org.apache.tuscany.sca.implementation.bpel.BPELFactory new file mode 100644 index 0000000000..4276e938f1 --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel/src/main/resources/META-INF/services/org.apache.tuscany.sca.implementation.bpel.BPELFactory @@ -0,0 +1,18 @@ +# 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. + +org.apache.tuscany.sca.implementation.bpel.impl.BPELFactoryImpl diff --git a/java/sca/contrib/modules/implementation-bpel/src/main/resources/impl-bpel-validation-messages.properties b/java/sca/contrib/modules/implementation-bpel/src/main/resources/impl-bpel-validation-messages.properties new file mode 100644 index 0000000000..b6d8bdc0f1 --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel/src/main/resources/impl-bpel-validation-messages.properties @@ -0,0 +1,34 @@ +# +# +# 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. +# +# +CannotResolveWSDLReference = BPELDocumentProcessor:resolve - unable to resolve WSDL referenced by BPEL import WSDL location: {0} WSDLNamespace: {1} +ContributionReadException = ContributionReadException occured due to : +PartnerLinkNoMatchingType = PartnerLink {0} has no matching partner link type +PartnerLinkTypeNoRoles = PartnerLinkType {0} has no Roles defined +ContributionResolveException = ContributionResolveException occured due to : +PartnerLinkHasBothAttr = BPEL PartnerLink {0} has both sca:reference and sca:service attributes set +ReferencePartnerLinkNotInList = BPEL TypeLoader - element references partnerLink {0} not in the list +MyRolePartnerRoleNull = Error: myRole and partnerRole port types are both null +NoInterfaceForPortType = Interface not found for port type {0} +AttributeProcessMissing = Attribute 'process' is missing. +AttributeWithoutNamespace = Attribute {0} with value {1} in your composite should be of the form {namespaceURI}localname +AttributeWithoutPrefix = Attribute {0} with value {1} in your composite should be prefixed (process=\"prefix:name\"). +AttributeUnrecognizedNamespace = Attribute {0} with value {1} in your composite has un unrecognized namespace prefix. +BPELProcessNotFound = Can't find BPEL Process : {0} \ No newline at end of file diff --git a/java/sca/contrib/modules/implementation-bpel/src/test/java/org/apache/tuscany/sca/implementation/bpel/BPELDocumentProcessorTestCase.java b/java/sca/contrib/modules/implementation-bpel/src/test/java/org/apache/tuscany/sca/implementation/bpel/BPELDocumentProcessorTestCase.java new file mode 100644 index 0000000000..e355b7adf9 --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel/src/test/java/org/apache/tuscany/sca/implementation/bpel/BPELDocumentProcessorTestCase.java @@ -0,0 +1,59 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.implementation.bpel; + +import java.net.URI; +import java.net.URL; + +import javax.xml.namespace.QName; + +import junit.framework.TestCase; + +import org.apache.tuscany.sca.contribution.processor.ExtensibleURLArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.URLArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.URLArtifactProcessorExtensionPoint; +import org.apache.tuscany.sca.core.DefaultExtensionPointRegistry; + +/** + * @version $Rev$ $Date$ + */ +public class BPELDocumentProcessorTestCase extends TestCase { + + protected static final String BPEL_PROCESS_FILE = "helloworld/helloworld.bpel"; + + private URLArtifactProcessor documentProcessor; + + @Override + protected void setUp() throws Exception { + DefaultExtensionPointRegistry extensionPoints = new DefaultExtensionPointRegistry(); + URLArtifactProcessorExtensionPoint documentProcessors = extensionPoints.getExtensionPoint(URLArtifactProcessorExtensionPoint.class); + documentProcessor = new ExtensibleURLArtifactProcessor(documentProcessors, null); + } + + public void testLoadBPELProcessDefinition() throws Exception { + URI processURI = getClass().getClassLoader().getResource(BPEL_PROCESS_FILE).toURI(); + URL processLocation = getClass().getClassLoader().getResource(BPEL_PROCESS_FILE); + BPELProcessDefinition bpelProcessDefinition = (BPELProcessDefinition)documentProcessor.read(null, processURI, processLocation); + + assertNotNull(bpelProcessDefinition); + assertEquals(new QName("http://tuscany.apache.org/implementation/bpel/example/helloworld", "HelloWorld"), bpelProcessDefinition.getName()); + assertEquals(processLocation.toString(), bpelProcessDefinition.getLocation()); + } +} diff --git a/java/sca/contrib/modules/implementation-bpel/src/test/java/org/apache/tuscany/sca/implementation/bpel/BPELImplementationProcessorTestCase.java b/java/sca/contrib/modules/implementation-bpel/src/test/java/org/apache/tuscany/sca/implementation/bpel/BPELImplementationProcessorTestCase.java new file mode 100644 index 0000000000..28cc562a3b --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel/src/test/java/org/apache/tuscany/sca/implementation/bpel/BPELImplementationProcessorTestCase.java @@ -0,0 +1,107 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.implementation.bpel; + +import java.io.StringReader; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamReader; + +import junit.framework.TestCase; + +import org.apache.tuscany.sca.assembly.Composite; +import org.apache.tuscany.sca.contribution.processor.DefaultStAXArtifactProcessorExtensionPoint; +import org.apache.tuscany.sca.contribution.processor.ExtensibleStAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessorExtensionPoint; +import org.apache.tuscany.sca.core.DefaultExtensionPointRegistry; +import org.apache.tuscany.sca.core.UtilityExtensionPoint; +import org.apache.tuscany.sca.monitor.DefaultMonitorFactory; +import org.apache.tuscany.sca.monitor.Monitor; +import org.apache.tuscany.sca.monitor.MonitorFactory; +import org.apache.tuscany.sca.monitor.Problem; + +/** + * @version $Rev$ $Date$ + */ +public class BPELImplementationProcessorTestCase extends TestCase { + + private static final String COMPOSITE = + "" + + "" + + " " + + " " + + " " + + ""; + + private static final String COMPOSITE_INVALID = + "" + + "" + + " " + + " " + + " " + + ""; + + private XMLInputFactory inputFactory; + private StAXArtifactProcessor staxProcessor; + private Monitor monitor; + + @Override + protected void setUp() throws Exception { + DefaultExtensionPointRegistry extensionPoints = new DefaultExtensionPointRegistry(); + inputFactory = XMLInputFactory.newInstance(); + // Create a monitor + UtilityExtensionPoint utilities = extensionPoints.getExtensionPoint(UtilityExtensionPoint.class); + MonitorFactory monitorFactory = new DefaultMonitorFactory(); + if (monitorFactory != null) { + monitor = monitorFactory.createMonitor(); + utilities.addUtility(monitorFactory); + } + StAXArtifactProcessorExtensionPoint staxProcessors = new DefaultStAXArtifactProcessorExtensionPoint(extensionPoints); + staxProcessor = new ExtensibleStAXArtifactProcessor(staxProcessors, inputFactory, null, null); + } + + /** + * Test parsing valid composite definition. Valid composite populated with correct values expected. + * @throws Exception + */ + public void testLoadValidComposite() throws Exception { + XMLStreamReader reader = inputFactory.createXMLStreamReader(new StringReader(COMPOSITE)); + + Composite composite = (Composite)staxProcessor.read(reader); + BPELImplementation implementation = (BPELImplementation)composite.getComponents().get(0).getImplementation(); + + assertNotNull(implementation); + assertEquals(new QName("http://tuscany.apache.org/implementation/bpel/example/helloworld", "HelloWorld"), implementation.getProcess()); + } + + /** + * Test parsing invalid composite definition. Exception should be thrown + * @throws Exception + */ + public void testLoadInvalidComposite() throws Exception { + XMLStreamReader reader = inputFactory.createXMLStreamReader(new StringReader(COMPOSITE_INVALID)); + staxProcessor.read(reader); + Problem problem = monitor.getLastProblem(); + assertNotNull(problem); + assertEquals("AttributeProcessMissing", problem.getMessageId()); + } +} diff --git a/java/sca/contrib/modules/implementation-bpel/src/test/resources/helloworld/helloworld.bpel b/java/sca/contrib/modules/implementation-bpel/src/test/resources/helloworld/helloworld.bpel new file mode 100644 index 0000000000..8cf91adc2c --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel/src/test/resources/helloworld/helloworld.bpel @@ -0,0 +1,66 @@ + + + + + + + + + + + + + + + + + + + + + + + + concat($tmpVar,' World') + + + + + + diff --git a/java/sca/contrib/modules/implementation-bpel/src/test/resources/helloworld/helloworld.wsdl b/java/sca/contrib/modules/implementation-bpel/src/test/resources/helloworld/helloworld.wsdl new file mode 100644 index 0000000000..1d71727b2d --- /dev/null +++ b/java/sca/contrib/modules/implementation-bpel/src/test/resources/helloworld/helloworld.wsdl @@ -0,0 +1,82 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/java/sca/contrib/modules/implementation-ejb/LICENSE b/java/sca/contrib/modules/implementation-ejb/LICENSE new file mode 100644 index 0000000000..8aa906c321 --- /dev/null +++ b/java/sca/contrib/modules/implementation-ejb/LICENSE @@ -0,0 +1,205 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + + diff --git a/java/sca/contrib/modules/implementation-ejb/META-INF/MANIFEST.MF b/java/sca/contrib/modules/implementation-ejb/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..17dc48478c --- /dev/null +++ b/java/sca/contrib/modules/implementation-ejb/META-INF/MANIFEST.MF @@ -0,0 +1,29 @@ +Manifest-Version: 1.0 +Export-Package: org.apache.tuscany.sca.implementation.ejb;uses:="org.a + pache.tuscany.sca.assembly";version="2.0.0" +Private-Package: org.apache.tuscany.sca.implementation.ejb.impl;versio + n="1.4",org.apache.tuscany.sca.implementation.ejb.xml;version="2.0.0" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA EJB Session Bean Implementation Model +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397451671 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA EJB Session Bean Implementation + Model +Import-Package: javax.xml.namespace,javax.xml.stream,org.apache.tuscan + y.sca.assembly;version="2.0.0",org.apache.tuscany.sca.contribution.proc + essor;version="2.0.0",org.apache.tuscany.sca.contribution.resolver;vers + ion="1.4",org.apache.tuscany.sca.core;version="2.0.0",org.apache.tuscan + y.sca.implementation.ejb;version="2.0.0",org.apache.tuscany.sca.monitor + ;version="2.0.0",org.apache.tuscany.sca.assembly.builder.impl;resolutio + n:=optional,org.apache.tuscany.sca.definitions;version="2.0.0";resoluti + on:=optional,org.apache.tuscany.sca.policy;version="2.0.0";resolution:= + optional,org.apache.tuscany.sca.interfacedef;version="2.0.0";resolution + :=optional,org.apache.tuscany.sc + a.assembly.builder;version="2.0.0";resolution:=optional +Bundle-SymbolicName: org.apache.tuscany.sca.implementation.ejb +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/implementation-ejb/NOTICE b/java/sca/contrib/modules/implementation-ejb/NOTICE new file mode 100644 index 0000000000..25bb89c9b2 --- /dev/null +++ b/java/sca/contrib/modules/implementation-ejb/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/implementation-ejb/pom.xml b/java/sca/contrib/modules/implementation-ejb/pom.xml new file mode 100644 index 0000000000..472f8f81ed --- /dev/null +++ b/java/sca/contrib/modules/implementation-ejb/pom.xml @@ -0,0 +1,62 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + + tuscany-implementation-ejb + Apache Tuscany SCA EJB Session Bean Implementation Model + + + + + org.apache.tuscany.sca + tuscany-assembly + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-assembly-xml + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-node-impl + 2.0-SNAPSHOT + test + + + + junit + junit + 4.5 + test + + + + + diff --git a/java/sca/contrib/modules/implementation-ejb/src/main/java/org/apache/tuscany/sca/implementation/ejb/EJBImplementation.java b/java/sca/contrib/modules/implementation-ejb/src/main/java/org/apache/tuscany/sca/implementation/ejb/EJBImplementation.java new file mode 100644 index 0000000000..0d3b05f0c9 --- /dev/null +++ b/java/sca/contrib/modules/implementation-ejb/src/main/java/org/apache/tuscany/sca/implementation/ejb/EJBImplementation.java @@ -0,0 +1,44 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.implementation.ejb; + +import org.apache.tuscany.sca.assembly.Implementation; + + + +/** + * The model representing an EJB implementation in an SCA assembly model. + * + * @version $Rev$ $Date$ + */ +public interface EJBImplementation extends Implementation { + + /** + * Returns the EJB link URI. + * @return the EJB link URI + */ + String getEJBLink(); + + /** + * Sets the EJB link URI. + * @param ejbLink the EJB link URI + */ + void setEJBLink(String ejbLink); + +} diff --git a/java/sca/contrib/modules/implementation-ejb/src/main/java/org/apache/tuscany/sca/implementation/ejb/EJBImplementationFactory.java b/java/sca/contrib/modules/implementation-ejb/src/main/java/org/apache/tuscany/sca/implementation/ejb/EJBImplementationFactory.java new file mode 100644 index 0000000000..bf9e13069b --- /dev/null +++ b/java/sca/contrib/modules/implementation-ejb/src/main/java/org/apache/tuscany/sca/implementation/ejb/EJBImplementationFactory.java @@ -0,0 +1,36 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.implementation.ejb; + + +/** + * Factory for the EJB implementation model. + * + * @version $Rev$ $Date$ + */ +public interface EJBImplementationFactory { + + /** + * Creates a new EJB implementation. + * @return a new EJB implementation + */ + EJBImplementation createEJBImplementation(); + +} diff --git a/java/sca/contrib/modules/implementation-ejb/src/main/java/org/apache/tuscany/sca/implementation/ejb/impl/EJBImplementationFactoryImpl.java b/java/sca/contrib/modules/implementation-ejb/src/main/java/org/apache/tuscany/sca/implementation/ejb/impl/EJBImplementationFactoryImpl.java new file mode 100644 index 0000000000..050d0cf17a --- /dev/null +++ b/java/sca/contrib/modules/implementation-ejb/src/main/java/org/apache/tuscany/sca/implementation/ejb/impl/EJBImplementationFactoryImpl.java @@ -0,0 +1,39 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.implementation.ejb.impl; + +import org.apache.tuscany.sca.implementation.ejb.EJBImplementation; +import org.apache.tuscany.sca.implementation.ejb.EJBImplementationFactory; + +/** + * Factory for the EJB implementation model. + * + * @version $Rev$ $Date$ + */ +public class EJBImplementationFactoryImpl implements EJBImplementationFactory { + + public EJBImplementationFactoryImpl() { + } + + public EJBImplementation createEJBImplementation() { + return new EJBImplementationImpl(); + } + +} diff --git a/java/sca/contrib/modules/implementation-ejb/src/main/java/org/apache/tuscany/sca/implementation/ejb/impl/EJBImplementationImpl.java b/java/sca/contrib/modules/implementation-ejb/src/main/java/org/apache/tuscany/sca/implementation/ejb/impl/EJBImplementationImpl.java new file mode 100644 index 0000000000..bf2e6354d5 --- /dev/null +++ b/java/sca/contrib/modules/implementation-ejb/src/main/java/org/apache/tuscany/sca/implementation/ejb/impl/EJBImplementationImpl.java @@ -0,0 +1,95 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.implementation.ejb.impl; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.tuscany.sca.assembly.ConstrainingType; +import org.apache.tuscany.sca.assembly.Property; +import org.apache.tuscany.sca.assembly.Reference; +import org.apache.tuscany.sca.assembly.Service; +import org.apache.tuscany.sca.implementation.ejb.EJBImplementation; + + +/** + * The model representing an EJB implementation in an SCA assembly model. + * + * @version $Rev$ $Date$ + */ +class EJBImplementationImpl implements EJBImplementation { + + private List properties = new ArrayList(); + private List services = new ArrayList(); + private List references = new ArrayList(); + private String ejbLink; + private String uri; + private boolean unresolved; + + /** + * Constructs a new EJB implementation. + */ + EJBImplementationImpl() { + } + + public ConstrainingType getConstrainingType() { + // The EJB implementation does not support constrainingTypes + return null; + } + + public List getProperties() { + return properties; + } + + public List getServices() { + return services; + } + + public List getReferences() { + return references; + } + + public String getEJBLink() { + return ejbLink; + } + + public void setConstrainingType(ConstrainingType constrainingType) { + // The EJB implementation does not support constrainingTypes + } + + public void setEJBLink(String ejbLink) { + this.ejbLink = ejbLink; + } + + public String getURI() { + return uri; + } + + public void setURI(String uri) { + this.uri = uri; + } + + public boolean isUnresolved() { + return unresolved; + } + + public void setUnresolved(boolean unresolved) { + this.unresolved = unresolved; + } +} diff --git a/java/sca/contrib/modules/implementation-ejb/src/main/java/org/apache/tuscany/sca/implementation/ejb/xml/EJBImplementationProcessor.java b/java/sca/contrib/modules/implementation-ejb/src/main/java/org/apache/tuscany/sca/implementation/ejb/xml/EJBImplementationProcessor.java new file mode 100644 index 0000000000..573bd7ef17 --- /dev/null +++ b/java/sca/contrib/modules/implementation-ejb/src/main/java/org/apache/tuscany/sca/implementation/ejb/xml/EJBImplementationProcessor.java @@ -0,0 +1,147 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.implementation.ejb.xml; + +import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; + +import org.apache.tuscany.sca.assembly.AssemblyFactory; +import org.apache.tuscany.sca.assembly.ComponentType; +import org.apache.tuscany.sca.contribution.processor.BaseStAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.ContributionReadException; +import org.apache.tuscany.sca.contribution.processor.ContributionResolveException; +import org.apache.tuscany.sca.contribution.processor.ContributionWriteException; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.core.FactoryExtensionPoint; +import org.apache.tuscany.sca.implementation.ejb.EJBImplementation; +import org.apache.tuscany.sca.implementation.ejb.EJBImplementationFactory; +import org.apache.tuscany.sca.monitor.Monitor; +import org.apache.tuscany.sca.monitor.Problem; +import org.apache.tuscany.sca.monitor.Problem.Severity; + + +/** + * Implements a StAX artifact processor for EJB implementations. + * + * @version $Rev$ $Date$ + */ +public class EJBImplementationProcessor extends BaseStAXArtifactProcessor implements StAXArtifactProcessor { + private static final String SCA10_NS = "http://www.osoa.org/xmlns/sca/1.0"; + private static final QName IMPLEMENTATION_EJB = new QName(SCA10_NS, "implementation.ejb"); + + private AssemblyFactory assemblyFactory; + private EJBImplementationFactory implementationFactory; + private Monitor monitor; + + public EJBImplementationProcessor(FactoryExtensionPoint modelFactories, Monitor monitor) { + this.assemblyFactory = modelFactories.getFactory(AssemblyFactory.class); + this.implementationFactory = modelFactories.getFactory(EJBImplementationFactory.class); + this.monitor = monitor; + } + + /** + * Report a error. + * + * @param problems + * @param message + * @param model + */ + private void error(String message, Object model, Object... messageParameters) { + if (monitor != null) { + Problem problem = monitor.createProblem(this.getClass().getName(), "impl-ejb-validation-messages", Severity.ERROR, model, message, (Object[])messageParameters); + monitor.problem(problem); + } + } + + public QName getArtifactType() { + // Returns the QName of the XML element processed by this processor + return IMPLEMENTATION_EJB; + } + + public Class getModelType() { + // Returns the type of model processed by this processor + return EJBImplementation.class; + } + + public EJBImplementation read(XMLStreamReader reader) throws ContributionReadException, XMLStreamException { + + // Read an element + EJBImplementation implementation = implementationFactory.createEJBImplementation(); + implementation.setUnresolved(true); + + // Read the ejb-link attribute + String ejbLink = getString(reader, "ejb-link"); + if (ejbLink != null) { + implementation.setEJBLink(ejbLink); + + // Set the URI of the component type + //implementation.setURI(ejbLink.replace('#', '/')); + int hashPosition = ejbLink.indexOf('#'); + if (hashPosition >= 0) { + implementation.setURI(ejbLink.substring(hashPosition + 1)); + } else { + implementation.setURI(ejbLink); + } + } else { + error("EJBLinkAttributeMissing", reader); + } + + // Skip to end element + while (reader.hasNext()) { + if (reader.next() == END_ELEMENT && IMPLEMENTATION_EJB.equals(reader.getName())) { + break; + } + } + + return implementation; + } + + public void resolve(EJBImplementation implementation, ModelResolver resolver) throws ContributionResolveException { + + // Resolve the component type + String uri = implementation.getURI(); + if (uri != null) { + ComponentType componentType = assemblyFactory.createComponentType(); + componentType.setURI(uri + ".componentType"); + componentType = resolver.resolveModel(ComponentType.class, componentType); + if (!componentType.isUnresolved()) { + + // Initialize the implementation's services, references and properties + implementation.getServices().addAll(componentType.getServices()); + implementation.getReferences().addAll(componentType.getReferences()); + implementation.getProperties().addAll(componentType.getProperties()); + } + } + implementation.setUnresolved(false); + } + + public void write(EJBImplementation implementation, XMLStreamWriter writer) throws ContributionWriteException, XMLStreamException { + + // Write + writeStart(writer, IMPLEMENTATION_EJB.getNamespaceURI(), IMPLEMENTATION_EJB.getLocalPart(), + new XAttr("ejb-link", implementation.getEJBLink())); + + writeEnd(writer); + } +} diff --git a/java/sca/contrib/modules/implementation-ejb/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor b/java/sca/contrib/modules/implementation-ejb/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor new file mode 100644 index 0000000000..ae6db609a2 --- /dev/null +++ b/java/sca/contrib/modules/implementation-ejb/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for the artifact processor extension +org.apache.tuscany.sca.implementation.ejb.xml.EJBImplementationProcessor;qname=http://www.osoa.org/xmlns/sca/1.0#implementation.ejb,model=org.apache.tuscany.sca.implementation.ejb.EJBImplementation,factory=org.apache.tuscany.sca.implementation.ejb.EJBImplementationFactory diff --git a/java/sca/contrib/modules/implementation-ejb/src/main/resources/META-INF/services/org.apache.tuscany.sca.implementation.ejb.EJBImplementationFactory b/java/sca/contrib/modules/implementation-ejb/src/main/resources/META-INF/services/org.apache.tuscany.sca.implementation.ejb.EJBImplementationFactory new file mode 100644 index 0000000000..fb828707a6 --- /dev/null +++ b/java/sca/contrib/modules/implementation-ejb/src/main/resources/META-INF/services/org.apache.tuscany.sca.implementation.ejb.EJBImplementationFactory @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for model factory +org.apache.tuscany.sca.implementation.ejb.impl.EJBImplementationFactoryImpl diff --git a/java/sca/contrib/modules/implementation-ejb/src/main/resources/impl-ejb-validation-messages.properties b/java/sca/contrib/modules/implementation-ejb/src/main/resources/impl-ejb-validation-messages.properties new file mode 100644 index 0000000000..4eaf2b9007 --- /dev/null +++ b/java/sca/contrib/modules/implementation-ejb/src/main/resources/impl-ejb-validation-messages.properties @@ -0,0 +1,21 @@ +# +# +# 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. +# +# +EJBLinkAttributeMissing = Reading implementation.ejb - ejb-link attribute missing \ No newline at end of file diff --git a/java/sca/contrib/modules/implementation-ejb/src/test/java/org/apache/tuscany/sca/implementation/ejb/xml/ReadTestCase.java b/java/sca/contrib/modules/implementation-ejb/src/test/java/org/apache/tuscany/sca/implementation/ejb/xml/ReadTestCase.java new file mode 100644 index 0000000000..ffbdf1d54c --- /dev/null +++ b/java/sca/contrib/modules/implementation-ejb/src/test/java/org/apache/tuscany/sca/implementation/ejb/xml/ReadTestCase.java @@ -0,0 +1,71 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.implementation.ejb.xml; + +import java.io.InputStream; + +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamReader; + +import junit.framework.TestCase; + +import org.apache.tuscany.sca.assembly.Composite; +import org.apache.tuscany.sca.assembly.builder.CompositeBuilder; +import org.apache.tuscany.sca.assembly.builder.CompositeBuilderExtensionPoint; +import org.apache.tuscany.sca.contribution.processor.DefaultStAXArtifactProcessorExtensionPoint; +import org.apache.tuscany.sca.contribution.processor.ExtensibleStAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessorExtensionPoint; +import org.apache.tuscany.sca.core.DefaultExtensionPointRegistry; +import org.apache.tuscany.sca.implementation.ejb.EJBImplementation; + +/** + * Test reading Node implementations. + * + * @version $Rev$ $Date$ + */ +public class ReadTestCase extends TestCase { + + private XMLInputFactory inputFactory; + private StAXArtifactProcessor staxProcessor; + private CompositeBuilder compositeBuilder; + + @Override + public void setUp() throws Exception { + DefaultExtensionPointRegistry extensionPoints = new DefaultExtensionPointRegistry(); + inputFactory = XMLInputFactory.newInstance(); + StAXArtifactProcessorExtensionPoint staxProcessors = new DefaultStAXArtifactProcessorExtensionPoint(extensionPoints); + staxProcessor = new ExtensibleStAXArtifactProcessor(staxProcessors, inputFactory, null, null); + + compositeBuilder = extensionPoints.getExtensionPoint(CompositeBuilderExtensionPoint.class).getCompositeBuilder("org.apache.tuscany.sca.assembly.builder.CompositeBuilder"); + } + + public void testReadComposite() throws Exception { + InputStream is = getClass().getResourceAsStream("TestEJB.composite"); + XMLStreamReader reader = inputFactory.createXMLStreamReader(is); + Composite composite = (Composite) staxProcessor.read(reader); + assertNotNull(composite); + + compositeBuilder.build(composite, null, null); + + assertTrue(((EJBImplementation) composite.getComponents().get(0).getImplementation()).getEJBLink().equals("module.jar#TestEJB")); + } + +} diff --git a/java/sca/contrib/modules/implementation-ejb/src/test/java/org/apache/tuscany/sca/implementation/ejb/xml/WriteTestCase.java b/java/sca/contrib/modules/implementation-ejb/src/test/java/org/apache/tuscany/sca/implementation/ejb/xml/WriteTestCase.java new file mode 100644 index 0000000000..8ba43dd635 --- /dev/null +++ b/java/sca/contrib/modules/implementation-ejb/src/test/java/org/apache/tuscany/sca/implementation/ejb/xml/WriteTestCase.java @@ -0,0 +1,68 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.implementation.ejb.xml; + +import java.io.ByteArrayOutputStream; +import java.io.InputStream; + +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLOutputFactory; + +import junit.framework.TestCase; + +import org.apache.tuscany.sca.assembly.Composite; +import org.apache.tuscany.sca.contribution.processor.DefaultStAXArtifactProcessorExtensionPoint; +import org.apache.tuscany.sca.contribution.processor.ExtensibleStAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessorExtensionPoint; +import org.apache.tuscany.sca.core.DefaultExtensionPointRegistry; + +/** + * Test reading/write WSDL interfaces. + * + * @version $Rev$ $Date$ + */ +public class WriteTestCase extends TestCase { + + private XMLInputFactory inputFactory; + private XMLOutputFactory outputFactory; + private StAXArtifactProcessor staxProcessor; + + @Override + public void setUp() throws Exception { + DefaultExtensionPointRegistry extensionPoints = new DefaultExtensionPointRegistry(); + inputFactory = XMLInputFactory.newInstance(); + outputFactory = XMLOutputFactory.newInstance(); + StAXArtifactProcessorExtensionPoint staxProcessors = new DefaultStAXArtifactProcessorExtensionPoint(extensionPoints); + staxProcessor = new ExtensibleStAXArtifactProcessor(staxProcessors, inputFactory, outputFactory, null); + } + + public void testReadWriteComposite() throws Exception { + InputStream is = getClass().getResourceAsStream("TestEJB.composite"); + Composite composite = (Composite) staxProcessor.read(inputFactory.createXMLStreamReader(is)); + assertNotNull(composite); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + staxProcessor.write(composite, outputFactory.createXMLStreamWriter(bos)); + + assertTrue(bos.toString().contains("module.jar#TestEJB")); + + } + +} diff --git a/java/sca/contrib/modules/implementation-ejb/src/test/resources/org/apache/tuscany/sca/implementation/ejb/xml/TestEJB.composite b/java/sca/contrib/modules/implementation-ejb/src/test/resources/org/apache/tuscany/sca/implementation/ejb/xml/TestEJB.composite new file mode 100644 index 0000000000..0c1368c4dd --- /dev/null +++ b/java/sca/contrib/modules/implementation-ejb/src/test/resources/org/apache/tuscany/sca/implementation/ejb/xml/TestEJB.composite @@ -0,0 +1,29 @@ + + + + + + + + + diff --git a/java/sca/contrib/modules/implementation-osgi/LICENSE b/java/sca/contrib/modules/implementation-osgi/LICENSE new file mode 100644 index 0000000000..6b0b1270ff --- /dev/null +++ b/java/sca/contrib/modules/implementation-osgi/LICENSE @@ -0,0 +1,203 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + diff --git a/java/sca/contrib/modules/implementation-osgi/NOTICE b/java/sca/contrib/modules/implementation-osgi/NOTICE new file mode 100644 index 0000000000..25bb89c9b2 --- /dev/null +++ b/java/sca/contrib/modules/implementation-osgi/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/implementation-osgi/pom.xml b/java/sca/contrib/modules/implementation-osgi/pom.xml new file mode 100644 index 0000000000..fbe98efefc --- /dev/null +++ b/java/sca/contrib/modules/implementation-osgi/pom.xml @@ -0,0 +1,145 @@ + + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + + tuscany-implementation-osgi + Apache Tuscany SCA OSGi Implementation Extension + + jar + + + + + org.apache.felix + org.apache.felix.main + 1.0.4 + + + + + org.apache.tuscany.sca + tuscany-host-embedded + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-sca-api + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-core + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-interface + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-interface-java + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-interface-java-xml + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-implementation-java + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-implementation-java-runtime + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-implementation-java-xml + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-assembly-xml + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-databinding + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-contribution-osgi + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-osgi-runtime + 2.0-SNAPSHOT + + + + junit + junit + 4.5 + test + + + + org.easymock + easymock + 2.2 + test + + + + org.apache.tuscany.sca + tuscany-binding-sca + 2.0-SNAPSHOT + test + + + + + diff --git a/java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/OSGiImplementation.java b/java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/OSGiImplementation.java new file mode 100644 index 0000000000..7bcb0a1da5 --- /dev/null +++ b/java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/OSGiImplementation.java @@ -0,0 +1,45 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.implementation.osgi; + +import java.util.List; + +import org.apache.tuscany.sca.assembly.ComponentProperty; +import org.apache.tuscany.sca.assembly.Extensible; +import org.apache.tuscany.sca.assembly.Implementation; + +/** + * + * The model representing an OSGi implementation in an SCA assembly model. + * + * @version $Rev$ $Date$ + */ +public interface OSGiImplementation extends Implementation, Extensible { + + String getBundleSymbolicName(); + + String getBundleVersion(); + + String[] getImports(); + + List getReferenceProperties(String referenceName); + + List getServiceProperties(String serviceName); + +} diff --git a/java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/context/OSGiAnnotations.java b/java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/context/OSGiAnnotations.java new file mode 100644 index 0000000000..e5a726c8c0 --- /dev/null +++ b/java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/context/OSGiAnnotations.java @@ -0,0 +1,325 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.implementation.osgi.context; + + +import java.lang.reflect.Method; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.ArrayList; +import java.util.Hashtable; + +import org.apache.tuscany.sca.assembly.AssemblyFactory; +import org.apache.tuscany.sca.context.RequestContextFactory; +import org.apache.tuscany.sca.contribution.ModelFactoryExtensionPoint; +import org.apache.tuscany.sca.core.invocation.ProxyFactory; +import org.apache.tuscany.sca.core.scope.Scope; +import org.apache.tuscany.sca.implementation.java.DefaultJavaImplementationFactory; +import org.apache.tuscany.sca.implementation.java.IntrospectionException; +import org.apache.tuscany.sca.implementation.java.JavaImplementation; +import org.apache.tuscany.sca.implementation.java.JavaImplementationFactory; +import org.apache.tuscany.sca.implementation.java.impl.JavaScopeImpl; +import org.apache.tuscany.sca.implementation.java.injection.JavaPropertyValueObjectFactory; +import org.apache.tuscany.sca.implementation.java.introspect.JavaClassVisitor; +import org.apache.tuscany.sca.implementation.java.introspect.impl.AllowsPassByReferenceProcessor; +import org.apache.tuscany.sca.implementation.java.introspect.impl.BaseJavaClassVisitor; +import org.apache.tuscany.sca.implementation.java.introspect.impl.ComponentNameProcessor; +import org.apache.tuscany.sca.implementation.java.introspect.impl.ConstructorProcessor; +import org.apache.tuscany.sca.implementation.java.introspect.impl.ContextProcessor; +import org.apache.tuscany.sca.implementation.java.introspect.impl.ConversationProcessor; +import org.apache.tuscany.sca.implementation.java.introspect.impl.DestroyProcessor; +import org.apache.tuscany.sca.implementation.java.introspect.impl.EagerInitProcessor; +import org.apache.tuscany.sca.implementation.java.introspect.impl.HeuristicPojoProcessor; +import org.apache.tuscany.sca.implementation.java.introspect.impl.InitProcessor; +import org.apache.tuscany.sca.implementation.java.introspect.impl.PolicyProcessor; +import org.apache.tuscany.sca.implementation.java.introspect.impl.PropertyProcessor; +import org.apache.tuscany.sca.implementation.java.introspect.impl.ReferenceProcessor; +import org.apache.tuscany.sca.implementation.java.introspect.impl.ResourceProcessor; +import org.apache.tuscany.sca.implementation.java.introspect.impl.ServiceProcessor; +import org.apache.tuscany.sca.interfacedef.java.JavaInterfaceFactory; +import org.apache.tuscany.sca.policy.PolicyFactory; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.osgi.framework.Bundle; + + +/** + * OSGi annotation processing + * OSGi bundles are not introspected by OSGiImplementation when a component is created. + * Instead if the list of implementation classes is specified in , + * the classes are introspected when the bundle is resolved. The classes are loaded using + * the bundle ClassLoader, and hence the delay in annotation processing is inevitable. + * There is one other difference compared to implementation.java. While instances (and + * the instance class) are associated with a component in Java, all Java annotations from + * the component implementation class apply to all the component instances. In OSGi, + * instances are associated with services, and a bundle can register multiple services. + * Hence annotations from classes need to be stored separately so that the right ones + * can be associated with the service instance. + * + * @version $Rev$ $Date$ + */ +public class OSGiAnnotations { + + private Scope scope = Scope.COMPOSITE; + private boolean isEagerInit; + + private String[] classList; + + private Bundle[] bundles; + + private RuntimeComponent runtimeComponent; + private JavaPropertyValueObjectFactory propertyValueFactory; + private ProxyFactory proxyFactory; + + private JavaImplementationFactory javaImplementationFactory; + private JavaInterfaceFactory javaInterfaceFactory; + private PolicyFactory policyFactory; + private RequestContextFactory requestContextFactory; + + private Hashtable, JavaImplementation> javaAnnotationInfo = + new Hashtable, JavaImplementation>(); + private Hashtable propertyInjectors = + new Hashtable(); + + private long maxAge = -1; + private long maxIdleTime = -1; + + private boolean annotationsProcessed; + + + + public OSGiAnnotations(ModelFactoryExtensionPoint modelFactories, + String[] classList, + RuntimeComponent runtimeComponent, + JavaPropertyValueObjectFactory propertyValueFactory, + ProxyFactory proxyFactory, + RequestContextFactory requestContextFactory, + Bundle mainBundle, + ArrayList dependentBundles) { + + + this.classList = classList; + this.runtimeComponent = runtimeComponent; + this.propertyValueFactory = propertyValueFactory; + this.proxyFactory = proxyFactory; + + AssemblyFactory assemblyFactory = modelFactories.getFactory(AssemblyFactory.class); + this.javaInterfaceFactory = modelFactories.getFactory(JavaInterfaceFactory.class); + this.javaImplementationFactory = createJavaImplementationFactory(assemblyFactory); + this.policyFactory = modelFactories.getFactory(PolicyFactory.class); + + bundles = new Bundle[dependentBundles.size() + 1]; + bundles[0] = mainBundle; + for (int i = 0; i < dependentBundles.size(); i++) + bundles[i + 1] = dependentBundles.get(i); + + } + + + public void processAnnotations() throws IntrospectionException { + + if (annotationsProcessed) + return; + annotationsProcessed = true; + for (String className : classList) { + for (Bundle bundle : bundles) { + try { + Class clazz = bundle.loadClass(className); + + processAnnotations(clazz); + + break; + + } catch (ClassNotFoundException e) { + } + } + } + } + + + public void injectProperties(Object instance) { + JavaImplementation javaImpl = getAnnotationInfo(instance); + if (javaImpl != null) { + OSGiPropertyInjector injector = propertyInjectors.get(javaImpl); + if (injector != null) + injector.injectProperties(instance); + } + } + + + public Scope getScope() { + return scope; + } + + + + public boolean isAllowsPassByReference(Object instance, Method method) { + + JavaImplementation javaImpl = getAnnotationInfo(instance); + if (javaImpl == null) { + return false; + } + if (javaImpl.isAllowsPassByReference()) { + return true; + } + return javaImpl.isAllowsPassByReference(method); + } + + + public boolean isEagerInit() { + return isEagerInit; + } + + public long getMaxAge() { + return maxAge; + } + + public long getMaxIdleTime() { + return maxIdleTime; + } + + public Method getInitMethod(Object instance) { + JavaImplementation javaImpl = getAnnotationInfo(instance); + return javaImpl == null? null : javaImpl.getInitMethod(); + } + + + public Method getDestroyMethod(Object instance) { + JavaImplementation javaImpl = getAnnotationInfo(instance); + return javaImpl == null? null : javaImpl.getDestroyMethod(); + } + + + /* + * Get the annotation corresponding to an instance + * + */ + private JavaImplementation getAnnotationInfo(final Object instance) { + + // The simplest case where the implementation class was listed under the + // classes attribute of , or this is the second call + // to this method for the implementation class. + // Allow privileged access to get classloader. Requires getClassLoader in security policy. + JavaImplementation javaImpl = AccessController.doPrivileged(new PrivilegedAction() { + public JavaImplementation run() { + return javaAnnotationInfo.get(instance.getClass()); + } + }); + if (javaImpl != null) + return javaImpl; + + // Process annotations from the instance class. + try { + return processAnnotations(instance.getClass()); + } catch (IntrospectionException e) { + // e.printStackTrace(); + } + + return null; + } + + + private JavaImplementation processAnnotations(Class clazz) + throws IntrospectionException { + + JavaImplementation javaImpl = javaImplementationFactory.createJavaImplementation(clazz); + + javaAnnotationInfo.put(clazz, javaImpl); + + OSGiPropertyInjector propertyInjector = new OSGiPropertyInjector( + javaImpl, runtimeComponent, propertyValueFactory, proxyFactory, requestContextFactory); + + propertyInjectors.put(javaImpl, propertyInjector); + + if (javaImpl.isEagerInit()) + isEagerInit = true; + if (javaImpl.getMaxAge() != -1) + maxAge = javaImpl.getMaxAge(); + if (javaImpl.getMaxIdleTime() != -1) + maxIdleTime = javaImpl.getMaxIdleTime(); + if (javaImpl.getJavaScope() != JavaScopeImpl.COMPOSITE) + scope = new Scope(javaImpl.getJavaScope().getScope()); + + return javaImpl; + } + + + + + private JavaImplementationFactory createJavaImplementationFactory(AssemblyFactory assemblyFactory) { + JavaImplementationFactory javaImplementationFactory = new DefaultJavaImplementationFactory(); + + // Create the list of class visitors + BaseJavaClassVisitor[] extensions = + new BaseJavaClassVisitor[] { + new ConstructorProcessor(assemblyFactory), + new AllowsPassByReferenceProcessor(assemblyFactory), + new ComponentNameProcessor(assemblyFactory), + new ContextProcessor(assemblyFactory), + new ConversationProcessor(assemblyFactory), + new DestroyProcessor(assemblyFactory), + new EagerInitProcessor(assemblyFactory), + new InitProcessor(assemblyFactory), + new PropertyProcessor(assemblyFactory), + new ReferenceProcessor(assemblyFactory, javaInterfaceFactory), + new ResourceProcessor(assemblyFactory), + new OSGiScopeProcessor(assemblyFactory), + new ServiceProcessor(assemblyFactory, javaInterfaceFactory), + new HeuristicPojoProcessor(assemblyFactory, javaInterfaceFactory), + new PolicyProcessor(assemblyFactory, policyFactory)}; + for (JavaClassVisitor extension : extensions) { + javaImplementationFactory.addClassVisitor(extension); + } + + return javaImplementationFactory; + } + + private class OSGiScopeProcessor extends BaseJavaClassVisitor { + + public OSGiScopeProcessor(AssemblyFactory factory) { + super(factory); + } + + @Override + public void visitClass(Class clazz, + JavaImplementation type) + throws IntrospectionException { + org.oasisopen.sca.annotation.Scope annotation = clazz.getAnnotation(org.oasisopen.sca.annotation.Scope.class); + if (annotation == null) { + type.setJavaScope(JavaScopeImpl.COMPOSITE); + return; + } + String name = annotation.value(); + JavaScopeImpl scope; + if ("COMPOSITE".equals(name)) { + scope = JavaScopeImpl.COMPOSITE; + } else if ("SESSION".equals(name)) { + scope = JavaScopeImpl.SESSION; + } else if ("CONVERSATION".equals(name)) { + scope = JavaScopeImpl.CONVERSATION; + } else if ("REQUEST".equals(name)) { + scope = JavaScopeImpl.REQUEST; + } else { + scope = new JavaScopeImpl(name); + } + type.setJavaScope(scope); + } + } + + +} diff --git a/java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/context/OSGiPropertyInjector.java b/java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/context/OSGiPropertyInjector.java new file mode 100644 index 0000000000..8eee337638 --- /dev/null +++ b/java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/context/OSGiPropertyInjector.java @@ -0,0 +1,293 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.implementation.osgi.context; + + +import java.lang.annotation.ElementType; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Member; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Hashtable; +import java.util.List; +import java.util.Map; + +import org.apache.tuscany.sca.assembly.ComponentProperty; +import org.apache.tuscany.sca.assembly.ComponentService; +import org.apache.tuscany.sca.context.RequestContextFactory; +import org.apache.tuscany.sca.core.context.RequestContextImpl; +import org.apache.tuscany.sca.core.factory.ObjectCreationException; +import org.apache.tuscany.sca.core.factory.ObjectFactory; +import org.apache.tuscany.sca.core.invocation.CallbackWireObjectFactory; +import org.apache.tuscany.sca.core.invocation.ProxyFactory; +import org.apache.tuscany.sca.implementation.java.IntrospectionException; +import org.apache.tuscany.sca.implementation.java.JavaImplementation; +import org.apache.tuscany.sca.implementation.java.impl.JavaElementImpl; +import org.apache.tuscany.sca.implementation.java.impl.JavaResourceImpl; +import org.apache.tuscany.sca.implementation.java.injection.ArrayMultiplicityObjectFactory; +import org.apache.tuscany.sca.implementation.java.injection.ConversationIDObjectFactory; +import org.apache.tuscany.sca.implementation.java.injection.FieldInjector; +import org.apache.tuscany.sca.implementation.java.injection.Injector; +import org.apache.tuscany.sca.implementation.java.injection.InvalidAccessorException; +import org.apache.tuscany.sca.implementation.java.injection.JavaPropertyValueObjectFactory; +import org.apache.tuscany.sca.implementation.java.injection.ListMultiplicityObjectFactory; +import org.apache.tuscany.sca.implementation.java.injection.MethodInjector; +import org.apache.tuscany.sca.implementation.java.injection.ResourceObjectFactory; +import org.apache.tuscany.sca.implementation.java.introspect.impl.JavaIntrospectionHelper; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeWire; +import org.oasisopen.sca.ComponentContext; +import org.oasisopen.sca.RequestContext; +import org.oasisopen.sca.annotation.ConversationID; + + +/** + * OSGi property injection support + * + * @version $Rev$ $Date$ + */ +public class OSGiPropertyInjector { + + + private ArrayList injectionSites = new ArrayList(); + private Hashtable factories = + new Hashtable(); + + private Injector[] injectors; + + public OSGiPropertyInjector( + JavaImplementation javaImpl, + RuntimeComponent component, + JavaPropertyValueObjectFactory propertyValueFactory, + ProxyFactory proxyFactory, + RequestContextFactory requestContextFactory) throws IntrospectionException { + + createInjectionSites(javaImpl, component, propertyValueFactory, proxyFactory, requestContextFactory); + + injectors = createInjectors(); + + } + + + @SuppressWarnings("unchecked") + public void injectProperties(Object instance) { + + for (Injector injector : injectors) { + injector.inject(instance); + } + + } + + + @SuppressWarnings("unchecked") + private void createInjectionSites( + JavaImplementation javaImpl, + RuntimeComponent component, + JavaPropertyValueObjectFactory propertyValueFactory, + ProxyFactory proxyFactory, + RequestContextFactory requestContextFactory) + { + + List componentProperties = component.getProperties(); + Map propertyMembers = javaImpl.getPropertyMembers(); + + for (ComponentProperty prop : componentProperties) { + JavaElementImpl element = propertyMembers.get(prop.getName()); + + if (element != null && !(element.getAnchor() instanceof Constructor) && prop.getValue() != null) { + Class propertyJavaType = JavaIntrospectionHelper.getBaseType(element.getType(), element.getGenericType()); + ObjectFactory objFactory = propertyValueFactory.createValueFactory(prop, prop.getValue(), propertyJavaType); + + factories.put(element, objFactory); + injectionSites.add(element); + } + } + + for (Member member : javaImpl.getConversationIDMembers()) { + ObjectFactory factory = new ConversationIDObjectFactory(); + if (member instanceof Field) { + JavaElementImpl element = new JavaElementImpl((Field) member); + element.setClassifer(ConversationID.class); + injectionSites.add(element); + factories.put(element, factory); + } else if (member instanceof Method) { + JavaElementImpl element = new JavaElementImpl((Method) member, 0); + element.setName(JavaIntrospectionHelper.toPropertyName(member.getName())); + element.setClassifer(ConversationID.class); + injectionSites.add(element); + factories.put(element, factory); + } else { + throw new InvalidAccessorException( + "Member must be a field or method: " + member.getName()); + } + + } + + if (!javaImpl.getCallbackMembers().isEmpty()) { + Map> callbackWires = new HashMap>(); + for (ComponentService service : component.getServices()) { + + RuntimeComponentReference callbackReference = (RuntimeComponentReference)service.getCallbackReference(); + if (callbackReference != null) { + List wires = callbackReference.getRuntimeWires(); + if (!wires.isEmpty()) { + callbackWires.put(wires.get(0).getSource().getInterfaceContract().getInterface().toString(), wires); + } + } + } + + for (Map.Entry> entry : javaImpl.getCallbackMembers() + .entrySet()) { + List wires = callbackWires.get(entry.getKey()); + if (wires == null) { + // this can happen when there are no client wires to a + // component that has a callback + continue; + } + for(JavaElementImpl element : entry.getValue()) { + ObjectFactory factory = new CallbackWireObjectFactory(element.getType(), proxyFactory, wires); + if (!(element.getAnchor() instanceof Constructor)) { + injectionSites.add(element); + } + factories.put(element, factory); + } + } + } + + for (JavaResourceImpl resource : javaImpl.getResources().values()) { + + ObjectFactory objectFactory; + Class type = resource.getElement().getType(); + if (ComponentContext.class.equals(type)) { + objectFactory = new ComponentContextFactory(component); + + } else if (RequestContext.class.equals(type)) { + objectFactory = new RequestContextObjectFactory(requestContextFactory, proxyFactory); + + } else { + boolean optional = resource.isOptional(); + String mappedName = resource.getMappedName(); + objectFactory = new ResourceObjectFactory(type, mappedName, optional, null); + } + factories.put(resource.getElement(), objectFactory); + if (!(resource.getElement().getAnchor() instanceof Constructor)) { + injectionSites.add(resource.getElement()); + } + } + + + } + + + @SuppressWarnings("unchecked") + private Injector[] createInjectors() { + + Injector[] injectors = (Injector[])new Injector[injectionSites.size()]; + + int i = 0; + for (JavaElementImpl element : injectionSites) { + Object obj = factories.get(element); + if (obj != null) { + if (obj instanceof ObjectFactory) { + ObjectFactory factory = (ObjectFactory)obj; + Member member = (Member)element.getAnchor(); + if (element.getElementType() == ElementType.FIELD) { + injectors[i++] = new FieldInjector((Field)member, factory); + } else if (element.getElementType() == ElementType.PARAMETER && member instanceof Method) { + injectors[i++] = new MethodInjector((Method)member, factory); + } else if (member instanceof Constructor) { + // Ignore + } else { + throw new AssertionError(String.valueOf(element)); + } + } else { + injectors[i++] = createMultiplicityInjector(element, (List>)obj); + } + } + } + return injectors; + } + + @SuppressWarnings("unchecked") + protected Injector createMultiplicityInjector(JavaElementImpl element, List> factories) { + Class interfaceType = JavaIntrospectionHelper.getBaseType(element.getType(), element.getGenericType()); + + if (element.getAnchor() instanceof Field) { + Field field = (Field)element.getAnchor(); + if (field.getType().isArray()) { + return new FieldInjector(field, new ArrayMultiplicityObjectFactory(interfaceType, factories)); + } else { + return new FieldInjector(field, new ListMultiplicityObjectFactory(factories)); + } + } else if (element.getAnchor() instanceof Method) { + Method method = (Method)element.getAnchor(); + if (method.getParameterTypes()[0].isArray()) { + return new MethodInjector(method, new ArrayMultiplicityObjectFactory(interfaceType, factories)); + } else { + return new MethodInjector(method, new ListMultiplicityObjectFactory(factories)); + } + } else { + throw new InvalidAccessorException("Member must be a field or method: " + element.getName()); + } + } + + private static class ComponentContextFactory implements ObjectFactory { + + RuntimeComponent component; + + private ComponentContextFactory(RuntimeComponent component) { + this.component = component; + } + + public Object getInstance() throws ObjectCreationException { + return component.getComponentContext(); + } + + } + + + private static class RequestContextObjectFactory implements ObjectFactory { + + private RequestContextFactory factory; + private ProxyFactory proxyFactory; + + public RequestContextObjectFactory(RequestContextFactory factory) { + this(factory, null); + } + + public RequestContextObjectFactory(RequestContextFactory factory, ProxyFactory proxyFactory) { + this.factory = factory; + this.proxyFactory = proxyFactory; + } + + public RequestContext getInstance() throws ObjectCreationException { + if (factory != null) { + return factory.createRequestContext(); + } else { + return new RequestContextImpl(proxyFactory); + } + } + + } + +} diff --git a/java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/context/OSGiPropertyValueObjectFactory.java b/java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/context/OSGiPropertyValueObjectFactory.java new file mode 100644 index 0000000000..38befa611b --- /dev/null +++ b/java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/context/OSGiPropertyValueObjectFactory.java @@ -0,0 +1,226 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.implementation.osgi.context; + + +import java.util.ArrayList; +import java.util.List; +import java.util.StringTokenizer; + +import org.apache.tuscany.sca.assembly.Property; +import org.apache.tuscany.sca.core.factory.ObjectCreationException; +import org.apache.tuscany.sca.core.factory.ObjectFactory; +import org.apache.tuscany.sca.databinding.Mediator; +import org.apache.tuscany.sca.databinding.SimpleTypeMapper; +import org.apache.tuscany.sca.databinding.impl.SimpleTypeMapperImpl; +import org.apache.tuscany.sca.databinding.xml.DOMDataBinding; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.impl.DataTypeImpl; +import org.apache.tuscany.sca.interfacedef.util.TypeInfo; +import org.apache.tuscany.sca.interfacedef.util.XMLType; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; + +/** + * + * Process properties and create property values. + * + * This code has been copied from the Java implementation to avoid dependencies on the Java implementation. + * + * @version $Rev$ $Date$ + */ +public class OSGiPropertyValueObjectFactory { + protected SimpleTypeMapper simpleTypeMapper = new SimpleTypeMapperImpl(); + boolean isSimpleType; + + + public OSGiPropertyValueObjectFactory() { + } + + public OSGiPropertyValueObjectFactory(Mediator mediator) { + } + + public ObjectFactory createValueFactory(Property property, Object propertyValue) { + + Class javaType = SimpleTypeMapperImpl.getJavaType(property.getXSDType()); + isSimpleType = isSimpleType(property); + Document doc = (Document)propertyValue; + Element rootElement = doc.getDocumentElement(); + if (property.isMany()) { + if (isSimpleType) { + String value = ""; + if (rootElement.getChildNodes().getLength() > 0) { + value = rootElement.getChildNodes().item(0).getTextContent(); + } + List values = + getSimplePropertyValues(value, javaType); + return new ListObjectFactoryImpl(property, + values, + isSimpleType, + javaType); + } else { + return new ListObjectFactoryImpl(property, + getComplexPropertyValues(doc), + isSimpleType, + javaType); + } + } else { + if (isSimpleType) { + String value = ""; + if (rootElement.getChildNodes().getLength() > 0) { + value = rootElement.getChildNodes().item(0).getTextContent(); + } + return new ObjectFactoryImpl(property, + value, + isSimpleType, + javaType); + } else { + Object value = getComplexPropertyValues(doc).get(0); + return new ObjectFactoryImpl(property, + value, + isSimpleType, + javaType); + } + + } + } + + private boolean isSimpleType(Property property) { + if (property.getXSDType() != null) { + return SimpleTypeMapperImpl.isSimpleXSDType(property.getXSDType()); + } else { + if (property instanceof Document) { + Document doc = (Document)property; + Element element = doc.getDocumentElement(); + if (element.getChildNodes().getLength() == 1 && + element.getChildNodes().item(0).getNodeType() == Node.TEXT_NODE) { + return true; + } + } + } + return false; + } + + private List getSimplePropertyValues(String concatenatedValue, Class javaType) { + List propValues = new ArrayList(); + StringTokenizer st = null; + if ( javaType.getName().equals("java.lang.String")) { + st = new StringTokenizer(concatenatedValue, "\""); + } else { + st = new StringTokenizer(concatenatedValue); + } + String aToken = null; + while (st.hasMoreTokens()) { + aToken = st.nextToken(); + if (aToken.trim().length() > 0) { + propValues.add(aToken); + } + } + return propValues; + } + + private List getComplexPropertyValues(Document document) { + Element rootElement = document.getDocumentElement(); + List propValues = new ArrayList(); + for (int count = 0 ; count < rootElement.getChildNodes().getLength() ; ++count) { + if (rootElement.getChildNodes().item(count).getNodeType() == Node.ELEMENT_NODE) { + propValues.add(rootElement.getChildNodes().item(count)); + } + } + return propValues; + } + + public abstract class ObjectFactoryImplBase implements ObjectFactory { + protected SimpleTypeMapper simpleTypeMapper = new SimpleTypeMapperImpl(); + protected Property property; + protected Object propertyValue; + protected Class javaType; + protected DataType sourceDataType; + protected DataType targetDataType; + boolean isSimpleType; + + public ObjectFactoryImplBase(Property property, Object propertyValue, boolean isSimpleType, Class javaType) { + this.isSimpleType = isSimpleType; + this.property = property; + this.propertyValue = propertyValue; + this.javaType = javaType; + sourceDataType = + new DataTypeImpl(DOMDataBinding.NAME, Node.class, + new XMLType(null, this.property.getXSDType())); + TypeInfo typeInfo = null; + if (this.property.getXSDType() != null) { + if (SimpleTypeMapperImpl.isSimpleXSDType(this.property.getXSDType())) { + typeInfo = new TypeInfo(property.getXSDType(), true, null); + } else { + typeInfo = new TypeInfo(property.getXSDType(), false, null); + } + } else { + typeInfo = new TypeInfo(property.getXSDType(), false, null); + } + + XMLType xmlType = new XMLType(typeInfo); + String dataBinding = null; //(String)property.getExtensions().get(DataBinding.class.getName()); + if (dataBinding != null) { + targetDataType = new DataTypeImpl(dataBinding, javaType, xmlType); + } else { + targetDataType = new DataTypeImpl(dataBinding, javaType, xmlType); + } + } + } + + public class ObjectFactoryImpl extends ObjectFactoryImplBase { + public ObjectFactoryImpl(Property property, Object propertyValue, boolean isSimpleType, Class javaType) { + super(property, propertyValue, isSimpleType, javaType); + } + + @SuppressWarnings("unchecked") + public Object getInstance() throws ObjectCreationException { + if (isSimpleType) { + return simpleTypeMapper.toJavaObject(property.getXSDType(), (String)propertyValue, null); + } else { + return null; + } + } + } + + public class ListObjectFactoryImpl extends ObjectFactoryImplBase { + public ListObjectFactoryImpl(Property property, ListpropertyValues, boolean isSimpleType, Class javaType) { + super(property, propertyValues, isSimpleType, javaType); + } + + @SuppressWarnings("unchecked") + public List getInstance() throws ObjectCreationException { + if (isSimpleType) { + List values = new ArrayList(); + for (String aValue : (List)propertyValue) { + values.add(simpleTypeMapper.toJavaObject(property.getXSDType(), aValue, null)); + } + return values; + } else { + List instances = new ArrayList(); + for (Node aValue : (List)propertyValue) { + instances.add(aValue); + } + return instances; + } + } + } +} + diff --git a/java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/impl/OSGiImplementationImpl.java b/java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/impl/OSGiImplementationImpl.java new file mode 100644 index 0000000000..fe3efd22cd --- /dev/null +++ b/java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/impl/OSGiImplementationImpl.java @@ -0,0 +1,168 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.implementation.osgi.impl; + + +import java.util.Hashtable; +import java.util.List; + +import org.apache.tuscany.sca.assembly.ComponentProperty; +import org.apache.tuscany.sca.assembly.impl.ImplementationImpl; +import org.apache.tuscany.sca.contribution.ModelFactoryExtensionPoint; +import org.apache.tuscany.sca.implementation.osgi.OSGiImplementation; + + +/** + * OSGi implementation + * All attributes from have getters in this class + * This class implements OSGiImplementationInterface which is associated with OSGiImplementationProvider. + * + * @version $Rev$ $Date$ + */ +public class OSGiImplementationImpl extends ImplementationImpl implements OSGiImplementation { + + private String bundleSymbolicName; + private String bundleVersion; + + private String[] imports; + private Hashtable> referenceProperties; + private Hashtable> serviceProperties; + + private Hashtable> referenceCallbackProperties; + private Hashtable> serviceCallbackProperties; + + private String[] classList; + + private ModelFactoryExtensionPoint modelFactories; + + private Object osgiBundle; + + public OSGiImplementationImpl( + ModelFactoryExtensionPoint modelFactories, + String bundleSymbolicName, + String bundleVersion, + String[] imports, + String[] classList, + Hashtable> refProperties, + Hashtable> serviceProperties) { + + super(); + this.bundleSymbolicName = bundleSymbolicName; + this.bundleVersion = bundleVersion; + this.imports = imports; + this.referenceProperties = refProperties; + this.serviceProperties = serviceProperties; + this.classList = classList; + this.modelFactories = modelFactories; + } + + public void setCallbackProperties(Hashtable> refCallbackProperties, + Hashtable> serviceCallbackProperties) { + + this.referenceCallbackProperties = refCallbackProperties; + this.serviceCallbackProperties = serviceCallbackProperties; + + } + + + public String getBundleSymbolicName() { + return bundleSymbolicName; + } + + public String getBundleVersion() { + return bundleVersion; + } + + public String[] getImports() { + return imports; + } + + public String[] getClassList() { + return classList; + } + + public ModelFactoryExtensionPoint getModelFactories() { + return modelFactories; + } + + public List getReferenceProperties(String referenceName) { + return referenceProperties.get(referenceName); + } + + public List getServiceProperties(String serviceName) { + return serviceProperties.get(serviceName); + } + + public List getReferenceCallbackProperties(String referenceName) { + return referenceCallbackProperties.get(referenceName); + } + + public List getServiceCallbackProperties(String serviceName) { + return serviceCallbackProperties.get(serviceName); + } + + /** + * Since OSGi implementation annotations may not be processed until much later, leave it to + * the OSGi invoker to decide whether pass-by-reference is allowed. + * @return + */ + public boolean isAllowsPassByReference() { + return true; + } + + public Object getOSGiBundle() { + return osgiBundle; + } + + public void setOSGiBundle(Object osgiBundle) { + this.osgiBundle = osgiBundle; + } + + private boolean areEqual(Object obj1, Object obj2) { + if (obj1 == obj2) + return true; + if (obj1 == null || obj2 == null) + return false; + return obj1.equals(obj2); + } + + @Override + public boolean equals(Object obj) { + + if (!(obj instanceof OSGiImplementationImpl)) + return super.equals(obj); + OSGiImplementationImpl impl = (OSGiImplementationImpl)obj; + if (!areEqual(bundleSymbolicName, impl.bundleSymbolicName)) + return false; + if (!areEqual(bundleVersion, impl.bundleVersion)) + return false; + if (!areEqual(serviceProperties, impl.serviceProperties)) + return false; + if (!areEqual(serviceCallbackProperties, impl.serviceCallbackProperties)) + return false; + if (!areEqual(referenceProperties, impl.referenceProperties)) + return false; + if (!areEqual(referenceCallbackProperties, impl.referenceCallbackProperties)) + return false; + return super.equals(obj); + } + + + +} diff --git a/java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/runtime/OSGiImplementationProvider.java b/java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/runtime/OSGiImplementationProvider.java new file mode 100644 index 0000000000..5664c77618 --- /dev/null +++ b/java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/runtime/OSGiImplementationProvider.java @@ -0,0 +1,1254 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.implementation.osgi.runtime; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.lang.reflect.Method; +import java.security.AccessController; +import java.security.PrivilegedActionException; +import java.security.PrivilegedExceptionAction; +import java.util.ArrayList; +import java.util.Dictionary; +import java.util.HashSet; +import java.util.Hashtable; +import java.util.List; +import java.util.StringTokenizer; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.jar.JarOutputStream; +import java.util.jar.Manifest; +import java.util.zip.ZipEntry; + +import org.apache.tuscany.sca.assembly.ComponentProperty; +import org.apache.tuscany.sca.assembly.ComponentReference; +import org.apache.tuscany.sca.assembly.ComponentService; +import org.apache.tuscany.sca.assembly.Multiplicity; +import org.apache.tuscany.sca.assembly.Property; +import org.apache.tuscany.sca.assembly.Reference; +import org.apache.tuscany.sca.assembly.Service; +import org.apache.tuscany.sca.context.RequestContextFactory; +import org.apache.tuscany.sca.core.context.InstanceWrapper; +import org.apache.tuscany.sca.core.factory.ObjectCreationException; +import org.apache.tuscany.sca.core.factory.ObjectFactory; +import org.apache.tuscany.sca.core.invocation.JDKProxyFactory; +import org.apache.tuscany.sca.core.invocation.ProxyFactory; +import org.apache.tuscany.sca.core.scope.Scope; +import org.apache.tuscany.sca.core.scope.ScopeContainer; +import org.apache.tuscany.sca.core.scope.ScopeRegistry; +import org.apache.tuscany.sca.core.scope.ScopedImplementationProvider; +import org.apache.tuscany.sca.core.scope.ScopedRuntimeComponent; +import org.apache.tuscany.sca.databinding.DataBindingExtensionPoint; +import org.apache.tuscany.sca.databinding.impl.SimpleTypeMapperImpl; +import org.apache.tuscany.sca.implementation.java.IntrospectionException; +import org.apache.tuscany.sca.implementation.java.injection.JavaPropertyValueObjectFactory; +import org.apache.tuscany.sca.implementation.osgi.OSGiImplementation; +import org.apache.tuscany.sca.implementation.osgi.context.OSGiAnnotations; +import org.apache.tuscany.sca.implementation.osgi.impl.OSGiImplementationImpl; +import org.apache.tuscany.sca.interfacedef.Interface; +import org.apache.tuscany.sca.interfacedef.InterfaceContractMapper; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.interfacedef.java.JavaInterface; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.MessageFactory; +import org.apache.tuscany.sca.osgi.runtime.OSGiRuntime; +import org.apache.tuscany.sca.runtime.EndpointReference; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; +import org.apache.tuscany.sca.runtime.RuntimeWire; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.BundleEvent; +import org.osgi.framework.BundleException; +import org.osgi.framework.BundleListener; +import org.osgi.framework.Constants; +import org.osgi.framework.FrameworkEvent; +import org.osgi.framework.FrameworkListener; +import org.osgi.framework.InvalidSyntaxException; +import org.osgi.framework.ServiceEvent; +import org.osgi.framework.ServiceListener; +import org.osgi.service.packageadmin.ExportedPackage; +import org.osgi.service.packageadmin.PackageAdmin; + +/** + * The runtime instantiation of OSGi component implementations + * + * @version $Rev$ $Date$ + */ +public class OSGiImplementationProvider implements ScopedImplementationProvider, + FrameworkListener, + BundleListener { + + private static final String COMPONENT_SERVICE_NAME = "component.service.name"; + + // Maximum milliseconds to wait for a method to complete + private static final long METHOD_TIMEOUT_MILLIS = 60000; + // Maximum milliseconds to wait for services to be registered into OSGi service registry + private static final long SERVICE_TIMEOUT_MILLIS = 300000; + + private OSGiImplementationImpl implementation; + private OSGiAnnotations osgiAnnotations; + private BundleContext bundleContext; + + private Hashtable referenceWires = new Hashtable(); + private Hashtable componentReferenceWires + = new Hashtable(); + private HashSet resolvedWires = new HashSet(); + private boolean wiresResolved; + + private AtomicInteger startBundleEntryCount = new AtomicInteger(); + private AtomicInteger processAnnotationsEntryCount = new AtomicInteger(); + + private JavaPropertyValueObjectFactory propertyValueFactory; + + + private Hashtable componentProperties = new Hashtable(); + private RuntimeComponent runtimeComponent; + + private Bundle osgiBundle; + private ArrayList dependentBundles = new ArrayList(); + private OSGiServiceListener osgiServiceListener; + private PackageAdmin packageAdmin; + + private OSGiRuntime osgiRuntime; + + private ScopeRegistry scopeRegistry; + private DataBindingExtensionPoint dataBindingRegistry; + + private boolean packagesRefreshed; + + private MessageFactory messageFactory; + private InterfaceContractMapper mapper; + + + public OSGiImplementationProvider(RuntimeComponent definition, + OSGiImplementation impl, + DataBindingExtensionPoint dataBindingRegistry, + JavaPropertyValueObjectFactory propertyValueFactory, + ProxyFactory proxyFactory, + ScopeRegistry scopeRegistry, + RequestContextFactory requestContextFactory, + MessageFactory messageFactory, + InterfaceContractMapper mapper) throws BundleException { + + + this.implementation = (OSGiImplementationImpl)impl; + this.runtimeComponent = definition; + this.dataBindingRegistry = dataBindingRegistry; + this.propertyValueFactory = propertyValueFactory; + this.scopeRegistry = scopeRegistry; + this.messageFactory = messageFactory; + this.mapper = mapper; + + bundleContext = getBundleContext(); + osgiBundle = (Bundle)implementation.getOSGiBundle(); + bundleContext.addBundleListener(this); + osgiServiceListener = new OSGiServiceListener(osgiBundle); + bundleContext.addServiceListener(osgiServiceListener); + + // Install and start all dependent bundles + String[] imports = implementation.getImports(); + for (int i = 0; i < imports.length; i++) { + String location = imports[i].trim(); + if (location.length() > 0) { + Bundle bundle = bundleContext.installBundle(location); + dependentBundles.add(bundle); + } + } + + + this.osgiAnnotations = new OSGiAnnotations( + implementation.getModelFactories(), + implementation.getClassList(), + runtimeComponent, + propertyValueFactory, + proxyFactory, + requestContextFactory, + osgiBundle, + dependentBundles); + + + // PackageAdmin is used to resolve bundles + org.osgi.framework.ServiceReference packageAdminReference = + bundleContext.getServiceReference("org.osgi.service.packageadmin.PackageAdmin"); + if (packageAdminReference != null) { + packageAdmin = (PackageAdmin) bundleContext.getService(packageAdminReference); + bundleContext.addFrameworkListener(this); + } + + + } + + protected RuntimeComponent getRuntimeComponent() { + return runtimeComponent; + } + + protected OSGiImplementationImpl getImplementation() { + return implementation; + } + + // Create a property table from the list of properties + // The source properties are properties read from elements + // Create property values in the table of the appropriate class based + // on the property type specified. + private void processProperties(List props, Hashtable propsTable) { + + if (props != null) { + for (Object p : props) { + + Property prop = (Property)p; + Class javaType = SimpleTypeMapperImpl.getJavaType(prop.getXSDType()); + ObjectFactory objFactory = propertyValueFactory.createValueFactory(prop, prop.getValue(), javaType); + Object value = objFactory.getInstance(); + + propsTable.put(prop.getName(), value); + } + } + } + + + private BundleContext getBundleContext() throws BundleException { + + try { + if (bundleContext == null) { + osgiRuntime = OSGiRuntime.getRuntime(); + bundleContext = osgiRuntime .getBundleContext(); + } + } catch (BundleException e) { + throw e; + } catch (Exception e) { + throw new BundleException("Could not start OSGi runtime", e); + } + + + return bundleContext; + } + + + private String getOSGiFilter(Hashtable props) { + + String filter = ""; + + if (props != null && props.size() > 0) { + int propCount = 0; + for (String propName : props.keySet()) { + if (propName.equals("service.pid")) + continue; + filter = filter + "(" + propName + "=" + props.get(propName) + ")"; + propCount++; + } + + if (propCount > 1) filter = "(&" + filter + ")"; + } + else + filter = null; + return filter; + } + + /* + * Return a matching service registered by the specified bundle. + * If has the attribute filter defined, return a service + * reference that matches the filter. Otherwise, return a service which has a component + * name equal to this component's name. If not found, return a service which no + * component name set. + * + * Even though services registered by this bundle can be filtered using the + * service listener, we use this method to filter all service references so that + * the service matching functionality of OSGi can be directly used. + */ + private org.osgi.framework.ServiceReference getOSGiServiceReference( + String scaServiceName, + String osgiServiceName, String filter) + throws InvalidSyntaxException { + + String compServiceName = runtimeComponent.getName() + "/" + scaServiceName; + if (filter != null && filter.length() > 0) { + org.osgi.framework.ServiceReference[] references = + bundleContext.getServiceReferences(osgiServiceName, filter); + + + org.osgi.framework.ServiceReference reference = null; + if (references != null) { + for (org.osgi.framework.ServiceReference ref : references) { + if (ref.getBundle() != osgiBundle) + continue; + Object compName = ref.getProperty(COMPONENT_SERVICE_NAME); + if (compName == null && reference == null) + reference = ref; + if (scaServiceName == null || compServiceName.equals(compName)) { + reference = ref; + break; + } + } + } + + return reference; + + } + + filter = scaServiceName == null? null : + "(" + COMPONENT_SERVICE_NAME + "="+ compServiceName + ")"; + + org.osgi.framework.ServiceReference[] references = + bundleContext.getServiceReferences(osgiServiceName, filter); + + if (references != null) { + for (org.osgi.framework.ServiceReference ref : references) { + if (ref.getBundle() == osgiBundle) { + return ref; + } + } + } + + references = bundleContext.getServiceReferences(osgiServiceName, null); + + org.osgi.framework.ServiceReference reference = null; + + if (references != null) { + for (org.osgi.framework.ServiceReference ref : references) { + + if (ref.getBundle() != osgiBundle) + continue; + Object compName = ref.getProperty(COMPONENT_SERVICE_NAME); + if (compName == null && reference == null) + reference = ref; + if (compServiceName.equals(compName)) { + reference = ref; + break; + } + } + } + + return reference; + } + + /** + * This method is used to avoid full synchronization of methods which should + * be executed only once. + * + * entryCount=0: The count is incremented, and this thread executes the method. Returns true. + * + * entryCount=1: Another thread is already executing this method. + * Wait for the thread to complete if doWait is true. Returns false. + * + * entryCount=2: The method has already been executed. Returns false. + * + * @param doWait If true, and another method is executing this method + * wait for method execution to complete + * @param entryCount Atomic integer used to ensure that the method is + * executed only once + * @return true if this thread has exclusive access to execute this method + */ + private boolean enterMethod(boolean doWait, AtomicInteger entryCount) { + + if (entryCount.compareAndSet(0, 1)) { + return true; + } + else { + if (doWait) { + synchronized (entryCount) { + if (entryCount.get() != 2) { + try { + entryCount.wait(METHOD_TIMEOUT_MILLIS); + } catch (InterruptedException e) { + } + } + } + } + return false; + } + } + + /** + * Called on method exit of methods which were entered after + * enterMethod returned true. Increments entryCount, and wakes + * up threads waiting for the method to complete. + * + * @param entryCount Atomic integer used for synchronization + */ + private void exitMethod(AtomicInteger entryCount) { + entryCount.compareAndSet(1, 2); + synchronized (entryCount) { + entryCount.notifyAll(); + } + } + + protected Bundle startBundle(boolean doWait) throws ObjectCreationException { + + try { + + if (enterMethod(doWait, startBundleEntryCount)) { + + configurePropertiesUsingConfigAdmin(); + + resolveBundle(); + + processAnnotations(true); + + + for (Bundle bundle : dependentBundles) { + try { + if (bundle.getState() != Bundle.ACTIVE && bundle.getState() != Bundle.STARTING) { + bundle.start(); + } + } catch (BundleException e) { + if (bundle.getHeaders().get("Fragment-Host") == null) + throw e; + } + } + + } + + if (osgiBundle.getState() != Bundle.ACTIVE && osgiBundle.getState() != Bundle.STARTING) { + + + int retry = 0; + + while (retry++ < 10) { + try { + AccessController.doPrivileged(new PrivilegedExceptionAction() { + public Object run() throws BundleException { + osgiBundle.start(); + return null; + } + }); + break; + // } catch ( BundleException e) { + } catch ( PrivilegedActionException e) { + // It is possible that the thread "Refresh Packages" is in the process of + // changing the state of this bundle. + Thread.yield(); + + if (retry == 10) + throw e; + } + } + } + + } catch (Exception e) { + throw new ObjectCreationException(e); + } finally { + exitMethod(startBundleEntryCount); + } + return osgiBundle; + } + + + // This method is called by OSGiInstanceWrapper.getInstance to obtain the OSGi service reference + // corresponding to the specified service. The properties used to filter the service should + // be chosen based on whether this is a normal service or a callback. + protected org.osgi.framework.ServiceReference getOSGiServiceReference(ComponentService service) + throws ObjectCreationException { + + Hashtable props = new Hashtable(); + if (!service.isCallback()) + processProperties(implementation.getServiceProperties(service.getName()), props); + else + processProperties(implementation.getServiceCallbackProperties(service.getName()), props); + + String filter = getOSGiFilter(props); + Interface serviceInterface = service.getInterfaceContract().getInterface(); + String scaServiceName = service.getName(); + + return getOSGiServiceReference(serviceInterface, filter, scaServiceName); + + } + + protected org.osgi.framework.ServiceReference getOSGiServiceReference( + EndpointReference from, Interface callbackInterface) + throws ObjectCreationException { + + RuntimeWire refWire = null; + String filter = null; + for (RuntimeWire wire : referenceWires.keySet()) { + if (wire.getSource() == from) { + refWire = wire; + break; + } + } + if (refWire != null) { + Hashtable props = new Hashtable(); + ComponentReference scaRef = componentReferenceWires.get(refWire); + processProperties(implementation.getReferenceCallbackProperties(scaRef.getName()), props); + filter = getOSGiFilter(props); + } + + return getOSGiServiceReference(callbackInterface, filter, null); + } + + private org.osgi.framework.ServiceReference getOSGiServiceReference(Interface serviceInterface, + String filter, String scaServiceName) + throws ObjectCreationException { + + try { + + String serviceInterfaceName = null; + + org.osgi.framework.ServiceReference osgiServiceReference = null; + + if (serviceInterface instanceof JavaInterface) { + serviceInterfaceName = ((JavaInterface)serviceInterface).getJavaClass().getName(); + + if ((osgiServiceReference = getOSGiServiceReference( + scaServiceName, + serviceInterfaceName, filter)) == null) { + + // The service listener for our bundle will notify us when the service is registered. + synchronized (implementation) { + + // When declarative services are used, the component is started asynchronously + // So this thread has to wait for the service to be registered by the component + // activate method + // For regular bundle activators, bundle.start activates the bundle synchronously + // and hence the service would probably have been started by the bundle activator + long startTime = System.currentTimeMillis(); + while ((osgiServiceReference = getOSGiServiceReference( + scaServiceName, + serviceInterfaceName, filter)) == null) { + + // Wait for the bundle to register the service + implementation.wait(100); + if (System.currentTimeMillis() - startTime > SERVICE_TIMEOUT_MILLIS) + break; + } + } + + } + } + + return osgiServiceReference; + + } catch (Exception e) { + throw new ObjectCreationException(e); + } + } + + + // Felix does not support bundle fragments. This is a temporary workaround. + protected Bundle installDummyBundleWithoutFragments(Class interfaceClass) + throws Exception { + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + + String EOL = System.getProperty("line.separator"); + + String interfaceName = interfaceClass.getName(); + String packageName = getPackageName(interfaceClass); + String bundleName = "dummy.sca." + packageName; + + String manifestStr = "Manifest-Version: 1.0" + EOL + + "Bundle-ManifestVersion: 2" + EOL + "Bundle-Name: " + + bundleName + EOL + "Bundle-SymbolicName: " + bundleName + EOL + + "Bundle-Version: " + "1.0.0" + EOL + + "Bundle-Localization: plugin" + EOL; + + ArrayList dummyClasses = new ArrayList(); + + StringBuilder manifestBuf = new StringBuilder(); + manifestBuf.append(manifestStr); + manifestBuf.append("Export-Package: " + packageName + EOL); + String exportedInterfaces = interfaceName; + Bundle existingBundle = getDummyHostBundle(packageName); + String existingClasses; + dummyClasses.add(interfaceClass.getName()); + for (Class clazz : interfaceClass.getClasses()) { + dummyClasses.add(clazz.getName()); + } + if (existingBundle != null && + (existingClasses = (String)existingBundle.getHeaders().get("SCA-Dummy-Classes")) != null) { + exportedInterfaces = exportedInterfaces + " " + existingClasses; + + StringTokenizer tokenizer = new StringTokenizer(existingClasses); + while (tokenizer.hasMoreTokens()) { + String className = tokenizer.nextToken(); + if (!dummyClasses.contains(className)) + dummyClasses.add(className); + } + } + + manifestBuf.append("SCA-Dummy-Classes: " + exportedInterfaces + EOL); + + ByteArrayInputStream manifestStream = new ByteArrayInputStream( + manifestBuf.toString().getBytes()); + Manifest manifest = new Manifest(); + manifest.read(manifestStream); + + JarOutputStream jarOut = new JarOutputStream(out, manifest); + + for (int i = 0; i < dummyClasses.size(); i++) { + + String className = dummyClasses.get(i); + + Class clazz = interfaceClass.getClassLoader().loadClass(className); + className = clazz.getName().replaceAll("\\.", "/") + ".class"; + ZipEntry ze = new ZipEntry(className); + jarOut.putNextEntry(ze); + InputStream stream = clazz.getResourceAsStream(clazz.getSimpleName() + ".class"); + + byte[] bytes = new byte[stream.available()]; + stream.read(bytes); + jarOut.write(bytes); + stream.close(); + } + + + jarOut.close(); + out.close(); + + if (existingBundle != null) { + existingBundle.stop(); + existingBundle.uninstall(); + } + + ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); + + Bundle bundle = bundleContext.installBundle("file://" + bundleName + + ".jar", in); + + bundle.start(); + + if (existingBundle != null && packageAdmin != null) { + refreshPackages(); + + } + + return bundle; + + } + + private Bundle getDummyHostBundle(String packageName) { + + if (packageAdmin == null) + return null; + + ExportedPackage exp = packageAdmin.getExportedPackage(packageName); + if (exp == null) + return null; + else + return exp.getExportingBundle(); + } + + private static String getPackageName(Class cls) { + String name = cls.getName(); + int index = name.lastIndexOf('.'); + return index == -1 ? "" : name.substring(0, index); + } + + private Bundle installDummyBundle(Class interfaceClass) + throws Exception { + + + if (!osgiRuntime.supportsBundleFragments()) { + return installDummyBundleWithoutFragments(interfaceClass); + } + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + + String EOL = System.getProperty("line.separator"); + ArrayList> dummyClasses = new ArrayList>(); + + String interfaceName = interfaceClass.getName(); + String packageName = getPackageName(interfaceClass); + String bundleName = "dummy.sca." + interfaceName; + + + String manifestStr = "Manifest-Version: 1.0" + EOL + + "Bundle-ManifestVersion: 2" + EOL + + "Bundle-Name: " + bundleName + EOL + + "Bundle-SymbolicName: " + bundleName + EOL + + "Bundle-Version: " + "1.0.0" + EOL + + "Bundle-Localization: plugin" + EOL; + + + StringBuilder manifestBuf = new StringBuilder(); + manifestBuf.append(manifestStr); + manifestBuf.append("Export-Package: " + packageName + EOL); + Bundle dummyHost = getDummyHostBundle(packageName); + if (dummyHost != null) + manifestBuf.append("Fragment-Host: " + dummyHost.getSymbolicName() + EOL); + + ByteArrayInputStream manifestStream = new ByteArrayInputStream(manifestBuf.toString().getBytes()); + Manifest manifest = new Manifest(); + manifest.read(manifestStream); + + dummyClasses.add(interfaceClass); + for (Class clazz : interfaceClass.getClasses()) { + dummyClasses.add(clazz); + } + + JarOutputStream jarOut = new JarOutputStream(out, manifest); + + for (int i = 0; i < dummyClasses.size(); i++) { + + Class clazz = dummyClasses.get(i); + String className = clazz.getName(); + className = clazz.getName().replaceAll("\\.", "/") + ".class"; + ZipEntry ze = new ZipEntry(className); + jarOut.putNextEntry(ze); + InputStream stream = clazz.getResourceAsStream(clazz.getSimpleName() + ".class"); + + byte[] bytes = new byte[stream.available()]; + stream.read(bytes); + jarOut.write(bytes); + stream.close(); + } + + jarOut.close(); + out.close(); + + + ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); + + + Bundle bundle = bundleContext.installBundle( + "file://" + bundleName + ".jar", + in); + + if (dummyHost == null) + bundle.start(); + + return bundle; + + } + + + + public InstanceWrapper createInstanceWrapper() throws ObjectCreationException { + + return new OSGiInstanceWrapper(this, osgiAnnotations, bundleContext); + } + + + + private void resolveWireCreateDummyBundles(final Class interfaceClass) throws Exception { + + + try { + + osgiBundle.loadClass(interfaceClass.getName()); + + } catch (ClassNotFoundException e) { + + // The interface used by the proxy is not in the source bundle + // A dummy bundle needs to be installed to create the proxy + // Allow privileged access to file system. Requires FileSystem permission in security + // policy. + Bundle dummyBundle = AccessController.doPrivileged(new PrivilegedExceptionAction() { + public Bundle run() throws Exception { + return installDummyBundle(interfaceClass); + } + }); + + if (packageAdmin != null) { + + packageAdmin.resolveBundles(new Bundle[]{dummyBundle, osgiBundle}); + + } + + } + } + + /** + * For OSGi->Java wires, create a proxy corresponding to the Java interfaces + * and register the proxy with the OSGi registry, so that the source OSGi bundle can + * locate the target Java instance from the registry like a regular OSGi service. + * + * For OSGi->OSGi wires, start the target OSGi bundle, so that references of the + * target are resolved before the source OSGi bundle is started. If the reference + * has properties specified, create a Proxy and register a service with highest + * possible ranking. The Proxy should wire to the correct OSGi instance specified + * in the SCA composite. + * + * The first phase determines whether a proxy should be installed. It also registers + * a dummy bundle if necessary to resolve the bundle. When phase1 is completed on all + * wires of the component, the bundle should be resolved. Phase2 registers the proxy service. + */ + private boolean resolveWireResolveReferences(Bundle bundle, Class interfaceClass, RuntimeWire wire, + boolean isOSGiToOSGiWire) throws Exception { + + + // FIXME: At the moment injection of values into instances require an instance to be obtained + // through the instance wrapper, and hence requires a proxy. When we do this processing here, + // we don't yet know whether the target requires any property or callback injection. So it is + // safer to create a proxy all the time. + boolean createProxy = true; + + ComponentReference scaRef = componentReferenceWires.get(wire); + Hashtable targetProperties = new Hashtable(); + processProperties(implementation.getReferenceProperties(scaRef.getName()), targetProperties); + + + if (isOSGiToOSGiWire) { + + OSGiImplementationProvider implProvider = (OSGiImplementationProvider)wire.getTarget().getComponent().getImplementationProvider(); + + // This is an OSGi->OSGi wire + isOSGiToOSGiWire = true; + + // If the target component is stateless, use a proxy to create a new service each time + if (!implProvider.getScope().equals(Scope.COMPOSITE)) createProxy = true; + + Interface interfaze = wire.getTarget().getInterfaceContract().getInterface(); + + // If the target interface is remotable, create a proxy to support pass-by-value semantics + // AllowsPassByReference is not detected until the target instance is obtained. + if (interfaze.isRemotable()) + createProxy = true; + + // If any of the operations in the target interface is non-blocking, create a proxy + List ops = interfaze.getOperations(); + for (Operation op : ops) { + if (op.isNonBlocking()) + createProxy = true; + } + + // If properties are specified for the reference, create a proxy since rewiring may be required + if (targetProperties.size() > 0) { + createProxy = true; + } + + // If properties are specified for the component, create a proxy for configuring + // the component services. + if (componentProperties.size() > 0) { + createProxy = true; + } + + // Since this is an OSGi->OSGi wire, start the target bundle before starting the + // source bundle if there is no proxy. For direct wiring without a proxy, this ordering + // is irrelevant in terms of class resolution, but the target needs to be started at some + // point. But there is no opportunity later on to start the target OSGi bundle without a proxy. + // When a Proxy is used, the target bundle needs to be resolved for the source bundle + // to be resolved so that the interface is visible to the source. In this case the bundle + // will be started when an instance is needed. + if (!createProxy) { + implProvider.startBundle(false); + } + else { + implProvider.resolveBundle(); + } + } + else { + createProxy = true; + } + + return createProxy; + } + + + // Register proxy service + private void resolveWireRegisterProxyService(final Bundle bundle, final Class interfaceClass, RuntimeWire wire) throws Exception { + + ComponentReference scaRef = componentReferenceWires.get(wire); + Hashtable targetProperties = new Hashtable(); + processProperties(implementation.getReferenceProperties(scaRef.getName()), targetProperties); + targetProperties.put(Constants.SERVICE_RANKING, Integer.MAX_VALUE); + + if (targetProperties.get(COMPONENT_SERVICE_NAME) == null && wire.getTarget().getComponent() != null) { + String compServiceName = wire.getTarget().getComponent().getName() + "/" + + wire.getTarget().getContract().getName(); + targetProperties.put(COMPONENT_SERVICE_NAME, compServiceName); + } + + + JDKProxyFactory proxyService = new JDKProxyFactory(messageFactory, mapper); + + // Allow privileged access to load classes. Requires getClassLoader permission in security + // policy. + final Class proxyInterface = AccessController.doPrivileged(new PrivilegedExceptionAction>() { + public Class run() throws Exception { + return bundle.loadClass(interfaceClass.getName()); + } + }); + + final Object proxy = proxyService.createProxy(proxyInterface, wire); + final Hashtable finalTargetProperties = targetProperties; + AccessController.doPrivileged(new PrivilegedExceptionAction() { + public Object run() throws Exception { + bundleContext.registerService(proxyInterface.getName(), proxy, finalTargetProperties); + return null; + } + }); + + + } + + + private void refreshPackages() { + + if (packageAdmin != null) { + synchronized (this) { + packagesRefreshed = false; + packageAdmin.refreshPackages(null); + + if (!packagesRefreshed) { + try { + this.wait(2000); + } catch (InterruptedException e) { + // ignore + } + } + packagesRefreshed = false; + } + } + } + + + private void resolveBundle() throws ObjectCreationException { + + + try { + + if (!wiresResolved) { + wiresResolved = true; + + if (!setReferencesAndProperties()) { + wiresResolved = false; + return; + } + + int refPlusServices = referenceWires.size() + runtimeComponent.getServices().size(); + boolean[] createProxyService = new boolean[refPlusServices]; + Class[] interfaceClasses = new Class[refPlusServices] ; + boolean[] isOSGiToOSGiWire = new boolean[refPlusServices]; + boolean[] wireResolved = new boolean[refPlusServices]; + int index = 0; + for (RuntimeWire wire : referenceWires.keySet()) { + + Reference reference = referenceWires.get(wire); + + isOSGiToOSGiWire[index] = wire.getTarget().getComponent() != null && + wire.getTarget().getComponent().getImplementationProvider() + instanceof OSGiImplementationProvider; + + Interface refInterface = reference.getInterfaceContract().getInterface(); + if (refInterface instanceof JavaInterface) { + interfaceClasses[index] = ((JavaInterface)refInterface).getJavaClass(); + + if (!isOSGiToOSGiWire[index]) + resolveWireCreateDummyBundles(interfaceClasses[index]); + + } + + if (!resolvedWires.contains(wire)) { + resolvedWires.add(wire); + } + else + wireResolved[index] = true; + + index++; + } + for (ComponentService service : runtimeComponent.getServices()) { + Interface callbackInterface = service.getInterfaceContract().getCallbackInterface(); + if (callbackInterface instanceof JavaInterface) { + interfaceClasses[index] = ((JavaInterface)callbackInterface).getJavaClass(); + + resolveWireCreateDummyBundles(interfaceClasses[index]); + } + + index++; + } + + index = 0; + for (RuntimeWire wire : referenceWires.keySet()) { + + if (!wireResolved[index]) { + createProxyService[index] = resolveWireResolveReferences(osgiBundle, + interfaceClasses[index], + wire, + isOSGiToOSGiWire[index]); + } + index++; + } + + refreshPackages(); + + + index = 0; + for (RuntimeWire wire : referenceWires.keySet()) { + + if (createProxyService[index] && !wireResolved[index]) + resolveWireRegisterProxyService(osgiBundle, interfaceClasses[index], wire); + index++; + } + } + else if (osgiBundle.getState() == Bundle.INSTALLED && packageAdmin != null) { + packageAdmin.resolveBundles(new Bundle[] {osgiBundle}); + } + + } catch (Exception e) { + e.printStackTrace(); + throw new ObjectCreationException(e); + } + } + + + @SuppressWarnings("unchecked") + private void configurePropertiesUsingConfigAdmin() { + + try { + + if (componentProperties.size() == 0) + return; + + org.osgi.framework.ServiceReference configAdminReference = + bundleContext.getServiceReference("org.osgi.service.cm.ConfigurationAdmin"); + if (configAdminReference != null) { + + Object cm = bundleContext.getService(configAdminReference); + Class cmClass = cm.getClass().getClassLoader().loadClass("org.osgi.service.cm.ConfigurationAdmin"); + Method getConfigMethod = cmClass.getMethod("getConfiguration", String.class, String.class); + + + Class configClass = cm.getClass().getClassLoader().loadClass("org.osgi.service.cm.Configuration"); + + Method getMethod = configClass.getMethod("getProperties"); + Method updateMethod = configClass.getMethod("update", Dictionary.class); + + List services = implementation.getServices(); + HashSet pidsProcessed = new HashSet(); + + for (Service service : services) { + + List serviceProps = implementation.getServiceProperties(service.getName()); + String pid = null; + + if (serviceProps != null) { + for (ComponentProperty prop : serviceProps) { + if (prop.getName().equals("service.pid")) { + ObjectFactory objFactory = propertyValueFactory.createValueFactory(prop, + prop.getValue(), String.class); + pid = (String)objFactory.getInstance(); + } + } + } + if (pid == null || pidsProcessed.contains(pid)) + continue; + + + + + Object config = getConfigMethod.invoke(cm, pid, null); + Dictionary props = (Dictionary) getMethod.invoke(config); + if (props == null) + props = new Hashtable(); + for (String propertyName : componentProperties.keySet()) { + + props.put(propertyName, componentProperties.get(propertyName)); + } + + updateMethod.invoke(config, props); + + + } + + } + + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + + public boolean isOptimizable() { + return false; + } + + public Scope getScope() { + return osgiAnnotations.getScope(); + } + + public boolean isEagerInit() { + return osgiAnnotations.isEagerInit(); + } + + public long getMaxAge() { + return osgiAnnotations.getMaxAge(); + } + + public long getMaxIdleTime() { + return osgiAnnotations.getMaxIdleTime(); + } + + protected ScopeContainer getScopeContainer() { + startBundle(true); + return ((ScopedRuntimeComponent)runtimeComponent).getScopeContainer(); + } + + public Invoker createTargetInvoker(RuntimeComponentService service, Operation operation) { + + + Interface serviceInterface = operation.getInterface(); + boolean isRemotable = serviceInterface.isRemotable(); + + + Invoker invoker = new OSGiTargetInvoker(operation, this, service); + if (isRemotable) { + return new OSGiRemotableInvoker(osgiAnnotations, dataBindingRegistry, operation, this, service); + } else { + return invoker; + } + + } + + + public Invoker createInvoker(RuntimeComponentService service, Operation operation) { + return createTargetInvoker(service, operation); + } + + public boolean supportsOneWayInvocation() { + return false; + } + + private boolean setReferencesAndProperties() { + + for (Reference ref: implementation.getReferences()) { + List wireList = null; + ComponentReference compRef = null; + for (ComponentReference cRef : runtimeComponent.getReferences()) { + if (cRef.getName().equals(ref.getName())) { + + wireList = ((RuntimeComponentReference)cRef).getRuntimeWires(); + + compRef = cRef; + break; + } + } + + if (ref.getMultiplicity() == Multiplicity.ONE_N || ref.getMultiplicity() == Multiplicity.ZERO_N) { + for (RuntimeWire wire : wireList) { + referenceWires.put(wire, ref); + componentReferenceWires.put(wire, compRef); + } + + } else { + if (wireList == null && ref.getMultiplicity() == Multiplicity.ONE_ONE) { + throw new IllegalStateException("Required reference is missing: " + ref.getName()); + } + if (wireList != null && !wireList.isEmpty()) { + RuntimeWire wire = wireList.get(0); + referenceWires.put(wire, ref); + componentReferenceWires.put(wire, compRef); + } + + } + + } + + processProperties(runtimeComponent.getProperties(), componentProperties); + + return true; + + } + + public void start() { + setReferencesAndProperties(); + } + + public void processAnnotations(boolean doWait) throws IntrospectionException { + + if (!enterMethod(doWait, processAnnotationsEntryCount)) + return; + + try { + osgiAnnotations.processAnnotations(); + + Scope scope = osgiAnnotations.getScope(); + if (scope.equals(Scope.SYSTEM) || scope.equals(Scope.COMPOSITE)) { + // Nothing + } else { + + if (runtimeComponent instanceof ScopedRuntimeComponent) { + + ScopedRuntimeComponent component = (ScopedRuntimeComponent) runtimeComponent; + + ScopeContainer oldScopeContainer = component.getScopeContainer(); + component.setScopeContainer(null); + ScopeContainer scopeContainer = scopeRegistry.getScopeContainer(runtimeComponent); + + if (oldScopeContainer != null && oldScopeContainer.getLifecycleState() == ScopeContainer.RUNNING) { + scopeContainer.start(); + } + + component.setScopeContainer(scopeContainer); + } + + } + } finally { + exitMethod(processAnnotationsEntryCount); + } + } + + public void stop() { + + if (osgiServiceListener != null) + bundleContext.removeServiceListener(osgiServiceListener); + } + + + + public void frameworkEvent(FrameworkEvent event) { + if (event.getType() == FrameworkEvent.PACKAGES_REFRESHED) { + synchronized (this) { + packagesRefreshed = true; + this.notifyAll(); + } + } + + } + + public void bundleChanged(BundleEvent event) { + if (event.getType() == BundleEvent.RESOLVED && event.getBundle() == osgiBundle) { + try { + processAnnotations(false); + } catch (Throwable e) { + e.printStackTrace(); + } + } + } + + private class OSGiServiceListener implements ServiceListener { + + private Bundle bundle; + + OSGiServiceListener(Bundle bundle) { + this.bundle = bundle; + } + + public void serviceChanged(org.osgi.framework.ServiceEvent event) { + + + org.osgi.framework.ServiceReference reference = event.getServiceReference(); + + if (event.getType() == ServiceEvent.REGISTERED && reference.getBundle() == bundle) { + + synchronized (implementation) { + + implementation.notifyAll(); + } + } + + if (event.getType() == ServiceEvent.UNREGISTERING && reference.getBundle() == bundle) { + // TODO: Process deregistering of OSGi services. + } + } + } +} diff --git a/java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/runtime/OSGiImplementationProviderFactory.java b/java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/runtime/OSGiImplementationProviderFactory.java new file mode 100644 index 0000000000..814d37f203 --- /dev/null +++ b/java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/runtime/OSGiImplementationProviderFactory.java @@ -0,0 +1,111 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.implementation.osgi.runtime; + + +import org.apache.tuscany.sca.context.ContextFactoryExtensionPoint; +import org.apache.tuscany.sca.context.RequestContextFactory; +import org.apache.tuscany.sca.contribution.ModelFactoryExtensionPoint; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.core.UtilityExtensionPoint; +import org.apache.tuscany.sca.core.invocation.ExtensibleProxyFactory; +import org.apache.tuscany.sca.core.invocation.ProxyFactory; +import org.apache.tuscany.sca.core.invocation.ProxyFactoryExtensionPoint; +import org.apache.tuscany.sca.core.scope.ScopeRegistry; +import org.apache.tuscany.sca.databinding.DataBindingExtensionPoint; +import org.apache.tuscany.sca.databinding.TransformerExtensionPoint; +import org.apache.tuscany.sca.databinding.impl.MediatorImpl; +import org.apache.tuscany.sca.implementation.java.injection.JavaPropertyValueObjectFactory; +import org.apache.tuscany.sca.implementation.osgi.OSGiImplementation; +import org.apache.tuscany.sca.interfacedef.InterfaceContractMapper; +import org.apache.tuscany.sca.invocation.MessageFactory; +import org.apache.tuscany.sca.provider.ImplementationProvider; +import org.apache.tuscany.sca.provider.ImplementationProviderFactory; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.osgi.framework.BundleException; + + +/** + * Builds a OSGi-based implementation provider from a component definition + * + * @version $Rev$ $Date$ + */ +public class OSGiImplementationProviderFactory implements ImplementationProviderFactory { + + private DataBindingExtensionPoint dataBindings; + private JavaPropertyValueObjectFactory propertyFactory; + private ProxyFactory proxyFactory; + private ScopeRegistry scopeRegistry; + private MessageFactory messageFactory; + private InterfaceContractMapper mapper; + + private RequestContextFactory requestContextFactory; + + public OSGiImplementationProviderFactory(ExtensionPointRegistry extensionPoints ) { + + dataBindings = extensionPoints.getExtensionPoint(DataBindingExtensionPoint.class); + ProxyFactoryExtensionPoint proxyFactories = extensionPoints.getExtensionPoint(ProxyFactoryExtensionPoint.class); + proxyFactory = new ExtensibleProxyFactory(proxyFactories); + ContextFactoryExtensionPoint contextFactories = extensionPoints.getExtensionPoint(ContextFactoryExtensionPoint.class); + requestContextFactory = contextFactories.getFactory(RequestContextFactory.class); + + + // FIXME: Scope registry is not an extension point, and this usage is specific + // to implementation.osgi since it needs to change scope after the component is + // created. Do we need to find a better way? + scopeRegistry = extensionPoints.getExtensionPoint(ScopeRegistry.class); + + TransformerExtensionPoint transformers = extensionPoints.getExtensionPoint(TransformerExtensionPoint.class); + MediatorImpl mediator = new MediatorImpl(dataBindings, transformers); + propertyFactory = new JavaPropertyValueObjectFactory(mediator); + + ModelFactoryExtensionPoint modelFactories = extensionPoints.getExtensionPoint(ModelFactoryExtensionPoint.class); + messageFactory = modelFactories.getFactory(MessageFactory.class); + + UtilityExtensionPoint utilities = extensionPoints.getExtensionPoint(UtilityExtensionPoint.class); + mapper = utilities.getUtility(InterfaceContractMapper.class); + } + + public ImplementationProvider createImplementationProvider(RuntimeComponent component, + OSGiImplementation implementation) { + + try { + + return new OSGiImplementationProvider(component, + implementation, + dataBindings, + propertyFactory, + proxyFactory, + scopeRegistry, + requestContextFactory, + messageFactory, + mapper + ); + + } catch (BundleException e) { + throw new RuntimeException(e); + } + + } + + public Class getModelType() { + return OSGiImplementation.class; + } + +} diff --git a/java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/runtime/OSGiInstanceWrapper.java b/java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/runtime/OSGiInstanceWrapper.java new file mode 100644 index 0000000000..a4fb1ec2ca --- /dev/null +++ b/java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/runtime/OSGiInstanceWrapper.java @@ -0,0 +1,299 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.implementation.osgi.runtime; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.util.Hashtable; +import java.util.Iterator; +import java.util.List; +import java.util.Random; +import java.util.jar.JarOutputStream; +import java.util.jar.Manifest; + +import org.apache.tuscany.sca.assembly.ComponentService; +import org.apache.tuscany.sca.core.context.InstanceWrapper; +import org.apache.tuscany.sca.core.scope.Scope; +import org.apache.tuscany.sca.core.scope.TargetDestructionException; +import org.apache.tuscany.sca.core.scope.TargetInitializationException; +import org.apache.tuscany.sca.implementation.osgi.context.OSGiAnnotations; +import org.apache.tuscany.sca.interfacedef.Interface; +import org.apache.tuscany.sca.interfacedef.java.JavaInterface; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.BundleException; +import org.osgi.framework.ServiceReference; +import org.oasisopen.sca.annotation.Destroy; +import org.oasisopen.sca.annotation.Init; + + +/** + * InstanceWrapper for creating instances for OSGi components. + * This class needs to implement InstanceWrapper since the wrapper is stored in + * the scope container. But getInstance() is called on this wrapper only through the + * OSGi target invoker. OSGiTargetInvoker always invokes getInstance for a specific + * service since one OSGi SCA component can associate different objects with + * different services (this is different from Java SCA components which always associate + * a single component instance with multiple services). + * + * @version $Rev$ $Date$ + */ +public class OSGiInstanceWrapper implements InstanceWrapper { + private static final Random RANDOM_NUMBER_GENERATOR = new Random(); + + private OSGiAnnotations annotationProcessor; + private OSGiImplementationProvider provider; + private BundleContext bundleContext; + private Hashtable> instanceInfoList = + new Hashtable>(); + + // Dummy bundles are used to create a new service object for scopes other than COMPOSITE + private Bundle dummyReferenceBundle; + + + public OSGiInstanceWrapper(OSGiImplementationProvider provider, + OSGiAnnotations annotationProcessor, + BundleContext bundleContext) { + + this.provider = provider; + this.annotationProcessor = annotationProcessor; + this.bundleContext = bundleContext; + } + + public synchronized T getInstance(ComponentService service) throws TargetInitializationException { + + // If an instance corresponding to this service has already been created, return the instance. + if (instanceInfoList.get(service) != null) + return instanceInfoList.get(service).osgiInstance; + + // There is no strict relation between service and callback instances. The instance semantics + // actually applies to the component instance in SCA. But for OSGi services, the callback + // is just another OSGi service, and could correspond to any of the service instances in + // the component. To implement the SCA scope semantics for callbacks, OSGi callbacks + // should also be made on the service object which implements the callback. The following code + // finds the first possible callback instance based on the interfaces implemented by the service + // objects in this component. Note that the interfaces are checked by name rather than using + // instanceof since the class seen by Tuscany could be from a different classloader from that + // used by the bundle. + if (service.isCallback()) { + Iterator> instances = instanceInfoList.values().iterator(); + while (instances.hasNext()) { + InstanceInfo instanceInfo = instances.next(); + Interface interfaze = service.getInterfaceContract().getInterface(); + if (interfaze instanceof JavaInterface && ((JavaInterface)interfaze).getJavaClass() != null) { + String interfaceName = ((JavaInterface)interfaze).getJavaClass().getName(); + Class[] interfaces = instanceInfo.osgiInstance.getClass().getInterfaces(); + for (Class clazz : interfaces) { + if (clazz.getName().equals(interfaceName)) { + return instanceInfo.osgiInstance; + } + } + + } + + } + } + + Bundle refBundle = provider.startBundle(true); + + // For scopes other than composite, the service object is obtained using a dummy reference + // bundle to guarantee that a new instance is created each time. This combined with the Tuscany + // scope container code guarantee SCA scope semantics for OSGi components as long as service + // factories are used. + if (!annotationProcessor.getScope().equals(Scope.COMPOSITE)) { + refBundle = getDummyReferenceBundle(); + } + + InstanceInfo instanceInfo = new InstanceInfo(); + + instanceInfo.refBundleContext = refBundle.getBundleContext(); + + instanceInfo.osgiInstance = getInstanceObject(instanceInfo, service); + + try { + + if (!isInitialized(instanceInfo.osgiInstance)) { + + annotationProcessor.injectProperties(instanceInfo.osgiInstance); + callLifecycleMethod(instanceInfo.osgiInstance, Init.class); + + instanceInfo.isFirstInstance = true; + } + + instanceInfoList.put(service, instanceInfo); + + } catch (Exception e) { + throw new TargetInitializationException(e); + } + + return instanceInfo.osgiInstance; + } + + + + // This method is provided purely to implement InstanceWrapper interface, and is never called. + public T getInstance() { + + return null; + } + + public void start() throws TargetInitializationException { + + if (provider.isEagerInit()) { + List services = provider.getRuntimeComponent().getServices(); + for (ComponentService service : services) { + getInstance(service); + } + } + } + + public synchronized void stop() throws TargetDestructionException { + + for (InstanceInfo instanceInfo : instanceInfoList.values()) { + if (instanceInfo.osgiInstance != null && instanceInfo.osgiServiceReference != null) { + + try { + + if (instanceInfo.isFirstInstance) + callLifecycleMethod(instanceInfo.osgiInstance, Destroy.class); + + instanceInfo.refBundleContext.ungetService(instanceInfo.osgiServiceReference); + + instanceInfo.osgiInstance = null; + instanceInfo.osgiServiceReference = null; + + } catch (Exception e) { + throw new TargetDestructionException(e); + } + } + } + instanceInfoList.clear(); + if (dummyReferenceBundle != null) { + try { + dummyReferenceBundle.uninstall(); + } catch (BundleException e) { + throw new TargetDestructionException(e); + } + dummyReferenceBundle = null; + } + } + + @SuppressWarnings("unchecked") + private T getInstanceObject(InstanceInfo instanceInfo, ComponentService service) { + + /** + * Since implementation.osgi is not well integrated with the OSGi lifecycle + * it is possible that the service is deactivated before the service instance + * is obtained when using declarative services. Retry in this case. + */ + int maxRetries = 10; + for (int i = 0; i < maxRetries; i++) { + instanceInfo.osgiServiceReference = provider.getOSGiServiceReference(service); + if (instanceInfo.osgiServiceReference == null) + return null; + T obj = (T)instanceInfo.refBundleContext.getService(instanceInfo.osgiServiceReference); + if (obj != null) + return obj; + } + return null; + } + + private Bundle getDummyReferenceBundle() throws TargetInitializationException { + + if (dummyReferenceBundle != null) + return dummyReferenceBundle; + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + + String EOL = System.getProperty("line.separator"); + String bundleName = "dummy.sca." + RANDOM_NUMBER_GENERATOR.nextInt(); + + + String manifestStr = "Manifest-Version: 1.0" + EOL + + "Bundle-ManifestVersion: 2" + EOL + + "Bundle-Name: " + bundleName + EOL + + "Bundle-SymbolicName: " + bundleName + EOL + + "Bundle-Version: " + "1.0.0" + EOL + + "Bundle-Localization: plugin" + EOL; + + + StringBuilder manifestBuf = new StringBuilder(); + manifestBuf.append(manifestStr); + + try { + ByteArrayInputStream manifestStream = new ByteArrayInputStream(manifestBuf.toString().getBytes()); + Manifest manifest = new Manifest(); + manifest.read(manifestStream); + + + JarOutputStream jarOut = new JarOutputStream(out, manifest); + + jarOut.close(); + out.close(); + + + ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); + + dummyReferenceBundle = bundleContext.installBundle("file://" + bundleName + ".jar", in); + + dummyReferenceBundle.start(); + + } catch (Exception e) { + throw new TargetInitializationException(e); + } + + return dummyReferenceBundle; + + } + + private void callLifecycleMethod(Object instance, + Class annotationClass) throws Exception { + + Method method = null; + if (annotationClass == Init.class) { + method = annotationProcessor.getInitMethod(instance); + } else if (annotationClass == Destroy.class) { + method = annotationProcessor.getDestroyMethod(instance); + } + + if (method != null) { + method.setAccessible(true); + method.invoke(instance); + } + } + + private boolean isInitialized(Object instance) { + for (InstanceInfo info : instanceInfoList.values()) { + if (info.osgiInstance == instance) + return true; + } + return false; + } + + private static class InstanceInfo { + private T osgiInstance; + private ServiceReference osgiServiceReference; + private BundleContext refBundleContext; + private boolean isFirstInstance; + + } + +} diff --git a/java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/runtime/OSGiRemotableInvoker.java b/java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/runtime/OSGiRemotableInvoker.java new file mode 100644 index 0000000000..deb44d26fb --- /dev/null +++ b/java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/runtime/OSGiRemotableInvoker.java @@ -0,0 +1,139 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.implementation.osgi.runtime; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.IdentityHashMap; +import java.util.Map; + +import org.apache.tuscany.sca.databinding.DataBinding; +import org.apache.tuscany.sca.databinding.DataBindingExtensionPoint; +import org.apache.tuscany.sca.implementation.osgi.context.OSGiAnnotations; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.DataExchangeSemantics; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; + +/** + * An interceptor to enforce pass-by-value semantics for remotable interfaces + * + * @version $Rev$ $Date$ + */ +public class OSGiRemotableInvoker extends OSGiTargetInvoker implements DataExchangeSemantics { + + private DataBindingExtensionPoint registry; + private Operation operation; + private OSGiAnnotations osgiAnnotations; + + /** + * @param registry + * @param operation + * @param method + * @param component + */ + public OSGiRemotableInvoker(OSGiAnnotations osgiAnnotations, + DataBindingExtensionPoint registry, + Operation operation, + OSGiImplementationProvider provider, + RuntimeComponentService service) { + super(operation, provider, service); + this.osgiAnnotations = osgiAnnotations; + this.registry = registry; + this.operation = operation; + } + + @Override + public Object invokeMethod(Object targetObject, Method m, Message msg) throws InvocationTargetException { + + Object result; + if (osgiAnnotations.isAllowsPassByReference(targetObject, m)) { + result = super.invokeMethod(targetObject, m, msg); + } else { + Object obj = msg.getBody(); + msg.setBody(copy((Object[])obj)); + + result = super.invokeMethod(targetObject, m, msg); + + if (operation.getOutputType() != null) { + String dataBindingId = operation.getOutputType().getDataBinding(); + DataBinding dataBinding = registry.getDataBinding(dataBindingId); + result = copy(result, operation.getOutputType(), dataBinding); + } + } + return result; + } + + public Object[] copy(Object[] args) { + if (args == null) { + return null; + } + Object[] copiedArgs = new Object[args.length]; + Map map = new IdentityHashMap(); + for (int i = 0; i < args.length; i++) { + if (args[i] == null) { + copiedArgs[i] = null; + } else { + Object copiedArg = map.get(args[i]); + if (copiedArg != null) { + copiedArgs[i] = copiedArg; + } else { + DataType dt = operation.getInputType().getLogical().get(i); + String dataBindingId = dt.getDataBinding(); + DataBinding dataBinding = registry.getDataBinding(dataBindingId); + copiedArg = copy(args[i], dt, dataBinding); + map.put(args[i], copiedArg); + copiedArgs[i] = copiedArg; + } + } + } + return copiedArgs; + } + + public Object copy(Object arg, DataType dataType, DataBinding argDataBinding) { + if (arg == null) { + return null; + } + Object copiedArg; + if (argDataBinding != null) { + copiedArg = argDataBinding.copy(arg, dataType, operation); + } else { + copiedArg = arg; + dataType = registry.introspectType(arg, operation); + if (dataType != null) { + DataBinding binding = registry.getDataBinding(dataType.getDataBinding()); + if (binding != null) { + copiedArg = binding.copy(arg, dataType, operation); + } + } + // FIXME: What to do if it's not recognized? + } + return copiedArg; + } + + /** + * @see org.apache.tuscany.sca.invocation.PassByValueAware#allowsPassByReference() + */ + public boolean allowsPassByReference() { + return true; + } + +} diff --git a/java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/runtime/OSGiTargetInvoker.java b/java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/runtime/OSGiTargetInvoker.java new file mode 100644 index 0000000000..deb39a47cd --- /dev/null +++ b/java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/runtime/OSGiTargetInvoker.java @@ -0,0 +1,199 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.implementation.osgi.runtime; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +import org.apache.tuscany.sca.core.context.InstanceWrapper; +import org.apache.tuscany.sca.core.invocation.TargetInvocationException; +import org.apache.tuscany.sca.core.scope.Scope; +import org.apache.tuscany.sca.core.scope.ScopeContainer; +import org.apache.tuscany.sca.core.scope.TargetResolutionException; +import org.apache.tuscany.sca.interfacedef.ConversationSequence; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.interfacedef.java.impl.JavaInterfaceUtil; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.runtime.EndpointReference; +import org.apache.tuscany.sca.runtime.ReferenceParameters; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; + +/** + * Java->OSGi references use OSGiTargetInvoker to call methods from OSGi bundles + * OSGi->Java references use JDKProxyService and invocation handler and do not use this class + * OSGi->OSGi references go through OSGi reference mechanisms when a proxy is not used + * When a proxy is used, this invoker is used to call methods from OSGi bundles + * A proxy is used for OSGi->OSGi if + * 1) target reference properties are specified OR + * 2) there are one or more non-blocking methods in the target interface OR + * 3) scope is not COMPOSITE + * + * @version $Rev$ $Date$ + */ +public class OSGiTargetInvoker implements Invoker { + + private Operation operation; + protected InstanceWrapper target; + + private final OSGiImplementationProvider provider; + private final RuntimeComponentService service; + + // Scope container is reset by the OSGi implementation provider if @Scope + // annotation is used to modify the scope (default is composite) + // Hence this field is initialized on the first invoke. + private ScopeContainer scopeContainer; + + public OSGiTargetInvoker( + Operation operation, + OSGiImplementationProvider provider, + RuntimeComponentService service) { + + + this.operation = operation; + this.service = service; + this.provider = provider; + + } + + /** + * Resolves the target service instance or returns a cached one + */ + @SuppressWarnings("unchecked") + protected InstanceWrapper getInstance(Object contextId) + throws TargetResolutionException, TargetInvocationException { + + if (scopeContainer == null) + scopeContainer = provider.getScopeContainer(); + + + return scopeContainer.getWrapper(contextId); + + } + + @SuppressWarnings("unchecked") + private Object invokeTarget(Message msg) throws InvocationTargetException { + + if (scopeContainer == null) + scopeContainer = provider.getScopeContainer(); + + + Operation op = msg.getOperation(); + if (op == null) { + op = this.operation; + } + ConversationSequence sequence = op.getConversationSequence(); + + Object contextId = null; + + EndpointReference from = msg.getFrom(); + ReferenceParameters parameters = null; + + if (from != null) { + parameters = from.getReferenceParameters(); + } + // check what sort of context is required + if (scopeContainer != null) { + Scope scope = scopeContainer.getScope(); + if (scope == Scope.REQUEST) { + contextId = Thread.currentThread(); + } else if (scope == Scope.CONVERSATION && parameters != null) { + contextId = parameters.getConversationID(); + } + } + + try { + + OSGiInstanceWrapper wrapper = (OSGiInstanceWrapper)getInstance(contextId); + Object instance; + + + // detects whether the scope container has created a conversation Id. This will + // happen in the case that the component has conversational scope but only the + // callback interface is conversational. Or in the callback case if the service interface + // is conversational and the callback interface isn't. If we are in this situation we need + // to get the contextId of this component and remove it after we have invoked the method on + // it. It is possible that the component instance will not go away when it is removed below + // because a callback conversation will still be holding a reference to it + boolean removeTemporaryConversationalComponentAfterCall = false; + if (parameters != null && (contextId == null) && (parameters.getConversationID() != null)) { + contextId = parameters.getConversationID(); + removeTemporaryConversationalComponentAfterCall = true; + } + + instance = wrapper.getInstance(service); + + Method m = JavaInterfaceUtil.findMethod(instance.getClass(), operation); + + Object ret = invokeMethod(instance, m, msg); + + scopeContainer.returnWrapper(wrapper, contextId); + + if ((sequence == ConversationSequence.CONVERSATION_END) || (removeTemporaryConversationalComponentAfterCall)) { + // if end conversation, or we have the special case where a conversational + // object was created to service the stateless half of a stateful component + scopeContainer.remove(contextId); + parameters.setConversationID(null); + } + + return ret; + } catch (InvocationTargetException e) { + throw e; + } catch (Exception e) { + throw new InvocationTargetException(e); + } + } + + protected Object invokeMethod(Object instance, Method m, Message msg) throws InvocationTargetException { + + try { + + Object payload = msg.getBody(); + + if (payload != null && !payload.getClass().isArray()) { + return m.invoke(instance, payload); + } else { + return m.invoke(instance, (Object[])payload); + } + + } catch (InvocationTargetException e) { + throw e; + } catch (Exception e) { + throw new InvocationTargetException(e); + } + } + + public Message invoke(Message msg) { + try { + // Object messageId = msg.getMessageID(); + // Message workContext = ThreadMessageContext.getMessageContext(); + // if (messageId != null) { + // workContext.setCorrelationID(messageId); + // } + Object resp = invokeTarget(msg); + msg.setBody(resp); + } catch (InvocationTargetException e) { + msg.setFaultBody(e.getCause()); + } + return msg; + } + + +} diff --git a/java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/xml/OSGiImplementationProcessor.java b/java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/xml/OSGiImplementationProcessor.java new file mode 100644 index 0000000000..7f246cb76c --- /dev/null +++ b/java/sca/contrib/modules/implementation-osgi/src/main/java/org/apache/tuscany/sca/implementation/osgi/xml/OSGiImplementationProcessor.java @@ -0,0 +1,550 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.implementation.osgi.xml; + +import static javax.xml.XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI; +import static javax.xml.XMLConstants.XMLNS_ATTRIBUTE_NS_URI; +import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; +import static javax.xml.stream.XMLStreamConstants.START_ELEMENT; + +import java.util.ArrayList; +import java.util.Hashtable; +import java.util.List; +import java.util.StringTokenizer; + +import javax.xml.namespace.QName; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.stream.XMLStreamConstants; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; + +import org.apache.tuscany.sca.assembly.AssemblyFactory; +import org.apache.tuscany.sca.assembly.ComponentProperty; +import org.apache.tuscany.sca.assembly.ComponentType; +import org.apache.tuscany.sca.assembly.Property; +import org.apache.tuscany.sca.assembly.Reference; +import org.apache.tuscany.sca.assembly.Service; +import org.apache.tuscany.sca.assembly.builder.impl.ProblemImpl; +import org.apache.tuscany.sca.assembly.xml.Constants; +import org.apache.tuscany.sca.contribution.ModelFactoryExtensionPoint; +import org.apache.tuscany.sca.contribution.osgi.BundleReference; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.resolver.ClassReference; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.contribution.service.ContributionReadException; +import org.apache.tuscany.sca.contribution.service.ContributionResolveException; +import org.apache.tuscany.sca.contribution.service.ContributionWriteException; +import org.apache.tuscany.sca.databinding.impl.SimpleTypeMapperImpl; +import org.apache.tuscany.sca.implementation.osgi.impl.OSGiImplementationImpl; +import org.apache.tuscany.sca.interfacedef.Interface; +import org.apache.tuscany.sca.interfacedef.InvalidInterfaceException; +import org.apache.tuscany.sca.interfacedef.java.JavaInterface; +import org.apache.tuscany.sca.interfacedef.java.JavaInterfaceContract; +import org.apache.tuscany.sca.interfacedef.java.JavaInterfaceFactory; +import org.apache.tuscany.sca.monitor.Monitor; +import org.apache.tuscany.sca.monitor.Problem; +import org.apache.tuscany.sca.monitor.Problem.Severity; +import org.osgi.framework.Bundle; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; + +/** + * + * Process an element in a component definition. An instance of + * OSGiImplementation is created. + * Also associates the component type file with the implementation. + * + * @version $Rev$ $Date$ + */ +public class OSGiImplementationProcessor implements StAXArtifactProcessor { + + public static final QName IMPLEMENTATION_OSGI = new QName(Constants.SCA10_TUSCANY_NS, "implementation.osgi"); + + private static final String BUNDLE_SYMBOLICNAME= "bundleSymbolicName"; + private static final String BUNDLE_VERSION = "bundleVersion"; + private static final String CLASSES = "classes"; + private static final String IMPORTS = "imports"; + + private static final QName PROPERTIES_QNAME = new QName(Constants.SCA10_TUSCANY_NS, "properties"); + private static final QName PROPERTY_QNAME = new QName(Constants.SCA10_TUSCANY_NS, "property"); + + private JavaInterfaceFactory javaInterfaceFactory; + private AssemblyFactory assemblyFactory; + private ModelFactoryExtensionPoint modelFactories; + private Monitor monitor; + + private static final DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); + static { + domFactory.setNamespaceAware(true); + } + + public OSGiImplementationProcessor(ModelFactoryExtensionPoint modelFactories, Monitor monitor) { + this.monitor = monitor; + this.modelFactories = modelFactories; + this.assemblyFactory = modelFactories.getFactory(AssemblyFactory.class); + this.javaInterfaceFactory = modelFactories.getFactory(JavaInterfaceFactory.class); + } + + /** + * Report a exception. + * + * @param problems + * @param message + * @param model + */ + private void error(String message, Object model, Exception ex) { + if (monitor != null) { + Problem problem = new ProblemImpl(this.getClass().getName(), "impl-osgi-validation-messages", Severity.ERROR, model, message, ex); + monitor.problem(problem); + } + } + + /** + * Report a error. + * + * @param problems + * @param message + * @param model + */ + private void error(String message, Object model, Object... messageParameters) { + if (monitor != null) { + Problem problem = new ProblemImpl(this.getClass().getName(), "impl-osgi-validation-messages", Severity.ERROR, model, message, (Object[])messageParameters); + monitor.problem(problem); + } + } + + public QName getArtifactType() { + return IMPLEMENTATION_OSGI; + } + + public Class getModelType() { + return OSGiImplementationImpl.class; + } + + private String[] tokenize(String str) { + StringTokenizer tokenizer = new StringTokenizer(str); + String[] tokens = new String[tokenizer.countTokens()]; + for (int i= 0; i < tokens.length; i++) { + tokens[i] = tokenizer.nextToken(); + } + + return tokens; + } + + public OSGiImplementationImpl read(XMLStreamReader reader) throws ContributionReadException, XMLStreamException { + assert IMPLEMENTATION_OSGI.equals(reader.getName()); + + String bundleSymbolicName = reader.getAttributeValue(null, BUNDLE_SYMBOLICNAME); + String bundleVersion = reader.getAttributeValue(null, BUNDLE_VERSION); + String imports = reader.getAttributeValue(null, IMPORTS); + String[] importList; + if (imports != null) + importList = tokenize(imports); + else + importList = new String[0]; + String classes = reader.getAttributeValue(null, CLASSES); + String[] classList; + if (classes != null) + classList = tokenize(classes); + else + classList = new String[0]; + + Hashtable> refProperties = + new Hashtable>(); + Hashtable> serviceProperties = + new Hashtable>(); + Hashtable> refCallbackProperties = + new Hashtable>(); + Hashtable> serviceCallbackProperties = + new Hashtable>(); + + while (reader.hasNext()) { + + int next = reader.next(); + if (next == END_ELEMENT && IMPLEMENTATION_OSGI.equals(reader.getName())) { + break; + } + else if (next == START_ELEMENT && PROPERTIES_QNAME.equals(reader.getName())) { + + // FIXME: This is temporary code which allows reference and service properties used + // for filtering OSGi services to be specified in + // This should really be provided in the component type file since these + // properties are associated with an implementation rather than a configured + // instance of an implementation. + String refName = reader.getAttributeValue(null, "reference"); + String serviceName = reader.getAttributeValue(null, "service"); + String refCallbackName = reader.getAttributeValue(null, "referenceCallback"); + String serviceCallbackName = reader.getAttributeValue(null, "serviceCallback"); + List props = readProperties(reader); + if (refName != null) + refProperties.put(refName, props); + else if (serviceName != null) + serviceProperties.put(serviceName, props); + else if (refCallbackName != null) + refCallbackProperties.put(refCallbackName, props); + else if (serviceCallbackName != null) + serviceCallbackProperties.put(serviceCallbackName, props); + else { + error("PropertyShouldSpecifySR", reader); + //throw new ContributionReadException("Properties in implementation.osgi should specify service or reference"); + } + } + + } + + OSGiImplementationImpl implementation = new OSGiImplementationImpl( + modelFactories, + bundleSymbolicName, + bundleVersion, + importList, + classList, + refProperties, + serviceProperties); + implementation.setCallbackProperties(refCallbackProperties, serviceCallbackProperties); + + implementation.setUnresolved(true); + + return implementation; + + } + + + public void resolve(OSGiImplementationImpl impl, ModelResolver resolver) throws ContributionResolveException { + + try { + + if (impl == null || !impl.isUnresolved()) + return; + + impl.setUnresolved(false); + + BundleReference bundleReference = new BundleReference(impl.getBundleSymbolicName(), impl.getBundleVersion()); + BundleReference resolvedBundle = resolver.resolveModel(BundleReference.class, bundleReference); + Bundle bundle = (Bundle)resolvedBundle.getBundle(); + if (bundle != null) { + impl.setOSGiBundle(bundle); + } else { + error("CouldNotLocateOSGiBundle", impl, impl.getBundleSymbolicName()); + //throw new ContributionResolveException("Could not locate OSGi bundle " + + //impl.getBundleSymbolicName()); + return; + } + + String bundleName = resolvedBundle.getBundleRelativePath(); + String ctURI = bundleName.endsWith(".jar") || bundleName.endsWith(".JAR")? + bundleName.substring(0, bundleName.lastIndexOf(".")) : bundleName; + ctURI = ctURI.replaceAll("\\.", "/"); + ctURI = ctURI + ".componentType"; + + ComponentType componentType = assemblyFactory.createComponentType(); + componentType.setURI(ctURI); + componentType.setUnresolved(true); + componentType = resolver.resolveModel(ComponentType.class, componentType); + if (componentType.isUnresolved()) { + error("MissingComponentTypeFile", impl, ctURI); + //throw new ContributionResolveException("missing .componentType side file " + ctURI); + return; + } + + List services = componentType.getServices(); + for (Service service : services) { + Interface interfaze = service.getInterfaceContract().getInterface(); + if (interfaze instanceof JavaInterface) { + JavaInterface javaInterface = (JavaInterface)interfaze; + if (javaInterface.getJavaClass() == null) { + + javaInterface.setJavaClass(getJavaClass(resolver, javaInterface.getName())); + } + Class callback = null; + if (service.getInterfaceContract().getCallbackInterface() instanceof JavaInterface) { + JavaInterface callbackInterface = (JavaInterface)service.getInterfaceContract().getCallbackInterface(); + if (callbackInterface.getJavaClass() == null) { + callbackInterface.setJavaClass(getJavaClass(resolver, callbackInterface.getName())); + } + callback = callbackInterface.getJavaClass(); + } + + Service serv = createService(service, javaInterface.getJavaClass(), callback); + impl.getServices().add(serv); + } + } + + List references = componentType.getReferences(); + for (Reference reference : references) { + Interface interfaze = reference.getInterfaceContract().getInterface(); + if (interfaze instanceof JavaInterface) { + JavaInterface javaInterface = (JavaInterface)interfaze; + if (javaInterface.getJavaClass() == null) { + javaInterface.setJavaClass(getJavaClass(resolver, javaInterface.getName())); + } + Reference ref = createReference(reference, javaInterface.getJavaClass()); + impl.getReferences().add(ref); + } + else + impl.getReferences().add(reference); + } + + List properties = componentType.getProperties(); + for (Property property : properties) { + impl.getProperties().add(property); + } + impl.setConstrainingType(componentType.getConstrainingType()); + + } catch (InvalidInterfaceException e) { + ContributionResolveException ce = new ContributionResolveException(e); + error("ContributionResolveException", resolver, ce); + //throw ce; + } + + } + + + private Class getJavaClass(ModelResolver resolver, String className) { + ClassReference ref = new ClassReference(className); + ref = resolver.resolveModel(ClassReference.class, ref); + return ref.getJavaClass(); + } + + private Service createService(Service serv, Class interfaze, Class callbackInterfaze) throws InvalidInterfaceException { + Service service = assemblyFactory.createService(); + JavaInterfaceContract interfaceContract = javaInterfaceFactory.createJavaInterfaceContract(); + service.setInterfaceContract(interfaceContract); + + + // create a relative URI + service.setName(serv.getName()); + + JavaInterface callInterface = javaInterfaceFactory.createJavaInterface(interfaze); + service.getInterfaceContract().setInterface(callInterface); + + if (callbackInterfaze != null) { + JavaInterface callbackInterface = javaInterfaceFactory.createJavaInterface(callbackInterfaze); + service.getInterfaceContract().setCallbackInterface(callbackInterface); + } + else if (callInterface.getCallbackClass() != null) { + JavaInterface callbackInterface = javaInterfaceFactory.createJavaInterface(callInterface.getCallbackClass()); + service.getInterfaceContract().setCallbackInterface(callbackInterface); + } + return service; + } + + private Reference createReference(Reference ref, Class clazz) throws InvalidInterfaceException { + org.apache.tuscany.sca.assembly.Reference reference = assemblyFactory.createReference(); + JavaInterfaceContract interfaceContract = javaInterfaceFactory.createJavaInterfaceContract(); + reference.setInterfaceContract(interfaceContract); + + reference.setName(ref.getName()); + reference.setMultiplicity(ref.getMultiplicity()); + + JavaInterface callInterface = javaInterfaceFactory.createJavaInterface(clazz); + reference.getInterfaceContract().setInterface(callInterface); + if (callInterface.getCallbackClass() != null) { + JavaInterface callbackInterface = javaInterfaceFactory.createJavaInterface(callInterface.getCallbackClass()); + reference.getInterfaceContract().setCallbackInterface(callbackInterface); + } + + return reference; + } + + public void write(OSGiImplementationImpl model, XMLStreamWriter outputSource) throws ContributionWriteException, XMLStreamException { + + //FIXME Implement this method + } + + + private QName getQNameValue(XMLStreamReader reader, String value) { + if (value != null) { + int index = value.indexOf(':'); + String prefix = index == -1 ? "" : value.substring(0, index); + String localName = index == -1 ? value : value.substring(index + 1); + String ns = reader.getNamespaceContext().getNamespaceURI(prefix); + if (ns == null) { + ns = ""; + } + return new QName(ns, localName, prefix); + } else { + return null; + } + } + + private void declareNamespace(Element element, String prefix, String ns) { + String qname = null; + if ("".equals(prefix)) { + qname = "xmlns"; + } else { + qname = "xmlns:" + prefix; + } + Node node = element; + boolean declared = false; + while (node != null && node.getNodeType() == Node.ELEMENT_NODE) { + NamedNodeMap attrs = node.getAttributes(); + if (attrs == null) { + break; + } + Node attr = attrs.getNamedItem(qname); + if (attr != null) { + declared = ns.equals(attr.getNodeValue()); + break; + } + node = node.getParentNode(); + } + if (!declared) { + org.w3c.dom.Attr attr = element.getOwnerDocument().createAttributeNS(XMLNS_ATTRIBUTE_NS_URI, qname); + attr.setValue(ns); + element.setAttributeNodeNS(attr); + } + } + + private Element createElement(Document document, QName name) { + String prefix = name.getPrefix(); + String qname = (prefix != null && prefix.length() > 0) ? prefix + ":" + name.getLocalPart() : name + .getLocalPart(); + return document.createElementNS(name.getNamespaceURI(), qname); + } + + private void loadElement(XMLStreamReader reader, Element root) throws XMLStreamException { + Document document = root.getOwnerDocument(); + Node current = root; + while (true) { + switch (reader.next()) { + case XMLStreamConstants.START_ELEMENT: + QName name = reader.getName(); + Element child = createElement(document, name); + + // push the new element and make it the current one + current.appendChild(child); + current = child; + + declareNamespace(child, name.getPrefix(), name.getNamespaceURI()); + + int count = reader.getNamespaceCount(); + for (int i = 0; i < count; i++) { + String prefix = reader.getNamespacePrefix(i); + String ns = reader.getNamespaceURI(i); + declareNamespace(child, prefix, ns); + } + + // add the attributes for this element + count = reader.getAttributeCount(); + for (int i = 0; i < count; i++) { + String ns = reader.getAttributeNamespace(i); + String prefix = reader.getAttributePrefix(i); + String localPart = reader.getAttributeLocalName(i); + String value = reader.getAttributeValue(i); + child.setAttributeNS(ns, localPart, value); + declareNamespace(child, prefix, ns); + } + + break; + case XMLStreamConstants.CDATA: + current.appendChild(document.createCDATASection(reader.getText())); + break; + case XMLStreamConstants.CHARACTERS: + current.appendChild(document.createTextNode(reader.getText())); + break; + case XMLStreamConstants.END_ELEMENT: + // if we are back at the root then we are done + if (current == root) { + return; + } + + // pop the element off the stack + current = current.getParentNode(); + } + } + } + + private Document readPropertyValue(XMLStreamReader reader, QName type) + throws XMLStreamException, ParserConfigurationException { + + Document doc = domFactory.newDocumentBuilder().newDocument(); + + // root element has no namespace and local name "value" + Element root = doc.createElementNS(null, "value"); + if (type != null) { + org.w3c.dom.Attr xsi = doc.createAttributeNS(XMLNS_ATTRIBUTE_NS_URI, "xmlns:xsi"); + xsi.setValue(W3C_XML_SCHEMA_INSTANCE_NS_URI); + root.setAttributeNodeNS(xsi); + + String prefix = type.getPrefix(); + if (prefix == null || prefix.length() == 0) { + prefix = "ns"; + } + + declareNamespace(root, prefix, type.getNamespaceURI()); + + org.w3c.dom.Attr xsiType = doc.createAttributeNS(W3C_XML_SCHEMA_INSTANCE_NS_URI, "xsi:type"); + xsiType.setValue(prefix + ":" + type.getLocalPart()); + root.setAttributeNodeNS(xsiType); + } + doc.appendChild(root); + + loadElement(reader, root); + return doc; + } + + private void readProperty(ComponentProperty prop, XMLStreamReader reader) + throws XMLStreamException, ContributionReadException { + + + prop.setName(reader.getAttributeValue(null, "name")); + String xsdType = reader.getAttributeValue(null, "type"); + if (xsdType != null) + prop.setXSDType(getQNameValue(reader, xsdType)); + else + prop.setXSDType(SimpleTypeMapperImpl.XSD_STRING); + + try { + Document value = readPropertyValue(reader, prop.getXSDType()); + prop.setValue(value); + } catch (ParserConfigurationException e) { + ContributionReadException ce = new ContributionReadException(e); + error("ContributionReadException", reader, ce); + throw ce; + } + } + + private List readProperties(XMLStreamReader reader) + throws XMLStreamException, ContributionReadException { + + List properties = new ArrayList(); + + while (reader.hasNext()) { + + int next = reader.next(); + if (next == END_ELEMENT && PROPERTIES_QNAME.equals(reader.getName())) { + break; + } + else if (next == START_ELEMENT && PROPERTY_QNAME.equals(reader.getName())) { + + ComponentProperty componentProperty = assemblyFactory.createComponentProperty(); + readProperty(componentProperty, reader); + properties.add(componentProperty); + } + } + + return properties; + + } + +} diff --git a/java/sca/contrib/modules/implementation-osgi/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor b/java/sca/contrib/modules/implementation-osgi/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor new file mode 100644 index 0000000000..9ecff71874 --- /dev/null +++ b/java/sca/contrib/modules/implementation-osgi/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for the artifact processor extension +org.apache.tuscany.sca.implementation.osgi.xml.OSGiImplementationProcessor;qname=http://tuscany.apache.org/xmlns/sca/1.0#implementation.osgi,model=org.apache.tuscany.sca.implementation.osgi.OSGiImplementation diff --git a/java/sca/contrib/modules/implementation-osgi/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.ImplementationProviderFactory b/java/sca/contrib/modules/implementation-osgi/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.ImplementationProviderFactory new file mode 100644 index 0000000000..c2cd957351 --- /dev/null +++ b/java/sca/contrib/modules/implementation-osgi/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.ImplementationProviderFactory @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for the implementation extension +org.apache.tuscany.sca.implementation.osgi.runtime.OSGiImplementationProviderFactory;model=org.apache.tuscany.sca.implementation.osgi.OSGiImplementation diff --git a/java/sca/contrib/modules/implementation-osgi/src/main/resources/impl-osgi-validation-messages.properties b/java/sca/contrib/modules/implementation-osgi/src/main/resources/impl-osgi-validation-messages.properties new file mode 100644 index 0000000000..2503be0b13 --- /dev/null +++ b/java/sca/contrib/modules/implementation-osgi/src/main/resources/impl-osgi-validation-messages.properties @@ -0,0 +1,25 @@ +# +# +# 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. +# +# +ContributionReadException = ContributionReadException occured due to: +ContributionResolveException = ContributionResolveException occured due to: +PropertyShouldSpecifySR = Properties in implementation.osgi should specify service or reference +CouldNotLocateOSGiBundle = Could not locate OSGi bundle: {0} +MissingComponentTypeFile = Missing .componentType side file: {0} \ No newline at end of file diff --git a/java/sca/contrib/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/runtime/OSGiPropertyTestCase.java b/java/sca/contrib/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/runtime/OSGiPropertyTestCase.java new file mode 100644 index 0000000000..fb4cb4207a --- /dev/null +++ b/java/sca/contrib/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/runtime/OSGiPropertyTestCase.java @@ -0,0 +1,49 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.implementation.osgi.runtime; + +import org.apache.tuscany.sca.implementation.osgi.test.OSGiTestBundles; +import org.apache.tuscany.sca.implementation.osgi.test.OSGiTestInterface; +import org.apache.tuscany.sca.implementation.osgi.test.OSGiTestWithPropertyImpl; + + +/** + * + * Test the execution of an OSGi implementation type + * + * @version $Rev$ $Date$ + */ +public class OSGiPropertyTestCase extends OSGiTestCase { + + @Override + protected void setUp() throws Exception { + + className = OSGiTestWithPropertyImpl.class.getName(); + compositeName = "osgiproptest.composite"; + + OSGiTestBundles.createBundle("target/test-classes/OSGiTestService.jar", + OSGiTestInterface.class, + OSGiTestWithPropertyImpl.class); + + } + + + +} diff --git a/java/sca/contrib/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/runtime/OSGiTestCase.java b/java/sca/contrib/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/runtime/OSGiTestCase.java new file mode 100644 index 0000000000..6a6d80f15e --- /dev/null +++ b/java/sca/contrib/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/runtime/OSGiTestCase.java @@ -0,0 +1,74 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.implementation.osgi.runtime; + +import java.lang.reflect.Proxy; + +import junit.framework.TestCase; + +import org.apache.tuscany.sca.host.embedded.SCADomain; +import org.apache.tuscany.sca.implementation.osgi.test.OSGiTestBundles; +import org.apache.tuscany.sca.implementation.osgi.test.OSGiTestImpl; +import org.apache.tuscany.sca.implementation.osgi.test.OSGiTestInterface; +import org.apache.tuscany.sca.osgi.runtime.OSGiRuntime; + + +/** + * + * Test the execution of an OSGi implementation type + * + * @version $Rev$ $Date$ + */ +public class OSGiTestCase extends TestCase { + + protected String className; + protected String compositeName; + + protected void setUp() throws Exception { + + className = OSGiTestImpl.class.getName(); + compositeName = "osgitest.composite"; + OSGiTestBundles.createBundle("target/test-classes/OSGiTestService.jar", OSGiTestInterface.class, OSGiTestImpl.class); + + } + + + @Override + protected void tearDown() throws Exception { + OSGiRuntime.stop(); + } + + public void testOSGiComponent() throws Exception { + + SCADomain scaDomain = SCADomain.newInstance(compositeName); + OSGiTestInterface testService = scaDomain.getService(OSGiTestInterface.class, "OSGiTestServiceComponent"); + assert(testService != null); + + assert(testService instanceof Proxy); + + String str = testService.testService(); + + assertEquals(className, str); + + scaDomain.close(); + + } + +} diff --git a/java/sca/contrib/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/test/OSGiTestBundles.java b/java/sca/contrib/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/test/OSGiTestBundles.java new file mode 100644 index 0000000000..93b4dee033 --- /dev/null +++ b/java/sca/contrib/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/test/OSGiTestBundles.java @@ -0,0 +1,116 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.implementation.osgi.test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.net.URL; +import java.util.jar.JarOutputStream; +import java.util.jar.Manifest; +import java.util.zip.ZipEntry; + + +/** + * + * Utility class to create OSGi bundles + * + * @version $Rev$ $Date$ + */ +public class OSGiTestBundles { + private static String getPackageName(Class cls) { + String name = cls.getName(); + int index = name.lastIndexOf('.'); + return index == -1 ? "" : name.substring(0, index); + } + + public static void createBundle(String jarName, + Class interfaceClass, Class implClass) throws Exception { + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + + String EOL = System.getProperty("line.separator"); + + String packageName = getPackageName(interfaceClass); + String bundleName = interfaceClass.getName(); + + String manifestStr = "Manifest-Version: 1.0" + EOL + + "Bundle-ManifestVersion: 2" + EOL + "Bundle-Name: " + + bundleName + EOL + "Bundle-SymbolicName: " + bundleName + EOL + + "Bundle-Version: " + "1.0.0" + EOL + + "Bundle-Localization: plugin" + EOL; + + StringBuilder manifestBuf = new StringBuilder(); + manifestBuf.append(manifestStr); + manifestBuf.append("Export-Package: " + packageName + EOL); + manifestBuf.append("Import-Package: org.osgi.framework" + EOL); + manifestBuf.append("Bundle-Activator: " + implClass.getName() + EOL); + + ByteArrayInputStream manifestStream = new ByteArrayInputStream(manifestBuf.toString().getBytes()); + Manifest manifest = new Manifest(); + manifest.read(manifestStream); + + + JarOutputStream jarOut = new JarOutputStream(out, manifest); + + String interfaceClassName = interfaceClass.getName().replaceAll("\\.", + "/") + + ".class"; + + URL url = interfaceClass.getClassLoader().getResource( + interfaceClassName); + String path = url.getPath(); + + ZipEntry ze = new ZipEntry(interfaceClassName); + + jarOut.putNextEntry(ze); + FileInputStream file = new FileInputStream(path); + byte[] fileContents = new byte[file.available()]; + file.read(fileContents); + jarOut.write(fileContents); + + String implClassName = implClass.getName().replaceAll("\\.", + "/") + + ".class"; + + url = implClass.getClassLoader().getResource(implClassName); + path = url.getPath(); + + ze = new ZipEntry(implClassName); + + jarOut.putNextEntry(ze); + file = new FileInputStream(path); + fileContents = new byte[file.available()]; + file.read(fileContents); + jarOut.write(fileContents); + + file.close(); + + jarOut.close(); + out.close(); + + FileOutputStream fileOut = new FileOutputStream(jarName); + fileOut.write(out.toByteArray()); + fileOut.close(); + + + } +} diff --git a/java/sca/contrib/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/test/OSGiTestImpl.java b/java/sca/contrib/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/test/OSGiTestImpl.java new file mode 100644 index 0000000000..d412f6bd6a --- /dev/null +++ b/java/sca/contrib/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/test/OSGiTestImpl.java @@ -0,0 +1,51 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.implementation.osgi.test; + +import java.util.Hashtable; + +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; + +/** + * + * Test class - Implementation of an OSGi service + * + * @version $Rev$ $Date$ + */ +public class OSGiTestImpl implements OSGiTestInterface, BundleActivator { + + public String testService() { + + return OSGiTestImpl.class.getName(); + + } + + public void start(BundleContext bc) throws Exception { + + bc.registerService(OSGiTestInterface.class.getName(), this, new Hashtable()); + + } + + public void stop(BundleContext bc) throws Exception { + } + + +} diff --git a/java/sca/contrib/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/test/OSGiTestInterface.java b/java/sca/contrib/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/test/OSGiTestInterface.java new file mode 100644 index 0000000000..feb9ce177e --- /dev/null +++ b/java/sca/contrib/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/test/OSGiTestInterface.java @@ -0,0 +1,32 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.implementation.osgi.test; + +/** + * + * Test class - Interface for an OSGi service + * + * @version $Rev$ $Date$ + */ +public interface OSGiTestInterface { + + String testService() throws Exception ; + +} diff --git a/java/sca/contrib/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/test/OSGiTestWithPropertyImpl.java b/java/sca/contrib/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/test/OSGiTestWithPropertyImpl.java new file mode 100644 index 0000000000..e59032e3ea --- /dev/null +++ b/java/sca/contrib/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/test/OSGiTestWithPropertyImpl.java @@ -0,0 +1,66 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.implementation.osgi.test; + +import java.util.Hashtable; + +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; +import org.oasisopen.sca.annotation.Property; + +/** + * + * Test class - Implementation of an OSGi service + * + * @version $Rev$ $Date$ + */ +public class OSGiTestWithPropertyImpl implements OSGiTestInterface, BundleActivator { + + @Property + public double exchangeRate; + + private String currency; + + @Property + public void setCurrency(String currency) { + this.currency = currency; + } + + public String testService() throws Exception { + + if (exchangeRate != 2.0) + throw new Exception("Property exchangeRate not set correctly, expected 2.0, got " + exchangeRate); + if (!"USD".equals(currency)) + throw new Exception("Property currency not set correctly, expected USD, got " + currency); + return OSGiTestWithPropertyImpl.class.getName(); + + } + + public void start(BundleContext bc) throws Exception { + + bc.registerService(OSGiTestInterface.class.getName(), this, new Hashtable()); + + } + + public void stop(BundleContext bc) throws Exception { + } + + +} diff --git a/java/sca/contrib/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/xml/OSGiReadImplTestCase.java b/java/sca/contrib/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/xml/OSGiReadImplTestCase.java new file mode 100644 index 0000000000..1831587896 --- /dev/null +++ b/java/sca/contrib/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/xml/OSGiReadImplTestCase.java @@ -0,0 +1,132 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.implementation.osgi.xml; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; + +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamReader; + +import junit.framework.TestCase; + +import org.apache.tuscany.sca.assembly.AssemblyFactory; +import org.apache.tuscany.sca.assembly.ComponentType; +import org.apache.tuscany.sca.assembly.Composite; +import org.apache.tuscany.sca.assembly.SCABindingFactory; +import org.apache.tuscany.sca.assembly.builder.CompositeBuilder; +import org.apache.tuscany.sca.assembly.builder.impl.CompositeBuilderImpl; +import org.apache.tuscany.sca.contribution.ModelFactoryExtensionPoint; +import org.apache.tuscany.sca.contribution.processor.DefaultStAXArtifactProcessorExtensionPoint; +import org.apache.tuscany.sca.contribution.processor.ExtensibleStAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessorExtensionPoint; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.core.DefaultExtensionPointRegistry; +import org.apache.tuscany.sca.core.UtilityExtensionPoint; +import org.apache.tuscany.sca.implementation.osgi.impl.OSGiImplementationImpl; +import org.apache.tuscany.sca.implementation.osgi.test.OSGiTestBundles; +import org.apache.tuscany.sca.implementation.osgi.test.OSGiTestImpl; +import org.apache.tuscany.sca.implementation.osgi.test.OSGiTestInterface; +import org.apache.tuscany.sca.interfacedef.InterfaceContractMapper; +import org.apache.tuscany.sca.interfacedef.impl.InterfaceContractMapperImpl; +import org.apache.tuscany.sca.policy.IntentAttachPointTypeFactory; + +/** + * Test reading OSGi implementations. + * + * @version $Rev$ $Date$ + */ +public class OSGiReadImplTestCase extends TestCase { + + private XMLInputFactory inputFactory; + private StAXArtifactProcessor staxProcessor; + private CompositeBuilder compositeBuilder; + + @Override + public void setUp() throws Exception { + DefaultExtensionPointRegistry extensionPoints = new DefaultExtensionPointRegistry(); + inputFactory = XMLInputFactory.newInstance(); + StAXArtifactProcessorExtensionPoint staxProcessors = new DefaultStAXArtifactProcessorExtensionPoint(extensionPoints); + staxProcessor = new ExtensibleStAXArtifactProcessor(staxProcessors, inputFactory, null, null); + + ModelFactoryExtensionPoint modelFactories = extensionPoints.getExtensionPoint(ModelFactoryExtensionPoint.class); + AssemblyFactory assemblyFactory = modelFactories.getFactory(AssemblyFactory.class); + SCABindingFactory scaBindingFactory = modelFactories.getFactory(SCABindingFactory.class); + UtilityExtensionPoint utilities = extensionPoints.getExtensionPoint(UtilityExtensionPoint.class); + InterfaceContractMapper mapper = utilities.getUtility(InterfaceContractMapper.class); + IntentAttachPointTypeFactory attachPointTypeFactory = modelFactories.getFactory(IntentAttachPointTypeFactory.class); + compositeBuilder = new CompositeBuilderImpl(assemblyFactory, scaBindingFactory, attachPointTypeFactory, mapper, null); + + OSGiTestBundles.createBundle("target/test-classes/OSGiTestService.jar", OSGiTestInterface.class, OSGiTestImpl.class); + + } + + public void testReadComposite() throws Exception { + InputStream is = getClass().getClassLoader().getResourceAsStream("osgitest.composite"); + XMLStreamReader reader = inputFactory.createXMLStreamReader(is); + Composite composite = (Composite)staxProcessor.read(reader); + assertNotNull(composite); + + compositeBuilder.build(composite); + } + + public void testReadAndResolveComposite() throws Exception { + InputStream is = getClass().getClassLoader().getResourceAsStream("osgitest.composite"); + XMLStreamReader reader = inputFactory.createXMLStreamReader(is); + Composite composite = (Composite)staxProcessor.read(reader); + assertNotNull(composite); + + is = getClass().getClassLoader().getResourceAsStream("OSGiTestService.componentType"); + reader = inputFactory.createXMLStreamReader(is); + ComponentType componentType = (ComponentType)staxProcessor.read(reader); + + ModelResolver resolver = new TestModelResolver(getClass().getClassLoader()); + staxProcessor.resolve(componentType, resolver); + resolver.addModel(componentType); + + staxProcessor.resolve(composite, resolver); + + compositeBuilder.build(composite); + } + + public void testReadOSGiImplementation() throws Exception { + + String str = "" + + ""; + ByteArrayInputStream is = new ByteArrayInputStream(str.getBytes()); + + XMLStreamReader reader = inputFactory.createXMLStreamReader(is); + reader.next(); + + OSGiImplementationImpl osgiImpl = (OSGiImplementationImpl)staxProcessor.read(reader); + + assertEquals(osgiImpl.getBundleSymbolicName(), "OSGiTestService"); + assertEquals(osgiImpl.getBundleVersion(), "2.0.0"); + assertTrue(osgiImpl.getImports().length == 2); + assertEquals(osgiImpl.getImports()[0], "import1.jar"); + assertEquals(osgiImpl.getImports()[1], "import2.jar"); + } + +} diff --git a/java/sca/contrib/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/xml/TestModelResolver.java b/java/sca/contrib/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/xml/TestModelResolver.java new file mode 100644 index 0000000000..e1bbd97655 --- /dev/null +++ b/java/sca/contrib/modules/implementation-osgi/src/test/java/org/apache/tuscany/sca/implementation/osgi/xml/TestModelResolver.java @@ -0,0 +1,106 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.implementation.osgi.xml; + +import java.lang.ref.WeakReference; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.tuscany.sca.assembly.ComponentType; +import org.apache.tuscany.sca.assembly.Property; +import org.apache.tuscany.sca.contribution.resolver.ClassReference; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.implementation.osgi.impl.OSGiImplementationImpl; + + +/** + * A default implementation of an artifact resolver, based on a map. + * + * @version $Rev$ $Date$ + */ +public class TestModelResolver implements ModelResolver { + private static final long serialVersionUID = -7826976465762296634L; + + private Map map = new HashMap(); + + private WeakReference classLoader; + + public TestModelResolver(ClassLoader classLoader) { + this.classLoader = new WeakReference(classLoader); + } + + public T resolveModel(Class modelClass, T unresolved) { + Object resolved = map.get(unresolved); + if (resolved != null) { + + if (unresolved instanceof OSGiImplementationImpl && !(resolved instanceof OSGiImplementationImpl)) { + + OSGiImplementationImpl impl = ((OSGiImplementationImpl)unresolved); + ComponentType componentType = (ComponentType)resolved; + + List properties = componentType.getProperties(); + for (Property property : properties) { + impl.getProperties().add(property); + } + impl.setUnresolved(false); + return unresolved; + } + + + // Return the resolved object + return modelClass.cast(resolved); + + } else if (unresolved instanceof ClassReference) { + + // Load a class on demand + ClassReference classReference = (ClassReference)unresolved; + Class clazz; + try { + clazz = Class.forName(classReference.getClassName(), true, classLoader.get()); + } catch (ClassNotFoundException e) { + + // Return the unresolved object + return unresolved; + } + + // Store a new ClassReference wrapping the loaded class + resolved = new ClassReference(clazz); + map.put(resolved, resolved); + + // Return the resolved ClassReference + return modelClass.cast(resolved); + + } else { + + // Return the unresolved object + return unresolved; + } + } + + public void addModel(Object resolved) { + map.put(resolved, resolved); + } + + public Object removeModel(Object resolved) { + return map.remove(resolved); + } + +} diff --git a/java/sca/contrib/modules/implementation-osgi/src/test/resources/OSGiTestService.componentType b/java/sca/contrib/modules/implementation-osgi/src/test/resources/OSGiTestService.componentType new file mode 100644 index 0000000000..254ce99d59 --- /dev/null +++ b/java/sca/contrib/modules/implementation-osgi/src/test/resources/OSGiTestService.componentType @@ -0,0 +1,28 @@ + + + + + + + + GBP + 1.0 + + diff --git a/java/sca/contrib/modules/implementation-osgi/src/test/resources/osgiproptest.composite b/java/sca/contrib/modules/implementation-osgi/src/test/resources/osgiproptest.composite new file mode 100644 index 0000000000..0b31145407 --- /dev/null +++ b/java/sca/contrib/modules/implementation-osgi/src/test/resources/osgiproptest.composite @@ -0,0 +1,37 @@ + + + + + + + + USD + 2.0 + + + + diff --git a/java/sca/contrib/modules/implementation-osgi/src/test/resources/osgitest.composite b/java/sca/contrib/modules/implementation-osgi/src/test/resources/osgitest.composite new file mode 100644 index 0000000000..5465eec8d9 --- /dev/null +++ b/java/sca/contrib/modules/implementation-osgi/src/test/resources/osgitest.composite @@ -0,0 +1,36 @@ + + + + + + + + USD + 2.0 + + + + diff --git a/java/sca/contrib/modules/implementation-pojo/LICENSE b/java/sca/contrib/modules/implementation-pojo/LICENSE new file mode 100644 index 0000000000..8aa906c321 --- /dev/null +++ b/java/sca/contrib/modules/implementation-pojo/LICENSE @@ -0,0 +1,205 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + + diff --git a/java/sca/contrib/modules/implementation-pojo/META-INF/MANIFEST.MF b/java/sca/contrib/modules/implementation-pojo/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..298921a55f --- /dev/null +++ b/java/sca/contrib/modules/implementation-pojo/META-INF/MANIFEST.MF @@ -0,0 +1,30 @@ +Manifest-Version: 1.0 +Export-Package: org.apache.tuscany.sca.pojo +Private-Package: org.apache.tuscany.sca.implementation.java.impl;versi + on="1.4",org.apache.tuscany.sca.implementation.java.introspect.impl;v + ersion="1.4" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA Java Implementation Model +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397153500 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA Java Implementation Model +Import-Package: javax.jws, + javax.xml.namespace, + org.apache.tuscany.sca.assembly;version="2.0.0", + org.apache.tuscany.sca.assembly.impl;version="2.0.0", + org.apache.tuscany.sca.core;version="2.0.0", + org.apache.tuscany.sca.interfacedef;version="2.0.0", + org.apache.tuscany.sca.interfacedef.java;version="2.0.0", + org.apache.tuscany.sca.interfacedef.java.impl;version="2.0.0";resolution:=optional, + org.apache.tuscany.sca.interfacedef.util;version="2.0.0", + org.apache.tuscany.sca.policy;version="2.0.0", + org.apache.tuscany.sca.policy.util;version="2.0.0", + org.oasisopen.sca;version="2.0.0", + org.oasisopen.sca.annotation;version="2.0.0" +Bundle-SymbolicName: org.apache.tuscany.sca.implementation.java +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/implementation-pojo/NOTICE b/java/sca/contrib/modules/implementation-pojo/NOTICE new file mode 100644 index 0000000000..25bb89c9b2 --- /dev/null +++ b/java/sca/contrib/modules/implementation-pojo/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/implementation-pojo/pom.xml b/java/sca/contrib/modules/implementation-pojo/pom.xml new file mode 100644 index 0000000000..2a93a36593 --- /dev/null +++ b/java/sca/contrib/modules/implementation-pojo/pom.xml @@ -0,0 +1,68 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + tuscany-implementation-pojo + Apache Tuscany SCA Implementation Pojo Model + + + + java.net + java.net Maven 1.x Repository + http://download.java.net/maven/1 + legacy + + + + + + org.apache.tuscany.sca + tuscany-assembly + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-interface-java + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-sca-api + 2.0-SNAPSHOT + + + + javax.jws + jsr181-api + 1.0-MR1 + + + + + + diff --git a/java/sca/contrib/modules/implementation-pojo/src/main/java/org/apache/tuscany/sca/pojo/JavaConstructor.java b/java/sca/contrib/modules/implementation-pojo/src/main/java/org/apache/tuscany/sca/pojo/JavaConstructor.java new file mode 100644 index 0000000000..5f81353606 --- /dev/null +++ b/java/sca/contrib/modules/implementation-pojo/src/main/java/org/apache/tuscany/sca/pojo/JavaConstructor.java @@ -0,0 +1,42 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.pojo; + +import java.lang.reflect.Constructor; + + +/** + * Hold injection information for the constructor used to instantiate a + * component implementation instance + * + * @version $Rev$ $Date$ + */ +public interface JavaConstructor { + + /** + * @return the constructor + */ + Constructor getConstructor(); + + /** + * @return the parameters + */ + JavaParameter[] getParameters(); + +} \ No newline at end of file diff --git a/java/sca/contrib/modules/implementation-pojo/src/main/java/org/apache/tuscany/sca/pojo/JavaElement.java b/java/sca/contrib/modules/implementation-pojo/src/main/java/org/apache/tuscany/sca/pojo/JavaElement.java new file mode 100644 index 0000000000..19d452d07f --- /dev/null +++ b/java/sca/contrib/modules/implementation-pojo/src/main/java/org/apache/tuscany/sca/pojo/JavaElement.java @@ -0,0 +1,92 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.pojo; + +import java.lang.annotation.Annotation; +import java.lang.annotation.ElementType; +import java.lang.reflect.AnnotatedElement; +import java.lang.reflect.Type; + + +/** + * This class represents a java element such as a Package, Class, Constructor, + * Field, Method or Parameter. + * + * @version $Rev$ $Date$ + */ +public interface JavaElement { + + /** + * @return the anchor + */ + AnnotatedElement getAnchor(); + + /** + * @return the elementType + */ + ElementType getElementType(); + + /** + * @return the genericType + */ + Type getGenericType(); + + /** + * @return the index + */ + int getIndex(); + + /** + * @return the type + */ + Class getType(); + + /** + * @return the annotations + */ + Annotation[] getAnnotations(); + + /** + * Return a given annotation + * @param annotationType the annotation type + * @return the annotation + */ + T getAnnotation(Class annotationType); + + /** + * @return the name + */ + String getName(); + + /** + * @param name the name to set + */ + void setName(String name); + + /** + * @return the classifier + */ + Class getClassifer(); + + /** + * @param classifer the classifier to set + */ + void setClassifer(Class classifer); + +} \ No newline at end of file diff --git a/java/sca/contrib/modules/implementation-pojo/src/main/java/org/apache/tuscany/sca/pojo/JavaFactory.java b/java/sca/contrib/modules/implementation-pojo/src/main/java/org/apache/tuscany/sca/pojo/JavaFactory.java new file mode 100644 index 0000000000..28375c86f8 --- /dev/null +++ b/java/sca/contrib/modules/implementation-pojo/src/main/java/org/apache/tuscany/sca/pojo/JavaFactory.java @@ -0,0 +1,82 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.pojo; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; + +/** + * Factory for the Java model used during introspection of java class/interfaces + * + * @version $Rev$ $Date$ + */ + +public interface JavaFactory { + + /** + * Create a model representing a java constructor + * @param clazz + * @return the java constructor + */ + JavaConstructor createJavaConstructor(Constructor constructor); + + /** + * Create model representing a java class + * @param clazz the class + * @return the java element representing the class + */ + JavaElement createJavaElement(Class clazz); + + /** + * Create a model representing a java property + * @param field the property + * @return the java element representing the property + */ + JavaElement createJavaElement(Field field); + + /** + * Create a model representing a java constructor + * @param constructor the constructor + * @param index the constructor position + * @return the java element representing the constructor + */ + JavaElement createJavaElement(Constructor constructor, int index); + + /** + * Create a model representing a java method + * @param method the method + * @param index the method position + * @return the java element representing the constructor + */ + JavaElement createJavaElement(Method method, int index); + + /** + * Create a model representing a java parameter + * @return the parameter + */ + JavaParameter createJavaParameter(Constructor constructor, int index); + + /** + * Create a model representing a java resource + * @return + */ + JavaResource createJavaResource(JavaElement element); + +} \ No newline at end of file diff --git a/java/sca/contrib/modules/implementation-pojo/src/main/java/org/apache/tuscany/sca/pojo/JavaParameter.java b/java/sca/contrib/modules/implementation-pojo/src/main/java/org/apache/tuscany/sca/pojo/JavaParameter.java new file mode 100644 index 0000000000..d5ded915db --- /dev/null +++ b/java/sca/contrib/modules/implementation-pojo/src/main/java/org/apache/tuscany/sca/pojo/JavaParameter.java @@ -0,0 +1,29 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.pojo; + +/** + * This class represents a java element such as a Package, Class, Constructor, + * Field, Method or Parameter. + * + * @version $Rev$ $Date$ + */ +public interface JavaParameter extends JavaElement { + +} \ No newline at end of file diff --git a/java/sca/contrib/modules/implementation-pojo/src/main/java/org/apache/tuscany/sca/pojo/JavaResource.java b/java/sca/contrib/modules/implementation-pojo/src/main/java/org/apache/tuscany/sca/pojo/JavaResource.java new file mode 100644 index 0000000000..38fbf75a71 --- /dev/null +++ b/java/sca/contrib/modules/implementation-pojo/src/main/java/org/apache/tuscany/sca/pojo/JavaResource.java @@ -0,0 +1,65 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.pojo; + + +/** + * A resource dependency declared by a Java component implementation + * + * @version $Rev$ $Date$ + */ +public interface JavaResource { + + /** + * The name of the resource + * + * @return the name of the resource + */ + String getName(); + + /** + * Returns the URI of the resource + * + * @return the URI of the resource + */ + String getMappedName(); + + /** + * Sets the resource URI + */ + void setMappedName(String mappedName); + + /** + * If true, the resource is optional + * + * @return true if the resource is optional + */ + boolean isOptional(); + + /** + * Sets whether the resource is optional + */ + void setOptional(boolean optional); + + /** + * @return the element + */ + JavaElement getElement(); + +} \ No newline at end of file diff --git a/java/sca/contrib/modules/implementation-pojo/src/main/java/org/apache/tuscany/sca/pojo/impl/JavaConstructorImpl.java b/java/sca/contrib/modules/implementation-pojo/src/main/java/org/apache/tuscany/sca/pojo/impl/JavaConstructorImpl.java new file mode 100644 index 0000000000..36a87420ab --- /dev/null +++ b/java/sca/contrib/modules/implementation-pojo/src/main/java/org/apache/tuscany/sca/pojo/impl/JavaConstructorImpl.java @@ -0,0 +1,54 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.pojo.impl; + +import java.lang.reflect.Constructor; + +import org.apache.tuscany.sca.pojo.JavaConstructor; + + +/** + * Hold injection information for the constructor used to instantiate a + * component implementation instance + * + * @version $Rev$ $Date$ + */ +public class JavaConstructorImpl implements JavaConstructor { + private Constructor constructor; + private JavaParameterImpl[] parameters; + + public JavaConstructorImpl(Constructor constructor) { + this.constructor = constructor; + int size = constructor.getParameterTypes().length; + parameters = new JavaParameterImpl[size]; + for (int i = 0; i < size; i++) { + parameters[i] = new JavaParameterImpl(constructor, i); + } + } + + + public Constructor getConstructor() { + return constructor; + } + + + public JavaParameterImpl[] getParameters() { + return parameters; + } +} diff --git a/java/sca/contrib/modules/implementation-pojo/src/main/java/org/apache/tuscany/sca/pojo/impl/JavaElementImpl.java b/java/sca/contrib/modules/implementation-pojo/src/main/java/org/apache/tuscany/sca/pojo/impl/JavaElementImpl.java new file mode 100644 index 0000000000..fc3ca3238f --- /dev/null +++ b/java/sca/contrib/modules/implementation-pojo/src/main/java/org/apache/tuscany/sca/pojo/impl/JavaElementImpl.java @@ -0,0 +1,194 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.pojo.impl; + +import java.lang.annotation.Annotation; +import java.lang.annotation.ElementType; +import java.lang.reflect.AnnotatedElement; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Type; + +import org.apache.tuscany.sca.pojo.JavaElement; + +/** + * This class represents a java element such as a Package, Class, Constructor, + * Field, Method or Parameter. + * + * @version $Rev$ $Date$ + */ +public class JavaElementImpl implements JavaElement { + private AnnotatedElement anchor; + private ElementType elementType; + private Class type; + private Type genericType; + private int index = -1; + private String name; + private Class classifer; + + public JavaElementImpl(Class clazz) { + this.anchor = clazz; + this.elementType = ElementType.TYPE; + this.type = clazz; + this.genericType = clazz; + this.name = clazz.getName(); + } + + public JavaElementImpl(Field field) { + this.anchor = field; + this.elementType = ElementType.FIELD; + this.type = field.getType(); + this.genericType = field.getGenericType(); + this.name = field.getName(); + } + + public JavaElementImpl(Constructor constructor, int index) { + this.anchor = constructor; + this.elementType = ElementType.PARAMETER; + this.type = constructor.getParameterTypes()[index]; + this.genericType = constructor.getGenericParameterTypes()[index]; + this.index = index; + this.name = ""; + } + + public JavaElementImpl(Method method, int index) { + this.anchor = method; + this.elementType = ElementType.PARAMETER; + this.type = method.getParameterTypes()[index]; + this.genericType = method.getGenericParameterTypes()[index]; + this.index = index; + this.name = ""; + } + + /** + * For testing purpose + * + * @param name + * @param type + * @param classifer TODO + * @param elementType + */ + public JavaElementImpl(String name, Class type, Class classifer) { + super(); + this.type = type; + this.name = name; + this.classifer = classifer; + } + + public AnnotatedElement getAnchor() { + return anchor; + } + + public ElementType getElementType() { + return elementType; + } + + public Type getGenericType() { + return genericType; + } + + public int getIndex() { + return index; + } + + public Class getType() { + return type; + } + + public Annotation[] getAnnotations() { + if (elementType == ElementType.PARAMETER) { + if (anchor instanceof Method) { + // We only care about the method-level annotations + return ((Method)anchor).getAnnotations(); + } + if (anchor instanceof Constructor) { + return ((Constructor)anchor).getParameterAnnotations()[index]; + } + } + return anchor.getAnnotations(); + } + + public T getAnnotation(Class annotationType) { + for (Annotation a : getAnnotations()) { + if (a.annotationType() == annotationType) { + return annotationType.cast(a); + } + } + return null; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Class getClassifer() { + return classifer; + } + + public void setClassifer(Class classifer) { + this.classifer = classifer; + } + + + @Override + public String toString() { + return anchor.toString() + (elementType == ElementType.PARAMETER ? "[" + index + "]" : ""); + } + + @Override + public int hashCode() { + final int PRIME = 31; + int result = 1; + result = PRIME * result + ((anchor == null) ? 0 : anchor.hashCode()); + result = PRIME * result + index; + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final JavaElementImpl other = (JavaElementImpl)obj; + if (anchor == null) { + if (other.anchor != null) { + return false; + } + } else if (!anchor.equals(other.anchor)) { + return false; + } + if (index != other.index) { + return false; + } + return true; + } + +} diff --git a/java/sca/contrib/modules/implementation-pojo/src/main/java/org/apache/tuscany/sca/pojo/impl/JavaFactoryImpl.java b/java/sca/contrib/modules/implementation-pojo/src/main/java/org/apache/tuscany/sca/pojo/impl/JavaFactoryImpl.java new file mode 100644 index 0000000000..d1b7d4c5ad --- /dev/null +++ b/java/sca/contrib/modules/implementation-pojo/src/main/java/org/apache/tuscany/sca/pojo/impl/JavaFactoryImpl.java @@ -0,0 +1,74 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.pojo.impl; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; + +import org.apache.tuscany.sca.pojo.JavaConstructor; +import org.apache.tuscany.sca.pojo.JavaElement; +import org.apache.tuscany.sca.pojo.JavaFactory; +import org.apache.tuscany.sca.pojo.JavaParameter; +import org.apache.tuscany.sca.pojo.JavaResource; + +/** + * Factory for the Java model used during introspection of java class/interfaces + * + * @version $Rev$ $Date$ + */ + +public class JavaFactoryImpl implements JavaFactory { + + public void JavaFactory() { + + } + + public JavaConstructor createJavaConstructor(Constructor constructor){ + return new JavaConstructorImpl(constructor); + } + + public JavaElement createJavaElement(Class clazz) { + return new JavaElementImpl(clazz); + } + + public JavaElement createJavaElement(Field field){ + return new JavaElementImpl(field); + + } + + public JavaElement createJavaElement(Constructor constructor, int index) { + return new JavaElementImpl(constructor, index); + + } + + public JavaElement createJavaElement(Method method, int index) { + return new JavaElementImpl(method, index); + } + + public JavaParameter createJavaParameter(Constructor constructor, int index) { + return new JavaParameterImpl(constructor, index); + } + + public JavaResource createJavaResource(JavaElement element) { + return new JavaResourceImpl(element); + } + +} + diff --git a/java/sca/contrib/modules/implementation-pojo/src/main/java/org/apache/tuscany/sca/pojo/impl/JavaParameterImpl.java b/java/sca/contrib/modules/implementation-pojo/src/main/java/org/apache/tuscany/sca/pojo/impl/JavaParameterImpl.java new file mode 100644 index 0000000000..417644be14 --- /dev/null +++ b/java/sca/contrib/modules/implementation-pojo/src/main/java/org/apache/tuscany/sca/pojo/impl/JavaParameterImpl.java @@ -0,0 +1,37 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.pojo.impl; + +import java.lang.reflect.Constructor; + +import org.apache.tuscany.sca.pojo.JavaParameter; + +/** + * @version $Rev$ $Date$ + */ +public class JavaParameterImpl extends JavaElementImpl implements JavaParameter { + /** + * @param constructor + * @param index + */ + public JavaParameterImpl(Constructor constructor, int index) { + super(constructor, index); + } +} diff --git a/java/sca/contrib/modules/implementation-pojo/src/main/java/org/apache/tuscany/sca/pojo/impl/JavaResourceImpl.java b/java/sca/contrib/modules/implementation-pojo/src/main/java/org/apache/tuscany/sca/pojo/impl/JavaResourceImpl.java new file mode 100644 index 0000000000..5a36a21db8 --- /dev/null +++ b/java/sca/contrib/modules/implementation-pojo/src/main/java/org/apache/tuscany/sca/pojo/impl/JavaResourceImpl.java @@ -0,0 +1,63 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.pojo.impl; + +import org.apache.tuscany.sca.pojo.JavaElement; +import org.apache.tuscany.sca.pojo.JavaResource; + +/** + * A resource dependency declared by a Java component implementation + * + * @version $Rev$ $Date$ + */ +public class JavaResourceImpl implements JavaResource { + private JavaElement element; + private String mappedName; + private boolean optional; + + public JavaResourceImpl(JavaElement element) { + this.element = element; + } + + public String getName() { + return element.getName(); + } + + public String getMappedName() { + return mappedName; + } + + public void setMappedName(String mappedName) { + this.mappedName = mappedName; + } + + public boolean isOptional() { + return optional; + } + + public void setOptional(boolean optional) { + this.optional = optional; + } + + public JavaElement getElement() { + return element; + } + + +} diff --git a/java/sca/contrib/modules/implementation-pojo/src/main/resources/META-INF/services/org.apache.tuscany.sca.pojo.JavaFactory b/java/sca/contrib/modules/implementation-pojo/src/main/resources/META-INF/services/org.apache.tuscany.sca.pojo.JavaFactory new file mode 100644 index 0000000000..5ed06a8dcd --- /dev/null +++ b/java/sca/contrib/modules/implementation-pojo/src/main/resources/META-INF/services/org.apache.tuscany.sca.pojo.JavaFactory @@ -0,0 +1,20 @@ +# 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. + + +# Implementation class for the java model factory +org.apache.tuscany.sca.pojo.impl.JavaFactoryImpl \ No newline at end of file diff --git a/java/sca/contrib/modules/implementation-resource-runtime/LICENSE b/java/sca/contrib/modules/implementation-resource-runtime/LICENSE new file mode 100644 index 0000000000..6e529a25c4 --- /dev/null +++ b/java/sca/contrib/modules/implementation-resource-runtime/LICENSE @@ -0,0 +1,205 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + + diff --git a/java/sca/contrib/modules/implementation-resource-runtime/META-INF/MANIFEST.MF b/java/sca/contrib/modules/implementation-resource-runtime/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..586b890ecc --- /dev/null +++ b/java/sca/contrib/modules/implementation-resource-runtime/META-INF/MANIFEST.MF @@ -0,0 +1,25 @@ +Manifest-Version: 1.0 +Private-Package: org.apache.tuscany.sca.implementation.resource.provid + er;version="2.0.0" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA Resource Implementation Runtime +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397274609 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA Resource Implementation Runtime +Import-Package: + org.apache.tuscany.sca.assembly;version="2.0.0", + org.apache.tuscany.sca.core;version="2.0.0", + org.apache.tuscany.sca.data.collection;version="2.0.0", + org.apache.tuscany.sca.implementation.resource;version="2.0.0", + org.apache.tuscany.sca.interfacedef;version="2.0.0", + org.apache.tuscany.sca.invocation;version="2.0.0", + org.apache.tuscany.sca.provider;version="2.0.0", + org.apache.tuscany.sca.runtime;version="2.0.0" +Bundle-SymbolicName: org.apache.tuscany.sca.implementation.resource.ru + ntime +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/implementation-resource-runtime/NOTICE b/java/sca/contrib/modules/implementation-resource-runtime/NOTICE new file mode 100644 index 0000000000..51042eab05 --- /dev/null +++ b/java/sca/contrib/modules/implementation-resource-runtime/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/implementation-resource-runtime/pom.xml b/java/sca/contrib/modules/implementation-resource-runtime/pom.xml new file mode 100644 index 0000000000..3f28bd9480 --- /dev/null +++ b/java/sca/contrib/modules/implementation-resource-runtime/pom.xml @@ -0,0 +1,67 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + + tuscany-implementation-resource-runtime + Apache Tuscany SCA Resource Implementation Runtime + + + + org.apache.tuscany.sca + tuscany-implementation-resource + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-core-spi + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-data-api + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-node-impl + 2.0-SNAPSHOT + test + + + + junit + junit + 4.5 + test + + + + + diff --git a/java/sca/contrib/modules/implementation-resource-runtime/src/main/java/org/apache/tuscany/sca/implementation/resource/provider/GetResourceInvoker.java b/java/sca/contrib/modules/implementation-resource-runtime/src/main/java/org/apache/tuscany/sca/implementation/resource/provider/GetResourceInvoker.java new file mode 100644 index 0000000000..582795625d --- /dev/null +++ b/java/sca/contrib/modules/implementation-resource-runtime/src/main/java/org/apache/tuscany/sca/implementation/resource/provider/GetResourceInvoker.java @@ -0,0 +1,67 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.implementation.resource.provider; + +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; + +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; + +/** + * An invoker for a get resource operation. + * + * @version $Rev$ $Date$ + */ +class GetResourceInvoker implements Invoker { + private String locationURL; + + GetResourceInvoker(String locationURL) { + this.locationURL = locationURL; + } + + public Message invoke(Message msg) { + + // Get the resource id from the request message + String id = (String)((Object[])msg.getBody())[0]; + try { + + // Return an input stream for the resource + URL url = new URL(locationURL +'/' + id); + URLConnection connection = url.openConnection(); + connection.setUseCaches(false); + InputStream is = connection.getInputStream(); + msg.setBody(is); + } catch (MalformedURLException e) { + + // Report exception as a fault + msg.setFaultBody(e); + } catch (IOException e) { + + // Report exception as a fault + msg.setFaultBody(e); + } + return msg; + } + +} diff --git a/java/sca/contrib/modules/implementation-resource-runtime/src/main/java/org/apache/tuscany/sca/implementation/resource/provider/ResourceImplementationProvider.java b/java/sca/contrib/modules/implementation-resource-runtime/src/main/java/org/apache/tuscany/sca/implementation/resource/provider/ResourceImplementationProvider.java new file mode 100644 index 0000000000..a974f68a7e --- /dev/null +++ b/java/sca/contrib/modules/implementation-resource-runtime/src/main/java/org/apache/tuscany/sca/implementation/resource/provider/ResourceImplementationProvider.java @@ -0,0 +1,75 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.implementation.resource.provider; + +import org.apache.tuscany.sca.implementation.resource.ResourceImplementation; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.provider.ImplementationProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; + +/** + * The model representing a resource implementation in an SCA assembly model. + * + * @version $Rev$ $Date$ + */ +class ResourceImplementationProvider implements ImplementationProvider { + + private ResourceImplementation implementation; + + /** + * Constructs a new resource implementation provider. + */ + ResourceImplementationProvider(RuntimeComponent component, ResourceImplementation implementation) { + this.implementation = implementation; + } + + public Invoker createInvoker(RuntimeComponentService service, Operation operation) { + if ("get".equals(operation.getName())) { + + // Return an instance of our get resource invoker + Invoker invoker = new GetResourceInvoker(implementation.getLocationURL().toString()); + return invoker; + + } else { + + // Return a dummy invoker that returns an "unsupported operation" + // exception for now + return new Invoker() { + public Message invoke(Message msg) { + msg.setFaultBody(new UnsupportedOperationException()); + return msg; + } + }; + } + } + + public boolean supportsOneWayInvocation() { + return false; + } + + public void start() { + } + + public void stop() { + } + +} diff --git a/java/sca/contrib/modules/implementation-resource-runtime/src/main/java/org/apache/tuscany/sca/implementation/resource/provider/ResourceImplementationProviderFactory.java b/java/sca/contrib/modules/implementation-resource-runtime/src/main/java/org/apache/tuscany/sca/implementation/resource/provider/ResourceImplementationProviderFactory.java new file mode 100644 index 0000000000..47e70b5581 --- /dev/null +++ b/java/sca/contrib/modules/implementation-resource-runtime/src/main/java/org/apache/tuscany/sca/implementation/resource/provider/ResourceImplementationProviderFactory.java @@ -0,0 +1,47 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.implementation.resource.provider; + +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.implementation.resource.ResourceImplementation; +import org.apache.tuscany.sca.provider.ImplementationProvider; +import org.apache.tuscany.sca.provider.ImplementationProviderFactory; +import org.apache.tuscany.sca.runtime.RuntimeComponent; + +/** + * A factory for resource implementation providers. + * + * @version $Rev$ $Date$ + */ +public class ResourceImplementationProviderFactory implements ImplementationProviderFactory { + + /** + * Constructs a resource implementation. + */ + public ResourceImplementationProviderFactory(ExtensionPointRegistry extensionPoints) { + } + + public ImplementationProvider createImplementationProvider(RuntimeComponent component, ResourceImplementation implementation) { + return new ResourceImplementationProvider(component, implementation); + } + + public Class getModelType() { + return ResourceImplementation.class; + } +} diff --git a/java/sca/contrib/modules/implementation-resource-runtime/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.ImplementationProviderFactory b/java/sca/contrib/modules/implementation-resource-runtime/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.ImplementationProviderFactory new file mode 100644 index 0000000000..656d8c2751 --- /dev/null +++ b/java/sca/contrib/modules/implementation-resource-runtime/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.ImplementationProviderFactory @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for the implementation extension +org.apache.tuscany.sca.implementation.resource.provider.ResourceImplementationProviderFactory;model=org.apache.tuscany.sca.implementation.resource.ResourceImplementation diff --git a/java/sca/contrib/modules/implementation-resource-runtime/src/test/java/org/apache/tuscany/sca/implementation/resource/ResourceImplementationTestCase.java b/java/sca/contrib/modules/implementation-resource-runtime/src/test/java/org/apache/tuscany/sca/implementation/resource/ResourceImplementationTestCase.java new file mode 100644 index 0000000000..9b3c959753 --- /dev/null +++ b/java/sca/contrib/modules/implementation-resource-runtime/src/test/java/org/apache/tuscany/sca/implementation/resource/ResourceImplementationTestCase.java @@ -0,0 +1,83 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.implementation.resource; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; + +import junit.framework.TestCase; + +import org.apache.tuscany.sca.node.Contribution; +import org.apache.tuscany.sca.node.ContributionLocationHelper; +import org.apache.tuscany.sca.node.Node; +import org.apache.tuscany.sca.node.NodeFactory; + +/** + * @version $Rev$ $Date$ + */ +public class ResourceImplementationTestCase extends TestCase { + + private Node node; + + @Override + protected void setUp() throws Exception { + String contribution = ContributionLocationHelper.getContributionLocation(getClass()); + node = NodeFactory.newInstance().createNode("resource.composite", new Contribution("test", contribution)); + node.start(); + } + + @Override + protected void tearDown() throws Exception { + node.stop(); + node.destroy(); + } + + public void testResource() throws Exception { + Resource resource = node.getService(Resource.class, "ResourceServiceComponent"); + InputStream is = resource.get("test.html"); + String document = read(is); + assertTrue(document.indexOf("

      hello") != -1); + } + + /** + * Read response stream from the given input stream. + * @param is + * @return + * @throws IOException + */ + private static String read(InputStream is) throws IOException { + BufferedReader reader = null; + try { + reader = new BufferedReader(new InputStreamReader(is)); + StringBuffer sb = new StringBuffer(); + String str; + while ((str = reader.readLine()) != null) { + sb.append(str); + } + return sb.toString(); + } finally { + if (reader != null) { + reader.close(); + } + } + } + +} diff --git a/java/sca/contrib/modules/implementation-resource-runtime/src/test/resources/content/test.html b/java/sca/contrib/modules/implementation-resource-runtime/src/test/resources/content/test.html new file mode 100644 index 0000000000..f4b79d7f01 --- /dev/null +++ b/java/sca/contrib/modules/implementation-resource-runtime/src/test/resources/content/test.html @@ -0,0 +1,21 @@ + + +

      hello + \ No newline at end of file diff --git a/java/sca/contrib/modules/implementation-resource-runtime/src/test/resources/resource.composite b/java/sca/contrib/modules/implementation-resource-runtime/src/test/resources/resource.composite new file mode 100644 index 0000000000..4654056cd7 --- /dev/null +++ b/java/sca/contrib/modules/implementation-resource-runtime/src/test/resources/resource.composite @@ -0,0 +1,30 @@ + + + + + + + + + diff --git a/java/sca/contrib/modules/implementation-resource/LICENSE b/java/sca/contrib/modules/implementation-resource/LICENSE new file mode 100644 index 0000000000..6e529a25c4 --- /dev/null +++ b/java/sca/contrib/modules/implementation-resource/LICENSE @@ -0,0 +1,205 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + + diff --git a/java/sca/contrib/modules/implementation-resource/META-INF/MANIFEST.MF b/java/sca/contrib/modules/implementation-resource/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..89e37fe4e3 --- /dev/null +++ b/java/sca/contrib/modules/implementation-resource/META-INF/MANIFEST.MF @@ -0,0 +1,31 @@ +Manifest-Version: 1.0 +Export-Package: org.apache.tuscany.sca.implementation.resource;uses:=" + org.apache.tuscany.sca.assembly,org.apache.tuscany.sca.data.collectio + n";version="2.0.0" +Private-Package: org.apache.tuscany.sca.implementation.resource.impl;v + ersion="2.0.0" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA Resource Implementation Model +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397272734 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA Resource Implementation Model +Import-Package: javax.xml.namespace, + javax.xml.stream, + org.apache.tuscany.sca.assembly;version="2.0.0", + org.apache.tuscany.sca.contribution;version="2.0.0", + org.apache.tuscany.sca.contribution.processor;version="2.0.0", + org.apache.tuscany.sca.contribution.resolver;version="2.0.0", + org.apache.tuscany.sca.core;version="2.0.0", + org.apache.tuscany.sca.data.collection;version="2.0.0", + org.apache.tuscany.sca.implementation.resource;version="2.0.0", + org.apache.tuscany.sca.interfacedef;version="2.0.0", + org.apache.tuscany.sca.interfacedef.java;version="2.0.0", + org.apache.tuscany.sca.monitor;version="2.0.0", + org.apache.tuscany.sca.policy;version="2.0.0" +Bundle-SymbolicName: org.apache.tuscany.sca.implementation.resource +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/implementation-resource/NOTICE b/java/sca/contrib/modules/implementation-resource/NOTICE new file mode 100644 index 0000000000..51042eab05 --- /dev/null +++ b/java/sca/contrib/modules/implementation-resource/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/implementation-resource/pom.xml b/java/sca/contrib/modules/implementation-resource/pom.xml new file mode 100644 index 0000000000..2562e253bf --- /dev/null +++ b/java/sca/contrib/modules/implementation-resource/pom.xml @@ -0,0 +1,60 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + + tuscany-implementation-resource + Apache Tuscany SCA Resource Implementation Model + + + + org.apache.tuscany.sca + tuscany-assembly + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-interface-java-xml + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-data-api + 2.0-SNAPSHOT + + + + junit + junit + 4.5 + test + + + + + diff --git a/java/sca/contrib/modules/implementation-resource/src/main/java/org/apache/tuscany/sca/implementation/resource/Resource.java b/java/sca/contrib/modules/implementation-resource/src/main/java/org/apache/tuscany/sca/implementation/resource/Resource.java new file mode 100644 index 0000000000..68219de701 --- /dev/null +++ b/java/sca/contrib/modules/implementation-resource/src/main/java/org/apache/tuscany/sca/implementation/resource/Resource.java @@ -0,0 +1,34 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.implementation.resource; + +import java.io.InputStream; + +import org.apache.tuscany.sca.data.collection.Collection; + +/** + * The service interface of resource implementations. This is not an API for application + * developers. Application developers should use the data collection API to invoke + * resource components. + * + * @version $Rev: 548609 $ $Date: 2007-06-18 23:31:03 -0700 (Mon, 18 Jun 2007) $ + */ +public interface Resource extends Collection { +} diff --git a/java/sca/contrib/modules/implementation-resource/src/main/java/org/apache/tuscany/sca/implementation/resource/ResourceImplementation.java b/java/sca/contrib/modules/implementation-resource/src/main/java/org/apache/tuscany/sca/implementation/resource/ResourceImplementation.java new file mode 100644 index 0000000000..be136ee792 --- /dev/null +++ b/java/sca/contrib/modules/implementation-resource/src/main/java/org/apache/tuscany/sca/implementation/resource/ResourceImplementation.java @@ -0,0 +1,57 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.implementation.resource; + +import java.net.URL; + +import org.apache.tuscany.sca.assembly.Implementation; + + +/** + * The model representing a resource implementation in an SCA assembly model. + * + * @version $Rev$ $Date$ + */ +public interface ResourceImplementation extends Implementation { + + /** + * The URI of the resource inside its contribution. + * @return the URI of the resource + */ + String getLocation(); + + /** + * Sets the URI of the resource inside its contribution. + * @param location the URI of the resource + */ + void setLocation(String location); + + /** + * Returns the URL of the resource. + * @return the URL of the resource + */ + URL getLocationURL(); + + /** + * Sets the URL of the resource. + * @param url the URL of the resource + */ + void setLocationURL(URL url); + +} diff --git a/java/sca/contrib/modules/implementation-resource/src/main/java/org/apache/tuscany/sca/implementation/resource/ResourceImplementationFactory.java b/java/sca/contrib/modules/implementation-resource/src/main/java/org/apache/tuscany/sca/implementation/resource/ResourceImplementationFactory.java new file mode 100644 index 0000000000..95ac452c66 --- /dev/null +++ b/java/sca/contrib/modules/implementation-resource/src/main/java/org/apache/tuscany/sca/implementation/resource/ResourceImplementationFactory.java @@ -0,0 +1,35 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.implementation.resource; + +/** + * Factory for the resource implementation model. + * + * @version $Rev$ $Date$ + */ +public interface ResourceImplementationFactory { + + /** + * Creates a new resource implementation. + * @return a new resource implementation + */ + ResourceImplementation createResourceImplementation(); + +} diff --git a/java/sca/contrib/modules/implementation-resource/src/main/java/org/apache/tuscany/sca/implementation/resource/impl/ResourceImplementationFactoryImpl.java b/java/sca/contrib/modules/implementation-resource/src/main/java/org/apache/tuscany/sca/implementation/resource/impl/ResourceImplementationFactoryImpl.java new file mode 100644 index 0000000000..2eb7b681b6 --- /dev/null +++ b/java/sca/contrib/modules/implementation-resource/src/main/java/org/apache/tuscany/sca/implementation/resource/impl/ResourceImplementationFactoryImpl.java @@ -0,0 +1,47 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.implementation.resource.impl; + +import org.apache.tuscany.sca.assembly.AssemblyFactory; +import org.apache.tuscany.sca.core.FactoryExtensionPoint; +import org.apache.tuscany.sca.implementation.resource.ResourceImplementation; +import org.apache.tuscany.sca.implementation.resource.ResourceImplementationFactory; +import org.apache.tuscany.sca.interfacedef.java.JavaInterfaceFactory; + +/** + * Factory for the resource implementation model. + * + * @version $Rev$ $Date$ + */ +public class ResourceImplementationFactoryImpl implements ResourceImplementationFactory { + + private AssemblyFactory assemblyFactory; + private JavaInterfaceFactory javaFactory; + + public ResourceImplementationFactoryImpl(FactoryExtensionPoint modelFactories) { + assemblyFactory = modelFactories.getFactory(AssemblyFactory.class); + javaFactory = modelFactories.getFactory(JavaInterfaceFactory.class); + } + + public ResourceImplementation createResourceImplementation() { + return new ResourceImplementationImpl(assemblyFactory, javaFactory); + } + +} diff --git a/java/sca/contrib/modules/implementation-resource/src/main/java/org/apache/tuscany/sca/implementation/resource/impl/ResourceImplementationImpl.java b/java/sca/contrib/modules/implementation-resource/src/main/java/org/apache/tuscany/sca/implementation/resource/impl/ResourceImplementationImpl.java new file mode 100644 index 0000000000..9cad0890a3 --- /dev/null +++ b/java/sca/contrib/modules/implementation-resource/src/main/java/org/apache/tuscany/sca/implementation/resource/impl/ResourceImplementationImpl.java @@ -0,0 +1,130 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.implementation.resource.impl; + +import java.net.URL; +import java.util.Collections; +import java.util.List; + +import org.apache.tuscany.sca.assembly.AssemblyFactory; +import org.apache.tuscany.sca.assembly.ConstrainingType; +import org.apache.tuscany.sca.assembly.Property; +import org.apache.tuscany.sca.assembly.Reference; +import org.apache.tuscany.sca.assembly.Service; +import org.apache.tuscany.sca.implementation.resource.Resource; +import org.apache.tuscany.sca.implementation.resource.ResourceImplementation; +import org.apache.tuscany.sca.interfacedef.InvalidInterfaceException; +import org.apache.tuscany.sca.interfacedef.java.JavaInterface; +import org.apache.tuscany.sca.interfacedef.java.JavaInterfaceContract; +import org.apache.tuscany.sca.interfacedef.java.JavaInterfaceFactory; + + +/** + * The model representing a resource implementation in an SCA assembly model. + * + * @version $Rev$ $Date$ + */ +class ResourceImplementationImpl implements ResourceImplementation { + + private Service resourceService; + + private String location; + private URL url; + private boolean unresolved; + + /** + * Constructs a new resource implementation. + */ + ResourceImplementationImpl(AssemblyFactory assemblyFactory, + JavaInterfaceFactory javaFactory) { + + // Resource implementation always provide a single service exposing + // the Resource interface, and have no references and properties + resourceService = assemblyFactory.createService(); + resourceService.setName("Resource"); + + // Create the Java interface contract for the Resource service + JavaInterface javaInterface; + try { + javaInterface = javaFactory.createJavaInterface(Resource.class); + } catch (InvalidInterfaceException e) { + throw new IllegalArgumentException(e); + } + JavaInterfaceContract interfaceContract = javaFactory.createJavaInterfaceContract(); + interfaceContract.setInterface(javaInterface); + resourceService.setInterfaceContract(interfaceContract); + } + + public String getLocation() { + return location; + } + + public void setLocation(String location) { + this.location = location; + } + + public URL getLocationURL() { + return url; + } + + public void setLocationURL(URL url) { + this.url = url; + } + + public ConstrainingType getConstrainingType() { + // The resource implementation does not support constrainingTypes + return null; + } + + public List getProperties() { + // The resource implementation does not support properties + return Collections.emptyList(); + } + + public List getServices() { + // The resource implementation does not support services + return Collections.singletonList(resourceService); + } + + public List getReferences() { + // The resource implementation does not support properties + return Collections.emptyList(); + } + + public String getURI() { + return location; + } + + public void setConstrainingType(ConstrainingType constrainingType) { + // The resource implementation does not support constrainingTypes + } + + public void setURI(String uri) { + this.location = uri; + } + + + public boolean isUnresolved() { + return unresolved; + } + + public void setUnresolved(boolean unresolved) { + this.unresolved = unresolved; + } +} diff --git a/java/sca/contrib/modules/implementation-resource/src/main/java/org/apache/tuscany/sca/implementation/resource/impl/ResourceImplementationProcessor.java b/java/sca/contrib/modules/implementation-resource/src/main/java/org/apache/tuscany/sca/implementation/resource/impl/ResourceImplementationProcessor.java new file mode 100644 index 0000000000..9c1453fba3 --- /dev/null +++ b/java/sca/contrib/modules/implementation-resource/src/main/java/org/apache/tuscany/sca/implementation/resource/impl/ResourceImplementationProcessor.java @@ -0,0 +1,166 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.implementation.resource.impl; + +import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; + +import java.io.IOException; +import java.net.URL; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; + +import org.apache.tuscany.sca.contribution.Artifact; +import org.apache.tuscany.sca.contribution.ContributionFactory; +import org.apache.tuscany.sca.contribution.processor.ContributionReadException; +import org.apache.tuscany.sca.contribution.processor.ContributionResolveException; +import org.apache.tuscany.sca.contribution.processor.ContributionWriteException; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.core.FactoryExtensionPoint; +import org.apache.tuscany.sca.implementation.resource.ResourceImplementation; +import org.apache.tuscany.sca.implementation.resource.ResourceImplementationFactory; +import org.apache.tuscany.sca.monitor.Monitor; +import org.apache.tuscany.sca.monitor.Problem; +import org.apache.tuscany.sca.monitor.Problem.Severity; + + +/** + * Implements a StAX artifact processor for resource implementations. + * + * @version $Rev$ $Date$ + */ +public class ResourceImplementationProcessor implements StAXArtifactProcessor { + private static final String SCA10_TUSCANY_NS = "http://tuscany.apache.org/xmlns/sca/1.0"; + private static final QName IMPLEMENTATION_RESOURCE = new QName(SCA10_TUSCANY_NS, "implementation.resource"); + + private ContributionFactory contributionFactory; + private ResourceImplementationFactory implementationFactory; + private Monitor monitor; + + public ResourceImplementationProcessor(FactoryExtensionPoint modelFactories, Monitor monitor) { + contributionFactory = modelFactories.getFactory(ContributionFactory.class); + implementationFactory = modelFactories.getFactory(ResourceImplementationFactory.class); + this.monitor = monitor; + } + + /** + * Report a exception. + * + * @param problems + * @param message + * @param model + */ + private void error(String message, Object model, Exception ex) { + if (monitor != null) { + Problem problem = monitor.createProblem(this.getClass().getName(), "impl-resource-validation-messages", Severity.ERROR, model, message, ex); + monitor.problem(problem); + } + } + + /** + * Report a error. + * + * @param problems + * @param message + * @param model + */ + private void error(String message, Object model, Object... messageParameters) { + if (monitor != null) { + Problem problem = monitor.createProblem(this.getClass().getName(), "impl-resource-validation-messages", Severity.ERROR, model, message, (Object[])messageParameters); + monitor.problem(problem); + } + } + + public QName getArtifactType() { + // Returns the QName of the XML element processed by this processor + return IMPLEMENTATION_RESOURCE; + } + + public Class getModelType() { + // Returns the type of model processed by this processor + return ResourceImplementation.class; + } + + public ResourceImplementation read(XMLStreamReader reader) throws ContributionReadException, XMLStreamException { + + // Read an element + + // Create and initialize the resource implementation model + ResourceImplementation implementation = null; + + // Read the location attribute specifying the location of the resources + String location = reader.getAttributeValue(null, "location"); + if (location != null) { + implementation = implementationFactory.createResourceImplementation(); + implementation.setLocation(location); + implementation.setUnresolved(true); + } else { + error("LocationAttributeMissing", reader); + //throw new ContributionReadException(MSG_LOCATION_MISSING); + } + + // Skip to end element + while (reader.hasNext()) { + if (reader.next() == END_ELEMENT && IMPLEMENTATION_RESOURCE.equals(reader.getName())) { + break; + } + } + + return implementation; + } + + public void resolve(ResourceImplementation implementation, ModelResolver resolver) throws ContributionResolveException { + + if (implementation == null) + return; + + // Resolve the resource directory location + Artifact artifact = contributionFactory.createArtifact(); + artifact.setURI(implementation.getLocation()); + Artifact resolved = resolver.resolveModel(Artifact.class, artifact); + if (resolved.getLocation() != null) { + try { + implementation.setLocationURL(new URL(resolved.getLocation())); + implementation.setUnresolved(false); + } catch (IOException e) { + ContributionResolveException ce = new ContributionResolveException(e); + error("ContributionResolveException", resolver, ce); + //throw ce; + } + } else { + error("CouldNotResolveLocation", resolver, implementation.getLocation()); + //throw new ContributionResolveException("Could not resolve implementation.resource location: " + implementation.getLocation()); + } + } + + public void write(ResourceImplementation implementation, XMLStreamWriter writer) throws ContributionWriteException, XMLStreamException { + + // Write + writer.writeStartElement(IMPLEMENTATION_RESOURCE.getNamespaceURI(), IMPLEMENTATION_RESOURCE.getLocalPart()); + + if (implementation.getLocation() != null) { + writer.writeAttribute("location", implementation.getLocation()); + } + + writer.writeEndElement(); + } +} diff --git a/java/sca/contrib/modules/implementation-resource/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor b/java/sca/contrib/modules/implementation-resource/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor new file mode 100644 index 0000000000..b5774c5c5b --- /dev/null +++ b/java/sca/contrib/modules/implementation-resource/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for the artifact processor extension +org.apache.tuscany.sca.implementation.resource.impl.ResourceImplementationProcessor;qname=http://tuscany.apache.org/xmlns/sca/1.0#implementation.resource,model=org.apache.tuscany.sca.implementation.resource.ResourceImplementation,factory=org.apache.tuscany.sca.implementation.resource.ResourceImplementationFactory diff --git a/java/sca/contrib/modules/implementation-resource/src/main/resources/META-INF/services/org.apache.tuscany.sca.implementation.resource.ResourceImplementationFactory b/java/sca/contrib/modules/implementation-resource/src/main/resources/META-INF/services/org.apache.tuscany.sca.implementation.resource.ResourceImplementationFactory new file mode 100644 index 0000000000..f77f723c3e --- /dev/null +++ b/java/sca/contrib/modules/implementation-resource/src/main/resources/META-INF/services/org.apache.tuscany.sca.implementation.resource.ResourceImplementationFactory @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for model factory +org.apache.tuscany.sca.implementation.resource.impl.ResourceImplementationFactoryImpl diff --git a/java/sca/contrib/modules/implementation-resource/src/main/resources/impl-resource-validation-messages.properties b/java/sca/contrib/modules/implementation-resource/src/main/resources/impl-resource-validation-messages.properties new file mode 100644 index 0000000000..7f619ef036 --- /dev/null +++ b/java/sca/contrib/modules/implementation-resource/src/main/resources/impl-resource-validation-messages.properties @@ -0,0 +1,23 @@ +# +# +# 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. +# +# +ContributionResolveException = ContributionResolveException occured due to: +LocationAttributeMissing = Reading implementation.resource - location attribute missing +CouldNotResolveLocation = Could not resolve implementation.resource location: {0} diff --git a/java/sca/contrib/modules/implementation-script-runtime/LICENSE b/java/sca/contrib/modules/implementation-script-runtime/LICENSE new file mode 100644 index 0000000000..4b5ab74408 --- /dev/null +++ b/java/sca/contrib/modules/implementation-script-runtime/LICENSE @@ -0,0 +1,251 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + +=============================================================================================================== + +Apache Tuscany SCA for Java Subcomponents +=========================================: + +The Tuscany SCA for Java release includes a number of subcomponents with +separate copyright notices and license terms. Your use of the source +code for the these subcomponents is subject to the terms and +conditions of the following licenses. + +================================================================================================================= + +This module implementation-script temporarily includes one file under the following BSD license: + + Copyright (c) 2006, Sun Microsystems, Inc. + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + - Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + - Neither the name of the Sun Microsystems, Inc. nor the names of + contributors may be used to endorse or promote products derived from this + software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND + CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED + WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH + DAMAGE. + +================================================================================================================= diff --git a/java/sca/contrib/modules/implementation-script-runtime/META-INF/MANIFEST.MF b/java/sca/contrib/modules/implementation-script-runtime/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..aed41dbb4f --- /dev/null +++ b/java/sca/contrib/modules/implementation-script-runtime/META-INF/MANIFEST.MF @@ -0,0 +1,58 @@ +Manifest-Version: 1.0 +Export-Package: org.apache.tuscany.sca.implementation.script.provider; + uses:="org.apache.tuscany.sca.databinding,org.apache.tuscany.sca.runt + ime,org.apache.tuscany.sca.assembly,org.apache.tuscany.sca.databindin + g.impl,org.apache.tuscany.sca.provider,org.apache.bsf.xml,org.apache. + tuscany.sca.core,org.apache.tuscany.sca.interfacedef.java,org.w3c.dom + ,javax.script,org.apache.tuscany.sca.interfacedef,javax.xml.namespace + ,org.apache.axiom.om,org.apache.tuscany.sca.implementation.script,org + .apache.tuscany.sca.invocation,org.apache.tuscany.sca.core.factory,or + g.apache.tuscany.sca.interfacedef.wsdl";version="2.0.0" +Private-Package: org.apache.tuscany.sca.implementation.script.engines; + version="2.0.0" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA Script Implementation Extension +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397459984 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA Script Implementation Extension +Import-Package: com.sun.script.jruby, + javax.script, + javax.xml.namespace, + org.apache.axiom.om, + org.apache.bsf.xml, + org.apache.tuscany.sca.assembly;version="2.0.0", + org.apache.tuscany.sca.core;version="2.0.0", + org.apache.tuscany.sca.core.factory;version="2.0.0", + org.apache.tuscany.sca.databinding;version="2.0.0", + org.apache.tuscany.sca.databinding.impl;version="2.0.0", + org.apache.tuscany.sca.implementation.script;version="2.0.0", + org.apache.tuscany.sca.implementation.script.provider;version="2.0.0", + org.apache.tuscany.sca.interfacedef;version="2.0.0", + org.apache.tuscany.sca.interfacedef.java;version="2.0.0", + org.apache.tuscany.sca.interfacedef.util;version="2.0.0", + org.apache.tuscany.sca.interfacedef.wsdl;version="2.0.0", + org.apache.tuscany.sca.invocation;version="2.0.0", + org.apache.tuscany.sca.policy;version="2.0.0", + org.apache.tuscany.sca.provider;version="2.0.0", + org.apache.tuscany.sca.runtime;version="2.0.0", + org.jruby, + org.jruby.ast, + org.jruby.exceptions, + org.jruby.internal.runtime, + org.jruby.javasupport, + org.jruby.runtime, + org.jruby.runtime.builtin, + org.jruby.runtime.load, + org.jruby.util, + org.jruby.util.io, + org.oasisopen.sca;version="2.0.0", + org.oasisopen.sca.annotation;version="2.0.0";resolution:=optional, + org.w3c.dom +Bundle-SymbolicName: org.apache.tuscany.sca.implementation.script.runt + ime +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/implementation-script-runtime/NOTICE b/java/sca/contrib/modules/implementation-script-runtime/NOTICE new file mode 100644 index 0000000000..ecbcc6a660 --- /dev/null +++ b/java/sca/contrib/modules/implementation-script-runtime/NOTICE @@ -0,0 +1,12 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + +This product also includes software under the BSD license +(see the LICENSE file contained in this distribution), with +the following copyright: + +Copyright (c) 2006, Sun Microsystems, Inc. +All rights reserved. diff --git a/java/sca/contrib/modules/implementation-script-runtime/pom.xml b/java/sca/contrib/modules/implementation-script-runtime/pom.xml new file mode 100644 index 0000000000..e2e0f59ce5 --- /dev/null +++ b/java/sca/contrib/modules/implementation-script-runtime/pom.xml @@ -0,0 +1,183 @@ + + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + + tuscany-implementation-script-runtime + Apache Tuscany SCA Script Implementation Extension + + + + org.apache.tuscany.sca + tuscany-sca-api + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-implementation-script + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-core + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-databinding + 2.0-SNAPSHOT + + + + org.apache.bsf + bsf-all + 3.0-beta2 + + + + org.apache.tuscany.sca + tuscany-interface-wsdl + 2.0-SNAPSHOT + + + + org.apache.ws.commons.axiom + axiom-api + + + xerces + xercesImpl + + + javax.mail + mail + + + commons-logging + commons-logging + + + xml-apis + xml-apis + + + 1.2.7 + + + + org.apache.ws.commons.axiom + axiom-impl + 1.2.7 + runtime + + + + junit + junit + 4.5 + test + + + + org.apache.tuscany.sca + tuscany-node-impl + 2.0-SNAPSHOT + test + + + + org.apache.tuscany.sca + tuscany-implementation-java-runtime + 2.0-SNAPSHOT + test + + + + commons-logging + commons-logging + 1.1.1 + + + commons-logging + commons-logging + + + javax.servlet + servlet-api + + + + + + + + rhino + js + 1.6R7 + compile + + + + org.jruby + jruby-complete + 1.1.3 + compile + + + asm + asm + + + asm + asm-commons + + + jline + jline + + + + + + org.python + jython + 2.2 + compile + + + + org.codehaus.groovy + groovy-all-minimal + 1.5.4 + compile + + + + diff --git a/java/sca/contrib/modules/implementation-script-runtime/src/main/java/org/apache/tuscany/sca/implementation/script/engines/TuscanyJRubyScriptEngine.java b/java/sca/contrib/modules/implementation-script-runtime/src/main/java/org/apache/tuscany/sca/implementation/script/engines/TuscanyJRubyScriptEngine.java new file mode 100644 index 0000000000..324246c32b --- /dev/null +++ b/java/sca/contrib/modules/implementation-script-runtime/src/main/java/org/apache/tuscany/sca/implementation/script/engines/TuscanyJRubyScriptEngine.java @@ -0,0 +1,697 @@ +/* +* Copyright (c) 2006, Sun Microsystems, Inc. +* All rights reserved. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* +* - Redistributions of source code must retain the above copyright notice, this +* list of conditions and the following disclaimer. +* +* - Redistributions in binary form must reproduce the above copyright notice, +* this list of conditions and the following disclaimer in the documentation +* and/or other materials provided with the distribution. +* +* - Neither the name of the Sun Microsystems, Inc. nor the names of +* contributors may be used to endorse or promote products derived from this +* software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND +* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED +* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF +* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE +* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH +* DAMAGE. +*/ +package org.apache.tuscany.sca.implementation.script.engines; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintStream; +import java.io.Reader; +import java.io.StringWriter; +import java.io.UnsupportedEncodingException; +import java.io.Writer; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.Charset; +import java.nio.charset.CharsetDecoder; +import java.nio.charset.CoderResult; +import java.nio.charset.CodingErrorAction; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import javax.script.AbstractScriptEngine; +import javax.script.Bindings; +import javax.script.Compilable; +import javax.script.CompiledScript; +import javax.script.Invocable; +import javax.script.ScriptContext; +import javax.script.ScriptEngine; +import javax.script.ScriptEngineFactory; +import javax.script.ScriptException; +import javax.script.SimpleBindings; + +import org.jruby.Ruby; +import org.jruby.RubyException; +import org.jruby.RubyIO; +import org.jruby.RubyObject; +import org.jruby.ast.Node; +import org.jruby.exceptions.RaiseException; +import org.jruby.internal.runtime.GlobalVariable; +import org.jruby.internal.runtime.GlobalVariables; +import org.jruby.internal.runtime.ReadonlyAccessor; +import org.jruby.internal.runtime.ValueAccessor; +import org.jruby.javasupport.Java; +import org.jruby.javasupport.JavaEmbedUtils; +import org.jruby.javasupport.JavaObject; +import org.jruby.javasupport.JavaUtil; +import org.jruby.runtime.Block; +import org.jruby.runtime.IAccessor; +import org.jruby.runtime.builtin.IRubyObject; +import org.jruby.util.KCode; + +import com.sun.script.jruby.JRubyScriptEngineFactory; + +/** + * This class is a copy of the class com.sun.script.ruby.JRubyScriptEngine with some minor modifications + * to work around problems with Tuscany setting SCA properties and references as global variable in JRuby + * Should only need it temporarily till a new BSF release fixes it. + * + * @version $Rev$ $Date$ + */ +@SuppressWarnings("unchecked") +public class TuscanyJRubyScriptEngine extends AbstractScriptEngine + implements Compilable, Invocable { + + // my factory, may be null + private ScriptEngineFactory factory; + private Ruby runtime; + + public TuscanyJRubyScriptEngine() { + // Allow privileged access to ready properties. Requires PropertyPermission in security + // policy. + String rubyPath = AccessController.doPrivileged(new PrivilegedAction() { + public String run() { + return System.getProperty("com.sun.script.jruby.loadpath"); + } + }); + init(rubyPath); + } + + public TuscanyJRubyScriptEngine(String loadPath) { + init(loadPath); + } + + // my implementation for CompiledScript + private class JRubyCompiledScript extends CompiledScript { + // my compiled code + private Node node; + + JRubyCompiledScript (Node node) { + this.node = node; + } + + public ScriptEngine getEngine() { + return TuscanyJRubyScriptEngine.this; + } + + public Object eval(ScriptContext ctx) throws ScriptException { + return evalNode(node, ctx); + } + } + + // Compilable methods + public CompiledScript compile(String script) + throws ScriptException { + Node node = compileScript(script, context); + return new JRubyCompiledScript(node); + } + + public CompiledScript compile (Reader reader) + throws ScriptException { + Node node = compileScript(reader, context); + return new JRubyCompiledScript(node); + } + + // Invocable methods + public Object invokeFunction(String name, Object... args) + throws ScriptException, NoSuchMethodException { + return invokeImpl(null, name, args, Object.class); + } + + public Object invokeMethod(Object obj, String name, Object... args) + throws ScriptException, NoSuchMethodException { + if (obj == null) { + throw new IllegalArgumentException("script object is null"); + } + return invokeImpl(obj, name, args, Object.class); + } + + public Object getInterface(Object obj, Class clazz) { + if (obj == null) { + throw new IllegalArgumentException("script object is null"); + } + return makeInterface(obj, clazz); + } + + public Object getInterface(Class clazz) { + return makeInterface(null, clazz); + } + + private T makeInterface(Object obj, Class clazz) { + if (clazz == null || !clazz.isInterface()) { + throw new IllegalArgumentException("interface Class expected"); + } + final Object thiz = obj; + return (T) Proxy.newProxyInstance( + clazz.getClassLoader(), + new Class[] { clazz }, + new InvocationHandler() { + public Object invoke(Object proxy, Method m, Object[] args) + throws Throwable { + return invokeImpl(thiz, m.getName(), + args, m.getReturnType()); + } + }); + } + + // ScriptEngine methods + public synchronized Object eval(String str, ScriptContext ctx) + throws ScriptException { + Node node = compileScript(str, ctx); + return evalNode(node, ctx); + } + + public synchronized Object eval(Reader reader, ScriptContext ctx) + throws ScriptException { + Node node = compileScript(reader, ctx); + return evalNode(node, ctx); + } + + public ScriptEngineFactory getFactory() { + synchronized (this) { + if (factory == null) { + factory = new JRubyScriptEngineFactory(); + } + } + return factory; + } + + public Bindings createBindings() { + return new SimpleBindings(); + } + + // package-private methods + void setFactory(ScriptEngineFactory factory) { + this.factory = factory; + } + + // internals only below this point + + private Object rubyToJava(IRubyObject value) { + return rubyToJava(value, Object.class); + } + + private Object rubyToJava(IRubyObject value, Class type) { + return JavaUtil.convertArgument( + runtime, + Java.ruby_to_java(value, value, Block.NULL_BLOCK), + type); + } + + private IRubyObject javaToRuby(Object value) { + if (value instanceof IRubyObject) { + return (IRubyObject) value; + } + IRubyObject result = JavaUtil.convertJavaToRuby(runtime, value); + if (result instanceof JavaObject) { + return runtime.getModule("JavaUtilities").callMethod(runtime.getCurrentContext(), "wrap", result); + } + return result; + } + + private synchronized Node compileScript(String script, ScriptContext ctx) + throws ScriptException { + GlobalVariables oldGlobals = runtime.getGlobalVariables(); + try { + setErrorWriter(ctx.getErrorWriter()); + setGlobalVariables(ctx); + String filename = (String) ctx.getAttribute(ScriptEngine.FILENAME); + if (filename == null) { + filename = ""; + } + return runtime.parseEval(script, filename, null, 0); + } catch (RaiseException e) { + RubyException re = e.getException(); + runtime.printError(re); + throw new ScriptException(e); + } catch (Exception e) { + throw new ScriptException(e); + } finally { + if (oldGlobals != null) { + setGlobalVariables(oldGlobals); + } + } + } + + private synchronized Node compileScript(Reader reader, ScriptContext ctx) + throws ScriptException { + GlobalVariables oldGlobals = runtime.getGlobalVariables(); + try { + setErrorWriter(ctx.getErrorWriter()); + setGlobalVariables(ctx); + String filename = (String) ctx.getAttribute(ScriptEngine.FILENAME); + if (filename == null) { + filename = ""; + String script = getRubyScript(reader); + return runtime.parseEval(script, filename, null, 0); + } + InputStream inputStream = getRubyReader(filename); + return runtime.parseFile(inputStream, filename, null); + } catch (RaiseException e) { + RubyException re = e.getException(); + runtime.printError(re); + throw new ScriptException(e); + } catch (Exception exp) { + throw new ScriptException(exp); + } finally { + if (oldGlobals != null) { + setGlobalVariables(oldGlobals); + } + } + } + + private String getRubyScript(Reader reader) throws IOException { + StringBuffer sb = new StringBuffer(); + char[] cbuf; + while (true) { + cbuf = new char[8*1024]; + int chars = reader.read(cbuf, 0, cbuf.length); + if (chars < 0) { + break; + } + sb.append(cbuf, 0, chars); + } + cbuf = null; + return (new String(sb)).trim(); + } + + private InputStream getRubyReader(String filename) throws FileNotFoundException { + File file = new File(filename); + return new FileInputStream(file); + } + + private void setGlobalVariables(final ScriptContext ctx) { + ctx.setAttribute("context", ctx, ScriptContext.ENGINE_SCOPE); + setGlobalVariables(new GlobalVariables(runtime) { + GlobalVariables parent = runtime.getGlobalVariables(); + + @Override + public void define(String name, IAccessor accessor) { + assert name != null; + assert accessor != null; + assert name.startsWith("$"); + synchronized (ctx) { + Bindings engineScope = ctx.getBindings(ScriptContext.ENGINE_SCOPE); + engineScope.put(name, new GlobalVariable(accessor)); + } + } + + @Override + public void defineReadonly(String name, IAccessor accessor) { + assert name != null; + assert accessor != null; + assert name.startsWith("$"); + synchronized (ctx) { + Bindings engineScope = ctx.getBindings(ScriptContext.ENGINE_SCOPE); + engineScope.put(name, new GlobalVariable(new + ReadonlyAccessor(name, accessor))); + } + } + + @Override + public boolean isDefined(String name) { + assert name != null; + assert name.startsWith("$"); + synchronized (ctx) { + String modifiedName = name.substring(1); + boolean defined = ctx.getAttributesScope(modifiedName) != -1; + return defined ? true : parent.isDefined(name); + } + } + + @Override + public void alias(String name, String oldName) { + assert name != null; + assert oldName != null; + assert name.startsWith("$"); + assert oldName.startsWith("$"); + + if (runtime.getSafeLevel() >= 4) { + throw runtime.newSecurityError("Insecure: can't alias global variable"); + } + + synchronized (ctx) { + int scope = ctx.getAttributesScope(name); + if (scope == -1) { + scope = ScriptContext.ENGINE_SCOPE; + } + + IRubyObject value = get(oldName); + ctx.setAttribute(name, rubyToJava(value), scope); + } + } + + @Override + public IRubyObject get(String name) { + assert name != null; + assert name.startsWith("$"); + + synchronized (ctx) { + // skip '$' and try + String modifiedName = name.substring(1); + int scope = ctx.getAttributesScope(modifiedName); + if (scope == -1) { + return parent.get(name); + } + + Object obj = ctx.getAttribute(modifiedName, scope); + if (obj instanceof IAccessor) { + return ((IAccessor)obj).getValue(); + } else { + return javaToRuby(obj); + } + } + } + + @Override + public IRubyObject set(String name, IRubyObject value) { + assert name != null; + assert name.startsWith("$"); + + if (runtime.getSafeLevel() >= 4) { + throw runtime.newSecurityError("Insecure: can't change global variable value"); + } + + synchronized (ctx) { + // skip '$' and try + String modifiedName = name.substring(1); + int scope = ctx.getAttributesScope(modifiedName); + if (scope == -1) { + scope = ScriptContext.ENGINE_SCOPE; + } + IRubyObject oldValue = get(name); + Object obj = ctx.getAttribute(modifiedName, scope); + if (obj instanceof IAccessor) { + ((IAccessor)obj).setValue(value); + } else { + ctx.setAttribute(modifiedName, rubyToJava(value), scope); + if ("KCODE".equals(modifiedName)) { + setKCode((String)rubyToJava(value)); + } else if ("stdout".equals(modifiedName)) { + equalOutputs((RubyObject)value); + } + } + return oldValue; + } + } + + @Override + public Set getNames() { + HashSet set = new HashSet(); + synchronized (ctx) { + for (Object scope : ctx.getScopes()) { + Bindings b = ctx.getBindings((Integer)scope); + if (b != null) { + for (Object key: b.keySet()) { + set.add(key); + } + } + } + } + for (Iterator names = parent.getNames().iterator(); names.hasNext();) { + set.add(names.next()); + } + return Collections.unmodifiableSet(set); + } + + @Override + public IRubyObject getDefaultSeparator() { + return parent.getDefaultSeparator(); + } + }); + } + + private void setGlobalVariables(GlobalVariables globals) { + runtime.setGlobalVariables(globals); + } + + private synchronized Object evalNode(Node node, ScriptContext ctx) + throws ScriptException { + GlobalVariables oldGlobals = runtime.getGlobalVariables(); + try { + setWriterOutputStream(ctx.getWriter()); + setErrorWriter(ctx.getErrorWriter()); + setGlobalVariables(ctx); + return rubyToJava(runtime.runNormally(node, false)); + } catch (Exception exp) { + throw new ScriptException(exp); + } finally { + try { + JavaEmbedUtils.terminate(runtime); + } catch (RaiseException e) { + RubyException re = e.getException(); + runtime.printError(re); + if (!runtime.fastGetClass("SystemExit").isInstance(re)) { + throw new ScriptException(e); + } + } finally { + if (oldGlobals != null) { + setGlobalVariables(oldGlobals); + } + } + } + } + + private void init(final String loadPath) { + AccessController.doPrivileged(new PrivilegedAction() { + public Object run() { + runtime = Ruby.newInstance(); + IAccessor d = new ValueAccessor(runtime.newString(" + + + + + + +

      Store

      +
      +

      Catalog

      +
      +
      +
      + +
      + +
      + +

      Your Shopping Cart

      +
      +
      +
      +
      +
      + + + (feed) +
      +
      + + diff --git a/java/sca/contrib/modules/implementation-widget-runtime/src/test/resources/content/storeJS.html b/java/sca/contrib/modules/implementation-widget-runtime/src/test/resources/content/storeJS.html new file mode 100644 index 0000000000..6bbc285377 --- /dev/null +++ b/java/sca/contrib/modules/implementation-widget-runtime/src/test/resources/content/storeJS.html @@ -0,0 +1,152 @@ + + + +Store + + + + + + + + + + +

      Store

      +
      +

      Catalog

      +
      +
      +
      + +
      + +
      + +

      Your Shopping Cart

      +
      +
      +
      +
      +
      + + + (feed) +
      +
      + + diff --git a/java/sca/contrib/modules/implementation-widget-runtime/src/test/resources/content/unitTests.html b/java/sca/contrib/modules/implementation-widget-runtime/src/test/resources/content/unitTests.html new file mode 100644 index 0000000000..352dd85508 --- /dev/null +++ b/java/sca/contrib/modules/implementation-widget-runtime/src/test/resources/content/unitTests.html @@ -0,0 +1,250 @@ + + + +Atom JavaScript Client Unit Tests + + + + + + + + +

      Atom JavaScript Client Unit Tests

      +

      This document tests the serialization and deserialization of the Atom JavaScript client. +

      Model to XML Tests

      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +

      Results

      + + + + diff --git a/java/sca/contrib/modules/implementation-widget-runtime/src/test/resources/widget.composite b/java/sca/contrib/modules/implementation-widget-runtime/src/test/resources/widget.composite new file mode 100644 index 0000000000..f23d6a20f5 --- /dev/null +++ b/java/sca/contrib/modules/implementation-widget-runtime/src/test/resources/widget.composite @@ -0,0 +1,54 @@ + + + + + + + en + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/java/sca/contrib/modules/implementation-widget-runtime/src/test/resources/widgetJS.composite b/java/sca/contrib/modules/implementation-widget-runtime/src/test/resources/widgetJS.composite new file mode 100644 index 0000000000..e44a56e520 --- /dev/null +++ b/java/sca/contrib/modules/implementation-widget-runtime/src/test/resources/widgetJS.composite @@ -0,0 +1,58 @@ + + + + + + + + en + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/java/sca/contrib/modules/implementation-widget/LICENSE b/java/sca/contrib/modules/implementation-widget/LICENSE new file mode 100644 index 0000000000..8aa906c321 --- /dev/null +++ b/java/sca/contrib/modules/implementation-widget/LICENSE @@ -0,0 +1,205 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + + diff --git a/java/sca/contrib/modules/implementation-widget/META-INF/MANIFEST.MF b/java/sca/contrib/modules/implementation-widget/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..f112dd57bf --- /dev/null +++ b/java/sca/contrib/modules/implementation-widget/META-INF/MANIFEST.MF @@ -0,0 +1,34 @@ +Manifest-Version: 1.0 +Export-Package: org.apache.tuscany.sca.implementation.widget;uses:="or + g.apache.tuscany.sca.data.collection,org.apache.tuscany.sca.assembly, + org.apache.tuscany.sca.contribution,org.apache.tuscany.sca.core,org.a + pache.tuscany.sca.monitor,org.apache.tuscany.sca.interfacedef.java,or + g.apache.tuscany.sca.interfacedef,javax.xml.namespace,javax.xml.strea + m,org.apache.tuscany.sca.contribution.resolver,org.apache.tuscany.sca + .contribution.processor";version="2.0.0" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA Widget Implementation Model +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397413234 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA Widget Implementation Model +Import-Package: javax.xml.namespace, + javax.xml.stream, + org.apache.tuscany.sca.assembly;version="2.0.0", + org.apache.tuscany.sca.assembly.xml;version="2.0.0", + org.apache.tuscany.sca.contribution;version="2.0.0", + org.apache.tuscany.sca.contribution.processor;version="2.0.0", + org.apache.tuscany.sca.contribution.resolver;version="2.0.0", + org.apache.tuscany.sca.core;version="2.0.0", + org.apache.tuscany.sca.data.collection;version="2.0.0", + org.apache.tuscany.sca.implementation.widget;version="2.0.0", + org.apache.tuscany.sca.interfacedef;version="2.0.0", + org.apache.tuscany.sca.interfacedef.java;version="2.0.0", + org.apache.tuscany.sca.monitor;version="2.0.0", + org.apache.tuscany.sca.policy;version="2.0.0" +Bundle-SymbolicName: org.apache.tuscany.sca.implementation.widget +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/implementation-widget/NOTICE b/java/sca/contrib/modules/implementation-widget/NOTICE new file mode 100644 index 0000000000..25bb89c9b2 --- /dev/null +++ b/java/sca/contrib/modules/implementation-widget/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/implementation-widget/pom.xml b/java/sca/contrib/modules/implementation-widget/pom.xml new file mode 100644 index 0000000000..85777f47ea --- /dev/null +++ b/java/sca/contrib/modules/implementation-widget/pom.xml @@ -0,0 +1,60 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + + tuscany-implementation-widget + Apache Tuscany SCA Widget Implementation Model + + + + org.apache.tuscany.sca + tuscany-assembly-xml + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-interface-java + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-data-api + 2.0-SNAPSHOT + + + + junit + junit + 4.5 + test + + + + + diff --git a/java/sca/contrib/modules/implementation-widget/src/main/java/org/apache/tuscany/sca/implementation/widget/Widget.java b/java/sca/contrib/modules/implementation-widget/src/main/java/org/apache/tuscany/sca/implementation/widget/Widget.java new file mode 100644 index 0000000000..f47850a05c --- /dev/null +++ b/java/sca/contrib/modules/implementation-widget/src/main/java/org/apache/tuscany/sca/implementation/widget/Widget.java @@ -0,0 +1,34 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.implementation.widget; + +import java.io.InputStream; + +import org.apache.tuscany.sca.data.collection.Collection; + +/** + * The service interface of widget implementations. This is not an API for application + * developers. Application developers should use the data collection API to invoke + * widget components. + * + * @version $Rev$ $Date$ + */ +public interface Widget extends Collection { +} diff --git a/java/sca/contrib/modules/implementation-widget/src/main/java/org/apache/tuscany/sca/implementation/widget/WidgetImplementation.java b/java/sca/contrib/modules/implementation-widget/src/main/java/org/apache/tuscany/sca/implementation/widget/WidgetImplementation.java new file mode 100644 index 0000000000..b35cc41dd4 --- /dev/null +++ b/java/sca/contrib/modules/implementation-widget/src/main/java/org/apache/tuscany/sca/implementation/widget/WidgetImplementation.java @@ -0,0 +1,134 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.implementation.widget; + +import java.net.URL; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.apache.tuscany.sca.assembly.AssemblyFactory; +import org.apache.tuscany.sca.assembly.ConstrainingType; +import org.apache.tuscany.sca.assembly.Implementation; +import org.apache.tuscany.sca.assembly.Property; +import org.apache.tuscany.sca.assembly.Reference; +import org.apache.tuscany.sca.assembly.Service; +import org.apache.tuscany.sca.interfacedef.InvalidInterfaceException; +import org.apache.tuscany.sca.interfacedef.java.JavaInterface; +import org.apache.tuscany.sca.interfacedef.java.JavaInterfaceContract; +import org.apache.tuscany.sca.interfacedef.java.JavaInterfaceFactory; + + +/** + * The model representing a widget implementation in an SCA assembly model. + * + * @version $Rev$ $Date$ + */ +public class WidgetImplementation implements Implementation { + private Service widgetService; + private List references = new ArrayList(); + private List properties = new ArrayList(); + + private String location; + private URL url; + private boolean unresolved; + + /** + * Constructs a new resource implementation. + */ + WidgetImplementation(AssemblyFactory assemblyFactory, + JavaInterfaceFactory javaFactory) { + + // Resource implementation always provide a single service exposing + // the Resource interface, and have no references and properties + widgetService = assemblyFactory.createService(); + widgetService.setName("Widget"); + + // Create the Java interface contract for the Resource service + JavaInterface javaInterface; + try { + javaInterface = javaFactory.createJavaInterface(Widget.class); + } catch (InvalidInterfaceException e) { + throw new IllegalArgumentException(e); + } + JavaInterfaceContract interfaceContract = javaFactory.createJavaInterfaceContract(); + interfaceContract.setInterface(javaInterface); + widgetService.setInterfaceContract(interfaceContract); + } + + public String getLocation() { + return location; + } + + public void setLocation(String location) { + this.location = location; + } + + public URL getLocationURL() { + return url; + } + + public void setLocationURL(URL url) { + this.url = url; + } + + public ConstrainingType getConstrainingType() { + // The resource implementation does not support constrainingTypes + return null; + } + + public List getProperties() { + return properties; + } + + public List getServices() { + // The resource implementation does not support services + return Collections.singletonList(widgetService); + } + + public List getReferences() { + return references; + } + + public String getURI() { + return location; + } + + public void setConstrainingType(ConstrainingType constrainingType) { + // The resource implementation does not support constrainingTypes + } + + public void setURI(String uri) { + this.location = uri; + } + + + public boolean isUnresolved() { + return unresolved; + } + + public void setUnresolved(boolean unresolved) { + this.unresolved = unresolved; + } + + @Override + public String toString() { + return "Widget : " + getLocation(); + } +} diff --git a/java/sca/contrib/modules/implementation-widget/src/main/java/org/apache/tuscany/sca/implementation/widget/WidgetImplementationFactory.java b/java/sca/contrib/modules/implementation-widget/src/main/java/org/apache/tuscany/sca/implementation/widget/WidgetImplementationFactory.java new file mode 100644 index 0000000000..dc5759a13d --- /dev/null +++ b/java/sca/contrib/modules/implementation-widget/src/main/java/org/apache/tuscany/sca/implementation/widget/WidgetImplementationFactory.java @@ -0,0 +1,45 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.implementation.widget; + +import org.apache.tuscany.sca.assembly.AssemblyFactory; +import org.apache.tuscany.sca.core.FactoryExtensionPoint; +import org.apache.tuscany.sca.interfacedef.java.JavaInterfaceFactory; + +/** + * Factory for the widget implementation model. + * + * @version $Rev$ $Date$ + */ +public class WidgetImplementationFactory { + + private AssemblyFactory assemblyFactory; + private JavaInterfaceFactory javaFactory; + + public WidgetImplementationFactory(FactoryExtensionPoint modelFactories) { + assemblyFactory = modelFactories.getFactory(AssemblyFactory.class); + javaFactory = modelFactories.getFactory(JavaInterfaceFactory.class); + } + + public WidgetImplementation createWidgetImplementation() { + return new WidgetImplementation(assemblyFactory, javaFactory); + } + +} diff --git a/java/sca/contrib/modules/implementation-widget/src/main/java/org/apache/tuscany/sca/implementation/widget/WidgetImplementationIntrospector.java b/java/sca/contrib/modules/implementation-widget/src/main/java/org/apache/tuscany/sca/implementation/widget/WidgetImplementationIntrospector.java new file mode 100644 index 0000000000..abe00bac5b --- /dev/null +++ b/java/sca/contrib/modules/implementation-widget/src/main/java/org/apache/tuscany/sca/implementation/widget/WidgetImplementationIntrospector.java @@ -0,0 +1,145 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.implementation.widget; + +import java.net.URL; +import java.net.URLConnection; +import java.util.Scanner; + +import org.apache.tuscany.sca.assembly.AssemblyFactory; +import org.apache.tuscany.sca.assembly.Property; +import org.apache.tuscany.sca.assembly.Reference; + +/** + * + * @version $Rev$ $Date$ + */ +class WidgetImplementationIntrospector { + private static final String WEB_REFERENCE_ANNOTATION = "//@Reference"; + private static final String WEB_PROPERTY_ANNOTATION = "//@Property"; + + private AssemblyFactory assemblyFactory; + private WidgetImplementation widgetImplementation; + + WidgetImplementationIntrospector(AssemblyFactory assemblyFactory, WidgetImplementation widgetImplementation) { + this.widgetImplementation = widgetImplementation; + this.assemblyFactory = assemblyFactory; + } + + + /** + * Introspect and populate a given widget implementation + */ + public void introspectImplementation() { + URL htmlWidget = widgetImplementation.getLocationURL(); + + try { + URLConnection connection = htmlWidget.openConnection(); + connection.setUseCaches(false); + Scanner scanner = new Scanner(connection.getInputStream()); + while(scanner.hasNextLine()) { + String line = scanner.nextLine(); + if(line.contains(WEB_PROPERTY_ANNOTATION)) { + //process the next line, as it has the property info + if (scanner.hasNextLine()) { + Property property = processPropertyScript(scanner.nextLine()); + if (property != null) { + widgetImplementation.getProperties().add(property); + } + } + + } else if(line.contains(WEB_REFERENCE_ANNOTATION)) { + //process the next line, as it has the reference info + if (scanner.hasNextLine()) { + Reference reference = processReferenceScript(scanner.nextLine()); + if(reference != null){ + widgetImplementation.getReferences().add(reference); + } + + } + } + } + + } catch(Exception e) { + + } + + + } + + + /** + * Process Property declaration in JavaScript code + * Supported ways: + * //@Property + * var locale = Property("locale"); + * + * //@Property + * locale = Property("locale"); + * + * @param scriptContent + * @return + */ + private Property processPropertyScript(String scriptContent) { + Property property = null; + String propertyName = null; + + String tokens[] = scriptContent.split("="); + tokens = tokens[0].split(" "); + propertyName = tokens[tokens.length -1]; + + if(propertyName != null) { + property = assemblyFactory.createProperty(); + property.setName(propertyName); + } + + return property; + } + + /** + * Process Reference declaration in JavaScript code + * Supported ways : + * //@Reference + * var catalog = new Reference("catalog"); + * + * //@Reference + * catalog = new Reference("catalog"); + * + * @param scriptContent + * @return + */ + private Reference processReferenceScript(String scriptContent) { + Reference reference = null; + String referenceName = null; + + String tokens[] = scriptContent.split("="); + + // find the string between the quotes + tokens = tokens[1].split("\""); + referenceName = tokens[1]; + + if(referenceName != null) { + reference = assemblyFactory.createReference(); + reference.setName(referenceName); + } + + return reference; + } +} diff --git a/java/sca/contrib/modules/implementation-widget/src/main/java/org/apache/tuscany/sca/implementation/widget/WidgetImplementationProcessor.java b/java/sca/contrib/modules/implementation-widget/src/main/java/org/apache/tuscany/sca/implementation/widget/WidgetImplementationProcessor.java new file mode 100644 index 0000000000..1d3e71dfcb --- /dev/null +++ b/java/sca/contrib/modules/implementation-widget/src/main/java/org/apache/tuscany/sca/implementation/widget/WidgetImplementationProcessor.java @@ -0,0 +1,175 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.implementation.widget; + +import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; + +import java.io.IOException; +import java.net.URL; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; + +import org.apache.tuscany.sca.assembly.AssemblyFactory; +import org.apache.tuscany.sca.assembly.xml.Constants; +import org.apache.tuscany.sca.contribution.Artifact; +import org.apache.tuscany.sca.contribution.ContributionFactory; +import org.apache.tuscany.sca.contribution.processor.ContributionReadException; +import org.apache.tuscany.sca.contribution.processor.ContributionResolveException; +import org.apache.tuscany.sca.contribution.processor.ContributionWriteException; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.core.FactoryExtensionPoint; +import org.apache.tuscany.sca.monitor.Monitor; +import org.apache.tuscany.sca.monitor.Problem; +import org.apache.tuscany.sca.monitor.Problem.Severity; + + +/** + * Implements a StAX artifact processor for Widget implementations. + * + * @version $Rev$ $Date$ + */ +public class WidgetImplementationProcessor implements StAXArtifactProcessor { + private static final QName IMPLEMENTATION_WIDGET = new QName(Constants.SCA10_TUSCANY_NS, "implementation.widget"); + + private AssemblyFactory assemblyFactory; + private ContributionFactory contributionFactory; + private WidgetImplementationFactory implementationFactory; + private Monitor monitor; + + public WidgetImplementationProcessor(FactoryExtensionPoint modelFactories, Monitor monitor) { + assemblyFactory = modelFactories.getFactory(AssemblyFactory.class); + contributionFactory = modelFactories.getFactory(ContributionFactory.class); + implementationFactory = new WidgetImplementationFactory(modelFactories); + this.monitor = monitor; + } + + /** + * Report a exception. + * + * @param problems + * @param message + * @param model + */ + private void error(String message, Object model, Exception ex) { + if (monitor != null) { + Problem problem = monitor.createProblem(this.getClass().getName(), "impl-widget-validation-messages", Severity.ERROR, model, message, ex); + monitor.problem(problem); + } + } + + /** + * Report a error. + * + * @param problems + * @param message + * @param model + */ + private void error(String message, Object model, Object... messageParameters) { + if (monitor != null) { + Problem problem = monitor.createProblem(this.getClass().getName(), "impl-widget-validation-messages", Severity.ERROR, model, message, (Object[])messageParameters); + monitor.problem(problem); + } + } + + public QName getArtifactType() { + // Returns the QName of the XML element processed by this processor + return IMPLEMENTATION_WIDGET; + } + + public Class getModelType() { + // Returns the type of model processed by this processor + return WidgetImplementation.class; + } + + public WidgetImplementation read(XMLStreamReader reader) throws ContributionReadException, XMLStreamException { + + // Read an element + + // Create and initialize the resource implementation model + WidgetImplementation implementation = null; + + // Read the location attribute specifying the location of the resources + String location = reader.getAttributeValue(null, "location"); + if (location != null) { + implementation = implementationFactory.createWidgetImplementation(); + implementation.setLocation(location); + implementation.setUnresolved(true); + } else { + error("LocationAttributeMissing", reader); + //throw new ContributionReadException(MSG_LOCATION_MISSING); + } + + // Skip to end element + while (reader.hasNext()) { + if (reader.next() == END_ELEMENT && IMPLEMENTATION_WIDGET.equals(reader.getName())) { + break; + } + } + + return implementation; + } + + public void resolve(WidgetImplementation implementation, ModelResolver resolver) throws ContributionResolveException { + + if (implementation != null) { + // Resolve the resource directory location + Artifact artifact = contributionFactory.createArtifact(); + artifact.setURI(implementation.getLocation()); + Artifact resolved = resolver.resolveModel(Artifact.class, artifact); + if (resolved.getLocation() != null) { + try { + implementation.setLocationURL(new URL(resolved.getLocation())); + + //introspect implementation + WidgetImplementationIntrospector widgetIntrospector = + new WidgetImplementationIntrospector(assemblyFactory, implementation); + widgetIntrospector.introspectImplementation(); + + implementation.setUnresolved(false); + } catch (IOException e) { + ContributionResolveException ce = new ContributionResolveException(e); + error("ContributionResolveException", resolver, ce); + //throw ce; + } + } else { + error("CouldNotResolveLocation", resolver, implementation.getLocation()); + //throw new ContributionResolveException("Could not resolve implementation.widget location: " + implementation.getLocation()); + } + } + } + + public void write(WidgetImplementation implementation, XMLStreamWriter writer) throws ContributionWriteException, XMLStreamException { + + // Write + writer.setPrefix("widget",IMPLEMENTATION_WIDGET.getNamespaceURI()); + writer.writeStartElement(IMPLEMENTATION_WIDGET.getNamespaceURI(), IMPLEMENTATION_WIDGET.getLocalPart()); + writer.writeNamespace("widget",IMPLEMENTATION_WIDGET.getNamespaceURI()); + + + if (implementation.getLocation() != null) { + writer.writeAttribute("location", implementation.getLocation()); + } + + writer.writeEndElement(); + } +} diff --git a/java/sca/contrib/modules/implementation-widget/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor b/java/sca/contrib/modules/implementation-widget/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor new file mode 100644 index 0000000000..6c167a6b31 --- /dev/null +++ b/java/sca/contrib/modules/implementation-widget/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for the artifact processor extension +org.apache.tuscany.sca.implementation.widget.WidgetImplementationProcessor;qname=http://tuscany.apache.org/xmlns/sca/1.0#implementation.widget,model=org.apache.tuscany.sca.implementation.widget.WidgetImplementation diff --git a/java/sca/contrib/modules/implementation-widget/src/main/resources/META-INF/services/org.apache.tuscany.sca.implementation.widget.WidgetImplementationFactory b/java/sca/contrib/modules/implementation-widget/src/main/resources/META-INF/services/org.apache.tuscany.sca.implementation.widget.WidgetImplementationFactory new file mode 100644 index 0000000000..fc45baa16d --- /dev/null +++ b/java/sca/contrib/modules/implementation-widget/src/main/resources/META-INF/services/org.apache.tuscany.sca.implementation.widget.WidgetImplementationFactory @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for model factory +org.apache.tuscany.sca.implementation.widget.WidgetImplementationFactory diff --git a/java/sca/contrib/modules/implementation-widget/src/main/resources/impl-widget-validation-messages.properties b/java/sca/contrib/modules/implementation-widget/src/main/resources/impl-widget-validation-messages.properties new file mode 100644 index 0000000000..3778bd4c50 --- /dev/null +++ b/java/sca/contrib/modules/implementation-widget/src/main/resources/impl-widget-validation-messages.properties @@ -0,0 +1,23 @@ +# +# +# 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. +# +# +ContributionResolveException = ContributionResolveException occured due to: +LocationAttributeMissing = Reading implementation.widget - location attribute missing +CouldNotResolveLocation = Could not resolve implementation.widget location: {0} diff --git a/java/sca/contrib/modules/implementation-xquery/LICENSE b/java/sca/contrib/modules/implementation-xquery/LICENSE new file mode 100644 index 0000000000..d645695673 --- /dev/null +++ b/java/sca/contrib/modules/implementation-xquery/LICENSE @@ -0,0 +1,202 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/java/sca/contrib/modules/implementation-xquery/META-INF/MANIFEST.MF b/java/sca/contrib/modules/implementation-xquery/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..380c00293e --- /dev/null +++ b/java/sca/contrib/modules/implementation-xquery/META-INF/MANIFEST.MF @@ -0,0 +1,64 @@ +Manifest-Version: 1.0 +Export-Package: org.apache.tuscany.sca.implementation.xquery;uses:="or + g.apache.tuscany.sca.databinding,org.apache.tuscany.sca.runtime,net.s + f.saxon.value,org.apache.tuscany.sca.interfacedef.util,org.apache.tus + cany.sca.provider,org.apache.tuscany.sca.databinding.saxon,net.sf.sax + on.trans,org.apache.tuscany.sca.core,javax.xml.transform.dom,net.sf.s + axon,org.apache.tuscany.sca.databinding.saxon.collection,javax.xml.na + mespace,net.sf.saxon.query,org.apache.tuscany.sca.core.factory,net.sf + .saxon.om,org.apache.tuscany.sca.assembly,org.apache.tuscany.sca.data + binding.impl,org.apache.tuscany.sca.interfacedef.java,org.apache.tusc + any.sca.interfacedef,org.w3c.dom,org.apache.tuscany.sca.implementatio + n.java.injection,org.apache.tuscany.sca.invocation,javax.xml.transfor + m,net.sf.saxon.event,javax.xml.transform.stream";version="2.0.0" +Private-Package: org.apache.tuscany.sca.implementation.xquery.impl;ver + sion="1.4",org.apache.tuscany.sca.implementation.xquery.xml;version=" + 1.4" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA XQuery Implementation Extension +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397469781 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA XQuery Implementation Extension +Import-Package: javax.xml.namespace, + javax.xml.stream, + javax.xml.transform, + javax.xml.transform.dom, + javax.xml.transform.stream, + net.sf.saxon, + net.sf.saxon.event, + net.sf.saxon.om, + net.sf.saxon.query, + net.sf.saxon.trans, + net.sf.saxon.value, + org.apache.tuscany.sca.assembly;version="2.0.0", + org.apache.tuscany.sca.assembly.impl;version="2.0.0", + org.apache.tuscany.sca.contribution;version="2.0.0", + org.apache.tuscany.sca.contribution.processor;version="2.0.0", + org.apache.tuscany.sca.contribution.resolver;version="2.0.0", + org.apache.tuscany.sca.core;version="2.0.0", + org.apache.tuscany.sca.core.factory;version="2.0.0", + org.apache.tuscany.sca.databinding;version="2.0.0", + org.apache.tuscany.sca.databinding.impl;version="2.0.0", + org.apache.tuscany.sca.databinding.javabeans;version="2.0.0", + org.apache.tuscany.sca.databinding.saxon;version="2.0.0", + org.apache.tuscany.sca.databinding.saxon.collection;version="2.0.0", + org.apache.tuscany.sca.implementation.java;version="2.0.0", + org.apache.tuscany.sca.implementation.java.injection;version="2.0.0", + org.apache.tuscany.sca.implementation.xquery;version="2.0.0", + org.apache.tuscany.sca.interfacedef;version="2.0.0", + org.apache.tuscany.sca.interfacedef.java;version="2.0.0", + org.apache.tuscany.sca.interfacedef.util;version="2.0.0", + org.apache.tuscany.sca.invocation;version="2.0.0", + org.apache.tuscany.sca.monitor;version="2.0.0", + org.apache.tuscany.sca.policy;version="2.0.0", + org.apache.tuscany.sca.provider;version="2.0.0", + org.apache.tuscany.sca.runtime;version="2.0.0", + org.oasisopen.sca;version="2.0.0", + org.w3c.dom +Bundle-SymbolicName: org.apache.tuscany.sca.implementation.xquery +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/implementation-xquery/NOTICE b/java/sca/contrib/modules/implementation-xquery/NOTICE new file mode 100644 index 0000000000..25bb89c9b2 --- /dev/null +++ b/java/sca/contrib/modules/implementation-xquery/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/implementation-xquery/pom.xml b/java/sca/contrib/modules/implementation-xquery/pom.xml new file mode 100644 index 0000000000..559c17e97d --- /dev/null +++ b/java/sca/contrib/modules/implementation-xquery/pom.xml @@ -0,0 +1,86 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + + tuscany-implementation-xquery + Apache Tuscany SCA XQuery Implementation Extension + + + + org.apache.tuscany.sca + tuscany-assembly + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-interface-java-xml + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-implementation-java-runtime + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-databinding-saxon + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-databinding-jaxb + 2.0-SNAPSHOT + runtime + + + + org.apache.tuscany.sca + tuscany-core-spi + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-node-impl + 2.0-SNAPSHOT + test + + + + junit + junit + 4.5 + test + + + + + diff --git a/java/sca/contrib/modules/implementation-xquery/src/main/java/org/apache/tuscany/sca/implementation/xquery/XQueryImplementation.java b/java/sca/contrib/modules/implementation-xquery/src/main/java/org/apache/tuscany/sca/implementation/xquery/XQueryImplementation.java new file mode 100644 index 0000000000..f5bc5dd9b8 --- /dev/null +++ b/java/sca/contrib/modules/implementation-xquery/src/main/java/org/apache/tuscany/sca/implementation/xquery/XQueryImplementation.java @@ -0,0 +1,75 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.implementation.xquery; + +import java.lang.reflect.Method; +import java.util.Map; + +import net.sf.saxon.query.XQueryExpression; + +import org.apache.tuscany.sca.assembly.Implementation; + +/** + * Class representing the XQuery implementation type + * @version $Rev$ $Date$ + */ +public interface XQueryImplementation extends Implementation { + + /** + * Location of the XQuery implementation file + * @return + */ + String getLocation(); + + void setLocation(String location); + + String getLocationURL(); + + void setLocationURL(String location); + + /** + * The XQuery expression that is loaded from the XQuery implementation file + * @return + */ + String getXqExpression(); + + void setXqExpression(String expression); + + /** + * The XQuery expression should be extended for with additional + * script, which provides the external variables needed to invoke + * a function. In this way for each function that is defined in the + * original XQuery expression additional expression is defined, which + * can invoke this function, using external variables as input. + * These expression extensions are stored in this map. It provides for + * each method of a service interface that is implemented by this component + * type corresponding expression extension + * @return + */ + Map getXqExpressionExtensionsMap(); + + /** + * This map is a kind of cache for function invocations. If a given + * XQuery function of this implementation has been invoked already + * its compiled expression can be reused. In this manner the performance + * can be increased + * @return + */ + Map getCompiledExpressionsCache(); +} diff --git a/java/sca/contrib/modules/implementation-xquery/src/main/java/org/apache/tuscany/sca/implementation/xquery/XQueryImplementationFactory.java b/java/sca/contrib/modules/implementation-xquery/src/main/java/org/apache/tuscany/sca/implementation/xquery/XQueryImplementationFactory.java new file mode 100644 index 0000000000..bdfd390499 --- /dev/null +++ b/java/sca/contrib/modules/implementation-xquery/src/main/java/org/apache/tuscany/sca/implementation/xquery/XQueryImplementationFactory.java @@ -0,0 +1,32 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.implementation.xquery; + +import org.apache.tuscany.sca.implementation.xquery.impl.XQueryImplementationFactoryImpl; + +/** + * Provides instances of XQueryImplementation classes + * @version $Rev$ $Date$ + */ +public interface XQueryImplementationFactory { + + XQueryImplementationFactory INSTANCE = new XQueryImplementationFactoryImpl(); + + XQueryImplementation createXQueryImplementation(); +} diff --git a/java/sca/contrib/modules/implementation-xquery/src/main/java/org/apache/tuscany/sca/implementation/xquery/XQueryImplementationProvider.java b/java/sca/contrib/modules/implementation-xquery/src/main/java/org/apache/tuscany/sca/implementation/xquery/XQueryImplementationProvider.java new file mode 100644 index 0000000000..63a3a49e13 --- /dev/null +++ b/java/sca/contrib/modules/implementation-xquery/src/main/java/org/apache/tuscany/sca/implementation/xquery/XQueryImplementationProvider.java @@ -0,0 +1,166 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.implementation.xquery; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.assembly.ComponentProperty; +import org.apache.tuscany.sca.assembly.Reference; +import org.apache.tuscany.sca.assembly.Service; +import org.apache.tuscany.sca.core.factory.ObjectFactory; +import org.apache.tuscany.sca.databinding.javabeans.SimpleJavaDataBinding; +import org.apache.tuscany.sca.databinding.saxon.SaxonNodeDataBinding; +import org.apache.tuscany.sca.databinding.saxon.SaxonValueDataBinding; +import org.apache.tuscany.sca.implementation.java.injection.JavaPropertyValueObjectFactory; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.Interface; +import org.apache.tuscany.sca.interfacedef.InterfaceContract; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.interfacedef.java.JavaInterface; +import org.apache.tuscany.sca.interfacedef.util.JavaXMLMapper; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.provider.ImplementationProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; + +/** + * Provides the runtime configuration of XQuery-typed component. + * + * Generally the following is done: + * 1. During construction all services and references are provided + * with the Saxon data binding, which is the one required by the + * XQueryInvoker + * + * 2. During startup: + * - a proxy is created for each reference and it is kept in the referenceProxies + * map, which is used later by the invoker to configure the Saxon parser; + * - each property value is read and put into the properties map. This is + * again used by the invoker to configure the Saxon parser + * + * @version $Rev$ $Date$ + */ +public class XQueryImplementationProvider implements ImplementationProvider { + + private RuntimeComponent component; + private XQueryImplementation implementation; + private Map referenceProxies = new HashMap(); + private Map properties = new HashMap(); + private JavaPropertyValueObjectFactory javaFactory; + + public XQueryImplementationProvider(RuntimeComponent component, + XQueryImplementation implementation, + JavaPropertyValueObjectFactory factory) { + this.component = component; + this.implementation = implementation; + this.javaFactory = factory; + init(); + } + + private void init() { + List services = implementation.getServices(); + for (Service sevice : services) { + InterfaceContract interfaceContract = sevice.getInterfaceContract(); + //interfaceContract.getInterface().setDefaultDataBinding(ValueRepresentation.class.getName()); + setDataBinding(interfaceContract.getInterface(), false); + } + + List references = implementation.getReferences(); + for (Reference reference : references) { + InterfaceContract interfaceContract = reference.getInterfaceContract(); + //interfaceContract.getInterface().setDefaultDataBinding(ValueRepresentation.class.getName()); + setDataBinding(interfaceContract.getInterface(), true); + } + } + + public Invoker createInvoker(RuntimeComponentService service, Operation operation) { + return new XQueryInvoker(service, operation, implementation, referenceProxies, properties); + } + + public boolean supportsOneWayInvocation() { + return false; + } + + public void start() { + + for (Reference reference : component.getReferences()) { + String refName = reference.getName(); + if (refName.startsWith("$self$.")) { + continue; + } + Class interfaze = ((JavaInterface)reference.getInterfaceContract().getInterface()).getJavaClass(); + Object refProxy = component.getComponentContext().getService(interfaze, refName); + referenceProxies.put(refName, refProxy); + } + + for (ComponentProperty property : component.getProperties()) { + String propName = property.getName(); + QName xmlType = property.getXSDType(); + Class clazz = JavaXMLMapper.getJavaType(xmlType); + + Object propertyValue = null; + if (clazz == null || java.lang.Object.class.equals(clazz)) { + propertyValue = property.getValue(); + } else { + ObjectFactory objfactory = javaFactory.createValueFactory(property, property.getValue(), clazz); + propertyValue = objfactory.getInstance(); + } + properties.put(propName, propertyValue); + } + } + + private void setDataBinding(Interface interfaze, boolean isReference) { + List operations = interfaze.getOperations(); + for (Operation operation : operations) { + operation.setDataBinding(SaxonNodeDataBinding.NAME); + DataType> inputType = operation.getInputType(); + if (inputType != null) { + List logical = inputType.getLogical(); + for (DataType inArg : logical) { + if (SimpleJavaDataBinding.NAME.equals(inArg.getDataBinding())) { + if (!isReference) { + inArg.setDataBinding(SaxonValueDataBinding.NAME); + } + } else { + inArg.setDataBinding(SaxonNodeDataBinding.NAME); + } + } + } + DataType outputType = operation.getOutputType(); + if (outputType != null) { + if (SimpleJavaDataBinding.NAME.equals(outputType.getDataBinding())) { + if (!isReference) { + outputType.setDataBinding(SaxonValueDataBinding.NAME); + } + } else { + outputType.setDataBinding(SaxonNodeDataBinding.NAME); + } + } + } + } + + public void stop() { + // TODO Auto-generated method stub + + } + +} diff --git a/java/sca/contrib/modules/implementation-xquery/src/main/java/org/apache/tuscany/sca/implementation/xquery/XQueryImplementationProviderFactory.java b/java/sca/contrib/modules/implementation-xquery/src/main/java/org/apache/tuscany/sca/implementation/xquery/XQueryImplementationProviderFactory.java new file mode 100644 index 0000000000..57536e502b --- /dev/null +++ b/java/sca/contrib/modules/implementation-xquery/src/main/java/org/apache/tuscany/sca/implementation/xquery/XQueryImplementationProviderFactory.java @@ -0,0 +1,54 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.implementation.xquery; + +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.databinding.DataBindingExtensionPoint; +import org.apache.tuscany.sca.databinding.TransformerExtensionPoint; +import org.apache.tuscany.sca.databinding.impl.MediatorImpl; +import org.apache.tuscany.sca.implementation.java.injection.JavaPropertyValueObjectFactory; +import org.apache.tuscany.sca.provider.ImplementationProvider; +import org.apache.tuscany.sca.provider.ImplementationProviderFactory; +import org.apache.tuscany.sca.runtime.RuntimeComponent; + +/** + * A factory for XQuery implementation providers + * @version $Rev$ $Date$ + */ +public class XQueryImplementationProviderFactory implements ImplementationProviderFactory { + + private JavaPropertyValueObjectFactory javaFactory; + + public XQueryImplementationProviderFactory(ExtensionPointRegistry registry) { + DataBindingExtensionPoint dataBindings = registry.getExtensionPoint(DataBindingExtensionPoint.class); + TransformerExtensionPoint transformers = registry.getExtensionPoint(TransformerExtensionPoint.class); + MediatorImpl mediator = new MediatorImpl(dataBindings, transformers); + this.javaFactory = new JavaPropertyValueObjectFactory(mediator); + } + + public ImplementationProvider createImplementationProvider(RuntimeComponent component, + XQueryImplementation implementation) { + return new XQueryImplementationProvider(component, implementation, javaFactory); + } + + public Class getModelType() { + return XQueryImplementation.class; + } + +} diff --git a/java/sca/contrib/modules/implementation-xquery/src/main/java/org/apache/tuscany/sca/implementation/xquery/XQueryInvokationException.java b/java/sca/contrib/modules/implementation-xquery/src/main/java/org/apache/tuscany/sca/implementation/xquery/XQueryInvokationException.java new file mode 100644 index 0000000000..0c628b3715 --- /dev/null +++ b/java/sca/contrib/modules/implementation-xquery/src/main/java/org/apache/tuscany/sca/implementation/xquery/XQueryInvokationException.java @@ -0,0 +1,33 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.implementation.xquery; + +/** + * Exception class used by the XQueryInvoker to report problems in + * XQuery script invocation + * @version $Rev$ $Date$ + */ +public class XQueryInvokationException extends Exception { + + private static final long serialVersionUID = -2674411654705699541L; + + public XQueryInvokationException(String msg) { + super(msg); + } +} diff --git a/java/sca/contrib/modules/implementation-xquery/src/main/java/org/apache/tuscany/sca/implementation/xquery/XQueryInvoker.java b/java/sca/contrib/modules/implementation-xquery/src/main/java/org/apache/tuscany/sca/implementation/xquery/XQueryInvoker.java new file mode 100644 index 0000000000..2a9673068b --- /dev/null +++ b/java/sca/contrib/modules/implementation-xquery/src/main/java/org/apache/tuscany/sca/implementation/xquery/XQueryInvoker.java @@ -0,0 +1,318 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.implementation.xquery; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.lang.reflect.Method; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +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 javax.xml.transform.stream.StreamSource; + +import net.sf.saxon.Configuration; +import net.sf.saxon.event.Builder; +import net.sf.saxon.om.DocumentInfo; +import net.sf.saxon.om.Item; +import net.sf.saxon.om.NodeInfo; +import net.sf.saxon.om.SequenceIterator; +import net.sf.saxon.query.DynamicQueryContext; +import net.sf.saxon.query.QueryResult; +import net.sf.saxon.query.StaticQueryContext; +import net.sf.saxon.query.XQueryExpression; +import net.sf.saxon.trans.XPathException; +import net.sf.saxon.value.Value; + +import org.apache.tuscany.sca.databinding.saxon.SaxonDataBindingHelper; +import org.apache.tuscany.sca.databinding.saxon.collection.ItemList; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.interfacedef.java.JavaInterface; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +/** + * Performs the invocation of a requested XQuery function + * @version $Rev$ $Date$ + */ +public class XQueryInvoker implements Invoker { + + private RuntimeComponentService service; + private Operation operation; + private Method theMethod; + private XQueryImplementation implementation; + private Map referenceProxies; + private Map properties; + + /** + * Constructs a new instance of the xquery invoker. + * Also performs a search of java.lang.Method instance + * that corresponds to the invoked operation + */ + public XQueryInvoker(RuntimeComponentService service, + Operation operation, + XQueryImplementation implementation, + Map referenceProxies, + Map properties) { + this.service = service; + this.operation = operation; + this.implementation = implementation; + this.referenceProxies = referenceProxies; + this.properties = properties; + + findMatchingMethod(); + } + + /** + * This method contains the XQuery invocation logic + * The following steps are performed: + * 1. XQuery expression is produced by combining the original expression + * and the function invocation extension (See XQueryImplementation.getXqExpressionExtensionsMap() + * for details) + * 2. A check is performed if this expression has been invoked already. If yes - + * it is taken from the cache + * 3. Configuration for the execution is either created or retrieved from + * the cached expression + * 4. The input parameters of the operation to be invoked are taken from the + * payload and transformed to ones that are built with the current + * configuration. + * NOTE: This is unnecessary overhead - can the Configuration + * object be attached in some way to the invocation request? + * 5. All parameters, reference proxies and property values are mapped + * to external variables of the XQuery script + * 6. The query is executed and all the results are stored in a ItemList object + * + * NOTE: During execution of the XQuery a static variable is set with + * the current configuration. This variable is used by the NodeInfo transformers + * to produce the correct NodeInfo for all Output2Output transformations, which + * happen as result of the XQuery component invoking some reference components + * The old state of the static configuration is preserved and in this way allowing + * to nest XQuery component invocations (i.e. one XQuery component invokes another + * one) + */ + private Object doInvoke(Object payload) throws XQueryInvokationException, XPathException { + if (theMethod == null) { + throw new XQueryInvokationException("No java method for operation: " + operation.getName()); + } + String xqExpression = + implementation.getXqExpression() + implementation.getXqExpressionExtensionsMap().get(theMethod); + + Configuration config = null; + Properties props = new Properties(); + props.setProperty(OutputKeys.METHOD, "xml"); + props.setProperty(OutputKeys.INDENT, "yes"); + + XQueryExpression exp = implementation.getCompiledExpressionsCache().get(xqExpression); + if (exp == null) { + config = new Configuration(); + StaticQueryContext sqc = new StaticQueryContext(config); + exp = sqc.compileQuery(xqExpression); + implementation.getCompiledExpressionsCache().put(xqExpression, exp); + } else { + config = exp.getStaticContext().getConfiguration(); + } + + Object[] params = prepareParameters(payload, config, props); + + DynamicQueryContext dynamicContext = new DynamicQueryContext(config); + + // Setting the parameters for function invocation + String methodName = theMethod.getName(); + for (int i = 0; i < params.length; i++) { + dynamicContext.setParameter(methodName + "_" + i, params[i]); + } + + // Setting references + for (Map.Entry entry : referenceProxies.entrySet()) { + dynamicContext.setParameter(entry.getKey(), entry.getValue()); + } + + // Setting properties + for (Map.Entry entry : properties.entrySet()) { + dynamicContext.setParameter(entry.getKey(), transformProperty(entry.getValue(), config)); + } + + SequenceIterator iterator = null; + Configuration oldConfigValue = SaxonDataBindingHelper.CURR_EXECUTING_CONFIG; + SaxonDataBindingHelper.CURR_EXECUTING_CONFIG = config; + try { + iterator = exp.iterator(dynamicContext); + } finally { + SaxonDataBindingHelper.CURR_EXECUTING_CONFIG = oldConfigValue; + } + + ItemList list = new ItemList(); + Item item = iterator.next(); + + while (item != null) { + list.add(item); + item = iterator.next(); + + } + + if (list.size() == 0) { + return null; + + } else if (list.size() == 1) { + + item = list.iterator().next(); + + if (item instanceof NodeInfo) { + return item; + } else { + return Value.asValue(item); + } + + } + + return list; + + } + + public Message invoke(Message msg) { + try { + Object resp = doInvoke(msg.getBody()); + msg.setBody(resp); + } catch (XQueryInvokationException e) { + msg.setFaultBody(e.getCause()); + } catch (XPathException e) { + msg.setFaultBody(e.getCause()); + } + return msg; + } + + private void findMatchingMethod() { + Class interfaze = ((JavaInterface)service.getInterfaceContract().getInterface()).getJavaClass(); + + for (Method method : interfaze.getMethods()) { + if (match(operation, method)) { + theMethod = method; + } + } + } + + private static boolean match(Operation operation, Method method) { + Class[] params = method.getParameterTypes(); + DataType> inputType = operation.getInputType(); + List types = inputType.getLogical(); + boolean matched = true; + if (types.size() == params.length && method.getName().equals(operation.getName())) { + for (int i = 0; i < params.length; i++) { + Class clazz = params[i]; + if (!clazz.equals(operation.getInputType().getLogical().get(i).getPhysical())) { + matched = false; + } + } + } else { + matched = false; + } + return matched; + + } + + private Object[] prepareParameters(Object payload, Configuration configuration, Properties props) { + if (payload == null) { + return new Object[0]; + } + Object[] inputArguments = null; + if (payload.getClass().isArray()) { + inputArguments = (Object[])payload; + } else { + inputArguments = new Object[1]; + inputArguments[0] = payload; + } + + Object[] parameters = new Object[inputArguments.length]; + + for (int i = 0; i < inputArguments.length; i++) { + if (inputArguments[i] instanceof NodeInfo) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + StreamResult sw = new StreamResult(baos); + try { + QueryResult.serialize((NodeInfo)inputArguments[i], sw, props, ((NodeInfo)inputArguments[i]).getConfiguration()); + baos.close(); + ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); + StreamSource ss = new StreamSource(bais); + parameters[i] = Builder.build(ss, null, configuration); + } catch (Exception e) { + e.printStackTrace(); + parameters[i] = null; + } + } else { + parameters[i] = inputArguments[i]; + } + } + + return parameters; + } + + private Object transformProperty(Object argument, Configuration configuration) { + Object parameter = argument; + if (argument instanceof Document) { + try { + Document doc = (Document)argument; + Node valueNode = doc.getFirstChild(); + DocumentInfo docInfo = null; + if (valueNode instanceof Element && valueNode.getNodeName().equals("value")) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + StreamResult sr = new StreamResult(baos); + try { + Node element = null; + NodeList list = valueNode.getChildNodes(); + for (int i = 0; i < list.getLength(); i++) { + if (list.item(i).getNodeType() == Node.ELEMENT_NODE) { + element = list.item(i); + break; + } + } + if (element == null) { + element = valueNode.getFirstChild(); + } + Transformer transformer = TransformerFactory.newInstance().newTransformer(); + transformer.transform(new DOMSource(element), sr); + ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); + docInfo = (DocumentInfo)Builder.build(new StreamSource(bais), null, configuration); + } catch (Exception e) { + e.printStackTrace(); + return parameter; + } + } else { + docInfo = (DocumentInfo)Builder.build(new DOMSource(doc), null, configuration); + } + parameter = docInfo; + } catch (XPathException e) { + e.printStackTrace(); + return parameter; + } + } + + return parameter; + } +} diff --git a/java/sca/contrib/modules/implementation-xquery/src/main/java/org/apache/tuscany/sca/implementation/xquery/impl/XQueryImplementationFactoryImpl.java b/java/sca/contrib/modules/implementation-xquery/src/main/java/org/apache/tuscany/sca/implementation/xquery/impl/XQueryImplementationFactoryImpl.java new file mode 100644 index 0000000000..5e77575c3c --- /dev/null +++ b/java/sca/contrib/modules/implementation-xquery/src/main/java/org/apache/tuscany/sca/implementation/xquery/impl/XQueryImplementationFactoryImpl.java @@ -0,0 +1,35 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.implementation.xquery.impl; + +import org.apache.tuscany.sca.implementation.xquery.XQueryImplementation; +import org.apache.tuscany.sca.implementation.xquery.XQueryImplementationFactory; + +/** + * Actual implementation of the XQuery implementation factory + * @version $Rev$ $Date$ + */ +public class XQueryImplementationFactoryImpl implements XQueryImplementationFactory { + + public XQueryImplementation createXQueryImplementation() { + XQueryImplementation implementation = new XQueryImplementationImpl(); + return implementation; + } + +} diff --git a/java/sca/contrib/modules/implementation-xquery/src/main/java/org/apache/tuscany/sca/implementation/xquery/impl/XQueryImplementationImpl.java b/java/sca/contrib/modules/implementation-xquery/src/main/java/org/apache/tuscany/sca/implementation/xquery/impl/XQueryImplementationImpl.java new file mode 100644 index 0000000000..77c8eea511 --- /dev/null +++ b/java/sca/contrib/modules/implementation-xquery/src/main/java/org/apache/tuscany/sca/implementation/xquery/impl/XQueryImplementationImpl.java @@ -0,0 +1,102 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.implementation.xquery.impl; + +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; + +import net.sf.saxon.query.XQueryExpression; + +import org.apache.tuscany.sca.assembly.impl.ImplementationImpl; +import org.apache.tuscany.sca.implementation.xquery.XQueryImplementation; + +/** + * Actual implementation of the XQuery implementation + * @version $Rev$ $Date$ + */ +public class XQueryImplementationImpl extends ImplementationImpl implements XQueryImplementation { + + private String location; + private String locationURL; + private String xqExpression; + + private Map compiledExpressionsCache = new HashMap(); + private Map xqExpressionExtensionsMap = new HashMap(); + + public XQueryImplementationImpl() { + setUnresolved(true); + } + + public String getLocation() { + return location; + } + + public void setLocation(String location) { + this.location = location; + } + + public String getLocationURL() { + return locationURL; + } + + public void setLocationURL(String locationURL) { + this.locationURL = locationURL; + } + + public String getXqExpression() { + return xqExpression; + } + + public void setXqExpression(String xqExpression) { + this.xqExpression = xqExpression; + } + + public Map getCompiledExpressionsCache() { + return compiledExpressionsCache; + } + + public Map getXqExpressionExtensionsMap() { + return xqExpressionExtensionsMap; + } + + @Override + public int hashCode() { + final int PRIME = 31; + int result = super.hashCode(); + result = PRIME * result + ((location == null) ? 0 : location.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null || getClass() != obj.getClass()) + return false; + final XQueryImplementationImpl other = (XQueryImplementationImpl)obj; + if (location == null) { + if (other.location != null) + return false; + } else if (!location.equals(other.location)) + return false; + return true; + } + +} diff --git a/java/sca/contrib/modules/implementation-xquery/src/main/java/org/apache/tuscany/sca/implementation/xquery/xml/XQueryImplementationProcessor.java b/java/sca/contrib/modules/implementation-xquery/src/main/java/org/apache/tuscany/sca/implementation/xquery/xml/XQueryImplementationProcessor.java new file mode 100644 index 0000000000..c8d19bf149 --- /dev/null +++ b/java/sca/contrib/modules/implementation-xquery/src/main/java/org/apache/tuscany/sca/implementation/xquery/xml/XQueryImplementationProcessor.java @@ -0,0 +1,157 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.implementation.xquery.xml; + +import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; + +import org.apache.tuscany.sca.assembly.AssemblyFactory; +import org.apache.tuscany.sca.contribution.Artifact; +import org.apache.tuscany.sca.contribution.ContributionFactory; +import org.apache.tuscany.sca.contribution.processor.ContributionReadException; +import org.apache.tuscany.sca.contribution.processor.ContributionResolveException; +import org.apache.tuscany.sca.contribution.processor.ContributionWriteException; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.core.FactoryExtensionPoint; +import org.apache.tuscany.sca.implementation.xquery.XQueryImplementation; +import org.apache.tuscany.sca.implementation.xquery.XQueryImplementationFactory; +import org.apache.tuscany.sca.interfacedef.java.JavaInterfaceFactory; +import org.apache.tuscany.sca.monitor.Monitor; +import org.apache.tuscany.sca.monitor.Problem; +import org.apache.tuscany.sca.monitor.Problem.Severity; + +/** + * Processor for the XQuery implementation type artifact + * @version $Rev$ $Date$ + */ +public class XQueryImplementationProcessor implements StAXArtifactProcessor { + private static final String SCA10_TUSCANY_NS = "http://tuscany.apache.org/xmlns/sca/1.0"; + private static final String LOCATION = "location"; + private static final String IMPLEMENTATION_XQUERY = "implementation.xquery"; + private static final QName IMPLEMENTATION_XQUERY_QNAME = + new QName(SCA10_TUSCANY_NS, IMPLEMENTATION_XQUERY); + + private AssemblyFactory assemblyFactory; + private JavaInterfaceFactory javaFactory; + private ContributionFactory contributionFactory; + private Monitor monitor; + + public XQueryImplementationProcessor(FactoryExtensionPoint modelFactoryExtensionPoint, Monitor monitor) { + assemblyFactory = modelFactoryExtensionPoint.getFactory(AssemblyFactory.class); + javaFactory = modelFactoryExtensionPoint.getFactory(JavaInterfaceFactory.class); + contributionFactory = modelFactoryExtensionPoint.getFactory(ContributionFactory.class); + this.monitor = monitor; + } + + /** + * Report a error. + * + * @param problems + * @param message + * @param model + */ + private void error(String message, Object model, Object... messageParameters) { + if (monitor != null) { + Problem problem = monitor.createProblem(this.getClass().getName(), "impl-xquery-validation-messages", Severity.ERROR, model, message, (Object[])messageParameters); + monitor.problem(problem); + } + } + + public QName getArtifactType() { + return IMPLEMENTATION_XQUERY_QNAME; + } + + /** + * Reads from the stream and sets the location attribute of the implementation correspondingly + */ + public XQueryImplementation read(XMLStreamReader reader) + throws ContributionReadException, XMLStreamException { + + /* Create the XQuery implementation and set the location into it */ + XQueryImplementation xqueryImplementation = null; + + /* Read the location attribute for the XQuery implementation */ + String xqueryLocation = reader.getAttributeValue(null, LOCATION); + if (xqueryLocation != null) { + xqueryImplementation = XQueryImplementationFactory.INSTANCE.createXQueryImplementation(); + xqueryImplementation.setLocation(xqueryLocation); + xqueryImplementation.setUnresolved(true); + } else { + error("LocationAttributeMissing", reader); + //throw new ContributionReadException(MSG_LOCATION_MISSING); + } + + // Skip to end element + while (reader.hasNext()) { + if (reader.next() == END_ELEMENT && IMPLEMENTATION_XQUERY_QNAME.equals(reader.getName())) { + break; + } + } // end while + + return xqueryImplementation; + } + + public void write(XQueryImplementation xqueryImplementation, XMLStreamWriter writer) + throws ContributionWriteException, XMLStreamException { + + writer.writeStartElement(SCA10_TUSCANY_NS, IMPLEMENTATION_XQUERY); + if (xqueryImplementation.getLocation() != null) { + writer.writeAttribute(LOCATION, xqueryImplementation.getLocation()); + } + writer.writeEndElement(); + + } + + public Class getModelType() { + return XQueryImplementation.class; + } + + /** + * Resolves the implementation: its services and references, by invoking the XQuery + * introspector + */ + public void resolve(XQueryImplementation xqueryImplementation, ModelResolver resolver) + throws ContributionResolveException { + + if (xqueryImplementation != null) { + Artifact artifact = contributionFactory.createArtifact(); + artifact.setURI(xqueryImplementation.getLocation()); + artifact = resolver.resolveModel(Artifact.class, artifact); + if (artifact.getLocation() != null) { + xqueryImplementation.setLocationURL(artifact.getLocation()); + + XQueryIntrospector introspector = new XQueryIntrospector(assemblyFactory, javaFactory); + + boolean success = introspector.introspect(xqueryImplementation, resolver); + if (success) { + xqueryImplementation.setUnresolved(false); + } + } else { + error("CouldNotLocateFile", resolver, xqueryImplementation.getLocation()); + //throw new ContributionResolveException("Could not locate file: " + xqueryImplementation.getLocation()); + } + } + } + +} diff --git a/java/sca/contrib/modules/implementation-xquery/src/main/java/org/apache/tuscany/sca/implementation/xquery/xml/XQueryIntrospector.java b/java/sca/contrib/modules/implementation-xquery/src/main/java/org/apache/tuscany/sca/implementation/xquery/xml/XQueryIntrospector.java new file mode 100644 index 0000000000..59ac68aa7d --- /dev/null +++ b/java/sca/contrib/modules/implementation-xquery/src/main/java/org/apache/tuscany/sca/implementation/xquery/xml/XQueryIntrospector.java @@ -0,0 +1,328 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.implementation.xquery.xml; + +import java.io.ByteArrayOutputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Method; +import java.net.URL; +import java.util.Iterator; + +import javax.xml.namespace.QName; + +import net.sf.saxon.Configuration; +import net.sf.saxon.om.NamespaceResolver; +import net.sf.saxon.query.StaticQueryContext; +import net.sf.saxon.query.XQueryExpression; +import net.sf.saxon.trans.XPathException; + +import org.apache.tuscany.sca.assembly.AssemblyFactory; +import org.apache.tuscany.sca.assembly.Multiplicity; +import org.apache.tuscany.sca.assembly.Property; +import org.apache.tuscany.sca.assembly.Reference; +import org.apache.tuscany.sca.assembly.Service; +import org.apache.tuscany.sca.contribution.processor.ContributionResolveException; +import org.apache.tuscany.sca.contribution.resolver.ClassReference; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.implementation.xquery.XQueryImplementation; +import org.apache.tuscany.sca.interfacedef.InvalidInterfaceException; +import org.apache.tuscany.sca.interfacedef.java.JavaInterface; +import org.apache.tuscany.sca.interfacedef.java.JavaInterfaceContract; +import org.apache.tuscany.sca.interfacedef.java.JavaInterfaceFactory; +import org.apache.tuscany.sca.interfacedef.util.JavaXMLMapper; + +/** + * This class introspects an XQuery file and extracts out of it + * all implemented service, references and properties + * It also creates expression extensions for each operation + * in the implemented services + * @version $Rev$ $Date$ + */ +public class XQueryIntrospector { + + private static final String SCA_SERVICE_PREFIX = "scaservice:java/"; + private static final String SCA_REFERENCE_PREFIX = "scareference:java/"; + private static final String SCA_PROPERTY_JAVA_PREFIX = "scaproperty:java/"; + private static final String SCA_PROPERTY_XML_PREFIX = "scaproperty:xml/"; + + private AssemblyFactory assemblyFactory; + private JavaInterfaceFactory javaFactory; + + public XQueryIntrospector(AssemblyFactory assemblyFactory, JavaInterfaceFactory javaFactory) { + super(); + this.assemblyFactory = assemblyFactory; + this.javaFactory = javaFactory; + } + + public boolean introspect(XQueryImplementation xqueryImplementation, ModelResolver resolver) throws ContributionResolveException { + + String xqExpression = null; + try { + URL url = new URL(xqueryImplementation.getLocationURL()); + xqExpression = loadXQExpression(url); + } catch (FileNotFoundException e) { + throw new ContributionResolveException(e); + } catch (IOException e) { + throw new ContributionResolveException(e); + } + + if (xqExpression == null) { + return false; + } + + xqueryImplementation.setXqExpression(xqExpression); + + xqExpression += "\r\n"; + + Configuration config = new Configuration(); + StaticQueryContext sqc = new StaticQueryContext(config); + XQueryExpression exp = null; + try { + exp = sqc.compileQuery(xqExpression); + } catch (XPathException e) { + throw new ContributionResolveException(e); + } + + if (exp == null) { + return false; + } + xqueryImplementation.getCompiledExpressionsCache().put(xqExpression, exp); + + try { + introspectServicesAndReferences(xqueryImplementation, exp, resolver); + } catch (ClassNotFoundException e) { + throw new ContributionResolveException(e); + } catch (InvalidInterfaceException e) { + throw new ContributionResolveException(e); + } + + fillExpressionExtensions(xqueryImplementation); + + return true; + } + + /** + * Loads the XQuery expression from the location that is provided with the implementation + */ + private String loadXQExpression(URL locationURL) throws FileNotFoundException, IOException { + + InputStream xqResourceStream = locationURL.openStream(); + + if (xqResourceStream == null) { + return null; + } + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + int i = 0; + while ((i = xqResourceStream.read()) >= 0) { + baos.write(i); + } + xqResourceStream.close(); + baos.flush(); + baos.close(); + + String xqExpression = baos.toString(); + + return xqExpression; + } + + private Class resolveClass(ModelResolver resolver, String className) throws ClassNotFoundException { + ClassReference classReference = new ClassReference(className); + classReference = resolver.resolveModel(ClassReference.class, classReference); + Class javaClass = classReference.getJavaClass(); + if (javaClass == null) { + throw new ClassNotFoundException(className); + } else { + return javaClass; + } + } + + /** + * From the compiled XQuery expression get all namespaces and see if they + * are services, references or properties declarations + */ + private void introspectServicesAndReferences(XQueryImplementation xqueryImplementation, XQueryExpression exp, ModelResolver resolver) + throws ClassNotFoundException, InvalidInterfaceException { + NamespaceResolver namespaceResolver = exp.getStaticContext().getNamespaceResolver(); + Iterator declaredPrefixesIterator = namespaceResolver.iteratePrefixes(); + while (declaredPrefixesIterator.hasNext()) { + String prefix = (String)declaredPrefixesIterator.next(); + String uri = namespaceResolver.getURIForPrefix(prefix, false); + if (uri.startsWith(SCA_SERVICE_PREFIX)) { + String serviceName = prefix; + String className = uri.substring(SCA_SERVICE_PREFIX.length()); + Class interfaze = resolveClass(resolver, className); + Service theService = createService(interfaze, serviceName); + xqueryImplementation.getServices().add(theService); + } else if (uri.startsWith(SCA_REFERENCE_PREFIX)) { + String referenceName = prefix; + String className = uri.substring(SCA_REFERENCE_PREFIX.length()); + Class interfaze = resolveClass(resolver, className); + Reference theReference = createReference(interfaze, referenceName); + xqueryImplementation.getReferences().add(theReference); + } else if (uri.startsWith(SCA_PROPERTY_JAVA_PREFIX)) { + String propertyName = prefix; + String className = uri.substring(SCA_PROPERTY_JAVA_PREFIX.length()); + Class clazz = resolveClass(resolver, className); + QName xmlType = JavaXMLMapper.getXMLType(clazz); + Property theProperty = createProperty(xmlType, propertyName); + xqueryImplementation.getProperties().add(theProperty); + } else if (uri.startsWith(SCA_PROPERTY_XML_PREFIX)) { + String propertyName = prefix; + String namespaceAndLocalname = uri.substring(SCA_PROPERTY_XML_PREFIX.length()); + int localNameDelimiterPostition = namespaceAndLocalname.lastIndexOf(':'); + String localName = null; + String namespace = null; + if (localNameDelimiterPostition < 0) { + localName = namespaceAndLocalname; + namespace = ""; + } else { + namespace = namespaceAndLocalname.substring(0, localNameDelimiterPostition); + localName = namespaceAndLocalname.substring(localNameDelimiterPostition + 1); + } + QName xmlType = new QName(namespace, localName); + Property theProperty = createProperty(xmlType, propertyName); + xqueryImplementation.getProperties().add(theProperty); + } + } + } + + /** + * Creates a Service for the component type based on its name and Java interface + */ + private Service createService(Class interfaze, String name) throws InvalidInterfaceException { + Service service = assemblyFactory.createService(); + JavaInterfaceContract interfaceContract = javaFactory.createJavaInterfaceContract(); + service.setInterfaceContract(interfaceContract); + + // Set the name for the service + service.setName(name); + + // Set the call interface and, if present, the callback interface + JavaInterface callInterface = null; + try { + callInterface = (JavaInterface) javaFactory.createJavaInterface(interfaze).clone(); + } catch (CloneNotSupportedException e) { + // Ignore + } + //setDataBindingForInterface(callInterface, DataObject.class.getName()); + service.getInterfaceContract().setInterface(callInterface); + if (callInterface.getCallbackClass() != null) { + JavaInterface callbackInterface = null; + try { + callbackInterface = (JavaInterface) javaFactory.createJavaInterface(callInterface.getCallbackClass()).clone(); + } catch (CloneNotSupportedException e) { + //Ignore + } + //setDataBindingForInterface(callbackInterface, DataObject.class.getName()); + service.getInterfaceContract().setCallbackInterface(callbackInterface); + } + return service; + } // end method createService + + protected Property createProperty(QName type, String name) { + + Property property = assemblyFactory.createProperty(); + property.setName(name); + property.setXSDType(type); + + property.setMany(false); + return property; + + } + + /** + * Creates a Reference for the component type based on its name and Java interface + */ + private Reference createReference(Class interfaze, String name) throws InvalidInterfaceException { + Reference reference = assemblyFactory.createReference(); + JavaInterfaceContract interfaceContract = javaFactory.createJavaInterfaceContract(); + reference.setInterfaceContract(interfaceContract); + + // Set the name of the reference to the supplied name and the multiplicity of the reference + // to 1..1 - for XQuery implementations, this is the only multiplicity supported + reference.setName(name); + reference.setMultiplicity(Multiplicity.ONE_ONE); + + // Set the call interface and, if present, the callback interface + // Set the call interface and, if present, the callback interface + JavaInterface callInterface = null; + try { + callInterface = (JavaInterface) javaFactory.createJavaInterface(interfaze).clone(); + } catch (CloneNotSupportedException e) { + // Ignore + } + reference.getInterfaceContract().setInterface(callInterface); + if (callInterface.getCallbackClass() != null) { + JavaInterface callbackInterface = null; + try { + callbackInterface = (JavaInterface) javaFactory.createJavaInterface(callInterface.getCallbackClass()).clone(); + } catch (CloneNotSupportedException e) { + //Ignore + } + reference.getInterfaceContract().setCallbackInterface(callbackInterface); + } + + return reference; + } + + /** + * For the methods of each implemented service corresponding expression extension + * is generated + * @param xqueryImplementation + */ + private void fillExpressionExtensions(XQueryImplementation xqueryImplementation) { + for (Service service : xqueryImplementation.getServices()) { + Class interfaze = ((JavaInterface)service.getInterfaceContract().getInterface()).getJavaClass(); + + // For each of the methods + for (Method method : interfaze.getMethods()) { + String expressionExtension = createExpressionExtension(method, interfaze, service.getName()); + xqueryImplementation.getXqExpressionExtensionsMap().put(method, expressionExtension); + } + } + } + + private String createExpressionExtension(Method method, Class interfaze, String serviceName) { + StringBuffer exprBuf = new StringBuffer(); + + exprBuf.append("\r\n"); + + String methodName = method.getName(); + + // For each of the declared parameters + for (int i = 0; i < method.getParameterTypes().length; i++) { + exprBuf.append("declare variable $" + methodName + "_" + i + " external;\r\n"); + } + + exprBuf.append(serviceName + ":" + methodName + "("); + + for (int i = 0; i < method.getParameterTypes().length; i++) { + exprBuf.append("$" + methodName + "_" + i); + if (i != method.getParameterTypes().length - 1) { + exprBuf.append(", "); + } + } + exprBuf.append(")"); + + return exprBuf.toString(); + } +} diff --git a/java/sca/contrib/modules/implementation-xquery/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor b/java/sca/contrib/modules/implementation-xquery/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor new file mode 100644 index 0000000000..a51995e56d --- /dev/null +++ b/java/sca/contrib/modules/implementation-xquery/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for the artifact processor extension +org.apache.tuscany.sca.implementation.xquery.xml.XQueryImplementationProcessor;qname=http://tuscany.apache.org/xmlns/sca/1.0#implementation.xquery,model=org.apache.tuscany.sca.implementation.xquery.XQueryImplementation diff --git a/java/sca/contrib/modules/implementation-xquery/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.ImplementationProviderFactory b/java/sca/contrib/modules/implementation-xquery/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.ImplementationProviderFactory new file mode 100644 index 0000000000..7ccc08d1ee --- /dev/null +++ b/java/sca/contrib/modules/implementation-xquery/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.ImplementationProviderFactory @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for the implementation extension +org.apache.tuscany.sca.implementation.xquery.XQueryImplementationProviderFactory;model=org.apache.tuscany.sca.implementation.xquery.XQueryImplementation diff --git a/java/sca/contrib/modules/implementation-xquery/src/main/resources/impl-xquery-validation-messages.properties b/java/sca/contrib/modules/implementation-xquery/src/main/resources/impl-xquery-validation-messages.properties new file mode 100644 index 0000000000..33c605de27 --- /dev/null +++ b/java/sca/contrib/modules/implementation-xquery/src/main/resources/impl-xquery-validation-messages.properties @@ -0,0 +1,22 @@ +# +# +# 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. +# +# +CouldNotLocateFile = Could not locate file: {0} +LocationAttributeMissing = Reading implementation.xquery - location attribute missing \ No newline at end of file diff --git a/java/sca/contrib/modules/node-dynamic/LICENSE b/java/sca/contrib/modules/node-dynamic/LICENSE new file mode 100644 index 0000000000..6e529a25c4 --- /dev/null +++ b/java/sca/contrib/modules/node-dynamic/LICENSE @@ -0,0 +1,205 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + + diff --git a/java/sca/contrib/modules/node-dynamic/NOTICE b/java/sca/contrib/modules/node-dynamic/NOTICE new file mode 100644 index 0000000000..51042eab05 --- /dev/null +++ b/java/sca/contrib/modules/node-dynamic/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/node-dynamic/pom.xml b/java/sca/contrib/modules/node-dynamic/pom.xml new file mode 100644 index 0000000000..91fbc9e025 --- /dev/null +++ b/java/sca/contrib/modules/node-dynamic/pom.xml @@ -0,0 +1,87 @@ + + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 1.4-SNAPSHOT + ../pom.xml + + + tuscany-node-dynamic + Apache Tuscany SCA Dynamic Node + + + + + org.apache.tuscany.sca + tuscany-node-impl + 1.4-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-binding-sca-jms + 1.4-SNAPSHOT + runtime + + + + org.apache.tuscany.sca + tuscany-implementation-java-runtime + 1.4-SNAPSHOT + runtime + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + org.apache.tuscany.sca.node.DynamicNodeMain + + + + + + + org.apache.felix + maven-bundle-plugin + + + + ${tuscany.version} + org.apache.tuscany.sca.node.dynamic + ${pom.name} + org.apache.tuscany.sca.node* + + + + + + + diff --git a/java/sca/contrib/modules/node-dynamic/src/main/java/org/apache/tuscany/sca/node/DynamicNodeMain.java b/java/sca/contrib/modules/node-dynamic/src/main/java/org/apache/tuscany/sca/node/DynamicNodeMain.java new file mode 100644 index 0000000000..af6155e500 --- /dev/null +++ b/java/sca/contrib/modules/node-dynamic/src/main/java/org/apache/tuscany/sca/node/DynamicNodeMain.java @@ -0,0 +1,50 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.node; + +import java.io.File; + +public class DynamicNodeMain { + + /** + * Start an SCA node + * @param args a list of contribution jars for the node to run + */ + public static void main(String[] args) throws Exception { + + SCAContribution[] contributions = new SCAContribution[args.length]; + for (int i=0; i + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + + tuscany-node-launcher-webapp + war + Apache Tuscany SCA Node WebApp + + + + org.apache.tuscany.sca + tuscany-node-launcher + 2.0-SNAPSHOT + runtime + + + + + + + + maven-eclipse-plugin + 2.5.1 + + + org.eclipse.jdt.core.javabuilder + + + org.eclipse.jdt.core.javanature + + + org.eclipse.jdt.launching.JRE_CONTAINER + + + + + org.apache.tuscany.sca + tuscany-maven-bundle-plugin + 2.0-SNAPSHOT + + true + + + + + + diff --git a/java/sca/contrib/modules/node-launcher-webapp/src/main/webapp/META-INF/sca-contribution.xml b/java/sca/contrib/modules/node-launcher-webapp/src/main/webapp/META-INF/sca-contribution.xml new file mode 100644 index 0000000000..78bbebbb83 --- /dev/null +++ b/java/sca/contrib/modules/node-launcher-webapp/src/main/webapp/META-INF/sca-contribution.xml @@ -0,0 +1,21 @@ + + + + diff --git a/java/sca/contrib/modules/node-launcher-webapp/src/main/webapp/WEB-INF/web.xml b/java/sca/contrib/modules/node-launcher-webapp/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..6c2c943c99 --- /dev/null +++ b/java/sca/contrib/modules/node-launcher-webapp/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,41 @@ + + + + + + + Apache Tuscany SCA Node + + + tuscany + org.apache.tuscany.sca.node.launcher.NodeServletFilter + + + + tuscany + /* + + + + index.jsp + + + diff --git a/java/sca/contrib/modules/node-launcher-webapp/src/main/webapp/index.jsp b/java/sca/contrib/modules/node-launcher-webapp/src/main/webapp/index.jsp new file mode 100644 index 0000000000..3cc6c7b504 --- /dev/null +++ b/java/sca/contrib/modules/node-launcher-webapp/src/main/webapp/index.jsp @@ -0,0 +1,27 @@ +<%-- + * 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. +--%> + +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + +Apache Tuscany SCA Node + + +

      It works!

      + + diff --git a/java/sca/contrib/modules/node-manager/LICENSE b/java/sca/contrib/modules/node-manager/LICENSE new file mode 100644 index 0000000000..8aa906c321 --- /dev/null +++ b/java/sca/contrib/modules/node-manager/LICENSE @@ -0,0 +1,205 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + + diff --git a/java/sca/contrib/modules/node-manager/META-INF/MANIFEST.MF b/java/sca/contrib/modules/node-manager/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..55a65fb055 --- /dev/null +++ b/java/sca/contrib/modules/node-manager/META-INF/MANIFEST.MF @@ -0,0 +1,22 @@ +Manifest-Version: 1.0 +Export-Package: org.apache.tuscany.sca.implementation.node.manager;use + s:="javax.servlet,org.oasisopen.sca.annotation,org.apache.tuscany.sca.dat + a.collection,org.apache.tuscany.sca.node.launcher,javax.xml.parsers,o + rg.osoa.sca,javax.servlet.http";version="2.0.0" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA Node Manager Application +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397411859 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA Node Manager Application +Import-Package: javax.servlet,javax.servlet.http,javax.xml.parsers,org + .apache.tuscany.sca.data.collection;version="2.0.0",org.apache.tuscany. + sca.implementation.node.manager;version="2.0.0",org.apache.tuscany.sca. + node.launcher;version="2.0.0",org.oasisopen.sca;version="2.0.0",org.oasisopen.sca.a + nnotations;version="2.0.0" +Bundle-SymbolicName: org.apache.tuscany.sca.node.manager +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/node-manager/NOTICE b/java/sca/contrib/modules/node-manager/NOTICE new file mode 100644 index 0000000000..25bb89c9b2 --- /dev/null +++ b/java/sca/contrib/modules/node-manager/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/node-manager/pom.xml b/java/sca/contrib/modules/node-manager/pom.xml new file mode 100644 index 0000000000..fa01090467 --- /dev/null +++ b/java/sca/contrib/modules/node-manager/pom.xml @@ -0,0 +1,112 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + + tuscany-node-manager + Apache Tuscany SCA Node Manager Application + + + + org.apache.tuscany.sca + tuscany-implementation-node + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-core-spi + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-node-api + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-node-launcher + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-data-api + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-host-http + 2.0-SNAPSHOT + + + + javax.servlet + servlet-api + 2.5 + + + + org.apache.tuscany.sca + tuscany-node-impl + 2.0-SNAPSHOT + runtime + + + + org.apache.tuscany.sca + tuscany-host-jetty + 2.0-SNAPSHOT + runtime + + + + org.apache.tuscany.sca + tuscany-implementation-java-runtime + 2.0-SNAPSHOT + runtime + + + + org.apache.tuscany.sca + tuscany-binding-atom-abdera + 2.0-SNAPSHOT + runtime + + + + junit + junit + 4.5 + test + + + + + diff --git a/java/sca/contrib/modules/node-manager/src/main/java/org/apache/tuscany/sca/implementation/node/manager/NodeManagerUtil.java b/java/sca/contrib/modules/node-manager/src/main/java/org/apache/tuscany/sca/implementation/node/manager/NodeManagerUtil.java new file mode 100644 index 0000000000..8dfae91314 --- /dev/null +++ b/java/sca/contrib/modules/node-manager/src/main/java/org/apache/tuscany/sca/implementation/node/manager/NodeManagerUtil.java @@ -0,0 +1,51 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.implementation.node.manager; + +/** + * Utility methods for node implementation launchers. + * + * @version $Rev$ $Date$ + */ +public class NodeManagerUtil { + + private static final String TUSCANY_DOMAIN = "TUSCANY_DOMAIN"; + private static final String DEFAULT_DOMAIN = "http://localhost:9990"; + + /** + * Determine the URI of a node configuration. The domain URI can be configured + * using a TUSCANY_DOMAIN system property or environment variable. + * + * @param nodeName + * @return + */ + public static String nodeConfigurationURI(String nodeName) { + String domain = System.getProperty(TUSCANY_DOMAIN); + if (domain == null || domain.length() == 0) { + domain = System.getenv(TUSCANY_DOMAIN); + } + if (domain == null || domain.length() ==0) { + domain = DEFAULT_DOMAIN; + } + String nodeConfiguration = domain + "/node-config/" + nodeName; + return nodeConfiguration; + } + +} diff --git a/java/sca/contrib/modules/node-manager/src/main/java/org/apache/tuscany/sca/implementation/node/manager/NodeProcessCollectionImpl.java b/java/sca/contrib/modules/node-manager/src/main/java/org/apache/tuscany/sca/implementation/node/manager/NodeProcessCollectionImpl.java new file mode 100644 index 0000000000..340c6236fa --- /dev/null +++ b/java/sca/contrib/modules/node-manager/src/main/java/org/apache/tuscany/sca/implementation/node/manager/NodeProcessCollectionImpl.java @@ -0,0 +1,338 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.implementation.node.manager; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; +import java.util.logging.Logger; + +import org.apache.tuscany.sca.data.collection.Entry; +import org.apache.tuscany.sca.data.collection.Item; +import org.apache.tuscany.sca.data.collection.ItemCollection; +import org.apache.tuscany.sca.data.collection.LocalItemCollection; +import org.apache.tuscany.sca.data.collection.NotFoundException; +import org.apache.tuscany.sca.node.launcher.NodeLauncher; +import org.oasisopen.sca.ServiceRuntimeException; +import org.oasisopen.sca.annotation.Init; +import org.oasisopen.sca.annotation.Scope; +import org.oasisopen.sca.annotation.Service; + +/** + * Implementation of a node process collection service. + * + * @version $Rev$ $Date$ + */ +@Scope("COMPOSITE") +@Service(interfaces={ItemCollection.class, LocalItemCollection.class}) +public class NodeProcessCollectionImpl implements ItemCollection, LocalItemCollection { + + private static final Logger logger = Logger.getLogger(NodeProcessCollectionImpl.class.getName()); + + private List nodeVMs = new ArrayList(); + + /** + * Initialize the component. + */ + @Init + public void initialize() { + } + + public Entry[] getAll() { + logger.fine("getAll"); + + // Return all the running VMs + List> entries = new ArrayList>(); + for (SCANodeVM vm: nodeVMs) { + entries.add(entry(vm)); + } + return entries.toArray(new Entry[entries.size()]); + } + + public Item get(String key) throws NotFoundException { + logger.fine("get " + key); + + // Return the specified VM + SCANodeVM vm = vm(key); + if (vm == null) { + throw new NotFoundException(); + } + + return item(vm); + } + + public String post(String key, Item item) { + logger.fine("post " + key); + + // If the VM is already running just return it + SCANodeVM vm = vm(key); + if (vm != null) { + if (vm.isAlive()) { + return key; + } else { + // Remove dead VM entry + try { + vm.stop(); + } catch (InterruptedException e) { + throw new ServiceRuntimeException(e); + } + nodeVMs.remove(vm); + } + } + + // Start a new VM and add it to the collection + vm = new SCANodeVM(key); + nodeVMs.add(0, vm); + try { + vm.start(); + } catch (IOException e) { + throw new ServiceRuntimeException(e); + } + + return key; + } + + public void put(String key, Item item) throws NotFoundException { + throw new UnsupportedOperationException(); + } + + public void delete(String key) throws NotFoundException { + logger.fine("delete " + key); + + // Stop a VM and remove it from the collection + SCANodeVM vm = vm(key); + if (vm != null) { + try { + vm.stop(); + } catch (InterruptedException e) { + throw new ServiceRuntimeException(e); + } + nodeVMs.remove(vm); + } else { + //throw new NotFoundException(); + } + } + + public Entry[] query(String queryString) { + logger.fine("query " + queryString); + + if (queryString.startsWith("node=")) { + + // Return the log for the specified VM + String key = queryString.substring(queryString.indexOf('=') + 1); + List> entries = new ArrayList>(); + for (SCANodeVM vm: nodeVMs) { + if (vm.getNodeName().equals(key)) { + entries.add(entry(vm)); + } + } + return entries.toArray(new Entry[entries.size()]); + + } else { + throw new UnsupportedOperationException(); + } + } + + /** + * Returns the specified VM. + * + * @param key + * @return + */ + private SCANodeVM vm(String key) { + for (SCANodeVM vm: nodeVMs) { + if (key.equals(vm.getNodeName())) { + return vm; + } + } + return null; + } + + /** + * Returns an entry representing a VM. + * + * @param vm + * @return + */ + private static Entry entry(SCANodeVM vm) { + Entry entry = new Entry(); + entry.setKey(vm.getNodeName()); + entry.setData(item(vm)); + return entry; + } + + /** + * Returns an item representing a VM. + * + * @param vm + * @return + */ + private static Item item(SCANodeVM vm) { + Item item = new Item(); + String key = vm.getNodeName(); + item.setTitle(title(key)); + item.setLink("/node-config/" + vm.getNodeName()); + item.setContents("" + vm.getLog().toString() + ""); + return item; + } + + /** + * Represent a child Java VM running an SCA node. + */ + private static class SCANodeVM { + private String nodeName; + private StringBuffer log; + private Process process; + private Thread monitor; + private int status; + + SCANodeVM(String nodeName) { + log = new StringBuffer(); + this.nodeName =nodeName; + } + + /** + * Starts a node in a new VM. + */ + private void start() throws IOException { + + // Determine the node configuration URI + String nodeConfigurationURI = NodeManagerUtil.nodeConfigurationURI(nodeName); + + // Build the Java VM command line + Properties props = System.getProperties(); + String java = props.getProperty("java.home") + "/bin/java"; + String cp = props.getProperty("java.class.path"); + String main = NodeLauncher.class.getName(); + final List command = new ArrayList(); + command.add(java); + command.add("-cp"); + command.add(cp); + + // Propagate TUSCANY properties + String tuscanyHome = props.getProperty("TUSCANY_HOME"); + if (tuscanyHome != null) { + command.add("-DTUSCANY_HOME=" + tuscanyHome); + } + String tuscanyPath = props.getProperty("TUSCANY_PATH"); + if (tuscanyPath != null) { + command.add("-DTUSCANY_PATH=" + tuscanyPath); + } + + // Specify the main class and parameters + command.add(main); + command.add(nodeConfigurationURI); + + logger.info("Starting " + "java " + main + " " + nodeConfigurationURI); + + // Start the VM + ProcessBuilder builder = new ProcessBuilder(command); + builder.redirectErrorStream(true); + process = builder.start(); + + logger.info("Started " + process); + + // Start a thread to monitor the process + final BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); + monitor = new Thread(new Runnable() { + public void run() { + try { + for (;;) { + String s = reader.readLine(); + if (s != null) { + logger.info(s); + log.append(s + "
      "); + } else { + break; + } + } + status = process.waitFor(); + } catch (IOException e) { + } catch (Exception e) { + throw new RuntimeException(e); + } + } + }); + monitor.start(); + } + + /** + * Returns the composite used to start this VM. + * @return + */ + String getNodeName() { + return nodeName; + } + + /** + * Returns the log for this VM. + * + * @return + */ + StringBuffer getLog() { + return log; + } + + /** + * Returns true if the VM is alive + * + * @return + */ + private boolean isAlive() { + return monitor.isAlive(); + } + + /** + * Returns the VM status code. + * @return + */ + int getStatus() { + return status; + } + + /** + * Stops the VM. + * + * @throws InterruptedException + */ + private void stop() throws InterruptedException { + logger.info("Stopping " + process); + + process.destroy(); + monitor.join(); + + logger.info("Stopped " + process); + } + } + + /** + * Returns a node title. + * + * @param key + * @return + */ + private static String title(String key) { + return key; + } + +} diff --git a/java/sca/contrib/modules/node-manager/src/main/java/org/apache/tuscany/sca/implementation/node/manager/PingServiceImpl.java b/java/sca/contrib/modules/node-manager/src/main/java/org/apache/tuscany/sca/implementation/node/manager/PingServiceImpl.java new file mode 100644 index 0000000000..d23674ed4a --- /dev/null +++ b/java/sca/contrib/modules/node-manager/src/main/java/org/apache/tuscany/sca/implementation/node/manager/PingServiceImpl.java @@ -0,0 +1,61 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.implementation.node.manager; + +import java.io.IOException; +import java.util.logging.Logger; + +import javax.servlet.Servlet; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.xml.parsers.ParserConfigurationException; + +import org.oasisopen.sca.annotation.Init; +import org.oasisopen.sca.annotation.Scope; +import org.oasisopen.sca.annotation.Service; + +/** + * Implementation of a ping service component. + * + * @version $Rev$ $Date$ + */ +@Scope("COMPOSITE") +@Service(interfaces={Servlet.class}) +public class PingServiceImpl extends HttpServlet { + private static final long serialVersionUID = -3477992129462720901L; + + private static final Logger logger = Logger.getLogger(PingServiceImpl.class.getName()); + + /** + * Initialize the component. + */ + @Init + public void initialize() throws ParserConfigurationException { + } + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + logger.fine("ping"); + response.getWriter().print("OK"); + } + +} diff --git a/java/sca/contrib/modules/node-manager/src/main/resources/NodeDaemon.composite b/java/sca/contrib/modules/node-manager/src/main/resources/NodeDaemon.composite new file mode 100644 index 0000000000..cb587b02fd --- /dev/null +++ b/java/sca/contrib/modules/node-manager/src/main/resources/NodeDaemon.composite @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + diff --git a/java/sca/contrib/modules/policy-logging/LICENSE b/java/sca/contrib/modules/policy-logging/LICENSE new file mode 100644 index 0000000000..6e529a25c4 --- /dev/null +++ b/java/sca/contrib/modules/policy-logging/LICENSE @@ -0,0 +1,205 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + + diff --git a/java/sca/contrib/modules/policy-logging/META-INF/MANIFEST.MF b/java/sca/contrib/modules/policy-logging/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..df410e306f --- /dev/null +++ b/java/sca/contrib/modules/policy-logging/META-INF/MANIFEST.MF @@ -0,0 +1,28 @@ +Manifest-Version: 1.0 +Private-Package: org.apache.tuscany.sca.policy.logging;version="2.0.0",o + rg.apache.tuscany.sca.policy.logging.jdk;version="2.0.0" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany Logging Policy Model +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397480671 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany Logging Policy Model +Import-Package: javax.xml.namespace, + javax.xml.stream, + org.apache.tuscany.sca.assembly;version="2.0.0", + org.apache.tuscany.sca.contribution.processor;version="2.0.0", + org.apache.tuscany.sca.contribution.resolver;version="2.0.0", + org.apache.tuscany.sca.core;version="2.0.0", + org.apache.tuscany.sca.definitions;version="2.0.0", + org.apache.tuscany.sca.interfacedef;version="2.0.0", + org.apache.tuscany.sca.invocation;version="2.0.0", + org.apache.tuscany.sca.monitor;version="2.0.0", + org.apache.tuscany.sca.policy;version="2.0.0", + org.apache.tuscany.sca.provider;version="2.0.0", + org.apache.tuscany.sca.runtime;version="2.0.0" +Bundle-SymbolicName: org.apache.tuscany.sca.policy.logging +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/policy-logging/NOTICE b/java/sca/contrib/modules/policy-logging/NOTICE new file mode 100644 index 0000000000..51042eab05 --- /dev/null +++ b/java/sca/contrib/modules/policy-logging/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/policy-logging/pom.xml b/java/sca/contrib/modules/policy-logging/pom.xml new file mode 100644 index 0000000000..218458c9fb --- /dev/null +++ b/java/sca/contrib/modules/policy-logging/pom.xml @@ -0,0 +1,52 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + tuscany-policy-logging + Apache Tuscany Logging Policy Model + + + + + org.apache.tuscany.sca + tuscany-contribution + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-assembly-xml + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-policy + 2.0-SNAPSHOT + + + + diff --git a/java/sca/contrib/modules/policy-logging/src/main/java/org/apache/tuscany/sca/policy/logging/LoggingPolicyDefinitionsProvider.java b/java/sca/contrib/modules/policy-logging/src/main/java/org/apache/tuscany/sca/policy/logging/LoggingPolicyDefinitionsProvider.java new file mode 100644 index 0000000000..836631541d --- /dev/null +++ b/java/sca/contrib/modules/policy-logging/src/main/java/org/apache/tuscany/sca/policy/logging/LoggingPolicyDefinitionsProvider.java @@ -0,0 +1,67 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.policy.logging; + +import java.net.URI; +import java.net.URL; +import java.security.AccessController; +import java.security.PrivilegedAction; + +import org.apache.tuscany.sca.contribution.processor.URLArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.URLArtifactProcessorExtensionPoint; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.definitions.Definitions; +import org.apache.tuscany.sca.provider.DefinitionsProvider; +import org.apache.tuscany.sca.provider.DefinitionsProviderException; + +/** + * Provider for Policy Intents and PolicySet definitions related to security + * + * @version $Rev$ $Date$ + */ +public class LoggingPolicyDefinitionsProvider implements DefinitionsProvider { + private String definitionsFile = "org/apache/tuscany/sca/policy/logging/definitions.xml"; + URLArtifactProcessor urlArtifactProcessor = null; + + public LoggingPolicyDefinitionsProvider(ExtensionPointRegistry registry) { + URLArtifactProcessorExtensionPoint documentProcessors = registry.getExtensionPoint(URLArtifactProcessorExtensionPoint.class); + urlArtifactProcessor = (URLArtifactProcessor)documentProcessors.getProcessor(Definitions.class); + } + + public Definitions getDefinitions() throws DefinitionsProviderException { + // Allow privileged access to load resource. Requires RuntimePermssion in security policy. + URL definitionsFileUrl = AccessController.doPrivileged(new PrivilegedAction() { + public URL run() { + return getClass().getClassLoader().getResource(definitionsFile); + } + }); + + Object scaDefn = null; + try { + URI uri = new URI(definitionsFile); + return (Definitions)urlArtifactProcessor.read(null, + uri, + definitionsFileUrl); + } catch ( Exception e ) { + throw new DefinitionsProviderException(e); + } + } + +} diff --git a/java/sca/contrib/modules/policy-logging/src/main/java/org/apache/tuscany/sca/policy/logging/jdk/JDKLoggingImplementationPolicyProvider.java b/java/sca/contrib/modules/policy-logging/src/main/java/org/apache/tuscany/sca/policy/logging/jdk/JDKLoggingImplementationPolicyProvider.java new file mode 100644 index 0000000000..c53c37ccf6 --- /dev/null +++ b/java/sca/contrib/modules/policy-logging/src/main/java/org/apache/tuscany/sca/policy/logging/jdk/JDKLoggingImplementationPolicyProvider.java @@ -0,0 +1,90 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.policy.logging.jdk; + +import org.apache.tuscany.sca.assembly.ConfiguredOperation; +import org.apache.tuscany.sca.assembly.Implementation; +import org.apache.tuscany.sca.assembly.OperationsConfigurator; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.Phase; +import org.apache.tuscany.sca.policy.PolicySet; +import org.apache.tuscany.sca.provider.PolicyProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; + +/** + * @version $Rev$ $Date$ + */ +public class JDKLoggingImplementationPolicyProvider implements PolicyProvider { + private RuntimeComponent component; + private Implementation implementation; + + public JDKLoggingImplementationPolicyProvider(RuntimeComponent component, Implementation implementation) { + super(); + this.component = component; + this.implementation = implementation; + } + + private String getContext() { + return "component.implementation: " + component.getURI() + "(" + implementation.getClass().getName() + ")"; + } + + private PolicySet findPolicySet(Operation operation) { + for (PolicySet ps : component.getPolicySets()) { + for (Object p : ps.getPolicies()) { + if (JDKLoggingPolicy.class.isInstance(p)) { + return ps; + } + } + } + + if ( component instanceof OperationsConfigurator ) { + for ( ConfiguredOperation confOp : ((OperationsConfigurator)component).getConfiguredOperations() ) { + if ( confOp.getName().equals(operation.getName())) { + for (PolicySet ps : confOp.getPolicySets()) { + for (Object p : ps.getPolicies()) { + if (JDKLoggingPolicy.class.isInstance(p)) { + return ps; + } + } + } + } + } + } + + return null; + } + + /** + * @see org.apache.tuscany.sca.provider.PolicyProvider#createInterceptor(org.apache.tuscany.sca.interfacedef.Operation) + */ + public Interceptor createInterceptor(Operation operation) { + PolicySet ps = findPolicySet(operation); + return ps == null ? null : new JDKLoggingPolicyInterceptor(getContext(), operation, ps); + } + + /** + * @see org.apache.tuscany.sca.provider.PolicyProvider#getPhase() + */ + public String getPhase() { + return Phase.IMPLEMENTATION_POLICY; + } + +} diff --git a/java/sca/contrib/modules/policy-logging/src/main/java/org/apache/tuscany/sca/policy/logging/jdk/JDKLoggingPolicy.java b/java/sca/contrib/modules/policy-logging/src/main/java/org/apache/tuscany/sca/policy/logging/jdk/JDKLoggingPolicy.java new file mode 100644 index 0000000000..b9ae619d11 --- /dev/null +++ b/java/sca/contrib/modules/policy-logging/src/main/java/org/apache/tuscany/sca/policy/logging/jdk/JDKLoggingPolicy.java @@ -0,0 +1,85 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.policy.logging.jdk; + +import java.util.logging.Level; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.policy.Policy; + +/** + * Implementation for policies that could be injected as parameter + * into the axis2config. + * + * @version $Rev$ $Date$ + */ +public class JDKLoggingPolicy implements Policy { + static final String SCA10_NS = "http://www.osoa.org/xmlns/sca/1.0"; + static final String SCA10_TUSCANY_NS = "http://tuscany.apache.org/xmlns/sca/1.0"; + private static final QName JDK_LOGGING_POLICY_QNAME = new QName(SCA10_TUSCANY_NS, "jdkLogger"); + + private String loggerName; + private String resourceBundleName; + private Level logLevel; + private boolean useParentHandlers = false; + + public String getLoggerName() { + return loggerName; + } + + public void setLoggerName(String loggerName) { + this.loggerName = loggerName; + } + + public Level getLogLevel() { + return logLevel; + } + + public void setLogLevel(Level logLevel) { + this.logLevel = logLevel; + } + + public String getResourceBundleName() { + return resourceBundleName; + } + + public void setResourceBundleName(String resourceBundleName) { + this.resourceBundleName = resourceBundleName; + } + + public boolean isUseParentHandlers() { + return useParentHandlers; + } + + public void setUseParentHandlers(boolean useParentHandlers) { + this.useParentHandlers = useParentHandlers; + } + + public QName getSchemaName() { + return JDK_LOGGING_POLICY_QNAME; + } + + public boolean isUnresolved() { + return false; + } + + public void setUnresolved(boolean unresolved) { + } +} diff --git a/java/sca/contrib/modules/policy-logging/src/main/java/org/apache/tuscany/sca/policy/logging/jdk/JDKLoggingPolicyInterceptor.java b/java/sca/contrib/modules/policy-logging/src/main/java/org/apache/tuscany/sca/policy/logging/jdk/JDKLoggingPolicyInterceptor.java new file mode 100644 index 0000000000..9a21f1e559 --- /dev/null +++ b/java/sca/contrib/modules/policy-logging/src/main/java/org/apache/tuscany/sca/policy/logging/jdk/JDKLoggingPolicyInterceptor.java @@ -0,0 +1,129 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.policy.logging.jdk; + +import java.util.logging.ConsoleHandler; +import java.util.logging.Handler; +import java.util.logging.Level; +import java.util.logging.Logger; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; +import org.apache.tuscany.sca.policy.PolicySet; + +/** + * Policy handler to handle PolicySet related to Logging with the QName + * {http://tuscany.apache.org/xmlns/sca/1.0/impl/java}LoggingPolicy + * + * @version $Rev$ $Date$ + */ +public class JDKLoggingPolicyInterceptor implements Interceptor { + public static final String loggingPolicy = "JDKLoggingPolicy"; + public static final QName policySetQName = new QName(JDKLoggingPolicy.SCA10_TUSCANY_NS, loggingPolicy); + private Logger logger = null; + + private Invoker next; + private Operation operation; + private PolicySet policySet = null; + private String context; + + public JDKLoggingPolicyInterceptor(String context, Operation operation, PolicySet policySet) { + super(); + this.operation = operation; + this.policySet = policySet; + this.context = context; + init(); + } + + private void init() { + if (policySet != null) { + JDKLoggingPolicy policy = (JDKLoggingPolicy)policySet.getPolicies().get(0); + logger = Logger.getLogger(policy.getLoggerName()); + logger.setLevel(policy.getLogLevel()); + logger.setUseParentHandlers(policy.isUseParentHandlers()); + + boolean found = false; + for (Handler handler : logger.getHandlers()) { + if (handler instanceof ConsoleHandler) { + found = true; + break; + } + } + + if (!found) { + ConsoleHandler consoleHandler = new ConsoleHandler(); + consoleHandler.setLevel(Level.ALL); + logger.addHandler(consoleHandler); + } + } + } + + public Message invoke(Message msg) { + if (logger == null) { + return getNext().invoke(msg); + } + Object msgBody = msg.getBody(); + if (msgBody instanceof Object[]) { + logger.logp(Level.INFO, context, "", "Invoking operation - " + operation.getName()); + + StringBuffer sb = new StringBuffer(); + if (msgBody == null) { + sb.append(""); + } else { + Object[] args = (Object[])msgBody; + for (int i = 0; i < args.length; i++) { + sb.append(args[i]); + if (i != args.length - 1) { + sb.append(", "); + } + } + } + + Object[] logParams = new Object[] {operation.getName(), sb.toString()}; + logger.logp(Level.FINER, context, "", "Invoking operation {0} with arguments {1}", logParams); + } + + Message responseMsg = null; + try { + responseMsg = getNext().invoke(msg); + return responseMsg; + } catch (RuntimeException e) { + logger.logp(Level.SEVERE, context, "", "Exception thrown from operation - " + operation.getName(), e); + throw e; + } finally { + if (responseMsg != null) { + Object[] logParams = new Object[] {operation.getName(), responseMsg.getBody()}; + logger.logp(Level.INFO, context, "", "Returned from operation - " + operation.getName()); + logger.logp(Level.FINER, context, "", "Returning from operation {0} with return value {1}", logParams); + } + } + } + + public Invoker getNext() { + return next; + } + + public void setNext(Invoker next) { + this.next = next; + } +} diff --git a/java/sca/contrib/modules/policy-logging/src/main/java/org/apache/tuscany/sca/policy/logging/jdk/JDKLoggingPolicyProcessor.java b/java/sca/contrib/modules/policy-logging/src/main/java/org/apache/tuscany/sca/policy/logging/jdk/JDKLoggingPolicyProcessor.java new file mode 100644 index 0000000000..5fd7a37a26 --- /dev/null +++ b/java/sca/contrib/modules/policy-logging/src/main/java/org/apache/tuscany/sca/policy/logging/jdk/JDKLoggingPolicyProcessor.java @@ -0,0 +1,136 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.policy.logging.jdk; + +import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; +import static javax.xml.stream.XMLStreamConstants.START_ELEMENT; + +import java.util.logging.Level; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; + +import org.apache.tuscany.sca.contribution.processor.ContributionReadException; +import org.apache.tuscany.sca.contribution.processor.ContributionResolveException; +import org.apache.tuscany.sca.contribution.processor.ContributionWriteException; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.core.FactoryExtensionPoint; +import org.apache.tuscany.sca.monitor.Monitor; + +/** + * + * @version $Rev$ $Date$ + */ +public class JDKLoggingPolicyProcessor implements StAXArtifactProcessor { + private static final QName JDK_LOGGING_POLICY_QNAME = new QName(JDKLoggingPolicy.SCA10_TUSCANY_NS, "jdkLogger"); + private static final String LOG_LEVEL = "logLevel"; + private static final String RESOURCE_BUNDLE = "resourceBundle"; + private static final String USE_PARENT_HANDLERS = "useParentHandlers"; + private static final String TUSACNY_NS = "http://tuscany.apache.org/xmlns/sca/1.0"; + + public QName getArtifactType() { + return JDK_LOGGING_POLICY_QNAME; + } + + public JDKLoggingPolicyProcessor(FactoryExtensionPoint modelFactories, Monitor monitor) { + } + + + public JDKLoggingPolicy read(XMLStreamReader reader) throws ContributionReadException, XMLStreamException { + JDKLoggingPolicy policy = new JDKLoggingPolicy(); + int event = reader.getEventType(); + QName name = null; + + + while (reader.hasNext()) { + event = reader.getEventType(); + switch (event) { + case START_ELEMENT : { + name = reader.getName(); + if ( name.equals(JDK_LOGGING_POLICY_QNAME) ) { + String loggerName = reader.getAttributeValue(null, "name"); + policy.setLoggerName(loggerName); + } else if ( LOG_LEVEL.equals(name.getLocalPart()) ) { + policy.setLogLevel(Level.parse(reader.getElementText())); + } else if ( RESOURCE_BUNDLE.equals(name.getLocalPart()) ) { + policy.setResourceBundleName(reader.getElementText()); + } else if ( USE_PARENT_HANDLERS.equals(name.getLocalPart()) ) { + policy.setUseParentHandlers(Boolean.getBoolean(reader.getElementText())); + } + break; + } + } + + if ( event == END_ELEMENT ) { + if ( JDK_LOGGING_POLICY_QNAME.equals(reader.getName()) ) { + break; + } + } + + //Read the next element + if (reader.hasNext()) { + reader.next(); + } + } + + return policy; + } + + public void write(JDKLoggingPolicy policy, XMLStreamWriter writer) throws ContributionWriteException, + XMLStreamException { + String prefix = "tuscany"; + writer.writeStartElement(prefix, + JDK_LOGGING_POLICY_QNAME.getLocalPart(), + JDK_LOGGING_POLICY_QNAME.getNamespaceURI()); + writer.writeNamespace("tuscany", JDKLoggingPolicy.SCA10_TUSCANY_NS); + + if (policy.getLoggerName() != null) { + writer.writeAttribute("name", policy.getLoggerName()); + } + if ( policy.getLogLevel() != null ) { + writer.writeStartElement(prefix, + LOG_LEVEL, + JDK_LOGGING_POLICY_QNAME.getNamespaceURI()); + writer.writeCharacters(policy.getLogLevel().getLocalizedName()); + writer.writeEndElement(); + } + + if ( policy.getResourceBundleName() != null ) { + writer.writeStartElement(prefix, + RESOURCE_BUNDLE, + JDK_LOGGING_POLICY_QNAME.getNamespaceURI()); + writer.writeCharacters(policy.getResourceBundleName()); + writer.writeEndElement(); + } + + writer.writeEndElement(); + } + + public Class getModelType() { + return JDKLoggingPolicy.class; + } + + public void resolve(JDKLoggingPolicy arg0, ModelResolver arg1) throws ContributionResolveException { + + } + +} diff --git a/java/sca/contrib/modules/policy-logging/src/main/java/org/apache/tuscany/sca/policy/logging/jdk/JDKLoggingPolicyProviderFactory.java b/java/sca/contrib/modules/policy-logging/src/main/java/org/apache/tuscany/sca/policy/logging/jdk/JDKLoggingPolicyProviderFactory.java new file mode 100644 index 0000000000..9bbae8956f --- /dev/null +++ b/java/sca/contrib/modules/policy-logging/src/main/java/org/apache/tuscany/sca/policy/logging/jdk/JDKLoggingPolicyProviderFactory.java @@ -0,0 +1,75 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.policy.logging.jdk; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.assembly.Implementation; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.provider.PolicyProvider; +import org.apache.tuscany.sca.provider.PolicyProviderFactory; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; + +/** + * @version $Rev$ $Date$ + */ +public class JDKLoggingPolicyProviderFactory implements PolicyProviderFactory { + private ExtensionPointRegistry registry; + + public JDKLoggingPolicyProviderFactory(ExtensionPointRegistry registry) { + super(); + this.registry = registry; + } + + /** + * @see org.apache.tuscany.sca.provider.PolicyProviderFactory#createImplementationPolicyProvider(org.apache.tuscany.sca.runtime.RuntimeComponent, org.apache.tuscany.sca.assembly.Implementation) + */ + public PolicyProvider createImplementationPolicyProvider(RuntimeComponent component, Implementation implementation) { + return new JDKLoggingImplementationPolicyProvider(component, implementation); + } + + /** + * @see org.apache.tuscany.sca.provider.PolicyProviderFactory#createReferencePolicyProvider(org.apache.tuscany.sca.runtime.RuntimeComponent, org.apache.tuscany.sca.runtime.RuntimeComponentReference, org.apache.tuscany.sca.assembly.Binding) + */ + public PolicyProvider createReferencePolicyProvider(RuntimeComponent component, + RuntimeComponentReference reference, + Binding binding) { + return new JDKLoggingReferencePolicyProvider(component, reference, binding); + } + + /** + * @see org.apache.tuscany.sca.provider.PolicyProviderFactory#createServicePolicyProvider(org.apache.tuscany.sca.runtime.RuntimeComponent, org.apache.tuscany.sca.runtime.RuntimeComponentService, org.apache.tuscany.sca.assembly.Binding) + */ + public PolicyProvider createServicePolicyProvider(RuntimeComponent component, + RuntimeComponentService service, + Binding binding) { + return new JDKLoggingServicePolicyProvider(component, service, binding); + } + + /** + * @see org.apache.tuscany.sca.provider.ProviderFactory#getModelType() + */ + public Class getModelType() { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/java/sca/contrib/modules/policy-logging/src/main/java/org/apache/tuscany/sca/policy/logging/jdk/JDKLoggingReferencePolicyProvider.java b/java/sca/contrib/modules/policy-logging/src/main/java/org/apache/tuscany/sca/policy/logging/jdk/JDKLoggingReferencePolicyProvider.java new file mode 100644 index 0000000000..feddc8c056 --- /dev/null +++ b/java/sca/contrib/modules/policy-logging/src/main/java/org/apache/tuscany/sca/policy/logging/jdk/JDKLoggingReferencePolicyProvider.java @@ -0,0 +1,89 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.policy.logging.jdk; + +import java.util.List; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.Phase; +import org.apache.tuscany.sca.policy.PolicySet; +import org.apache.tuscany.sca.policy.PolicySetAttachPoint; +import org.apache.tuscany.sca.provider.PolicyProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; + +/** + * @version $Rev$ $Date$ + */ +public class JDKLoggingReferencePolicyProvider implements PolicyProvider { + private RuntimeComponent component; + private RuntimeComponentReference reference; + private Binding binding; + + public JDKLoggingReferencePolicyProvider(RuntimeComponent component, + RuntimeComponentReference reference, + Binding binding) { + super(); + this.component = component; + this.reference = reference; + this.binding = binding; + } + + private PolicySet findPolicySet() { + if (binding instanceof PolicySetAttachPoint) { + List policySets = ((PolicySetAttachPoint)binding).getApplicablePolicySets(); + for (PolicySet ps : policySets) { + for (Object p : ps.getPolicies()) { + if (JDKLoggingPolicy.class.isInstance(p)) { + return ps; + } + } + } + } + return null; + } + + private String getContext() { + return "component.reference: " + component.getURI() + + "#" + + reference.getName() + + "(" + + binding.getClass().getName() + + ")"; + } + + /** + * @see org.apache.tuscany.sca.provider.PolicyProvider#createInterceptor(org.apache.tuscany.sca.interfacedef.Operation) + */ + public Interceptor createInterceptor(Operation operation) { + PolicySet ps = findPolicySet(); + return ps == null ? null : new JDKLoggingPolicyInterceptor(getContext(), operation, ps); + } + + /** + * @see org.apache.tuscany.sca.provider.PolicyProvider#getPhase() + */ + public String getPhase() { + return Phase.REFERENCE_POLICY; + } + +} diff --git a/java/sca/contrib/modules/policy-logging/src/main/java/org/apache/tuscany/sca/policy/logging/jdk/JDKLoggingServicePolicyProvider.java b/java/sca/contrib/modules/policy-logging/src/main/java/org/apache/tuscany/sca/policy/logging/jdk/JDKLoggingServicePolicyProvider.java new file mode 100644 index 0000000000..472f76c680 --- /dev/null +++ b/java/sca/contrib/modules/policy-logging/src/main/java/org/apache/tuscany/sca/policy/logging/jdk/JDKLoggingServicePolicyProvider.java @@ -0,0 +1,87 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.policy.logging.jdk; + +import java.util.List; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.Phase; +import org.apache.tuscany.sca.policy.PolicySet; +import org.apache.tuscany.sca.policy.PolicySetAttachPoint; +import org.apache.tuscany.sca.provider.PolicyProvider; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; + +/** + * @version $Rev$ $Date$ + */ +public class JDKLoggingServicePolicyProvider implements PolicyProvider { + private RuntimeComponent component; + private RuntimeComponentService service; + private Binding binding; + + public JDKLoggingServicePolicyProvider(RuntimeComponent component, RuntimeComponentService service, Binding binding) { + super(); + this.component = component; + this.service = service; + this.binding = binding; + } + + private PolicySet findPolicySet() { + if (binding instanceof PolicySetAttachPoint) { + List policySets = ((PolicySetAttachPoint)binding).getApplicablePolicySets(); + for (PolicySet ps : policySets) { + for (Object p : ps.getPolicies()) { + if (JDKLoggingPolicy.class.isInstance(p)) { + return ps; + } + } + } + } + return null; + } + + private String getContext() { + return "component.service: " + component.getURI() + + "#" + + service.getName() + + "(" + + binding.getClass().getName() + + ")"; + } + + /** + * @see org.apache.tuscany.sca.provider.PolicyProvider#createInterceptor(org.apache.tuscany.sca.interfacedef.Operation) + */ + public Interceptor createInterceptor(Operation operation) { + PolicySet ps = findPolicySet(); + return ps == null ? null : new JDKLoggingPolicyInterceptor(getContext(), operation, ps); + } + + /** + * @see org.apache.tuscany.sca.provider.PolicyProvider#getPhase() + */ + public String getPhase() { + return Phase.SERVICE_POLICY; + } + +} diff --git a/java/sca/contrib/modules/policy-logging/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor b/java/sca/contrib/modules/policy-logging/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor new file mode 100644 index 0000000000..f56f96e4b9 --- /dev/null +++ b/java/sca/contrib/modules/policy-logging/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for the artifact processor extension +org.apache.tuscany.sca.policy.logging.jdk.JDKLoggingPolicyProcessor;qname=http://tuscany.apache.org/xmlns/sca/1.0#jdkLogger,model=org.apache.tuscany.sca.policy.logging.jdk.JDKLoggingPolicy diff --git a/java/sca/contrib/modules/policy-logging/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.DefinitionsProvider b/java/sca/contrib/modules/policy-logging/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.DefinitionsProvider new file mode 100644 index 0000000000..ec40cb7dc5 --- /dev/null +++ b/java/sca/contrib/modules/policy-logging/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.DefinitionsProvider @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for SCA Definitions Providers +org.apache.tuscany.sca.policy.logging.LoggingPolicyDefinitionsProvider \ No newline at end of file diff --git a/java/sca/contrib/modules/policy-logging/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.PolicyProviderFactory b/java/sca/contrib/modules/policy-logging/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.PolicyProviderFactory new file mode 100644 index 0000000000..e14c657d80 --- /dev/null +++ b/java/sca/contrib/modules/policy-logging/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.PolicyProviderFactory @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for the policy extension +org.apache.tuscany.sca.policy.logging.jdk.JDKLoggingPolicyProviderFactory;model=org.apache.tuscany.sca.policy.logging.jdk.JDKLoggingPolicy diff --git a/java/sca/contrib/modules/policy-logging/src/main/resources/org/apache/tuscany/sca/policy/logging/definitions.xml b/java/sca/contrib/modules/policy-logging/src/main/resources/org/apache/tuscany/sca/policy/logging/definitions.xml new file mode 100644 index 0000000000..956a8983a2 --- /dev/null +++ b/java/sca/contrib/modules/policy-logging/src/main/resources/org/apache/tuscany/sca/policy/logging/definitions.xml @@ -0,0 +1,31 @@ + + + + + + + + All messages to and from this implementation must be logged + + + \ No newline at end of file diff --git a/java/sca/contrib/modules/policy-logging/src/test/java/org/apache/tuscany/sca/policy/logging/jdk/PolicyReadTestCase.java b/java/sca/contrib/modules/policy-logging/src/test/java/org/apache/tuscany/sca/policy/logging/jdk/PolicyReadTestCase.java new file mode 100644 index 0000000000..d5b1b9eedc --- /dev/null +++ b/java/sca/contrib/modules/policy-logging/src/test/java/org/apache/tuscany/sca/policy/logging/jdk/PolicyReadTestCase.java @@ -0,0 +1,91 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.policy.logging.jdk; + + +import java.io.InputStream; +import java.io.StringReader; +import java.io.StringWriter; +import java.net.URL; +import java.util.logging.Level; + +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLOutputFactory; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; + +import junit.framework.TestCase; + +/** + * Test the reading of ws config params policy. + * + * @version $Rev$ $Date$ + */ +public class PolicyReadTestCase extends TestCase { + + @Override + public void setUp() throws Exception { + } + + @Override + public void tearDown() throws Exception { + } + + public void testPolicyReading() throws Exception { + JDKLoggingPolicyProcessor processor = new JDKLoggingPolicyProcessor(null, null); + + URL url = getClass().getResource("mock_policies.xml"); + XMLInputFactory inputFactory = XMLInputFactory.newInstance(); + + InputStream urlStream = url.openStream(); + XMLStreamReader reader = inputFactory.createXMLStreamReader(urlStream); + + + JDKLoggingPolicy policy = processor.read(reader); + assertEquals(policy.getLoggerName(), "test.logger"); + assertEquals(policy.getLogLevel(), Level.INFO ); + assertEquals(policy.getResourceBundleName(), "Trace_Messages.properties"); + } + + public void testPolicyWriting() throws Exception { + JDKLoggingPolicyProcessor processor = new JDKLoggingPolicyProcessor(null, null); + + JDKLoggingPolicy policy = new JDKLoggingPolicy(); + policy.setLoggerName("test.logger"); + policy.setLogLevel(Level.INFO); + policy.setResourceBundleName("Trace_Messages.properties"); + + XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); + StringWriter sw = new StringWriter(); + XMLStreamWriter writer = outputFactory.createXMLStreamWriter(sw); + processor.write(policy, writer); + writer.close(); + + XMLInputFactory inputFactory = XMLInputFactory.newInstance(); + StringReader sr = new StringReader(sw.toString()); + XMLStreamReader reader = inputFactory.createXMLStreamReader(sr); + + policy = processor.read(reader); + assertEquals(policy.getLoggerName(), "test.logger"); + assertEquals(policy.getLogLevel(), Level.INFO ); + assertEquals(policy.getResourceBundleName(), "Trace_Messages.properties"); + + } + +} diff --git a/java/sca/contrib/modules/policy-logging/src/test/resources/org/apache/tuscany/sca/policy/logging/jdk/mock_policies.xml b/java/sca/contrib/modules/policy-logging/src/test/resources/org/apache/tuscany/sca/policy/logging/jdk/mock_policies.xml new file mode 100644 index 0000000000..fabb554236 --- /dev/null +++ b/java/sca/contrib/modules/policy-logging/src/test/resources/org/apache/tuscany/sca/policy/logging/jdk/mock_policies.xml @@ -0,0 +1,23 @@ + + + + INFO + Trace_Messages.properties + \ No newline at end of file diff --git a/java/sca/contrib/modules/policy-reliability/LICENSE b/java/sca/contrib/modules/policy-reliability/LICENSE new file mode 100644 index 0000000000..8aa906c321 --- /dev/null +++ b/java/sca/contrib/modules/policy-reliability/LICENSE @@ -0,0 +1,205 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + + diff --git a/java/sca/contrib/modules/policy-reliability/NOTICE b/java/sca/contrib/modules/policy-reliability/NOTICE new file mode 100644 index 0000000000..25bb89c9b2 --- /dev/null +++ b/java/sca/contrib/modules/policy-reliability/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/policy-reliability/pom.xml b/java/sca/contrib/modules/policy-reliability/pom.xml new file mode 100644 index 0000000000..b1cf5a48bb --- /dev/null +++ b/java/sca/contrib/modules/policy-reliability/pom.xml @@ -0,0 +1,70 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 1.4-SNAPSHOT + ../pom.xml + + tuscany-policy-reliability + Apache Tuscany Reliability Policy Model + + + + org.apache.tuscany.sca + tuscany-contribution + 1.4-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-assembly-xml + 1.4-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-contribution-impl + 1.4-SNAPSHOT + test + + + + + + + org.apache.felix + maven-bundle-plugin + + + + ${tuscany.version} + org.apache.tuscany.sca.policy.reliability + ${pom.name} + org.apache.tuscany.sca.policy.reliability* + + + + + + + diff --git a/java/sca/contrib/modules/policy-reliability/src/main/java/org/apache/tuscany/sca/policy/reliability/ReliabilityPolicyDefinitionsProvider.java b/java/sca/contrib/modules/policy-reliability/src/main/java/org/apache/tuscany/sca/policy/reliability/ReliabilityPolicyDefinitionsProvider.java new file mode 100644 index 0000000000..60e28f5231 --- /dev/null +++ b/java/sca/contrib/modules/policy-reliability/src/main/java/org/apache/tuscany/sca/policy/reliability/ReliabilityPolicyDefinitionsProvider.java @@ -0,0 +1,72 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.policy.reliability; + +import java.net.URI; +import java.net.URL; +import java.security.AccessController; +import java.security.PrivilegedAction; + +import org.apache.tuscany.sca.contribution.processor.URLArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.URLArtifactProcessorExtensionPoint; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.definitions.SCADefinitions; +import org.apache.tuscany.sca.provider.SCADefinitionsProvider; +import org.apache.tuscany.sca.provider.SCADefinitionsProviderException; + +/** + * Provider for Policy Intents and PolicySet definitions related to security + * + * @version $Rev$ $Date$ + */ +public class ReliabilityPolicyDefinitionsProvider implements SCADefinitionsProvider { + private String definitionsFile = "org/apache/tuscany/sca/policy/reliability/definitions.xml"; + URLArtifactProcessor urlArtifactProcessor = null; + + public ReliabilityPolicyDefinitionsProvider(ExtensionPointRegistry registry) { + URLArtifactProcessorExtensionPoint documentProcessors = registry.getExtensionPoint(URLArtifactProcessorExtensionPoint.class); + urlArtifactProcessor = (URLArtifactProcessor)documentProcessors.getProcessor(SCADefinitions.class); + } + + public SCADefinitions getSCADefinition() throws SCADefinitionsProviderException { + SCADefinitions scaDefns = null; + SCADefinitions tuscanyDefns = null; + try { + // Allow privileged access to load resource. Requires RuntimePermssion in security policy. + URL definitionsFileUrl = AccessController.doPrivileged(new PrivilegedAction() { + public URL run() { + return getClass().getClassLoader().getResource(definitionsFile); + } + }); + + URI uri = new URI(definitionsFile); + + scaDefns = (SCADefinitions)urlArtifactProcessor.read(null, + uri, + definitionsFileUrl); + + return scaDefns; + + } catch ( Exception e ) { + throw new SCADefinitionsProviderException(e); + } + } + +} diff --git a/java/sca/contrib/modules/policy-reliability/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.SCADefinitionsProvider b/java/sca/contrib/modules/policy-reliability/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.SCADefinitionsProvider new file mode 100644 index 0000000000..7f616cb3d4 --- /dev/null +++ b/java/sca/contrib/modules/policy-reliability/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.SCADefinitionsProvider @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for SCA Definitions Providers +org.apache.tuscany.sca.policy.reliability.ReliabilityPolicyDefinitionsProvider \ No newline at end of file diff --git a/java/sca/contrib/modules/policy-reliability/src/main/resources/org/apache/tuscany/sca/policy/reliability/definitions.xml b/java/sca/contrib/modules/policy-reliability/src/main/resources/org/apache/tuscany/sca/policy/reliability/definitions.xml new file mode 100644 index 0000000000..df87906ab8 --- /dev/null +++ b/java/sca/contrib/modules/policy-reliability/src/main/resources/org/apache/tuscany/sca/policy/reliability/definitions.xml @@ -0,0 +1,62 @@ + + + + + + + + + This intent is used to indicate that a message sent + by a client is always delivered to the component. + + + + + + This intent is used to indicate that a message that was + successfully sent by a client is not delivered more than + once to the component. + + + + + + This intent is used to indicate that all the messages + are delivered to the component in the order they were + sent by the client. + + + + + + This profile intent is used to indicate that a message + sent by a client is always delivered to the component. + It also indicates that duplicate messages are not + delivered to the component. + + + \ No newline at end of file diff --git a/java/sca/contrib/modules/policy-security-jsr250/LICENSE b/java/sca/contrib/modules/policy-security-jsr250/LICENSE new file mode 100644 index 0000000000..8aa906c321 --- /dev/null +++ b/java/sca/contrib/modules/policy-security-jsr250/LICENSE @@ -0,0 +1,205 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + + diff --git a/java/sca/contrib/modules/policy-security-jsr250/META-INF/MANIFEST.MF b/java/sca/contrib/modules/policy-security-jsr250/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..a8d8f4fe9a --- /dev/null +++ b/java/sca/contrib/modules/policy-security-jsr250/META-INF/MANIFEST.MF @@ -0,0 +1,28 @@ +Manifest-Version: 1.0 +Private-Package: org.apache.tuscany.sca.policy.jsr250;version="2.0.0",or + g.apache.tuscany.sca.policy.jsr250.introspect.impl;version="2.0.0" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA Java JSR250 Implementation +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397483046 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA Java JSR250 Implementation +Import-Package: javax.annotation.security,javax.xml.namespace,org.apac + he.tuscany.sca.assembly;version="2.0.0",org.apache.tuscany.sca.core;ver + sion="1.4",org.apache.tuscany.sca.implementation.java;version="2.0.0",o + rg.apache.tuscany.sca.implementation.java.introspect;version="2.0.0",or + g.apache.tuscany.sca.policy;version="2.0.0",org.apache.tuscany.sca.poli + cy.authorization;version="2.0.0",org.apache.tuscany.sca.policy.identity + ;version="2.0.0",org.apache.tuscany.sca.implementation.java.introspect. + impl;resolution:=optional,org.oasisopen.sca.annotation;version="2.0.0";reso + lution:=optional,org.apache.tuscany.sca.interfacedef.java;version="1. + 4";resolution:=optional,org.apache.tuscany.sca.interfacedef;version=" + 1.4";resolution:=optional,org.ap + ache.tuscany.sca.interfacedef.java.impl;version="2.0.0";resolution:=opt + ional +Bundle-SymbolicName: org.apache.tuscany.sca.policy.security.jsr250 +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/policy-security-jsr250/NOTICE b/java/sca/contrib/modules/policy-security-jsr250/NOTICE new file mode 100644 index 0000000000..25bb89c9b2 --- /dev/null +++ b/java/sca/contrib/modules/policy-security-jsr250/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/policy-security-jsr250/pom.xml b/java/sca/contrib/modules/policy-security-jsr250/pom.xml new file mode 100644 index 0000000000..ddd8e5e307 --- /dev/null +++ b/java/sca/contrib/modules/policy-security-jsr250/pom.xml @@ -0,0 +1,64 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + tuscany-policy-security-jsr250 + Apache Tuscany SCA Java JSR250 Implementation + + + + org.apache.tuscany.sca + tuscany-assembly + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-sca-api + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-policy-security + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-implementation-java + 2.0-SNAPSHOT + + + + javax.annotation + jsr250-api + 1.0 + + + + + diff --git a/java/sca/contrib/modules/policy-security-jsr250/src/main/java/org/apache/tuscany/sca/policy/jsr250/JSR250Activator.java b/java/sca/contrib/modules/policy-security-jsr250/src/main/java/org/apache/tuscany/sca/policy/jsr250/JSR250Activator.java new file mode 100644 index 0000000000..e6279f4811 --- /dev/null +++ b/java/sca/contrib/modules/policy-security-jsr250/src/main/java/org/apache/tuscany/sca/policy/jsr250/JSR250Activator.java @@ -0,0 +1,51 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.policy.jsr250; + +import org.apache.tuscany.sca.assembly.AssemblyFactory; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.core.FactoryExtensionPoint; +import org.apache.tuscany.sca.core.ModuleActivator; +import org.apache.tuscany.sca.implementation.java.JavaImplementationFactory; +import org.apache.tuscany.sca.policy.PolicyFactory; +import org.apache.tuscany.sca.policy.jsr250.introspect.impl.JSR250PolicyProcessor; + +/** + * A module activator for the Java implementation model. + * + * @version $Rev$ $Date$ + */ +public class JSR250Activator implements ModuleActivator { + + public void start(ExtensionPointRegistry registry) { + FactoryExtensionPoint modelFactories = registry.getExtensionPoint(FactoryExtensionPoint.class); + AssemblyFactory assemblyFactory = modelFactories.getFactory(AssemblyFactory.class); + PolicyFactory policyFactory = modelFactories.getFactory(PolicyFactory.class); + + JavaImplementationFactory javaImplementationFactory = modelFactories.getFactory(JavaImplementationFactory.class); + javaImplementationFactory.addClassVisitor(new JSR250PolicyProcessor(assemblyFactory, policyFactory)); + + } + + public void stop(ExtensionPointRegistry registry) { + + } + +} diff --git a/java/sca/contrib/modules/policy-security-jsr250/src/main/java/org/apache/tuscany/sca/policy/jsr250/introspect/impl/JSR250PolicyProcessor.java b/java/sca/contrib/modules/policy-security-jsr250/src/main/java/org/apache/tuscany/sca/policy/jsr250/introspect/impl/JSR250PolicyProcessor.java new file mode 100644 index 0000000000..2622886075 --- /dev/null +++ b/java/sca/contrib/modules/policy-security-jsr250/src/main/java/org/apache/tuscany/sca/policy/jsr250/introspect/impl/JSR250PolicyProcessor.java @@ -0,0 +1,179 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.policy.jsr250.introspect.impl; + +import java.lang.reflect.Method; + +import javax.annotation.security.DenyAll; +import javax.annotation.security.PermitAll; +import javax.annotation.security.RolesAllowed; +import javax.annotation.security.RunAs; +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.assembly.AssemblyFactory; +import org.apache.tuscany.sca.assembly.ConfiguredOperation; +import org.apache.tuscany.sca.assembly.OperationsConfigurator; +import org.apache.tuscany.sca.implementation.java.IntrospectionException; +import org.apache.tuscany.sca.implementation.java.JavaImplementation; +import org.apache.tuscany.sca.implementation.java.introspect.BaseJavaClassVisitor; +import org.apache.tuscany.sca.policy.PolicyFactory; +import org.apache.tuscany.sca.policy.PolicySet; +import org.apache.tuscany.sca.policy.authorization.AuthorizationPolicy; +import org.apache.tuscany.sca.policy.identity.SecurityIdentityPolicy; + +/** + * Processes an {@link javax.annotation.security.*} annotation + * Below is a list of annotations + * + * Type Method + * RunAs x + * RolesAllowed x x + * PermitAll x x + * DenyAll x + * + * @version $Rev$ $Date$ + */ +public class JSR250PolicyProcessor extends BaseJavaClassVisitor { + private static final QName RUN_AS = new QName("http://www.osoa.org/xmlns/sca/1.0","runAs"); + private static final QName ALLOW = new QName("http://www.osoa.org/xmlns/sca/1.0","allow"); + private static final QName PERMIT_ALL = new QName("http://www.osoa.org/xmlns/sca/1.0","permitAll"); + private static final QName DENY_ALL = new QName("http://www.osoa.org/xmlns/sca/1.0","denyAll"); + + private PolicyFactory policyFactory; + + public JSR250PolicyProcessor(AssemblyFactory assemblyFactory, PolicyFactory policyFactory) { + super(assemblyFactory); + this.policyFactory = policyFactory; + } + + + @Override + public void visitClass(Class clazz, JavaImplementation type) throws IntrospectionException { + + RunAs runAs = clazz.getAnnotation(javax.annotation.security.RunAs.class); + if (runAs != null) { + + String roleName = runAs.value(); + if(roleName == null) { + //FIXME handle monitor or error + } + + SecurityIdentityPolicy policy = new SecurityIdentityPolicy(); + policy.setRunAsRole(roleName); + + PolicySet policySet = policyFactory.createPolicySet(); + policySet.setName(RUN_AS); + policySet.getPolicies().add(policy); + policySet.setUnresolved(false); + ((org.apache.tuscany.sca.policy.PolicySetAttachPoint)type).getPolicySets().add(policySet); + } + + RolesAllowed rolesAllowed = clazz.getAnnotation(javax.annotation.security.RolesAllowed.class); + if(rolesAllowed != null) { + if(rolesAllowed.value().length == 0) { + //FIXME handle monitor or error + } + + AuthorizationPolicy policy = new AuthorizationPolicy(); + policy.setAccessControl(AuthorizationPolicy.AcessControl.allow); + + for(String role : rolesAllowed.value()) { + policy.getRoleNames().add(role); + } + + PolicySet policySet = policyFactory.createPolicySet(); + policySet.setName(ALLOW); + policySet.getPolicies().add(policy); + policySet.setUnresolved(false); + ((org.apache.tuscany.sca.policy.PolicySetAttachPoint)type).getPolicySets().add(policySet); + } + + PermitAll permitAll = clazz.getAnnotation(javax.annotation.security.PermitAll.class); + if(permitAll != null) { + AuthorizationPolicy policy = new AuthorizationPolicy(); + policy.setAccessControl(AuthorizationPolicy.AcessControl.permitAll); + + PolicySet policySet = policyFactory.createPolicySet(); + policySet.setName(PERMIT_ALL); + policySet.getPolicies().add(policy); + policySet.setUnresolved(false); + ((org.apache.tuscany.sca.policy.PolicySetAttachPoint)type).getPolicySets().add(policySet); + } + + } + + @Override + public void visitMethod(Method method, JavaImplementation type) throws IntrospectionException { + RolesAllowed rolesAllowed = method.getAnnotation(javax.annotation.security.RolesAllowed.class); + if(rolesAllowed != null) { + if(rolesAllowed.value().length == 0) { + //FIXME handle monitor or error + } + + AuthorizationPolicy policy = new AuthorizationPolicy(); + policy.setAccessControl(AuthorizationPolicy.AcessControl.allow); + + for(String role : rolesAllowed.value()) { + policy.getRoleNames().add(role); + } + + ConfiguredOperation confOp = assemblyFactory.createConfiguredOperation(); + confOp.setName(method.getName()); + ((OperationsConfigurator)type).getConfiguredOperations().add(confOp); + + PolicySet policySet = policyFactory.createPolicySet(); + policySet.setName(ALLOW); + policySet.getPolicies().add(policy); + policySet.setUnresolved(false); + confOp.getPolicySets().add(policySet); + } + + PermitAll permitAll = method.getAnnotation(javax.annotation.security.PermitAll.class); + if(permitAll != null) { + AuthorizationPolicy policy = new AuthorizationPolicy(); + policy.setAccessControl(AuthorizationPolicy.AcessControl.permitAll); + + ConfiguredOperation confOp = assemblyFactory.createConfiguredOperation(); + confOp.setName(method.getName()); + ((OperationsConfigurator)type).getConfiguredOperations().add(confOp); + + PolicySet policySet = policyFactory.createPolicySet(); + policySet.setName(PERMIT_ALL); + policySet.getPolicies().add(policy); + policySet.setUnresolved(false); + confOp.getPolicySets().add(policySet); + } + + DenyAll denyAll = method.getAnnotation(javax.annotation.security.DenyAll.class); + if(denyAll != null) { + AuthorizationPolicy policy = new AuthorizationPolicy(); + policy.setAccessControl(AuthorizationPolicy.AcessControl.denyAll); + + ConfiguredOperation confOp = assemblyFactory.createConfiguredOperation(); + confOp.setName(method.getName()); + ((OperationsConfigurator)type).getConfiguredOperations().add(confOp); + + PolicySet policySet = policyFactory.createPolicySet(); + policySet.setName(DENY_ALL); + policySet.getPolicies().add(policy); + policySet.setUnresolved(false); + confOp.getPolicySets().add(policySet); + } + } +} diff --git a/java/sca/contrib/modules/policy-security-jsr250/src/main/resources/META-INF/services/org.apache.tuscany.sca.core.ModuleActivator b/java/sca/contrib/modules/policy-security-jsr250/src/main/resources/META-INF/services/org.apache.tuscany.sca.core.ModuleActivator new file mode 100644 index 0000000000..5feb961dc2 --- /dev/null +++ b/java/sca/contrib/modules/policy-security-jsr250/src/main/resources/META-INF/services/org.apache.tuscany.sca.core.ModuleActivator @@ -0,0 +1,18 @@ +# 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. + +org.apache.tuscany.sca.policy.jsr250.JSR250Activator diff --git a/java/sca/contrib/modules/policy-security-jsr250/src/test/java/org/apache/tuscany/sca/policy/jsr250/introspect/impl/PolicyProcessorTestCaseFIXME.java b/java/sca/contrib/modules/policy-security-jsr250/src/test/java/org/apache/tuscany/sca/policy/jsr250/introspect/impl/PolicyProcessorTestCaseFIXME.java new file mode 100644 index 0000000000..14454a1466 --- /dev/null +++ b/java/sca/contrib/modules/policy-security-jsr250/src/test/java/org/apache/tuscany/sca/policy/jsr250/introspect/impl/PolicyProcessorTestCaseFIXME.java @@ -0,0 +1,399 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.policy.jsr250.introspect.impl; + +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import junit.framework.TestCase; + +import org.apache.tuscany.sca.assembly.ConfiguredOperation; +import org.apache.tuscany.sca.assembly.DefaultAssemblyFactory; +import org.apache.tuscany.sca.assembly.OperationsConfigurator; +import org.apache.tuscany.sca.implementation.java.DefaultJavaImplementationFactory; +import org.apache.tuscany.sca.implementation.java.JavaImplementation; +import org.apache.tuscany.sca.implementation.java.JavaImplementationFactory; +import org.apache.tuscany.sca.policy.DefaultPolicyFactory; +import org.apache.tuscany.sca.policy.Intent; +import org.apache.tuscany.sca.policy.PolicySetAttachPoint; +import org.oasisopen.sca.annotation.Requires; +import org.oasisopen.sca.annotation.Service; + +/** + * @version $Rev$ $Date$ + */ +public class PolicyProcessorTestCaseFIXME extends TestCase { + private JSR250PolicyProcessor policyProcessor; + private JavaImplementation type; + + // This actually is a test for PolicyJavaInterfaceProcessor. It will get + // invoked via the call to ImplementationProcessorServiceImpl.createService in + // ServiceProcessor. Of course ServiceProcessor class has to be working. + public void stestSingleInterfaceWithIntentsOnInterfaceAtInterfaceLevel() throws Exception { + policyProcessor.visitClass(Service1.class, type); + verifyIntents(Service1.class, type); + } + + public void stestMultipleInterfacesWithIntentsOnInterfaceAtInterfaceLevel() throws Exception { + policyProcessor.visitClass(Service2.class, type); + verifyIntents(Service2.class, type); + } + + public void stestSingleInterfaceWithIntentsOnImplAtClassLevel() throws Exception { + policyProcessor.visitClass(Service3.class, type); + verifyIntents(Service3.class, type); + } + + public void stestMultipleInterfacesWithIntentsOnImplAtClassLevel() throws Exception { + policyProcessor.visitClass(Service4.class, type); + verifyIntents(Service4.class, type); + } + + public void stestSingleInterfaceWithIntentsOnInterfaceAtMethodLevel() throws Exception { + policyProcessor.visitClass(Service5.class, type); + verifyIntents(Service5.class, type); + } + + public void testSingleInterfaceWithIntentsOnServiceAndInterfaceAtImplAndInertfaceAndMethodLevel() throws Exception { + policyProcessor.visitClass(Service6.class, type); + for (Method method : Service6.class.getDeclaredMethods()) { + policyProcessor.visitMethod(method, type); + } + verifyIntents(Service6.class, type); + } + + private void verifyIntents(Class serviceImplClass, JavaImplementation type) { + if ( !(type instanceof PolicySetAttachPoint) ) { + fail("No Intents on the service "); + } + Requires serviceImplIntentAnnotation = (Requires)serviceImplClass.getAnnotation(Requires.class); + if (serviceImplIntentAnnotation != null) { + String[] serviceImplIntents = serviceImplIntentAnnotation.value(); + List requiredIntents = ((PolicySetAttachPoint)type).getRequiredIntents(); + if (serviceImplIntents.length > 0) { + if (requiredIntents == null || requiredIntents.size() == 0) { + fail("No Intents on the service "); + } + Map intentMap = new HashMap(); + for (Intent intent : requiredIntents) { + intentMap.put(intent.getName().getLocalPart(), intent); + } + for (String intent : serviceImplIntents) { + assertTrue("ComponentType for Service class " + serviceImplClass.getName() + + " did not contain Service Implementation intent " + + intent, intentMap.containsKey(intent)); + } + } + } + + // This should match what was specified on @Service for a Service Implementation + // If we use these to get the Service names and we get a null Service + // name then it would seem that wrong values were put on the @Service annotation + // or the wrong interfaces were specified on the implements list of the class + // statement? + Map serviceMap = new HashMap(); + for (org.apache.tuscany.sca.assembly.Service service: type.getServices()) { + serviceMap.put(service.getName(), service); + } + for (Class interfaceClass : serviceImplClass.getInterfaces()) { + Requires interfaceIntentAnnotation = (Requires)interfaceClass.getAnnotation(Requires.class); + org.apache.tuscany.sca.assembly.Service service = serviceMap.get(interfaceClass.getSimpleName()); + if (service == null) { + fail("No service defined for interface " + interfaceClass.getSimpleName() + + " on Service Implementation " + + serviceImplClass.getName()); + } + + if (interfaceIntentAnnotation != null) { + String[] interfaceIntents = interfaceIntentAnnotation.value(); + List requiredIntents = service.getInterfaceContract().getInterface().getRequiredIntents(); + if (interfaceIntents.length > 0) { + if (requiredIntents == null || requiredIntents.size() == 0) { + fail("No Intents on the service " + service.getName()); + } + Map intentMap = new HashMap(); + for (Intent intent : requiredIntents) { + intentMap.put(intent.getName().getLocalPart(), intent); + } + for (String intent : interfaceIntents) { + assertTrue("Interface " + service.getName() + + " did not contain Service Interface intent " + + intent, intentMap.containsKey(intent)); + } + } + } + + for (Method method : interfaceClass.getDeclaredMethods()) { + Requires methodIntentAnnotation = method.getAnnotation(Requires.class); + + // Verify that each of the Intents on each of the Service + // Interface Methods exist on their associated operation. + if (methodIntentAnnotation != null) { + String[] methodIntents = methodIntentAnnotation.value(); + if (methodIntents.length > 0) { + List requiredIntents = null; + for ( ConfiguredOperation confOp : service.getConfiguredOperations() ) { + if ( confOp.getName().equals(method.getName()) && + confOp.getContractName().equals(service.getName()) ) { + requiredIntents = confOp.getRequiredIntents(); + } + } + + if (requiredIntents == null || requiredIntents.size() == 0) { + fail("No Intents on operation " + method.getName()); + } + for (String intent : methodIntents) { + boolean found = false; + for (Intent requiredIntent: requiredIntents) { + if (requiredIntent.getName().getLocalPart().equals(intent)) { + found = true; + break; + } + } + assertTrue("Operation " + method.getName() + + " did not contain Service Interface method intent " + + intent, found); + } + } + } + } + + for (Method method : serviceImplClass.getDeclaredMethods()) { + Requires methodIntentAnnotation = method.getAnnotation(Requires.class); + + // Verify that each of the Intents on each of the Service + // Implementation Methods exist on their associated + // operation. + if (methodIntentAnnotation != null) { + String[] methodIntents = methodIntentAnnotation.value(); + if (methodIntents.length > 0) { + List requiredIntents = null; + for ( ConfiguredOperation confOp : ((OperationsConfigurator)type).getConfiguredOperations() ) { + if ( confOp.getName().equals(method.getName()) ) { + requiredIntents = confOp.getRequiredIntents(); + } + } + + if (requiredIntents == null || requiredIntents.size() == 0) { + fail("No Intents on operation " + method.getName()); + } + + for (String intent : methodIntents) { + boolean found = false; + for (Intent requiredIntent: requiredIntents) { + if (requiredIntent.getName().getLocalPart().equals(intent)) { + found = true; + break; + } + } + assertTrue("Operation " + method.getName() + + " did not contain Implementation method intent " + + intent, found); + } + } + } + } + } + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + policyProcessor = new JSR250PolicyProcessor(new DefaultAssemblyFactory(), new DefaultPolicyFactory()); + JavaImplementationFactory javaImplementationFactory = new DefaultJavaImplementationFactory(); + type = javaImplementationFactory.createJavaImplementation(); + } + + // @Remotable + @Requires( {"transaction.global"}) + private interface Interface1 { + int method1(); + + int method2(); + + int method3(); + + int method4(); + } + + @Service(Interface1.class) + private class Service1 implements Interface1 { + public int method1() { + return 0; + } + + public int method2() { + return 0; + } + + public int method3() { + return 0; + } + + public int method4() { + return 0; + } + } + + // @Remotable + @Requires( {"transaction.local"}) + private interface Interface2 { + int method5(); + + int method6(); + } + + @Service(interfaces = {Interface1.class, Interface2.class}) + private class Service2 implements Interface1, Interface2 { + public int method1() { + return 0; + } + + public int method2() { + return 0; + } + + public int method3() { + return 0; + } + + public int method4() { + return 0; + } + + public int method5() { + return 0; + } + + public int method6() { + return 0; + } + } + + // @Remotable + private interface Interface3 { + int method1(); + + int method2(); + + int method3(); + + int method4(); + } + + @Service(Interface3.class) + @Requires( {"transaction.global"}) + private class Service3 implements Interface3 { + public int method1() { + return 0; + } + + public int method2() { + return 0; + } + + public int method3() { + return 0; + } + + public int method4() { + return 0; + } + } + + // @Remotable + private interface Interface4 { + int method5(); + + int method6(); + } + + @Service(interfaces = {Interface3.class, Interface4.class}) + @Requires( {"transaction.local"}) + private class Service4 implements Interface3, Interface4 { + public int method1() { + return 0; + } + + public int method2() { + return 0; + } + + public int method3() { + return 0; + } + + public int method4() { + return 0; + } + + public int method5() { + return 0; + } + + public int method6() { + return 0; + } + } + + private interface Interface5 { + @Requires( {"transaction.global"}) + int method1(); + + @Requires( {"transaction.local"}) + int method2(); + } + + @Service(Interface5.class) + private class Service5 implements Interface5 { + public int method1() { + return 0; + } + + public int method2() { + return 0; + } + } + + @Requires( {"transaction.global.Interface6"}) + private interface Interface6 { + @Requires( {"transaction.global.Interface6.method1"}) + int method1(); + + @Requires( {"transaction.local.Interface6.method2"}) + int method2(); + } + + @Service(Interface6.class) + @Requires( {"transaction.global.Service6"}) + private class Service6 implements Interface6 { + @Requires( {"transaction.global.Service6.method1"}) + public int method1() { + return 0; + } + + @Requires( {"transaction.global.Service6.method1"}) + public int method2() { + return 0; + } + } + +} diff --git a/java/sca/contrib/modules/policy-transaction/LICENSE b/java/sca/contrib/modules/policy-transaction/LICENSE new file mode 100644 index 0000000000..6e529a25c4 --- /dev/null +++ b/java/sca/contrib/modules/policy-transaction/LICENSE @@ -0,0 +1,205 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + + diff --git a/java/sca/contrib/modules/policy-transaction/META-INF/MANIFEST.MF b/java/sca/contrib/modules/policy-transaction/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..7a81ed85eb --- /dev/null +++ b/java/sca/contrib/modules/policy-transaction/META-INF/MANIFEST.MF @@ -0,0 +1,45 @@ +Manifest-Version: 1.0 +Export-Package: org.apache.tuscany.sca.policy.transaction;uses:="org.a + pache.tuscany.sca.runtime,org.apache.geronimo.transaction.log,org.apa + che.tuscany.sca.assembly,org.apache.tuscany.sca.provider,org.apache.t + uscany.sca.definitions,org.apache.tuscany.sca.core,org.apache.tuscany + .sca.monitor,org.apache.tuscany.sca.policy,org.apache.tuscany.sca.int + erfacedef,javax.xml.namespace,org.apache.tuscany.sca.definitions.util + ,org.apache.tuscany.sca.invocation,javax.xml.stream,org.apache.tuscan + y.sca.contribution.resolver,javax.transaction,org.apache.tuscany.sca. + contribution.processor,org.apache.geronimo.transaction.manager";versi + on="1.4" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany SCA Transaction Policy Model +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397486843 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA Transaction Policy Model +Import-Package: javax.resource.spi, + javax.transaction;version="1.0.1", + javax.transaction.xa;version="1.1";resolution:=optional, + javax.xml.namespace, + javax.xml.stream, + + org.apache.geronimo.transaction.log, + org.apache.geronimo.transaction.manager, + org.apache.tuscany.sca.assembly;version="2.0.0", + org.apache.tuscany.sca.contribution.processor;version="2.0.0", + org.apache.tuscany.sca.contribution.resolver;version="2.0.0", + org.apache.tuscany.sca.core;version="2.0.0", + org.apache.tuscany.sca.definitions;version="2.0.0", + org.apache.tuscany.sca.definitions.util;version="2.0.0", + org.apache.tuscany.sca.interfacedef;version="2.0.0", + org.apache.tuscany.sca.invocation;version="2.0.0", + org.apache.tuscany.sca.monitor;version="2.0.0", + org.apache.tuscany.sca.policy;version="2.0.0", + org.apache.tuscany.sca.policy.transaction;version="2.0.0", + org.apache.tuscany.sca.provider;version="2.0.0", + org.apache.tuscany.sca.runtime;version="2.0.0", + org.objectweb.howl.log;version="1.0.1" +Bundle-SymbolicName: org.apache.tuscany.sca.policy.transaction +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/policy-transaction/NOTICE b/java/sca/contrib/modules/policy-transaction/NOTICE new file mode 100644 index 0000000000..51042eab05 --- /dev/null +++ b/java/sca/contrib/modules/policy-transaction/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/policy-transaction/pom.xml b/java/sca/contrib/modules/policy-transaction/pom.xml new file mode 100644 index 0000000000..281219136b --- /dev/null +++ b/java/sca/contrib/modules/policy-transaction/pom.xml @@ -0,0 +1,58 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + tuscany-policy-transaction + Apache Tuscany SCA Transaction Policy Model + + + + + org.apache.tuscany.sca + tuscany-contribution + 2.0-SNAPSHOT + + + + org.apache.tuscany.sca + tuscany-assembly-xml + 2.0-SNAPSHOT + + + + org.apache.geronimo.components + geronimo-transaction + 2.1.1 + + + + org.apache.geronimo.components + geronimo-connector + 2.1.1 + + + + diff --git a/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/IncompatibleIntentException.java b/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/IncompatibleIntentException.java new file mode 100644 index 0000000000..8a242924ee --- /dev/null +++ b/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/IncompatibleIntentException.java @@ -0,0 +1,44 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.policy.transaction; + +/** + * @version $Rev$ $Date$ + */ +public class IncompatibleIntentException extends Exception { + private static final long serialVersionUID = -2993825019200280397L; + + public IncompatibleIntentException() { + super(); + } + + public IncompatibleIntentException(String message, Throwable cause) { + super(message, cause); + } + + public IncompatibleIntentException(String message) { + super(message); + } + + public IncompatibleIntentException(Throwable cause) { + super(cause); + } + +} diff --git a/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionImplementationPolicyProvider.java b/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionImplementationPolicyProvider.java new file mode 100644 index 0000000000..3c11fef865 --- /dev/null +++ b/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionImplementationPolicyProvider.java @@ -0,0 +1,61 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.policy.transaction; + +import java.util.List; + +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.Phase; +import org.apache.tuscany.sca.policy.PolicySet; +import org.apache.tuscany.sca.policy.PolicySetAttachPoint; +import org.apache.tuscany.sca.provider.PolicyProvider; + +/** + * @version $Rev$ $Date$ + */ +public class TransactionImplementationPolicyProvider implements PolicyProvider { + private TransactionManagerHelper helper; + private List policySets; + + public TransactionImplementationPolicyProvider(TransactionManagerHelper helper, PolicySetAttachPoint attachPoint) { + super(); + this.helper = helper; + this.policySets = attachPoint.getApplicablePolicySets(); + } + + public Interceptor createInterceptor(Operation operation) { + for (PolicySet policySet : policySets) { + for (Object p : policySet.getPolicies()) { + if (p instanceof TransactionPolicy) { + TransactionInterceptor interceptor = + new TransactionInterceptor(helper, false, (TransactionPolicy)p, null); + return interceptor; + } + } + } + return null; + } + + public String getPhase() { + return Phase.IMPLEMENTATION_POLICY; + } + +} diff --git a/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionIntent.java b/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionIntent.java new file mode 100644 index 0000000000..b3e90c23cd --- /dev/null +++ b/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionIntent.java @@ -0,0 +1,28 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.policy.transaction; + +/** + * + * @version $Rev$ $Date$ + */ +public enum TransactionIntent { + managedTransactionLocal, managedTransactionGlobal, noManagedTransaction, propagatesTransacton, suspendsTransaction, transactedOneWay, immediateOneWay +} diff --git a/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionInterceptor.java b/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionInterceptor.java new file mode 100644 index 0000000000..0de98592cb --- /dev/null +++ b/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionInterceptor.java @@ -0,0 +1,122 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.policy.transaction; + +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.Invoker; +import org.apache.tuscany.sca.invocation.Message; + +/** + * @version $Rev$ $Date$ + */ +public class TransactionInterceptor implements Interceptor { + private Invoker next; + private TransactionManagerHelper helper; + private boolean outbound; + private TransactionPolicy interactionPolicy; + private TransactionPolicy implementationPolicy; + + public TransactionInterceptor(TransactionManagerHelper helper, + boolean outbound, + TransactionPolicy interactionPolicy, + TransactionPolicy implementationPolicy) { + super(); + this.helper = helper; + this.outbound = outbound; + this.interactionPolicy = interactionPolicy; + this.implementationPolicy = implementationPolicy; + } + + /** + * @see org.apache.tuscany.sca.invocation.Interceptor#getNext() + */ + public Invoker getNext() { + return next; + } + + /** + * @see org.apache.tuscany.sca.invocation.Interceptor#setNext(org.apache.tuscany.sca.invocation.Invoker) + */ + public void setNext(Invoker next) { + this.next = next; + } + + /** + * @see org.apache.tuscany.sca.invocation.Invoker#invoke(org.apache.tuscany.sca.invocation.Message) + */ + public Message invoke(Message msg) { + TransactionalInvocation invocation = new TransactionalInvocation(next, msg); + + Message result = null; + if (msg.getOperation().isNonBlocking()) { + + } + TransactionIntent interactionIntent = TransactionIntent.propagatesTransacton; + if (interactionPolicy != null) { + if (interactionPolicy.getAction() == TransactionPolicy.Action.PROPAGATE) { + interactionIntent = TransactionIntent.propagatesTransacton; + } else { + interactionIntent = TransactionIntent.suspendsTransaction; + } + } + TransactionIntent implementationIntent = TransactionIntent.managedTransactionGlobal; + if (implementationPolicy != null) { + switch (implementationPolicy.getAction()) { + case REQUIRE_GLOBAL: + implementationIntent = TransactionIntent.managedTransactionGlobal; + break; + case REQUIRE_LOCAL: + implementationIntent = TransactionIntent.managedTransactionLocal; + break; + default: + implementationIntent = TransactionIntent.noManagedTransaction; + break; + } + } + try { + if (outbound) { + result = helper.handlesOutbound(interactionIntent, implementationIntent, invocation); + } else { + result = helper.handlesInbound(interactionIntent, implementationIntent, invocation); + } + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return result; + } + + private static class TransactionalInvocation implements TransactionalAction { + private final Invoker invoker; + private final Message message; + + public TransactionalInvocation(Invoker invoker, Message message) { + super(); + this.invoker = invoker; + this.message = message; + } + + public Message run() throws Exception { + return invoker.invoke(message); + } + + } + +} diff --git a/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionManagerHelper.java b/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionManagerHelper.java new file mode 100644 index 0000000000..defe12967e --- /dev/null +++ b/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionManagerHelper.java @@ -0,0 +1,243 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.policy.transaction; + +import java.lang.reflect.InvocationTargetException; + +import javax.transaction.HeuristicMixedException; +import javax.transaction.HeuristicRollbackException; +import javax.transaction.InvalidTransactionException; +import javax.transaction.NotSupportedException; +import javax.transaction.RollbackException; +import javax.transaction.Status; +import javax.transaction.SystemException; +import javax.transaction.Transaction; +import javax.transaction.TransactionManager; + +/** + * @version $Rev$ $Date$ + */ +public class TransactionManagerHelper { + // private static final Logger logger = Logger.getLogger(TransactionManagerHelper.class.getName()); + + private TransactionManager tm; + + public TransactionManagerHelper(TransactionManager tm) { + super(); + this.tm = tm; + } + + public Transaction managedGlobalTransactionPreInvoke() throws SystemException, NotSupportedException { + int status = tm.getStatus(); + if (status == Status.STATUS_COMMITTED || status == Status.STATUS_NO_TRANSACTION + || status == Status.STATUS_ROLLEDBACK) { + tm.begin(); + return tm.getTransaction(); + } + return null; + } + + public void managedGlobalTransactionPostInvoke(Transaction created, boolean rollback) + throws InvalidTransactionException, IllegalStateException, SystemException, SecurityException, + HeuristicMixedException, HeuristicRollbackException, RollbackException { + if (created != null) { + int status = created.getStatus(); + if (status == Status.STATUS_MARKED_ROLLBACK) { + created.rollback(); + } else if (status == Status.STATUS_ACTIVE) { + if (rollback) { + created.rollback(); + } else { + created.commit(); + } + } + } + } + + public Transaction suspendsTransactionPreInvoke() throws SystemException { + if (tm.getTransaction() != null) { + return tm.suspend(); + } else { + return null; + } + } + + public void suspendsTransactionPostInvoke(Transaction suspended) throws InvalidTransactionException, + IllegalStateException, SystemException { + if (suspended != null) { + tm.resume(suspended); + } + } + + public TransactionManager getTransactionManager() { + return tm; + } + + public void setTransactionManager(TransactionManager tm) { + this.tm = tm; + } + + public void validateOneway(TransactionIntent onewayIntent, TransactionIntent implIntent) + throws IncompatibleIntentException { + if (onewayIntent == TransactionIntent.transactedOneWay) { + if (implIntent != TransactionIntent.managedTransactionGlobal) { + throw new IncompatibleIntentException(onewayIntent + "<-X->" + implIntent); + } + } + } + + public void validateInbound(TransactionIntent serviceIntent, TransactionIntent implIntent) + throws IncompatibleIntentException { + if (serviceIntent == TransactionIntent.propagatesTransacton) { + if (implIntent != TransactionIntent.managedTransactionGlobal) { + throw new IncompatibleIntentException(serviceIntent + "<-X->" + implIntent); + } + } + } + + public void validateOutbound(TransactionIntent referenceIntent, TransactionIntent implIntent) + throws IncompatibleIntentException { + if (referenceIntent == TransactionIntent.propagatesTransacton) { + if (implIntent != TransactionIntent.managedTransactionGlobal) { + throw new IncompatibleIntentException(referenceIntent + "<-X->" + implIntent); + } + } + } + + public T handlesOutbound(TransactionIntent referenceIntent, + TransactionIntent implIntent, + TransactionalAction action) throws Exception { + + if (implIntent == null) { + implIntent = TransactionIntent.noManagedTransaction; + } + + if (referenceIntent == TransactionIntent.propagatesTransacton) { + if (implIntent != TransactionIntent.managedTransactionGlobal) { + throw new IncompatibleIntentException(referenceIntent + "<-X->" + implIntent); + } else { + // propagates the current TX + return run(action); + } + } else if (referenceIntent == TransactionIntent.suspendsTransaction) { + Transaction tx = suspendsTransactionPreInvoke(); + try { + return run(action); + } finally { + suspendsTransactionPostInvoke(tx); + } + } else { + return run(action); + } + } + + private T run(TransactionalAction action) throws Exception { + // Make sure a global TX is in place + Transaction tx = managedGlobalTransactionPreInvoke(); + boolean rollback = false; + try { + return action.run(); + } catch (InvocationTargetException e) { + throw e; + } catch (Throwable e) { + rollback = true; + if (e instanceof Error) { + throw (Error)e; + } else if (e instanceof RuntimeException) { + throw (RuntimeException)e; + } else { + throw (Exception)e; + } + } finally { + managedGlobalTransactionPostInvoke(tx, rollback); + } + } + + public T handlesInbound(TransactionIntent serviceIntent, + TransactionIntent implIntent, + TransactionalAction action) throws Exception { + if (serviceIntent == null && implIntent == null) { + return run(action); + } + + if (implIntent == null) { + implIntent = TransactionIntent.noManagedTransaction; + } + + if (serviceIntent == TransactionIntent.propagatesTransacton) { + if (implIntent != TransactionIntent.managedTransactionGlobal) { + throw new IncompatibleIntentException(serviceIntent + "<-X->" + implIntent); + } else { + return run(action); + } + } else if (serviceIntent == TransactionIntent.suspendsTransaction) { + Transaction tx1 = suspendsTransactionPreInvoke(); + try { + if (implIntent == TransactionIntent.managedTransactionGlobal) { + return run(action); + } else { + return action.run(); + } + } finally { + suspendsTransactionPostInvoke(tx1); + } + } else { + if (implIntent == TransactionIntent.managedTransactionGlobal) { + // Start a new TX + return run(action); + } else { + return action.run(); + } + } + } + + public void handlesOneWay(TransactionIntent onewayIntent, + TransactionIntent implIntent, + TransactionalAction action) throws Exception { + if (implIntent == null) { + implIntent = TransactionIntent.noManagedTransaction; + } + + if (onewayIntent == null) { + // Assume transactedOneWay + run(action); + return; + } + + if (onewayIntent == TransactionIntent.transactedOneWay) { + if (implIntent != TransactionIntent.managedTransactionGlobal) { + throw new IncompatibleIntentException(onewayIntent + "<-X->" + implIntent); + } else { + run(action); + return; + } + } else { + // TransactionIntent.immediateOneWay + Transaction tx = suspendsTransactionPreInvoke(); + try { + run(action); + return; + } finally { + suspendsTransactionPostInvoke(tx); + } + } + } + +} diff --git a/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionManagerWrapper.java b/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionManagerWrapper.java new file mode 100644 index 0000000000..31beab4fca --- /dev/null +++ b/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionManagerWrapper.java @@ -0,0 +1,90 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.policy.transaction; + +import java.io.File; + +import javax.transaction.TransactionManager; + +import org.apache.geronimo.transaction.log.HOWLLog; +import org.apache.geronimo.transaction.manager.GeronimoTransactionManager; +import org.apache.geronimo.transaction.manager.XidFactory; +import org.apache.geronimo.transaction.manager.XidFactoryImpl; + +/** + * @version $Rev$ $Date$ + */ +public class TransactionManagerWrapper { + private TransactionManager transactionManager; + private HOWLLog howlLog; + + private String logFileDir = "target/logs"; + private String bufferClassName = "org.objectweb.howl.log.BlockLogBuffer"; + private int bufferSizeKBytes = 32; + private boolean checksumEnabled = true; + private boolean adler32Checksum = true; + private int flushSleepTimeMilliseconds = 50; + private String logFileExt = "log"; + private String logFileName = "transaction"; + private int maxBlocksPerFile = -1; + private int maxLogFiles = 2; + private int maxBuffers = 0; + private int minBuffers = 4; + private int threadsWaitingForceThreshold = -1; + private File serverBaseDir = new File(System.getProperty("basedir", System.getProperty("user.dir"))); + + public TransactionManagerWrapper() { + super(); + } + + public void start() { + try { + XidFactory xidFactory = new XidFactoryImpl(); + howlLog = + new HOWLLog(bufferClassName, bufferSizeKBytes, checksumEnabled, adler32Checksum, + flushSleepTimeMilliseconds, logFileDir, logFileExt, logFileName, maxBlocksPerFile, + maxBuffers, maxLogFiles, minBuffers, threadsWaitingForceThreshold, xidFactory, + serverBaseDir); + + howlLog.doStart(); + transactionManager = new GeronimoTransactionManager(1200, xidFactory, howlLog); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + + /** + * @see org.apache.tuscany.sca.core.ModuleActivator#stop(org.apache.tuscany.sca.core.ExtensionPointRegistry) + */ + public void stop() { + try { + if (howlLog != null) { + howlLog.doStop(); + } + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + + public TransactionManager getTransactionManager() { + return transactionManager; + } + +} diff --git a/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionModuleActivator.java b/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionModuleActivator.java new file mode 100644 index 0000000000..3339f2e338 --- /dev/null +++ b/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionModuleActivator.java @@ -0,0 +1,84 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.policy.transaction; + +import javax.transaction.TransactionManager; + +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.core.ModuleActivator; +import org.apache.tuscany.sca.core.UtilityExtensionPoint; + +/** + * @version $Rev$ $Date$ + */ +public class TransactionModuleActivator implements ModuleActivator { + private TransactionManagerWrapper wrapper; + + /** + * @see org.apache.tuscany.sca.core.ModuleActivator#start(org.apache.tuscany.sca.core.ExtensionPointRegistry) + */ + public void start(ExtensionPointRegistry registry) { + if (registry != null) { + UtilityExtensionPoint utilities = registry.getExtensionPoint(UtilityExtensionPoint.class); + TransactionManager transactionManager = utilities.getUtility(TransactionManager.class); + if (transactionManager != null) { + // The transaction manage is provided by the hosting environment +// RuntimeWireProcessorExtensionPoint wireProcessorExtensionPoint = +// registry.getExtensionPoint(RuntimeWireProcessorExtensionPoint.class); +// TransactionManagerHelper helper = new TransactionManagerHelper(transactionManager); +// wireProcessorExtensionPoint.addWireProcessor(new TransactionRuntimeWireProcessor(helper)); + return; + } + } + try { + wrapper = new TransactionManagerWrapper(); + wrapper.start(); + } catch (Exception e) { + throw new IllegalStateException(e); + } + if (registry != null) { + UtilityExtensionPoint utilities = registry.getExtensionPoint(UtilityExtensionPoint.class); + utilities.addUtility(wrapper.getTransactionManager()); +// RuntimeWireProcessorExtensionPoint wireProcessorExtensionPoint = +// registry.getExtensionPoint(RuntimeWireProcessorExtensionPoint.class); +// TransactionManagerHelper helper = new TransactionManagerHelper(wrapper.getTransactionManager()); +// wireProcessorExtensionPoint.addWireProcessor(new TransactionRuntimeWireProcessor(helper)); + } + } + + /** + * @see org.apache.tuscany.sca.core.ModuleActivator#stop(org.apache.tuscany.sca.core.ExtensionPointRegistry) + */ + public void stop(ExtensionPointRegistry registry) { + try { + if (wrapper != null) { + wrapper.stop(); + wrapper = null; + } + if (registry != null && wrapper != null) { + UtilityExtensionPoint utilities = registry.getExtensionPoint(UtilityExtensionPoint.class); + utilities.removeUtility(wrapper.getTransactionManager()); + } + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + +} diff --git a/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionPolicy.java b/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionPolicy.java new file mode 100644 index 0000000000..3a397e10d0 --- /dev/null +++ b/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionPolicy.java @@ -0,0 +1,46 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.policy.transaction; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.policy.Policy; + +/** + * The model for Tuscany transaction policy + * + * @version $Rev$ $Date$ + */ +public interface TransactionPolicy extends Policy { + String SCA10_TUSCANY_NS = "http://tuscany.apache.org/xmlns/sca/1.0"; + QName NAME = new QName(SCA10_TUSCANY_NS, "transactionPolicy"); + + enum Action { + PROPAGATE, SUSPEND, REQUIRE_GLOBAL, REQUIRE_LOCAL, REQUIRE_NONE + }; + + int getTransactionTimeout(); + + void setTransactionTimeout(int seconds); + + void setAction(Action action); + + Action getAction(); +} diff --git a/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionPolicyDefinitionsProvider.java b/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionPolicyDefinitionsProvider.java new file mode 100644 index 0000000000..0dfa986177 --- /dev/null +++ b/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionPolicyDefinitionsProvider.java @@ -0,0 +1,71 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.policy.transaction; + +import java.net.URI; +import java.net.URL; + +import org.apache.tuscany.sca.contribution.processor.URLArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.URLArtifactProcessorExtensionPoint; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.definitions.Definitions; +import org.apache.tuscany.sca.definitions.util.DefinitionsUtil; +import org.apache.tuscany.sca.provider.DefinitionsProvider; +import org.apache.tuscany.sca.provider.DefinitionsProviderException; + +/** + * Provider for Policy Intents and PolicySet definitions related to transaction + * + * @version $Rev$ $Date$ + */ +public class TransactionPolicyDefinitionsProvider implements DefinitionsProvider { + private static final String scaDefinitionsFile = "definitions.xml"; + private static final String tuscanyDefinitionsFile = "tuscany_definitions.xml"; + private URLArtifactProcessor urlArtifactProcessor; + + public TransactionPolicyDefinitionsProvider(ExtensionPointRegistry registry) { + URLArtifactProcessorExtensionPoint documentProcessors = + registry.getExtensionPoint(URLArtifactProcessorExtensionPoint.class); + urlArtifactProcessor = (URLArtifactProcessor)documentProcessors.getProcessor(Definitions.class); + } + + public Definitions getDefinitions() throws DefinitionsProviderException { + + try { + Definitions scaTransactionPolicyDefns = null; + Definitions tuscanyTransactionPolicyDefns = null; + + URI uri = new URI(scaDefinitionsFile); + URL defintionsFileUrl = getClass().getResource(scaDefinitionsFile); + scaTransactionPolicyDefns = (Definitions)urlArtifactProcessor.read(null, uri, defintionsFileUrl); + + uri = new URI(tuscanyDefinitionsFile); + defintionsFileUrl = getClass().getResource(tuscanyDefinitionsFile); + tuscanyTransactionPolicyDefns = (Definitions)urlArtifactProcessor.read(null, uri, defintionsFileUrl); + + DefinitionsUtil.aggregate(tuscanyTransactionPolicyDefns, scaTransactionPolicyDefns); + + return scaTransactionPolicyDefns; + } catch (Exception e) { + throw new DefinitionsProviderException(e); + } + } + +} diff --git a/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionPolicyImpl.java b/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionPolicyImpl.java new file mode 100644 index 0000000000..f178876a72 --- /dev/null +++ b/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionPolicyImpl.java @@ -0,0 +1,59 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.policy.transaction; + +import javax.xml.namespace.QName; + +/** + * @version $Rev$ $Date$ + */ +public class TransactionPolicyImpl implements TransactionPolicy { + private boolean unresolved; + private int transactionTimeout = 1200; + private Action action = Action.PROPAGATE; + + public int getTransactionTimeout() { + return transactionTimeout; + } + + public void setTransactionTimeout(int transactionTimeout) { + this.transactionTimeout = transactionTimeout; + } + + public Action getAction() { + return action; + } + + public void setAction(Action policy) { + this.action = policy; + } + + public QName getSchemaName() { + return NAME; + } + + public boolean isUnresolved() { + return unresolved; + } + + public void setUnresolved(boolean unresolved) { + this.unresolved = unresolved; + } +} diff --git a/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionPolicyProcessor.java b/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionPolicyProcessor.java new file mode 100644 index 0000000000..831cd13914 --- /dev/null +++ b/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionPolicyProcessor.java @@ -0,0 +1,96 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.policy.transaction; + +import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; +import static javax.xml.stream.XMLStreamConstants.START_ELEMENT; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; + +import org.apache.tuscany.sca.contribution.processor.ContributionReadException; +import org.apache.tuscany.sca.contribution.processor.ContributionResolveException; +import org.apache.tuscany.sca.contribution.processor.ContributionWriteException; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.core.FactoryExtensionPoint; +import org.apache.tuscany.sca.monitor.Monitor; + +/** + * @version $Rev$ $Date$ + */ +public class TransactionPolicyProcessor implements StAXArtifactProcessor { + public static final String TIMEOUT = "transactionTimeout"; + public static final String ACTION = "action"; + + public QName getArtifactType() { + return TransactionPolicy.NAME; + } + + public TransactionPolicyProcessor(FactoryExtensionPoint modelFactories, Monitor monitor) { + } + + public TransactionPolicy read(XMLStreamReader reader) throws ContributionReadException, XMLStreamException { + TransactionPolicy txPolicy = new TransactionPolicyImpl(); + int event = reader.getEventType(); + while (reader.hasNext()) { + event = reader.getEventType(); + switch (event) { + case START_ELEMENT: { + String timeout = reader.getAttributeValue(null, TIMEOUT); + if (timeout != null) { + txPolicy.setTransactionTimeout(Integer.parseInt(timeout)); + } + String action = reader.getAttributeValue(null, ACTION); + if (action != null) { + txPolicy.setAction(TransactionPolicy.Action.valueOf(action)); + } + break; + } + } + + if (event == END_ELEMENT) { + if (TransactionPolicy.NAME.equals(reader.getName())) { + break; + } + } + + //Read the next element + if (reader.hasNext()) { + reader.next(); + } + } + + return txPolicy; + } + + public void write(TransactionPolicy policy, XMLStreamWriter writer) throws ContributionWriteException, + XMLStreamException { + } + + public Class getModelType() { + return TransactionPolicy.class; + } + + public void resolve(TransactionPolicy policy, ModelResolver resolver) throws ContributionResolveException { + + } +} diff --git a/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionPolicyProviderFactory.java b/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionPolicyProviderFactory.java new file mode 100644 index 0000000000..be97090378 --- /dev/null +++ b/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionPolicyProviderFactory.java @@ -0,0 +1,92 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.policy.transaction; + +import javax.transaction.TransactionManager; + +import org.apache.tuscany.sca.assembly.Binding; +import org.apache.tuscany.sca.assembly.Implementation; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.core.UtilityExtensionPoint; +import org.apache.tuscany.sca.policy.PolicySetAttachPoint; +import org.apache.tuscany.sca.provider.PolicyProvider; +import org.apache.tuscany.sca.provider.PolicyProviderFactory; +import org.apache.tuscany.sca.runtime.RuntimeComponent; +import org.apache.tuscany.sca.runtime.RuntimeComponentReference; +import org.apache.tuscany.sca.runtime.RuntimeComponentService; + +/** + * @version $Rev$ $Date$ + */ +public class TransactionPolicyProviderFactory implements PolicyProviderFactory { + private TransactionManagerHelper helper; + + public TransactionPolicyProviderFactory(ExtensionPointRegistry registry) { + super(); + UtilityExtensionPoint utilities = registry.getExtensionPoint(UtilityExtensionPoint.class); + TransactionManager tm = utilities.getUtility(TransactionManager.class); + this.helper = new TransactionManagerHelper(tm); + } + + /** + * @see org.apache.tuscany.sca.provider.PolicyProviderFactory#createImplementationPolicyProvider(org.apache.tuscany.sca.runtime.RuntimeComponent, org.apache.tuscany.sca.assembly.Implementation) + */ + public PolicyProvider createImplementationPolicyProvider(RuntimeComponent component, Implementation implementation) { + if (component instanceof PolicySetAttachPoint) { + return new TransactionImplementationPolicyProvider(helper, (PolicySetAttachPoint)component); + } else { + return null; + } + } + + /** + * @see org.apache.tuscany.sca.provider.PolicyProviderFactory#createReferencePolicyProvider(org.apache.tuscany.sca.runtime.RuntimeComponent, org.apache.tuscany.sca.runtime.RuntimeComponentReference, org.apache.tuscany.sca.assembly.Binding) + */ + public PolicyProvider createReferencePolicyProvider(RuntimeComponent component, + RuntimeComponentReference reference, + Binding binding) { + if (binding instanceof PolicySetAttachPoint) { + return new TransactionReferencePolicyProvider(helper, (PolicySetAttachPoint)binding); + } else { + return null; + } + } + + /** + * @see org.apache.tuscany.sca.provider.PolicyProviderFactory#createServicePolicyProvider(org.apache.tuscany.sca.runtime.RuntimeComponent, org.apache.tuscany.sca.runtime.RuntimeComponentService, org.apache.tuscany.sca.assembly.Binding) + */ + public PolicyProvider createServicePolicyProvider(RuntimeComponent component, + RuntimeComponentService service, + Binding binding) { + if (binding instanceof PolicySetAttachPoint) { + return new TransactionServicePolicyProvider(helper, (PolicySetAttachPoint)binding); + } else { + return null; + } + } + + /** + * @see org.apache.tuscany.sca.provider.ProviderFactory#getModelType() + */ + public Class getModelType() { + return TransactionPolicy.class; + } + +} diff --git a/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionReferencePolicyProvider.java b/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionReferencePolicyProvider.java new file mode 100644 index 0000000000..0795a4e5cf --- /dev/null +++ b/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionReferencePolicyProvider.java @@ -0,0 +1,61 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.policy.transaction; + +import java.util.List; + +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.Phase; +import org.apache.tuscany.sca.policy.PolicySet; +import org.apache.tuscany.sca.policy.PolicySetAttachPoint; +import org.apache.tuscany.sca.provider.PolicyProvider; + +/** + * @version $Rev$ $Date$ + */ +public class TransactionReferencePolicyProvider implements PolicyProvider { + private TransactionManagerHelper helper; + private List policySets; + + public TransactionReferencePolicyProvider(TransactionManagerHelper helper, PolicySetAttachPoint attachPoint) { + super(); + this.helper = helper; + this.policySets = attachPoint.getApplicablePolicySets(); + } + + public Interceptor createInterceptor(Operation operation) { + for (PolicySet policySet : policySets) { + for (Object p : policySet.getPolicies()) { + if (p instanceof TransactionPolicy) { + TransactionInterceptor interceptor = + new TransactionInterceptor(helper, true, (TransactionPolicy)p, null); + return interceptor; + } + } + } + return null; + } + + public String getPhase() { + return Phase.REFERENCE_POLICY; + } + +} diff --git a/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionServicePolicyProvider.java b/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionServicePolicyProvider.java new file mode 100644 index 0000000000..9f9088a380 --- /dev/null +++ b/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionServicePolicyProvider.java @@ -0,0 +1,61 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.policy.transaction; + +import java.util.List; + +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.invocation.Interceptor; +import org.apache.tuscany.sca.invocation.Phase; +import org.apache.tuscany.sca.policy.PolicySet; +import org.apache.tuscany.sca.policy.PolicySetAttachPoint; +import org.apache.tuscany.sca.provider.PolicyProvider; + +/** + * @version $Rev$ $Date$ + */ +public class TransactionServicePolicyProvider implements PolicyProvider { + private TransactionManagerHelper helper; + private List policySets; + + public TransactionServicePolicyProvider(TransactionManagerHelper helper, PolicySetAttachPoint attachPoint) { + super(); + this.helper = helper; + this.policySets = attachPoint.getApplicablePolicySets(); + } + + public Interceptor createInterceptor(Operation operation) { + for (PolicySet policySet : policySets) { + for (Object p : policySet.getPolicies()) { + if (p instanceof TransactionPolicy) { + TransactionInterceptor interceptor = + new TransactionInterceptor(helper, true, (TransactionPolicy)p, null); + return interceptor; + } + } + } + return null; + } + + public String getPhase() { + return Phase.SERVICE_POLICY; + } + +} diff --git a/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionalAction.java b/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionalAction.java new file mode 100644 index 0000000000..5a7ae5c4cc --- /dev/null +++ b/java/sca/contrib/modules/policy-transaction/src/main/java/org/apache/tuscany/sca/policy/transaction/TransactionalAction.java @@ -0,0 +1,31 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.policy.transaction; + +/** + * @version $Rev$ $Date$ + */ +public interface TransactionalAction { + /** + * @return + * @throws Exception + */ + T run() throws Exception; +} diff --git a/java/sca/contrib/modules/policy-transaction/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor b/java/sca/contrib/modules/policy-transaction/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor new file mode 100644 index 0000000000..1d034e23a2 --- /dev/null +++ b/java/sca/contrib/modules/policy-transaction/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for the artifact processor extension +org.apache.tuscany.sca.policy.transaction.TransactionPolicyProcessor;qname=http://tuscany.apache.org/xmlns/sca/1.0#transactionPolicy,model=org.apache.tuscany.sca.policy.transaction.TransactionPolicy \ No newline at end of file diff --git a/java/sca/contrib/modules/policy-transaction/src/main/resources/META-INF/services/org.apache.tuscany.sca.core.ModuleActivator b/java/sca/contrib/modules/policy-transaction/src/main/resources/META-INF/services/org.apache.tuscany.sca.core.ModuleActivator new file mode 100644 index 0000000000..9a35d62cad --- /dev/null +++ b/java/sca/contrib/modules/policy-transaction/src/main/resources/META-INF/services/org.apache.tuscany.sca.core.ModuleActivator @@ -0,0 +1,18 @@ +# 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. +# Implementation class for the ModuleActivator +org.apache.tuscany.sca.policy.transaction.TransactionModuleActivator diff --git a/java/sca/contrib/modules/policy-transaction/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.DefinitionsProvider b/java/sca/contrib/modules/policy-transaction/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.DefinitionsProvider new file mode 100644 index 0000000000..e9d9fab519 --- /dev/null +++ b/java/sca/contrib/modules/policy-transaction/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.DefinitionsProvider @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for SCA Definitions Providers +org.apache.tuscany.sca.policy.transaction.TransactionPolicyDefinitionsProvider \ No newline at end of file diff --git a/java/sca/contrib/modules/policy-transaction/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.PolicyProviderFactory b/java/sca/contrib/modules/policy-transaction/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.PolicyProviderFactory new file mode 100644 index 0000000000..eeec814f60 --- /dev/null +++ b/java/sca/contrib/modules/policy-transaction/src/main/resources/META-INF/services/org.apache.tuscany.sca.provider.PolicyProviderFactory @@ -0,0 +1,19 @@ +# 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. + +# Implementation class for the policy extension +org.apache.tuscany.sca.policy.transaction.TransactionPolicyProviderFactory;model=org.apache.tuscany.sca.policy.transaction.TransactionPolicy diff --git a/java/sca/contrib/modules/policy-transaction/src/main/resources/log4j.properties b/java/sca/contrib/modules/policy-transaction/src/main/resources/log4j.properties new file mode 100644 index 0000000000..698ee41d7e --- /dev/null +++ b/java/sca/contrib/modules/policy-transaction/src/main/resources/log4j.properties @@ -0,0 +1,29 @@ +# 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. +# +# Set root logger level to DEBUG and its only appender to A1. +log4j.rootLogger=INFO, CONSOLE + +# CONSOLE is set to be a ConsoleAppender. +log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender + +# A1 uses PatternLayout. +log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout + + +# Print only messages of level WARN or above in the package com.foo. +log4j.logger.org.apache.tuscany=INFO \ No newline at end of file diff --git a/java/sca/contrib/modules/policy-transaction/src/main/resources/org/apache/tuscany/sca/policy/transaction/definitions.xml b/java/sca/contrib/modules/policy-transaction/src/main/resources/org/apache/tuscany/sca/policy/transaction/definitions.xml new file mode 100644 index 0000000000..ff51b131b7 --- /dev/null +++ b/java/sca/contrib/modules/policy-transaction/src/main/resources/org/apache/tuscany/sca/policy/transaction/definitions.xml @@ -0,0 +1,66 @@ + + + + + + Used to indicate the transaction environment desired by a component implementation. + + + + Used to indicate that a component implementation requires a managed global transaction. + + + + + Used to indicate that a component implementation requires a managed local transaction. + + + + + Used to indicate that a component implementation will manage its own transaction resources. + + + + + Used to indicate that a reference will propagate any client transaction or that a service will be dispatched + under any received transaction. + + + + + Used to indicate that a reference will not propagate any client transaction or that a service will not be + dispatched under any received transaction. + + + + + Used to indicate that the component requires the SCA runtime to transact OneWay send of messages as part of + any client global transaction or to transact oneWay message receipt as part of any service global + transaction. + + + + + Used to indicate that the component requires the SCA runtime to process the sending or receiving of OneWay + messages immediately, regardless of any transaction under which the sending/receiving component runs. + + + \ No newline at end of file diff --git a/java/sca/contrib/modules/policy-transaction/src/main/resources/org/apache/tuscany/sca/policy/transaction/tuscany_definitions.xml b/java/sca/contrib/modules/policy-transaction/src/main/resources/org/apache/tuscany/sca/policy/transaction/tuscany_definitions.xml new file mode 100644 index 0000000000..324fa03da6 --- /dev/null +++ b/java/sca/contrib/modules/policy-transaction/src/main/resources/org/apache/tuscany/sca/policy/transaction/tuscany_definitions.xml @@ -0,0 +1,54 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/java/sca/contrib/modules/policy-transaction/src/test/java/org/apache/tuscany/sca/policy/transaction/PolicyReadTestCase.java b/java/sca/contrib/modules/policy-transaction/src/test/java/org/apache/tuscany/sca/policy/transaction/PolicyReadTestCase.java new file mode 100644 index 0000000000..e8560d775d --- /dev/null +++ b/java/sca/contrib/modules/policy-transaction/src/test/java/org/apache/tuscany/sca/policy/transaction/PolicyReadTestCase.java @@ -0,0 +1,54 @@ +/* + * 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. + */ +package org.apache.tuscany.sca.policy.transaction; + +import java.io.InputStream; +import java.net.URL; + +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamReader; + +import junit.framework.TestCase; + +/** + * Test the reading of ws config params policy. + * + * @version $Rev$ $Date$ + */ +public class PolicyReadTestCase extends TestCase { + + @Override + public void setUp() throws Exception { + } + + public void testPolicyReading() throws Exception { + + TransactionPolicyProcessor processor = new TransactionPolicyProcessor(null, null); + + URL url = getClass().getResource("/org/apache/tuscany/sca/policy/transaction/tuscany_definitions.xml"); + XMLInputFactory inputFactory = XMLInputFactory.newInstance(); + + InputStream urlStream = url.openStream(); + XMLStreamReader reader = inputFactory.createXMLStreamReader(urlStream); + + TransactionPolicy policy = processor.read(reader); + assertEquals(1200, policy.getTransactionTimeout()); + } + +} diff --git a/java/sca/contrib/modules/policy-transaction/src/test/java/org/apache/tuscany/sca/policy/transaction/TransactionManagerHelperTestCase.java b/java/sca/contrib/modules/policy-transaction/src/test/java/org/apache/tuscany/sca/policy/transaction/TransactionManagerHelperTestCase.java new file mode 100644 index 0000000000..544e0f68c0 --- /dev/null +++ b/java/sca/contrib/modules/policy-transaction/src/test/java/org/apache/tuscany/sca/policy/transaction/TransactionManagerHelperTestCase.java @@ -0,0 +1,194 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.policy.transaction; + +import java.util.logging.Logger; + +import javax.transaction.Transaction; +import javax.transaction.TransactionManager; +import javax.transaction.xa.XAException; +import javax.transaction.xa.XAResource; +import javax.transaction.xa.Xid; + +import junit.framework.TestCase; + +import org.apache.geronimo.transaction.manager.NamedXAResource; + +/** + * @version $Rev$ $Date$ + */ +public class TransactionManagerHelperTestCase extends TestCase { + private static final Logger logger = Logger.getLogger(TransactionManagerHelper.class.getName()); + + public static class MockXAResource implements NamedXAResource { + + private String rm; + private String id; + private int timeout = 1000; + + public MockXAResource(String rm, String id) { + super(); + this.rm = rm; + this.id = id; + } + + public String getName() { + return rm + ":" + id; + } + + public void commit(Xid xid, boolean onePhase) throws XAException { + logger.info(id + ": commit(" + xid + "," + onePhase + ")"); + } + + public void end(Xid xid, int flags) throws XAException { + logger.info(id + ": end(" + xid + "," + toString(flags) + ")"); + } + + public void forget(Xid xid) throws XAException { + logger.info(id + ": forget(" + xid + ")"); + } + + public int getTransactionTimeout() throws XAException { + return timeout; + } + + public boolean isSameRM(XAResource xares) throws XAException { + if (xares instanceof MockXAResource) { + MockXAResource res = (MockXAResource)xares; + return res.rm.endsWith(rm); + } else { + return false; + } + } + + public int prepare(Xid xid) throws XAException { + logger.info(id + ": prepare(" + xid + ")"); + return XA_OK; + } + + public Xid[] recover(int flag) throws XAException { + return null; + } + + public void rollback(Xid xid) throws XAException { + logger.info(id + ": rollback(" + xid + ")"); + } + + public boolean setTransactionTimeout(int seconds) throws XAException { + this.timeout = seconds; + return true; + } + + public void start(Xid xid, int flags) throws XAException { + logger.info(id + ": start(" + xid + "," + toString(flags) + ")"); + } + + private String toString(int flags) { + StringBuffer sb = new StringBuffer(); + if ((flags & TMENDRSCAN) != 0) { + sb.append("TMENDRSCAN "); + } + if ((flags & TMFAIL) != 0) { + sb.append("TMFAIL "); + } + if ((flags & TMJOIN) != 0) { + sb.append("TMJOIN "); + } + if ((flags & TMONEPHASE) != 0) { + sb.append("TMONEPHASE "); + } + if ((flags & TMRESUME) != 0) { + sb.append("TMRESUME "); + } + if ((flags & TMSTARTRSCAN) != 0) { + sb.append("TMSTARTRSCAN "); + } + if ((flags & TMSUCCESS) != 0) { + sb.append("TMSUCCESS "); + } + if ((flags & TMSUSPEND) != 0) { + sb.append("TMSUSPEND "); + } + if (sb.length() == 0) { + sb.append("TMNOFLAGS"); + } else { + sb.deleteCharAt(sb.length() - 1); + } + return sb.toString(); + } + + } + + public void testHelper() throws Exception { + TransactionManagerWrapper activator = new TransactionManagerWrapper(); + activator.start(); + TransactionManager tm = activator.getTransactionManager(); + // GeronimoUserTransaction tx = new GeronimoUserTransaction(tm); + TransactionManagerHelper helper = new TransactionManagerHelper(tm); + + // No TX yet + assertNull(tm.getTransaction()); + Transaction t1 = helper.managedGlobalTransactionPreInvoke(); + // Should create T1 + assertNotNull(t1); + // The current TX should be T1 + assertSame(t1, tm.getTransaction()); + + XAResource res1 = new MockXAResource("Derby", "001"); + XAResource res2 = new MockXAResource("DB2", "002"); + tm.getTransaction().enlistResource(res1); + tm.getTransaction().enlistResource(res2); + + Transaction suspended = helper.suspendsTransactionPreInvoke(); + suspended.delistResource(res1, XAResource.TMSUSPEND); + suspended.delistResource(res2, XAResource.TMSUSPEND); + + // T1 is suspended + assertSame(t1, suspended); + // No more active TX + assertNull(tm.getTransaction()); + + Transaction t2 = helper.managedGlobalTransactionPreInvoke(); + assertNotNull(t2); + // The current TX should be T2 + assertSame(t2, tm.getTransaction()); + + XAResource res3 = new MockXAResource("Oracle", "003"); + tm.getTransaction().enlistResource(res3); + + tm.getTransaction().delistResource(res3, XAResource.TMSUCCESS); + tm.rollback(); + + // Skip post + // helper.managedGlobalTransactionPostInvoke(t2); + + helper.suspendsTransactionPostInvoke(suspended); + suspended.enlistResource(res1); + suspended.enlistResource(res2); + // T1 is now resumed + assertSame(t1, tm.getTransaction()); + + helper.managedGlobalTransactionPostInvoke(t1, false); + assertNotNull(tm.getTransaction()); + assertEquals(6, t1.getStatus()); + + activator.stop(); + } +} diff --git a/java/sca/contrib/modules/tracing-aspectj/LICENSE b/java/sca/contrib/modules/tracing-aspectj/LICENSE new file mode 100644 index 0000000000..6e529a25c4 --- /dev/null +++ b/java/sca/contrib/modules/tracing-aspectj/LICENSE @@ -0,0 +1,205 @@ + + 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: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) 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 + + (d) 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. + + + diff --git a/java/sca/contrib/modules/tracing-aspectj/META-INF/MANIFEST.MF b/java/sca/contrib/modules/tracing-aspectj/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..5a415a3fe4 --- /dev/null +++ b/java/sca/contrib/modules/tracing-aspectj/META-INF/MANIFEST.MF @@ -0,0 +1,22 @@ +Manifest-Version: 1.0 +Private-Package: org.apache.tuscany.sca.aspectj;version="2.0.0" +Tool: Bnd-0.0.255 +Bundle-Name: Apache Tuscany AOP-based Logging and Tracing +Created-By: 1.6.0_07 (Sun Microsystems Inc.) +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bnd-LastModified: 1225397489546 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: The Apache Software Foundation provides support fo + r the Apache community of open-source software projects. The Apach + e projects are characterized by a collaborative, consensus based deve + lopment process, an open and pragmatic software license, and a des + ire to create high quality software that leads the way in its field. + We consider ourselves not simply a group of projects sharing a ser + ver, but rather a community of developers and users. +Import-Package: org.aspectj.lang,org.aspectj.lang.annotation,org.aspec + tj.lang.reflect +Bundle-SymbolicName: org.apache.tuscany.sca.tracing.aspect +Bundle-DocURL: http://www.apache.org/ + diff --git a/java/sca/contrib/modules/tracing-aspectj/NOTICE b/java/sca/contrib/modules/tracing-aspectj/NOTICE new file mode 100644 index 0000000000..51042eab05 --- /dev/null +++ b/java/sca/contrib/modules/tracing-aspectj/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/java/sca/contrib/modules/tracing-aspectj/launcher.bat b/java/sca/contrib/modules/tracing-aspectj/launcher.bat new file mode 100644 index 0000000000..a5305f486d --- /dev/null +++ b/java/sca/contrib/modules/tracing-aspectj/launcher.bat @@ -0,0 +1,5 @@ +@echo off +set TUSCANY_HOME=C:\Apache\tuscany-sca-1.3 +set ASPECTJ_WEAVER=%HOMEPATH%\.m2\repository\org\aspectj\aspectjweaver\1.6.1\aspectjweaver-1.6.1.jar +set CP=%ASPECTJ_WEAVER%;%TUSCANY_HOME%\lib\tuscany-sca-manifest.jar;%TUSCANY_HOME%\samples\calculator\target\sample-calculator.jar +java -javaagent:"%ASPECTJ_WEAVER%" -cp "%CP%;target\classes" calculator.CalculatorClient \ No newline at end of file diff --git a/java/sca/contrib/modules/tracing-aspectj/pom.xml b/java/sca/contrib/modules/tracing-aspectj/pom.xml new file mode 100644 index 0000000000..d96d1ef8d6 --- /dev/null +++ b/java/sca/contrib/modules/tracing-aspectj/pom.xml @@ -0,0 +1,98 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0-SNAPSHOT + ../pom.xml + + tuscany-tracing-aspectj + Apache Tuscany AOP-based Logging and Tracing + + + org.aspectj + aspectjrt + 1.6.1 + + + org.aspectj + aspectjlib + 1.6.1 + + + org.aspectj + aspectjweaver + 1.6.1 + test + + + + + + + org.apache.maven.plugins + maven-dependency-plugin + 2.0 + + + copy + process-sources + + copy + + + + + org.aspectj + aspectjweaver + 1.6.1 + jar + true + ${project.build.directory}/dependency + + + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + LATEST + + + **/*TestCase.java + + brief + false + once + + -ea -Xmx128m -javaagent:target/dependency/aspectjweaver-1.6.1.jar + + + + + diff --git a/java/sca/contrib/modules/tracing-aspectj/src/main/java/org/apache/tuscany/sca/aspectj/LoggingAspect.java b/java/sca/contrib/modules/tracing-aspectj/src/main/java/org/apache/tuscany/sca/aspectj/LoggingAspect.java new file mode 100644 index 0000000000..630bcb285b --- /dev/null +++ b/java/sca/contrib/modules/tracing-aspectj/src/main/java/org/apache/tuscany/sca/aspectj/LoggingAspect.java @@ -0,0 +1,105 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.aspectj; + +import java.util.Arrays; + +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.After; +import org.aspectj.lang.annotation.AfterReturning; +import org.aspectj.lang.annotation.AfterThrowing; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Before; +import org.aspectj.lang.annotation.Pointcut; + +/** + * LoggingAspect performs standard logging of method signatures, arguments, and + * return values. All Tuscany methods, constructors, and statics are logged. + * @version $Rev$ $Date$ + */ +@Aspect +public class LoggingAspect { + @Pointcut("call(* org.apache.tuscany.sca..*(..)) && (!within(org.apache.tuscany.sca.aspectj.*Aspect))") + public void anyMethodCall() { + } + + @Pointcut("execution(* org.apache.tuscany.sca..*(..)) && (!within(org.apache.tuscany.sca.aspectj.*Aspect))") + public void anyMethodExecution() { + } + + @Pointcut("call(* java.util.logging.Logger.info(..))") + public void anyLogCall() { + } + + @Pointcut("cflow(anyMethodExecution()) && anyLogCall()") + public void anyLog() { + } + + @Pointcut("call(org.apache.tuscany.sca..*.new(..))") + public void anyConstructor() { + } + + // e.g. org.apache.tuscany.sca.implementation.java.introspect.impl.JavaIntrospectionHelper + @Pointcut("staticinitialization(org.apache.tuscany.sca.implementation..*)") + public void anyStatic() { + } + + @Before("anyMethodCall()") + public void before(JoinPoint jp) { + // System.out.println("Logging anyMethodCall before jp=" + jp); + // System.out.println("Logging anyMethodCall before jp.getSourceLocation=" + jp.getSourceLocation()); + // System.out.println("Logging anyMethodCall before jp.getThis=" + jp.getThis()); + // System.out.println("Logging anyMethodCall before jp.getTarget=" + jp.getTarget()); + System.out.println("Logging Before anyMethodCall jp.getSignature=" + jp.getSignature()); + java.lang.Object[] args = jp.getArgs(); + if (( args != null ) && ( args.length > 0 )) { + System.out.println("Logging Before anyMethodCall jp.getArgs=" + Arrays.asList(args)); + } + } + + @AfterReturning(pointcut = "anyMethodCall()", returning = "result") + public void afterReturning(JoinPoint jp, Object result) { + // Note that result is null for methods with void return. + System.out.println("Logging AfterReturning anyMethodCall jp=" + jp + ", result=" + result); + } + + @AfterThrowing(pointcut = "anyMethodCall()", throwing = "t") + public void afterThrowing(JoinPoint jp, Throwable t) { + System.out.println("Logging AfterThrowing anyMethodCall jp=" + jp + ", t=" + t); + } + + @Before("anyConstructor()") + public void beforeConstructor(JoinPoint jp) { + System.out.println("Logging Before anyConstructor jp.getSignature=" + jp.getSignature()); + java.lang.Object[] args = jp.getArgs(); + if (( args != null ) && ( args.length > 0 )) { + System.out.println("Logging Before anyConstructor jp.getArgs=" + Arrays.asList(args)); + } + } + + @Before("anyStatic()") + public void beforeStatic(JoinPoint jp) { + System.out.println("Logging Before anyStatic before jp=" + jp); + System.out.println("Logging anyMethodCall before jp.getSourceLocation=" + jp.getSourceLocation()); + } + +} diff --git a/java/sca/contrib/modules/tracing-aspectj/src/main/java/org/apache/tuscany/sca/aspectj/SimpleTracingAspect.java b/java/sca/contrib/modules/tracing-aspectj/src/main/java/org/apache/tuscany/sca/aspectj/SimpleTracingAspect.java new file mode 100644 index 0000000000..965cfa5b5d --- /dev/null +++ b/java/sca/contrib/modules/tracing-aspectj/src/main/java/org/apache/tuscany/sca/aspectj/SimpleTracingAspect.java @@ -0,0 +1,87 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.aspectj; + +import java.util.Arrays; + +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Pointcut; + +/** + * SimpleTraceAspect performs tracing of method signatures, arguments, and + * return values. All Tuscany methods, constructors, and statics are traced. + * + * @version $Rev$ $Date$ + */ +@Aspect +public class SimpleTracingAspect extends TracingAspect { + + @Pointcut("execution(public * org.apache.tuscany.sca..*.*(..))") + // @Pointcut("call(* org.apache.tuscany.sca..*(..))") + protected void entry() { + } + + @Pointcut("within(org.apache.tuscany.sca..*) && !within(org.apache.tuscany.sca.aspectj..*Aspect)") + protected void withinScope() { + } + + @Override + protected void startLog() { + System.out.println(">>> ----------------------------------------------------"); + } + + @Override + protected void completeLog() { + System.out.println("<<< ----------------------------------------------------"); + } + + @Override + protected void logEnter(JoinPoint jp) { + System.out.println("> logEnter jp.getSignature=" + jp.getSignature()); + java.lang.Object[] args = jp.getArgs(); + if (( args != null ) && ( args.length > 0 )) { + // See http://www.eclipse.org/aspectj/doc/released/progguide/pitfalls-infiniteLoops.html + // System.out.println("Logging anyMethodCall before jp.getArgs=" + Arrays.asList(args)); + System.out.print(" logEnter jp.getArgs(" + args.length + ")=[" ); + for ( int i = 0; i < args.length; i++ ){ + if ( i > 0 ) System.out.print( ","); + System.out.print( args[ i ]); + } + System.out.println("]" ); + } + } + + @Override + protected void logExit(JoinPoint jp, Object result) { + // Note that result is null for methods with void return. + System.out.println("< logExit jp.getSignature=" + jp.getSignature() +", result=" + result ); + } + + @Override + protected void logThrowable(JoinPoint jp, Throwable throwable) { + while ( throwable.getCause() != null ) + throwable = throwable.getCause(); + System.out.println("! logThrowable jp.getSignature=" + jp.getSignature() + ", throwable=" + throwable); + // System.out.println("! logThowable stackTrace=" ); + // throwable.printStackTrace( System.out ); + } + +} diff --git a/java/sca/contrib/modules/tracing-aspectj/src/main/java/org/apache/tuscany/sca/aspectj/TimingAspect.java b/java/sca/contrib/modules/tracing-aspectj/src/main/java/org/apache/tuscany/sca/aspectj/TimingAspect.java new file mode 100644 index 0000000000..262742e867 --- /dev/null +++ b/java/sca/contrib/modules/tracing-aspectj/src/main/java/org/apache/tuscany/sca/aspectj/TimingAspect.java @@ -0,0 +1,60 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.aspectj; + +import java.util.Arrays; + +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.After; +import org.aspectj.lang.annotation.AfterReturning; +import org.aspectj.lang.annotation.AfterThrowing; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Before; +import org.aspectj.lang.annotation.Pointcut; + +/** + * The TimingAspect is used to perform timing metrics on various calls. + * The Pointcut "timedCall" is not defined here, but rather in the aop.xml + * configuration file. You may provide a point cut to state which type + * of call you would like timed and reported in the output files. + * + * @version $Rev$ $Date$ + */ +@Aspect +public abstract class TimingAspect { + // Abstract pointcut. Pointcut is defined in aop.xml file. + @Pointcut + public void timedCall() { + } + + @Around("timedCall()") + public Object timedSection(ProceedingJoinPoint jp) throws Throwable { + System.out.println("Timing Around timedSection jp=" + jp); + long start = System.currentTimeMillis(); + try { + return jp.proceed(); + } finally { + long end = System.currentTimeMillis(); + System.out.println("Timing Around timedSection Roundtrip is " + (end - start) + "ms for jp.getSignature=" + jp.getSignature()); + } + } +} diff --git a/java/sca/contrib/modules/tracing-aspectj/src/main/java/org/apache/tuscany/sca/aspectj/TracingAspect.java b/java/sca/contrib/modules/tracing-aspectj/src/main/java/org/apache/tuscany/sca/aspectj/TracingAspect.java new file mode 100644 index 0000000000..0178ebdb6e --- /dev/null +++ b/java/sca/contrib/modules/tracing-aspectj/src/main/java/org/apache/tuscany/sca/aspectj/TracingAspect.java @@ -0,0 +1,92 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.aspectj; + +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.annotation.After; +import org.aspectj.lang.annotation.AfterReturning; +import org.aspectj.lang.annotation.AfterThrowing; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Before; +import org.aspectj.lang.annotation.Pointcut; + +/** + * @version $Rev$ $Date$ + */ + +@Aspect +public abstract class TracingAspect { + + @Pointcut("") + protected abstract void entry(); + + @Pointcut("") + protected abstract void withinScope(); + + @Pointcut("call(* java..*.*(..))") + protected void exit() { + } + + @Pointcut("entry() && !cflowbelow(entry())") + void start() { + } + + // @Pointcut("withinScope() && cflow(entry()) && !cflow(exit()) && !within(org.apache.tuscany.sca.aspectj.*Aspect) && !within(*.toString)") + @Pointcut("withinScope() && entry()") + // @Pointcut("withinScope() && entry()&& !cflow(execution(String toString())") + void trace() { + } + + @Pointcut("!handler(*) && !preinitialization(new(..))") + protected void supportsAfterAdvice() { + } + + @Before("start()") + public void beforeStart() { + startLog(); + } + + @Before("trace() && supportsAfterAdvice()") + public void beforeTrace(JoinPoint jp) { + logEnter(jp); + } + + @AfterReturning(pointcut = "trace() && supportsAfterAdvice()", returning = "result") + public void afterReturning(JoinPoint jp, Object result) { + logExit(jp, result); + } + + @AfterThrowing(pointcut = "trace() && supportsAfterAdvice()", throwing = "e") + public void afterThrowing(JoinPoint jp, Throwable e) { + logThrowable(jp, e); + } + + @After("start()") + public void afterStart() { + completeLog(); + } + + protected abstract void logEnter(JoinPoint jp); + protected abstract void logExit(JoinPoint jp, Object result); + protected abstract void logThrowable(JoinPoint jp, Throwable throwable); + + protected abstract void startLog(); + protected abstract void completeLog(); +} diff --git a/java/sca/contrib/modules/tracing-aspectj/src/main/resources/META-INF/aop.xml b/java/sca/contrib/modules/tracing-aspectj/src/main/resources/META-INF/aop.xml new file mode 100644 index 0000000000..f699a140e3 --- /dev/null +++ b/java/sca/contrib/modules/tracing-aspectj/src/main/resources/META-INF/aop.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/java/sca/contrib/modules/tracing-aspectj/src/test/java/org/apache/tuscany/sca/aspectj/TracingTestCase.java b/java/sca/contrib/modules/tracing-aspectj/src/test/java/org/apache/tuscany/sca/aspectj/TracingTestCase.java new file mode 100644 index 0000000000..7b76faaf36 --- /dev/null +++ b/java/sca/contrib/modules/tracing-aspectj/src/test/java/org/apache/tuscany/sca/aspectj/TracingTestCase.java @@ -0,0 +1,41 @@ +/* + * 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. + */ + +package org.apache.tuscany.sca.aspectj; + +import java.util.logging.Logger; + +import org.junit.Test; + +/** + * @version $Rev$ $Date$ + */ +public class TracingTestCase { + + @Test + public void testAOP() { + Logger log = Logger.getLogger(getClass().getName()); + System.out.println("doSomething()"); + log.info("Hello, Log"); + } + + public static void main(String[] args) { + new TracingTestCase().testAOP(); + } +} -- cgit v1.2.3