From e5b7380c874745c989d1816b8f552504f038e1bc Mon Sep 17 00:00:00 2001 From: lresende Date: Thu, 26 Sep 2013 20:33:20 +0000 Subject: 2.0 branch for possible maintenance release git-svn-id: http://svn.us.apache.org/repos/asf/tuscany@1526672 13f79535-47bb-0310-9956-ffa450edef68 --- .../branches/2.0/modules/databinding/LICENSE | 244 ++++++ .../2.0/modules/databinding/META-INF/MANIFEST.MF | 71 ++ .../branches/2.0/modules/databinding/NOTICE | 6 + .../branches/2.0/modules/databinding/pom.xml | 97 +++ .../tuscany/sca/databinding/BaseDataBinding.java | 108 +++ .../tuscany/sca/databinding/BaseTransformer.java | 52 ++ .../tuscany/sca/databinding/DataBinding.java | 83 ++ .../sca/databinding/DataBindingContext.java | 95 ++ .../sca/databinding/DataBindingExtensionPoint.java | 75 ++ .../apache/tuscany/sca/databinding/DataPipe.java | 46 + .../sca/databinding/DataPipeTransformer.java | 29 + .../DefaultDataBindingExtensionPoint.java | 261 ++++++ .../DefaultTransformerExtensionPoint.java | 321 +++++++ .../apache/tuscany/sca/databinding/Mediator.java | 216 +++++ .../tuscany/sca/databinding/PullTransformer.java | 39 + .../tuscany/sca/databinding/PushTransformer.java | 36 + .../tuscany/sca/databinding/SimpleTypeMapper.java | 70 ++ .../sca/databinding/TransformationContext.java | 89 ++ .../sca/databinding/TransformationException.java | 66 ++ .../tuscany/sca/databinding/Transformer.java | 51 ++ .../sca/databinding/TransformerExtensionPoint.java | 81 ++ .../tuscany/sca/databinding/WrapperHandler.java | 79 ++ .../tuscany/sca/databinding/XMLTypeHelper.java | 69 ++ .../sca/databinding/annotation/DataBinding.java | 56 ++ .../sca/databinding/annotation/DataType.java | 43 + .../externalizable/ExternalizableDataBinding.java | 39 + .../sca/databinding/impl/DirectedGraph.java | 469 ++++++++++ .../databinding/impl/Group2GroupTransformer.java | 91 ++ .../sca/databinding/impl/GroupDataBinding.java | 104 +++ .../impl/Java2SimpleTypeTransformer.java | 72 ++ .../tuscany/sca/databinding/impl/MediatorImpl.java | 687 +++++++++++++++ .../sca/databinding/impl/PipedTransformer.java | 70 ++ .../impl/SimpleType2JavaTransformer.java | 91 ++ .../sca/databinding/impl/SimpleTypeMapperImpl.java | 402 +++++++++ .../impl/TransformationContextImpl.java | 101 +++ .../sca/databinding/impl/XSDDataTypeConverter.java | 970 +++++++++++++++++++++ .../javabeans/DOMNode2JavaBeanTransformer.java | 98 +++ .../javabeans/Java2XMLMapperException.java | 69 ++ .../javabeans/JavaBean2DOMNodeTransformer.java | 76 ++ .../JavaBean2XMLStreamReaderTransformer.java | 68 ++ .../javabeans/JavaBean2XMLTransformer.java | 262 ++++++ .../javabeans/JavaBeansDataBinding.java | 178 ++++ .../javabeans/JavaExceptionDataBinding.java | 35 + .../javabeans/SimpleJavaDataBinding.java | 89 ++ .../javabeans/XML2JavaBeanTransformer.java | 329 +++++++ .../javabeans/XML2JavaMapperException.java | 76 ++ .../ServiceReferenceDataBinding.java | 42 + .../ServiceReferenceTypeHelper.java | 74 ++ .../sca/databinding/util/DataTypeHelper.java | 167 ++++ .../util/OperationDataBindingHelper.java | 98 +++ .../databinding/xml/BeanXMLStreamReaderImpl.java | 300 +++++++ .../sca/databinding/xml/DOMDataBinding.java | 131 +++ .../sca/databinding/xml/DOMWrapperHandler.java | 151 ++++ .../sca/databinding/xml/InputSource2Node.java | 74 ++ .../sca/databinding/xml/InputSource2SAX.java | 65 ++ .../sca/databinding/xml/InputStream2Node.java | 76 ++ .../sca/databinding/xml/InputStream2SAX.java | 64 ++ .../sca/databinding/xml/Node2OutputStream.java | 75 ++ .../sca/databinding/xml/Node2SimpleJavaType.java | 45 + .../databinding/xml/Node2SourceTransformer.java | 61 ++ .../tuscany/sca/databinding/xml/Node2String.java | 68 ++ .../tuscany/sca/databinding/xml/Node2Writer.java | 74 ++ .../sca/databinding/xml/Node2XMLStreamReader.java | 65 ++ .../tuscany/sca/databinding/xml/Reader2Node.java | 73 ++ .../tuscany/sca/databinding/xml/Reader2SAX.java | 60 ++ .../tuscany/sca/databinding/xml/SAX2DOMPipe.java | 78 ++ .../sca/databinding/xml/SimpleJavaType2Node.java | 66 ++ .../databinding/xml/Source2NodeTransformer.java | 70 ++ .../databinding/xml/Source2ResultTransformer.java | 71 ++ .../databinding/xml/Source2StringTransformer.java | 76 ++ .../sca/databinding/xml/StAXDataBinding.java | 53 ++ .../sca/databinding/xml/StreamDataPipe.java | 65 ++ .../tuscany/sca/databinding/xml/String2Node.java | 60 ++ .../tuscany/sca/databinding/xml/String2SAX.java | 61 ++ .../databinding/xml/String2SourceTransformer.java | 62 ++ .../databinding/xml/String2XMLStreamReader.java | 62 ++ .../sca/databinding/xml/Writer2ReaderDataPipe.java | 63 ++ .../sca/databinding/xml/XMLGroupDataBinding.java | 57 ++ .../sca/databinding/xml/XMLStreamReader2Node.java | 84 ++ .../sca/databinding/xml/XMLStreamReader2SAX.java | 77 ++ .../databinding/xml/XMLStreamReader2String.java | 64 ++ .../sca/databinding/xml/XMLStringDataBinding.java | 51 ++ .../org.apache.tuscany.sca.databinding.DataBinding | 27 + ...scany.sca.databinding.DataBindingExtensionPoint | 19 + .../org.apache.tuscany.sca.databinding.Mediator | 17 + ....apache.tuscany.sca.databinding.PullTransformer | 41 + ....apache.tuscany.sca.databinding.PushTransformer | 27 + ...apache.tuscany.sca.databinding.SimpleTypeMapper | 17 + ...scany.sca.databinding.TransformerExtensionPoint | 19 + .../databinding-validation-messages.properties | 35 + .../extension/DataBindingExtensionTestCase.java | 83 ++ .../SimpleTypeMapperExtensionTestCase.java.fixme | 124 +++ .../TransformerExtensionTestCase.java.fixme | 77 ++ .../extension/XSDDataTypeConverterTestCase.java | 58 ++ .../sca/databinding/impl/DataBindingTestCase.java | 48 + .../databinding/impl/DirectedGraphTestCase.java | 127 +++ .../sca/databinding/impl/MediatorImplTestCase.java | 125 +++ .../impl/XMLDocumentStreamReaderTestCase.java | 60 ++ .../xml/BeanXMLStreamReaderTestCase.java | 188 ++++ .../sca/databinding/xml/DOM2StAXTestCase.java | 116 +++ .../databinding/xml/DOMWrapperHandlerTestCase.java | 163 ++++ .../sca/databinding/xml/DataPipeTestCase.java | 98 +++ .../xml/JavaBean2XMLStreamReaderTestCase.java | 137 +++ .../sca/databinding/xml/Node2StringTestCase.java | 43 + .../xml/PushTransformationTestCase.java | 81 ++ .../databinding/xml/TraxTransformerTestCase.java | 102 +++ .../apache/tuscany/sca/databinding/impl/ipo.xsd | 136 +++ .../apache/tuscany/sca/databinding/impl/order.wsdl | 76 ++ .../org/apache/tuscany/sca/databinding/xml/foo.xml | 22 + 109 files changed, 11708 insertions(+) create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/LICENSE create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/META-INF/MANIFEST.MF create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/NOTICE create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/pom.xml create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/BaseDataBinding.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/BaseTransformer.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DataBinding.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DataBindingContext.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DataBindingExtensionPoint.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DataPipe.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DataPipeTransformer.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DefaultDataBindingExtensionPoint.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DefaultTransformerExtensionPoint.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/Mediator.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/PullTransformer.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/PushTransformer.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/SimpleTypeMapper.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/TransformationContext.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/TransformationException.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/Transformer.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/TransformerExtensionPoint.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/WrapperHandler.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/XMLTypeHelper.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/annotation/DataBinding.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/annotation/DataType.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/externalizable/ExternalizableDataBinding.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/DirectedGraph.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/Group2GroupTransformer.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/GroupDataBinding.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/Java2SimpleTypeTransformer.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/MediatorImpl.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/PipedTransformer.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/SimpleType2JavaTransformer.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/SimpleTypeMapperImpl.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/TransformationContextImpl.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/XSDDataTypeConverter.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/DOMNode2JavaBeanTransformer.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/Java2XMLMapperException.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/JavaBean2DOMNodeTransformer.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/JavaBean2XMLStreamReaderTransformer.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/JavaBean2XMLTransformer.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/JavaBeansDataBinding.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/JavaExceptionDataBinding.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/SimpleJavaDataBinding.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/XML2JavaBeanTransformer.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/XML2JavaMapperException.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/servicereference/ServiceReferenceDataBinding.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/servicereference/ServiceReferenceTypeHelper.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/util/DataTypeHelper.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/util/OperationDataBindingHelper.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/BeanXMLStreamReaderImpl.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/DOMDataBinding.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/DOMWrapperHandler.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/InputSource2Node.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/InputSource2SAX.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/InputStream2Node.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/InputStream2SAX.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Node2OutputStream.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Node2SimpleJavaType.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Node2SourceTransformer.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Node2String.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Node2Writer.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Node2XMLStreamReader.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Reader2Node.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Reader2SAX.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/SAX2DOMPipe.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/SimpleJavaType2Node.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Source2NodeTransformer.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Source2ResultTransformer.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Source2StringTransformer.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/StAXDataBinding.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/StreamDataPipe.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/String2Node.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/String2SAX.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/String2SourceTransformer.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/String2XMLStreamReader.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Writer2ReaderDataPipe.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLGroupDataBinding.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLStreamReader2Node.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLStreamReader2SAX.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLStreamReader2String.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLStringDataBinding.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.DataBinding create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.DataBindingExtensionPoint create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.Mediator create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PullTransformer create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PushTransformer create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.SimpleTypeMapper create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.TransformerExtensionPoint create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/main/resources/org/apache/tuscany/sca/databinding/databinding-validation-messages.properties create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/extension/DataBindingExtensionTestCase.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/extension/SimpleTypeMapperExtensionTestCase.java.fixme create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/extension/TransformerExtensionTestCase.java.fixme create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/extension/XSDDataTypeConverterTestCase.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/impl/DataBindingTestCase.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/impl/DirectedGraphTestCase.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/impl/MediatorImplTestCase.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/impl/XMLDocumentStreamReaderTestCase.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/BeanXMLStreamReaderTestCase.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/DOM2StAXTestCase.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/DOMWrapperHandlerTestCase.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/DataPipeTestCase.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/JavaBean2XMLStreamReaderTestCase.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/Node2StringTestCase.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/PushTransformationTestCase.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/TraxTransformerTestCase.java create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/test/resources/org/apache/tuscany/sca/databinding/impl/ipo.xsd create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/test/resources/org/apache/tuscany/sca/databinding/impl/order.wsdl create mode 100644 sca-java-2.x/branches/2.0/modules/databinding/src/test/resources/org/apache/tuscany/sca/databinding/xml/foo.xml (limited to 'sca-java-2.x/branches/2.0/modules/databinding') diff --git a/sca-java-2.x/branches/2.0/modules/databinding/LICENSE b/sca-java-2.x/branches/2.0/modules/databinding/LICENSE new file mode 100644 index 0000000000..616bec99ed --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/LICENSE @@ -0,0 +1,244 @@ + + 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. + +----------------------------------------------------------------- +The test cases use xmlunit with the following license: +----------------------------------------------------------------- + +/* +****************************************************************** +Copyright (c) 2001-2007, Jeff Martin, Tim Bacon +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 xmlunit.sourceforge.net nor the names + of its 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/sca-java-2.x/branches/2.0/modules/databinding/META-INF/MANIFEST.MF b/sca-java-2.x/branches/2.0/modules/databinding/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..8fed859030 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/META-INF/MANIFEST.MF @@ -0,0 +1,71 @@ +Manifest-Version: 1.0 +Export-Package: org.apache.tuscany.sca.databinding;uses:="org.apache.t + uscany.sca.interfacedef.util,org.apache.tuscany.sca.databinding.impl, + org.apache.tuscany.sca.interfacedef,org.apache.tuscany.sca.extensibil + ity,javax.xml.namespace,org.apache.tuscany.sca.contribution.resolver, + org.apache.tuscany.sca.interfacedef.impl,org.apache.tuscany.sca.xsd"; + version="2.0.0",org.apache.tuscany.sca.databinding.xml;uses:="org.apach + e.tuscany.sca.databinding,org.apache.tuscany.sca.interfacedef.util,or + g.apache.tuscany.sca.databinding.impl,javax.xml.parsers,javax.xml.tra + nsform.dom,org.w3c.dom,org.apache.tuscany.sca.interfacedef,org.xml.sa + x,javax.xml.namespace,javax.xml.stream,javax.xml.stream.util,org.xml. + sax.ext,javax.xml.transform,javax.xml.transform.stream,org.apache.tus + cany.sca.interfacedef.impl,javax.xml.transform.sax,org.apache.tuscany + .sca.databinding.javabeans,org.xml.sax.helpers";version="2.0.0",org.apa + che.tuscany.sca.databinding.impl;uses:="org.apache.tuscany.sca.databi + nding,org.apache.tuscany.sca.interfacedef.util,javax.xml.parsers,org. + apache.tuscany.sca.interfacedef,org.w3c.dom,javax.xml.datatype,javax. + xml.namespace,javax.xml.transform,org.apache.tuscany.sca.interfacedef + .impl";version="2.0.0",org.apache.tuscany.sca.databinding.util;uses:="o + rg.apache.tuscany.sca.interfacedef.util,org.apache.tuscany.sca.interf + acedef";version="2.0.0",org.apache.tuscany.sca.databinding.annotation;v + ersion="2.0.0",org.apache.tuscany.sca.databinding.javabeans;uses:="org. + apache.tuscany.sca.databinding,org.apache.tuscany.sca.databinding.xml + ,org.apache.tuscany.sca.interfacedef.util,org.apache.tuscany.sca.data + binding.impl,javax.xml.parsers,org.w3c.dom,org.apache.tuscany.sca.int + erfacedef,javax.xml.datatype,javax.xml.namespace,javax.xml.stream";ve + rsion="2.0.0" +Private-Package: org.apache.tuscany.sca.databinding.externalizable;ver + sion="2.0.0" +SCA-Version: 1.1 +Bundle-Name: Apache Tuscany SCA DataBinding Framework +Bundle-Vendor: The Apache Software Foundation +Bundle-Version: 2.0.0 +Bundle-ManifestVersion: 2 +Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt +Bundle-Description: Apache Tuscany SCA DataBinding Framework +Import-Package: javax.xml.datatype, + javax.xml.namespace, + 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.apache.tuscany.sca.common.xml.dom;version="2.0.0", + org.apache.tuscany.sca.common.xml.sax;version="2.0.0", + org.apache.tuscany.sca.common.xml.stax;version="2.0.0", + org.apache.tuscany.sca.common.xml.stax.reader;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.annotation;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.util;version="2.0.0", + org.apache.tuscany.sca.databinding.xml;version="2.0.0", + org.apache.tuscany.sca.extensibility;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.policy;version="2.0.0", + org.apache.tuscany.sca.xsd;version="2.0.0", + org.oasisopen.sca;version="2.0.0", + org.w3c.dom, + org.xml.sax, + org.xml.sax.ext, + org.xml.sax.helpers +Bundle-SymbolicName: org.apache.tuscany.sca.databinding +Bundle-DocURL: http://www.apache.org/ +Bundle-RequiredExecutionEnvironment: J2SE-1.5,JavaSE-1.6 diff --git a/sca-java-2.x/branches/2.0/modules/databinding/NOTICE b/sca-java-2.x/branches/2.0/modules/databinding/NOTICE new file mode 100644 index 0000000000..b01801136b --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2012 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/sca-java-2.x/branches/2.0/modules/databinding/pom.xml b/sca-java-2.x/branches/2.0/modules/databinding/pom.xml new file mode 100644 index 0000000000..e72f799234 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/pom.xml @@ -0,0 +1,97 @@ + + + + 4.0.0 + + org.apache.tuscany.sca + tuscany-modules + 2.0 + ../pom.xml + + tuscany-databinding + Apache Tuscany SCA DataBinding Framework + + + + org.apache.tuscany.sca + tuscany-extensibility + 2.0 + + + + org.apache.tuscany.sca + tuscany-assembly + 2.0 + + + + org.apache.tuscany.sca + tuscany-contribution + 2.0 + + + + org.apache.tuscany.sca + tuscany-xsd + 2.0 + + + + org.apache.tuscany.sca + tuscany-sca-api + 2.0 + + + + org.apache.tuscany.sca + tuscany-common-xml + 2.0 + + + + + xmlunit + xmlunit + 1.2 + test + + + + + diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/BaseDataBinding.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/BaseDataBinding.java new file mode 100644 index 0000000000..aa019ebdcf --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/BaseDataBinding.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.databinding; + + +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; + +/** + * Base Implementation of DataBinding + * + * @version $Rev$ $Date$ + * @tuscany.spi.extension.inheritfrom + */ +public abstract class BaseDataBinding implements DataBinding { + + private Class baseType; + + private String name; + + /** + * Create a databinding with the base java type whose name will be used as + * the name of the databinding + * + * @param baseType The base java class or interface representing the + * databinding, for example, org.w3c.dom.Node + */ + protected BaseDataBinding(Class baseType) { + this(baseType.getName(), baseType); + } + + /** + * Create a databinding with the name and base java type + * + * @param name The name of the databinding + * @param baseType The base java class or interface representing the + * databinding, for example, org.w3c.dom.Node + */ + protected BaseDataBinding(String name, Class baseType) { + this.name = name; + this.baseType = baseType; + } + + @SuppressWarnings("unchecked") + public boolean introspect(DataType type, Operation operation) { + assert type != null; + Class cls = type.getPhysical(); + if (baseType != null && baseType.isAssignableFrom(cls)) { + type.setDataBinding(getName()); + if (type.getLogical() == null) { + type.setLogical(XMLType.UNKNOWN); + } + return true; + } + return false; + } + + public DataType introspect(Object value, Operation operation) { + if (value == null) { + return null; + } else { + DataType dataType = new DataTypeImpl(value.getClass(), value.getClass()); + if (introspect(dataType, (Operation) null)) { + return dataType; + } else { + return null; + } + } + } + + public final String getName() { + return name; + } + + /** + * @see org.apache.tuscany.sca.databinding.DataBinding#getWrapperHandler() + */ + public WrapperHandler getWrapperHandler() { + return null; + } + + public Object copy(Object object, DataType sourceDataType, DataType targetDataType, Operation sourceOperation, Operation targetOperation) { + return object; + } + + public XMLTypeHelper getXMLTypeHelper() { + return null; + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/BaseTransformer.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/BaseTransformer.java new file mode 100644 index 0000000000..f5b92de2fb --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/BaseTransformer.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.databinding; + + +/** + * Base Implementation of Transformer which provides the registration to the + * transformer registry + * + * @version $Rev$ $Date$ + * @tuscany.spi.extension.inheritfrom + */ +public abstract class BaseTransformer implements Transformer { + + protected BaseTransformer() { + super(); + } + + protected abstract Class getSourceType(); + + protected abstract Class getTargetType(); + + public String getSourceDataBinding() { + return getSourceType().getName(); + } + + public String getTargetDataBinding() { + return getTargetType().getName(); + } + + public int getWeight() { + // default to 50 + return 50; + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DataBinding.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DataBinding.java new file mode 100644 index 0000000000..46806c77f1 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DataBinding.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; + + +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.Operation; + +/** + * DataBinding represents a data representation, for example, SDO, JAXB and AXIOM + * + * @version $Rev$ $Date$ + * @tuscany.spi.extension.asclient + */ +public interface DataBinding { + + /** + * The name of a databinding should be case-insensitive and unique + * + * @return The name of the databinding + */ + String getName(); + + /** + * Introspect and populate information to a DataType model + * + * @param dataType The data type to be introspected + * @param operation The operation + * @return true if the databinding has recognized the given data type + */ + boolean introspect(DataType dataType, Operation operation); + + /** + * Introspect the data to figure out the corresponding data type + * + * @param value The object to be checked + * @param operation The operation + * @return The DataType or null if the java type is not supported by this databinding + */ + DataType introspect(Object value, Operation operation); + + /** + * Provide a WrapperHandler for this databinding + * @return A wrapper handler which can handle wrapping/wrapping for this databinding + */ + WrapperHandler getWrapperHandler(); + + /** + * Make a copy of the object for "pass-by-value" semantics and cross classloader invocations. + * + * @param object source object to copy + * @param sourceDataType The source data type + * @param targetDataType the target data type + * @param sourceOperation The source operation + * @param targetOperation The target operation + * @return copy of the object passed in as argument + */ + Object copy(Object object, DataType sourceDataType, DataType targetDataType, Operation sourceOperation, Operation targetOperation); + + /** + * Get the XML type helper for Java types + * @return The databinding-specific XML type helper class + */ + XMLTypeHelper getXMLTypeHelper(); + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DataBindingContext.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DataBindingContext.java new file mode 100644 index 0000000000..c77d0ad0f6 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DataBindingContext.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.databinding; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; + +import org.apache.tuscany.sca.interfacedef.Operation; + +/** + * The context for databinding processing + */ +public class DataBindingContext { + + private String contentType; + private Class type; + private Type genericType; + private Annotation[] annotations; + private Operation operation; + + public DataBindingContext(Class type, + Type genericType, + Annotation[] annotations, + Operation operation, + String contentType) { + super(); + this.type = type; + this.genericType = genericType; + this.annotations = annotations; + this.operation = operation; + this.contentType = contentType; + } + + public DataBindingContext(Class type, Type genericType, Annotation[] annotations) { + super(); + this.type = type; + this.genericType = genericType; + this.annotations = annotations; + } + + public DataBindingContext(Class type) { + super(); + this.type = type; + this.genericType = type; + } + + public Class getType() { + return type; + } + + public Type getGenericType() { + return genericType; + } + + public Annotation[] getAnnotations() { + return annotations; + } + + public Operation getOperation() { + return operation; + } + + public A getAnnotation(Class type) { + if (annotations == null) { + return null; + } + for (Annotation a : annotations) { + if (a.annotationType() == type) { + return type.cast(a); + } + } + return null; + } + + public String getContentType() { + return contentType; + } +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DataBindingExtensionPoint.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DataBindingExtensionPoint.java new file mode 100644 index 0000000000..ff3afd8181 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DataBindingExtensionPoint.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; + + +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.Operation; + +/** + * An extension point for data binding extensions. + * + * @version $Rev$ $Date$ + * @tuscany.spi.extension.asclient + */ +public interface DataBindingExtensionPoint { + + /** + * Register a data binding + * + * @param dataBinding + */ + void addDataBinding(DataBinding dataBinding); + + /** + * Look up a data binding by id + * + * @param id The name of the databinding + * @return The databinding + */ + DataBinding getDataBinding(String id); + + /** + * Unregister a data binding + * + * @param id + * @return The unregistered databinding + */ + DataBinding removeDataBinding(String id); + + /** + * Introspect the java class to figure out what DataType supports it. + * + * @param dataType The initial data type + * @param operation TODO + * @return A DataType representing the java type or null if no databinding + * recognizes the java type + */ + boolean introspectType(DataType dataType, Operation operation); + + /** + * Introspect the value to figure out the corresponding DataType + * + * @param value The object value + * @param operation TODO + * @return A DataType representing the value or null if no databinding + * recognizes the value + */ + DataType introspectType(Object value, Operation operation); +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DataPipe.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DataPipe.java new file mode 100644 index 0000000000..505a810276 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DataPipe.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.databinding; + +/** + * Data pipe allows a data source pushes data into its sink and pipe the data into its result + * + * @param The data binding type of the sink + * @param The data binding type of the result + * + * @version $Rev$ $Date$ + */ +public interface DataPipe { + + /** + * Returns a sink (for example, java.io.OutputStream, java.io.Writer or org.xml.sax.ContentHandler) to receive data + * pushed by the source + * + * @return The sink to consume data + */ + S getSink(); + + /** + * Returns the data populated by the sink + * + * @return + */ + R getResult(); + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DataPipeTransformer.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DataPipeTransformer.java new file mode 100644 index 0000000000..1aac6d48be --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DataPipeTransformer.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; + +/** + * Data pipe allows a data source pushes data into its sink and pipe the data into its result + * + * @version $Rev$ $Date$ + */ +public interface DataPipeTransformer extends Transformer { + + DataPipe newInstance(); +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DefaultDataBindingExtensionPoint.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DefaultDataBindingExtensionPoint.java new file mode 100644 index 0000000000..22b6e8646e --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DefaultDataBindingExtensionPoint.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.databinding; + +import java.io.IOException; +import java.lang.reflect.Constructor; +import java.lang.reflect.GenericArrayType; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.databinding.javabeans.JavaBeansDataBinding; +import org.apache.tuscany.sca.databinding.javabeans.JavaExceptionDataBinding; +import org.apache.tuscany.sca.extensibility.ServiceDeclaration; +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; + +/** + * The default implementation of a data binding extension point. + * + * @version $Rev$ $Date$ + */ +public class DefaultDataBindingExtensionPoint implements DataBindingExtensionPoint { + private ExtensionPointRegistry registry; + private final Map bindings = new HashMap(); + private final List databindings = new ArrayList(); + private static final Logger logger = Logger.getLogger(DefaultDataBindingExtensionPoint.class.getName()); + private boolean loadedDataBindings; + +// public DefaultDataBindingExtensionPoint() { +// } + + public DefaultDataBindingExtensionPoint(ExtensionPointRegistry registry) { + this.registry = registry; + } + + public DataBinding getDataBinding(String id) { + if (id == null) { + return null; + } + loadDataBindings(); + DataBinding dataBinding = bindings.get(id.toLowerCase()); + if (dataBinding == null) { + loadDataBindings(); + dataBinding = bindings.get(id.toLowerCase()); + } + return dataBinding; + } + + public void addDataBinding(DataBinding dataBinding) { + if (logger.isLoggable(Level.FINE)) { + String className = dataBinding.getClass().getName(); + boolean lazy = false; + if (dataBinding instanceof LazyDataBinding) { + className = ((LazyDataBinding)dataBinding).dataBindingDeclaration.getClassName(); + lazy = true; + } + logger.fine("Adding databinding: " + className + ";name=" + dataBinding.getName() + ",lazy=" + lazy); + } + databindings.add(dataBinding); + bindings.put(dataBinding.getName().toLowerCase(), dataBinding); + + } + + public DataBinding removeDataBinding(String id) { + if (id == null) { + return null; + } + DataBinding dataBinding = bindings.remove(id.toLowerCase()); + if (dataBinding != null) { + databindings.remove(dataBinding); + } + return dataBinding; + } + + /** + * Dynamically load data bindings declared under META-INF/services + */ + private synchronized void loadDataBindings() { + if (loadedDataBindings) + return; + + // Get the databinding service declarations + Collection dataBindingDeclarations; + try { + dataBindingDeclarations = registry.getServiceDiscovery().getServiceDeclarations(DataBinding.class.getName()); + } catch (IOException e) { + throw new IllegalStateException(e); + } + + // Load data bindings + for (ServiceDeclaration dataBindingDeclaration : dataBindingDeclarations) { + Map attributes = dataBindingDeclaration.getAttributes(); + String name = attributes.get("name"); + + // Create a data binding wrapper and register it + DataBinding dataBinding = new LazyDataBinding(name, dataBindingDeclaration); + addDataBinding(dataBinding); + } + + loadedDataBindings = true; + } + + /** + * A data binding facade allowing data bindings to be lazily loaded and + * initialized. + */ + private class LazyDataBinding implements DataBinding { + + private String name; + private ServiceDeclaration dataBindingDeclaration; + private DataBinding dataBinding; + + private LazyDataBinding(String type, ServiceDeclaration dataBindingDeclaration) { + this.name = type; + this.dataBindingDeclaration = dataBindingDeclaration; + } + + /** + * Load and instantiate the data binding class. + * + * @return The data binding. + */ + @SuppressWarnings("unchecked") + private DataBinding getDataBinding() { + if (dataBinding == null) { + try { + Class dataBindingClass = (Class)dataBindingDeclaration.loadClass(); + try { + Constructor constructor = dataBindingClass.getConstructor(); + dataBinding = constructor.newInstance(); + } catch (NoSuchMethodException e) { + Constructor constructor = + dataBindingClass.getConstructor(ExtensionPointRegistry.class); + dataBinding = constructor.newInstance(DefaultDataBindingExtensionPoint.this.registry); + } + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + return dataBinding; + } + + public Object copy(Object object, DataType sourceDataType, DataType targetDataType, Operation sourceOperation, Operation targetOperation) { + return getDataBinding().copy(object, sourceDataType, targetDataType, sourceOperation, targetOperation); + } + + public String getName() { + return name; + } + + public XMLTypeHelper getXMLTypeHelper() { + return getDataBinding().getXMLTypeHelper(); + } + + public WrapperHandler getWrapperHandler() { + return getDataBinding().getWrapperHandler(); + } + + public boolean introspect(DataType dataType, Operation operation) { + return getDataBinding().introspect(dataType, operation); + } + + public DataType introspect(Object value, Operation operation) { + return getDataBinding().introspect(value, operation); + } + } + + //FIXME The following methods should not be on the extension point + // they should be on a separate class + public boolean introspectType(DataType dataType, Operation operation) { + loadDataBindings(); + for (DataBinding binding : databindings) { + // don't introspect for JavaBeansDatabinding as all javatypes will + // anyways match to its basetype + // which is java.lang.Object. Default to this only if no databinding + // results + if (!binding.getName().equals(JavaBeansDataBinding.NAME)) { + if (binding.introspect(dataType, operation)) { + return true; + } + } + } + // FIXME: Should we honor the databinding from operation/interface + // level? + Class physical = dataType.getPhysical(); + if (physical == Object.class) { + dataType.setDataBinding(JavaBeansDataBinding.NAME); + return false; + } + if (dataType.getPhysical().isArray()) { + introspectArray(dataType, operation); + return true; + } else if (Throwable.class.isAssignableFrom(physical)) { + dataType.setDataBinding(JavaExceptionDataBinding.NAME); + return true; + } else { + dataType.setDataBinding(JavaBeansDataBinding.NAME); + return false; + } + } + + private boolean introspectArray(DataType dataType, Operation operation) { + Class physical = dataType.getPhysical(); + if (!physical.isArray() || physical == byte[].class) { + return false; + } + Class componentType = physical.getComponentType(); + Type genericComponentType = componentType; + if(dataType.getGenericType() instanceof GenericArrayType) { + genericComponentType = ((GenericArrayType) dataType.getGenericType()).getGenericComponentType(); + } + DataType logical = new DataTypeImpl(dataType.getDataBinding(), componentType, genericComponentType, dataType.getLogical()); + introspectType(logical, operation); + dataType.setDataBinding("java:array"); + dataType.setLogical(logical); + return true; + } + + public DataType introspectType(Object value, Operation operation) { + loadDataBindings(); + DataType dataType = null; + for (DataBinding binding : databindings) { + // don't introspect for JavaBeansDatabinding as all javatypes will + // anyways match to its basetype + // which is java.lang.Object. Default to this only if no databinding + // results + if (!binding.getName().equals(JavaBeansDataBinding.NAME)) { + dataType = binding.introspect(value, operation); + } + if (dataType != null) { + return dataType; + } + } + return new DataTypeImpl(JavaBeansDataBinding.NAME, value.getClass(), XMLType.UNKNOWN); + } +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DefaultTransformerExtensionPoint.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DefaultTransformerExtensionPoint.java new file mode 100644 index 0000000000..39889b1e97 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/DefaultTransformerExtensionPoint.java @@ -0,0 +1,321 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * 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; + +import java.io.IOException; +import java.lang.reflect.Constructor; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.databinding.impl.DirectedGraph; +import org.apache.tuscany.sca.extensibility.ServiceDeclaration; +import org.apache.tuscany.sca.extensibility.ServiceDiscovery; + +/** + * @version $Rev$ $Date$ + */ +public class DefaultTransformerExtensionPoint implements TransformerExtensionPoint { + private static final Logger logger = Logger.getLogger(DefaultTransformerExtensionPoint.class.getName()); + private boolean loadedTransformers; + + private ExtensionPointRegistry registry; + private final DirectedGraph graph = new DirectedGraph(); + + public DefaultTransformerExtensionPoint(ExtensionPointRegistry registry) { + this.registry = registry; + } + + public void addTransformer(String sourceType, String resultType, int weight, Transformer transformer, boolean publicTransformer) { + if (logger.isLoggable(Level.FINE)) { + String className = transformer.getClass().getName(); + boolean lazy = false; + boolean pull = (transformer instanceof PullTransformer); + if (transformer instanceof LazyPullTransformer) { + className = ((LazyPullTransformer)transformer).transformerDeclaration.getClassName(); + lazy = true; + } + if (transformer instanceof LazyPushTransformer) { + className = ((LazyPushTransformer)transformer).transformerDeclaration.getClassName(); + lazy = true; + } + + logger.fine("Adding transformer: " + className + + ";source=" + + sourceType + + ",target=" + + resultType + + ",weight=" + + weight + + ",type=" + + (pull ? "pull" : "push") + + ",lazy=" + + lazy); + } + graph.addEdge(sourceType, resultType, transformer, weight, publicTransformer); + } + + public void addTransformer(Transformer transformer, boolean publicTransformer) { + addTransformer(transformer.getSourceDataBinding(), + transformer.getTargetDataBinding(), + transformer.getWeight(), + transformer, publicTransformer); + } + + public boolean removeTransformer(String sourceType, String resultType) { + return graph.removeEdge(sourceType, resultType); + } + + public Transformer getTransformer(String sourceType, String resultType) { + loadTransformers(); + + DirectedGraph.Edge edge = graph.getEdge(sourceType, resultType); + return (edge == null) ? null : edge.getValue(); + } + + /** + * Dynamically load transformers registered under META-INF/services. + * + */ + private synchronized void loadTransformers() { + if (loadedTransformers) { + return; + } + loadedTransformers = true; + loadTransformers(PullTransformer.class); + loadTransformers(PushTransformer.class); + + } + + /** + * Dynamically load transformers registered under META-INF/services. + * + * @param transformerClass + */ + private synchronized void loadTransformers(Class transformerClass) { + + // Get the transformer service declarations + Collection transformerDeclarations; + + try { + transformerDeclarations = registry.getServiceDiscovery().getServiceDeclarations(transformerClass.getName()); + + } catch (IOException e) { + throw new IllegalStateException(e); + } + + // Load transformers + for (ServiceDeclaration transformerDeclaration : transformerDeclarations) { + Map attributes = transformerDeclaration.getAttributes(); + + String source = attributes.get("source"); + String target = attributes.get("target"); + int weight = Integer.valueOf(attributes.get("weight")); + String b = attributes.get("public"); + boolean pub = true; + if (b != null) { + pub = Boolean.valueOf(b); + } + + // Create a transformer wrapper and register it + Transformer transformer; + if (transformerClass == PullTransformer.class) { + transformer = new LazyPullTransformer(source, target, weight, transformerDeclaration); + } else { + transformer = new LazyPushTransformer(source, target, weight, transformerDeclaration); + } + addTransformer(transformer, pub); + } + } + + /** + * A transformer facade allowing transformers to be lazily loaded + * and initialized. + */ + private class LazyPullTransformer implements PullTransformer { + + private String source; + private String target; + private int weight; + private ServiceDeclaration transformerDeclaration; + private PullTransformer transformer; + + public LazyPullTransformer(String source, String target, int weight, ServiceDeclaration transformerDeclaration) { + this.source = source; + this.target = target; + this.weight = weight; + this.transformerDeclaration = transformerDeclaration; + } + + /** + * Load and instantiate the transformer class. + * + * @return The transformer. + */ + @SuppressWarnings("unchecked") + private PullTransformer getTransformer() { + if (transformer == null) { + try { + Class> transformerClass = + (Class>)transformerDeclaration.loadClass(); + try { + Constructor> constructor = transformerClass.getConstructor(); + transformer = constructor.newInstance(); + } catch (NoSuchMethodException e) { + Constructor> constructor = + transformerClass.getConstructor(ExtensionPointRegistry.class); + transformer = constructor.newInstance(registry); + } + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + return transformer; + } + + public String getSourceDataBinding() { + return source; + } + + public String getTargetDataBinding() { + return target; + } + + public int getWeight() { + return weight; + } + + public Object transform(Object source, TransformationContext context) { + return getTransformer().transform(source, context); + } + + @Override + public String toString() { + StringBuffer sb = new StringBuffer(super.toString()); + sb.append(";className=").append(transformerDeclaration.getClassName()); + return sb.toString(); + } + } + + /** + * A transformer facade allowing transformers to be lazily loaded + * and initialized. + */ + private class LazyPushTransformer implements PushTransformer { + + private String source; + private String target; + private int weight; + private ServiceDeclaration transformerDeclaration; + private PushTransformer transformer; + + public LazyPushTransformer(String source, String target, int weight, ServiceDeclaration transformerDeclaration) { + this.source = source; + this.target = target; + this.weight = weight; + this.transformerDeclaration = transformerDeclaration; + } + + /** + * Load and instantiate the transformer class. + * + * @return The transformer. + */ + @SuppressWarnings("unchecked") + private PushTransformer getTransformer() { + if (transformer == null) { + try { + Class> transformerClass = + (Class>)transformerDeclaration.loadClass(); + try { + Constructor> constructor = transformerClass.getConstructor(); + transformer = constructor.newInstance(); + } catch (NoSuchMethodException e) { + Constructor> constructor = + transformerClass.getConstructor(ExtensionPointRegistry.class); + transformer = constructor.newInstance(registry); + } + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + return transformer; + } + + public String getSourceDataBinding() { + return source; + } + + public String getTargetDataBinding() { + return target; + } + + public int getWeight() { + return weight; + } + + public void transform(Object source, Object sink, TransformationContext context) { + getTransformer().transform(source, sink, context); + } + + @Override + public String toString() { + StringBuffer sb = new StringBuffer(super.toString()); + sb.append(";className=").append(transformerDeclaration.getClassName()); + return sb.toString(); + } + } + + //FIXME The following methods should be on a different class from + // extension point + + public List getTransformerChain(String sourceType, String resultType) { + loadTransformers(); + + String source = sourceType; + String result = resultType; + List transformers = new ArrayList(); + // First check if there is a direct path, if yes, use it regardless of the weight + DirectedGraph.Edge link = graph.getEdge(sourceType, resultType); + if (link != null) { + transformers.add(link.getValue()); + } else { + DirectedGraph.Path path = graph.getShortestPath(source, result); + if (path == null) { + return null; + } + for (DirectedGraph.Edge edge : path.getEdges()) { + transformers.add(edge.getValue()); + } + } + return transformers; + } + + @Override + public String toString() { + loadTransformers(); + + return graph.toString(); + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/Mediator.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/Mediator.java new file mode 100644 index 0000000000..ceb2f59e80 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/Mediator.java @@ -0,0 +1,216 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * 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; + +import java.util.Map; + +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.Operation; + +/** + * This interface will be used as a Tuscany system service to perform data mediations + * + * Mediate the data from one type to the other one + * + * @version $Rev$ $Date$ + * @tuscany.spi.extension.asclient + */ +public interface Mediator { + + // Constants used by the databinding framework's TransformationContext metadata + public final static String SOURCE_OPERATION = "source.operation"; + public final static String TARGET_OPERATION = "target.operation"; + + // Use String constants rather than an enum, in case the dependency isn't factored + // out well enough and someone needs to use the String values. + public static final String BODY_TYPE = "body.type"; + public static final String BODY_TYPE_INPUT = "input"; + public static final String BODY_TYPE_OUTPUT = "output"; + public static final String BODY_TYPE_FAULT = "fault"; + + /** + * Mediate the data from the source type to the target type + * @param source The data to be mediated + * @param sourceDataType Data type for the source data + * @param targetDataType Data type for the target data + * @param context + * @return + */ + Object mediate(Object source, DataType sourceDataType, DataType targetDataType, Map context); + + /** + * Mediate the source data into the target which is a sink to receive the data + * @param source The data to be mediated + * @param target The sink to receive data + * @param sourceDataType Data type for the source data + * @param targetDataType Data type for the target data + */ + void mediate(Object source, + Object target, + DataType sourceDataType, + DataType targetDataType, + Map context); + + /** + * Transform the input parameters for the source operation to the expected parameters for + * the target operation + * @param input The input data, typically an array of parameters + * @param sourceOperation The source operation + * @param targetOperation The target operation + * @param metadata Additional metadata + * @return The transformed input data for the target operation + */ + Object mediateInput(Object input, Operation sourceOperation, Operation targetOperation, Map metadata); + + /** + * Transform the return value for the target operation to the expected return value for + * the source operation + * @param output The output data, typically the return value + * @param sourceOperation The source operation + * @param targetOperation The target operation + * @param metadata Additional metadata + * @return The transformed output data for the source operation + */ + Object mediateOutput(Object output, + Operation sourceOperation, + Operation targetOperation, + Map metadata); + + /** + * Transform the fault data for the target operation to the expected fault data for + * the source operation + * @param fault The fault data, such as Java exception or fault message + * @param sourceOperation The source operation + * @param targetOperation The target operation + * @param metadata Additional metadata + * @return The transformed fault data for the source operation + */ + Object mediateFault(Object fault, Operation sourceOperation, Operation targetOperation, Map metadata); + + /** + * Copy the data + * @param data The orginal data + * @param dataType The data type + * @return The copy + */ + Object copy(Object data, DataType dataType); + + /** + * Copy the data + * @param data The orginal data + * @param dataType The source data type + * @param targetDataType The target data type + * @return The copy + */ + Object copy(Object data, DataType sourceDataType, DataType targetDataType); + + /** + * Copy the data + * @param data The orginal data + * @param sourceDataType The source data type + * @param targetDataType The target data type + * @param sourceOperation The source operation + * @param targetOperation The target operation + * @return The copy + */ + Object copy(Object data, + DataType sourceDataType, + DataType targetDataType, + Operation sourceOperation, + Operation targetOperation); + + /** + * Copy an array of data objects passed to an operation + * @param data array of objects to copy + * @return the copy + */ + public Object copyInput(Object input, Operation operation); + + /** + * Copy an array of data objects passed to an operation + * @param sourceOperation The source operation + * @param targetOperation The target operation + * @return the copy + */ + public Object copyInput(Object input, Operation sourceOperation, Operation targetOperation); + + /** + * Copy the output data + * @param data The orginal output + * @param operation The operation + * @return The copy + */ + Object copyOutput(Object data, Operation operation); + + /** + * Copy the output data from target operation into source operation + * @param data The orginal output + * @param sourceOperation The operation + * @param targetOperation The target operation + * @return The copy + */ + Object copyOutput(Object data, Operation sourceOperation, Operation targetOperation); + + /** + * Copy the fault data + * @param fault The orginal fault data + * @param operation The operation + * @return The copy + */ + Object copyFault(Object fault, Operation operation); + + /** + * Copy the fault data from target operation into source operation + * @param fault The orginal fault data + * @param sourceOperation The operation + * @param targetOperation The target operation + * @return The copy + */ + Object copyFault(Object fault, Operation sourceOperation, Operation targetOperation); + + /** + * Get the DataBindings used by this mediator. + * @return + */ + DataBindingExtensionPoint getDataBindings(); + + /** + * Get the Transformers used by this mediator. + * @return + */ + TransformerExtensionPoint getTransformers(); + + /** + * Create an instance of TransformationContext + * @return + */ + TransformationContext createTransformationContext(); + + /** + * Create an instance of TransformationContext + * @param sourceDataType + * @param targetDataType + * @param metadata + * @return + */ + TransformationContext createTransformationContext(DataType sourceDataType, + DataType targetDataType, + Map metadata); + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/PullTransformer.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/PullTransformer.java new file mode 100644 index 0000000000..b65d392393 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/PullTransformer.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.databinding; + +/** + * PullTransformer transforms data from one binding format to the other one which can be directly consumed + * + * @param The source data type + * @param the target data type + * + * @version $Rev$ $Date$ + * @tuscany.spi.extension.inheritfrom + */ +public interface PullTransformer extends Transformer { + /** + * Transform source data into the result type. + * + * @param source The source data + * @param context The context for the transformation + * @return The transformed result + */ + R transform(S source, TransformationContext context); +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/PushTransformer.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/PushTransformer.java new file mode 100644 index 0000000000..600a6477f6 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/PushTransformer.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.databinding; + +/** + * A transformer that pushes data from its source into the sink + * + * @param + * @param + * + * @version $Rev$ $Date$ + */ +public interface PushTransformer extends Transformer { + /** + * @param source The source data + * @param sink The sink to receive the data + * @param context + */ + void transform(S source, R sink, TransformationContext context); +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/SimpleTypeMapper.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/SimpleTypeMapper.java new file mode 100644 index 0000000000..6f2795fb51 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/SimpleTypeMapper.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; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.interfacedef.util.TypeInfo; + +/** + * Type Mapper between XML schema simple data types and java objects + * + * @version $Rev$ $Date$ + * @tuscany.spi.extension.asclient + */ +public interface SimpleTypeMapper { + /** + * Parse the XML lexical representation into a java object + * @param simpleType The XSD simple type + * @param value the XML lexical representation + * @param context The context of the transformation + * @return A java object for the XML value + */ + Object toJavaObject(QName simpleType, String value, TransformationContext context); + /** + * Create the XML lexical representation for a java object + * @param simpleType The XSD simple type + * @param obj The java object + * @param context The context of the transformation + * @return The XML lexical representation + */ + String toXMLLiteral(QName simpleType, Object obj, TransformationContext context); + + /** + * Get the java type for a simple xml type + * @param xmlType + * @return + */ + Class getJavaType(QName xmlType); + + /** + * Get the xml type for a java type + * @param javaType + * @return + */ + TypeInfo getXMLType(Class javaType); + + /** + * Check if an xml type is a simple type + * @param xmlType + * @return + */ + boolean isSimpleXSDType(QName xmlType); +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/TransformationContext.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/TransformationContext.java new file mode 100644 index 0000000000..64740b8e08 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/TransformationContext.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; + +import java.util.Map; + +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.Operation; + +/** + * Context for data transformation + * + * @version $Rev$ $Date$ + * @tuscany.spi.extension.asclient + */ +public interface TransformationContext { + + /** + * @return + */ + Operation getSourceOperation(); + + /** + * @param sourceOperation + */ + void setSourceOperation(Operation sourceOperation); + + /** + * @return + */ + Operation getTargetOperation(); + + /** + * @param targetOperation + */ + void setTargetOperation(Operation targetOperation); + + /** + * Get the source data type + * + * @return + */ + DataType getSourceDataType(); + + /** + * Get the target data type + * + * @return + */ + DataType getTargetDataType(); + + /** + * Set the source data type + * + * @param sourceDataType + */ + void setSourceDataType(DataType sourceDataType); + + /** + * Set the target data type + * + * @param targetDataType + */ + void setTargetDataType(DataType targetDataType); + + /** + * Get a map of metadata + * + * @return Returns a map of the metadata + */ + Map getMetadata(); + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/TransformationException.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/TransformationException.java new file mode 100644 index 0000000000..f32465d63a --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/TransformationException.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; + + +/** + * Reports problems during data transformation + * + * @version $Rev$ $Date$ + * @tuscany.spi.extension.asclient + */ +public class TransformationException extends RuntimeException { + + private static final long serialVersionUID = 7662385613693006428L; + private String sourceDataBinding; + private String targetDataBinding; + + public TransformationException() { + super(); + } + + public TransformationException(String message, Throwable cause) { + super(message, cause); + } + + public TransformationException(String message) { + super(message); + } + + public TransformationException(Throwable cause) { + super(cause); + } + + public String getSourceDataBinding() { + return sourceDataBinding; + } + + public void setSourceDataBinding(String sourceDataBinding) { + this.sourceDataBinding = sourceDataBinding; + } + + public String getTargetDataBinding() { + return targetDataBinding; + } + + public void setTargetDataBinding(String targetDataBinding) { + this.targetDataBinding = targetDataBinding; + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/Transformer.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/Transformer.java new file mode 100644 index 0000000000..2aa0ad7c15 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/Transformer.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.databinding; + +/** + * A transformer provides the data transformation from source type to target type. The cost of the transformation is + * modelled as weight. + * + * @version $Rev$ $Date$ + */ +public interface Transformer { + /** + * Get the source type that this transformer transforms data from. The type is used as the key when the transformer + * is registered with TransformerRegistry. + * + * @return A key identifying the source type + */ + String getSourceDataBinding(); + + /** + * Get the target type that this transformer transforms data into. The type is used as the key when the transformer + * is registered with TransformerRegistry. + * + * @return A key identifying the target type + */ + String getTargetDataBinding(); + + /** + * Get the cost of the transformation. The weight can be used to choose the most efficient path if there are more + * than one available from the source to the target. + * + * @return An integer representing the cost of the transformation + */ + int getWeight(); +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/TransformerExtensionPoint.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/TransformerExtensionPoint.java new file mode 100644 index 0000000000..ee7efe4860 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/TransformerExtensionPoint.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.databinding; + +import java.util.List; + +/** + * An extension point for data transformer extensions. + * + * @version $Rev$ $Date$ + */ +public interface TransformerExtensionPoint { + + /** + * Register a transformer + * + * @param sourceDataBinding + * @param targetDataBinding + * @param weight + * @param transformer + * @param publicTransformer TODO + */ + void addTransformer(String sourceDataBinding, + String targetDataBinding, + int weight, + Transformer transformer, + boolean publicTransformer); + + /** + * Register a transformer + * + * @param transformer + * @param publicTransformer TODO + */ + void addTransformer(Transformer transformer, boolean publicTransformer); + + /** + * Unregister a transformer + * + * @param sourceDataBinding + * @param targetDataBinding + * @return + */ + boolean removeTransformer(String sourceDataBinding, String targetDataBinding); + + /** + * Get the direct Transformer which can transform data from source type to + * result type + * + * @param sourceDataBinding + * @param targetDataBinding + * @return + */ + Transformer getTransformer(String sourceDataBinding, String targetDataBinding); + + /** + * Get the a chain of Transformers which can transform data from source type + * to result type + * + * @param sourceDataBinding + * @param targetDataBinding + * @return + */ + List getTransformerChain(String sourceDataBinding, String targetDataBinding); +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/WrapperHandler.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/WrapperHandler.java new file mode 100644 index 0000000000..4d32b41d4c --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/WrapperHandler.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.databinding; + +import java.util.List; + +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.Operation; + +/** + * A contract for transformers to deal with wrapping/unwrapping for WSDL wrapper style operations + * + * @version $Rev$ $Date$ + * @tuscany.spi.extension.inheritfrom + */ +public interface WrapperHandler { + /** + * Create a wrapper element + * @param operation The operation + * @param input Is it for input or output + * @return An object representing the wrapper element + */ + T create(Operation operation, boolean input); + + /** + * Get the data type for the wrapper + * @param operation The operation + * @param input Is it for input or output? + * @return The data type of the wrapper, null if it's not a wrapper type + */ + DataType getWrapperType(Operation operation, boolean input); + + /** + * Check if the given data is an instance of the wrapper + * @param wrapper + * @param operation The operation + * @param input Input or output + * @return + */ + boolean isInstance(Object wrapper, Operation operation, boolean input); + + /** + * Populate the wrapper element with the child objects + * @param wrapper The wrapper object + * @param childObjects The child objects + * @param operation The operation + * @param input Is it for input or output + */ + void setChildren(T wrapper, + Object[] childObjects, + Operation operation, + boolean input); + + /** + * Get a list of child elements from the wrapper + * @param wrapper The wrapper object + * @param operation The operation + * @param input Is it for input or output + * @return child elements under the wrapper + */ + List getChildren(T wrapper, Operation operation, boolean input); +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/XMLTypeHelper.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/XMLTypeHelper.java new file mode 100644 index 0000000000..19e1f7e13f --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/XMLTypeHelper.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; + +import java.util.List; + +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.Interface; +import org.apache.tuscany.sca.interfacedef.util.TypeInfo; +import org.apache.tuscany.sca.xsd.XSDFactory; +import org.apache.tuscany.sca.xsd.XSDefinition; + +/** + * XML and schema helper for Java types + * @tuscany.spi.extension.inheritfrom + */ +public interface XMLTypeHelper { + + // FIXME: This method seems to require the XMLHelper instance to be stateful + /** + * Convert a Java type into XML type information + * @param javaType the physical Java class + * @param logical the logical type information + * @return the XML type information + */ + TypeInfo getTypeInfo(Class javaType, Object logical); + + /** + * Get schema definitions for the Java types known to this helper + * @return A list of schema definitions + */ + // List getSchemaDefinitions(XSDFactory factory, ModelResolver resolver); + + /** + * Get a list of XML schemas for the given data types + * @param factory + * @param resolver + * @param dataTypes + * @return + */ + List getSchemaDefinitions(XSDFactory factory, ModelResolver resolver, List dataTypes); + /** + * Get a list of XML schemas for the given interface + * @param factory + * @param resolver + * @param intf + * @return + */ + List getSchemaDefinitions(XSDFactory factory, ModelResolver resolver, Interface intf); + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/annotation/DataBinding.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/annotation/DataBinding.java new file mode 100644 index 0000000000..4405077e29 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/annotation/DataBinding.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.databinding.annotation; + +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +/** + * Used to demarcate the mapping style for an interface or operation + * + * @version $Rev$ $Date$ + */ +// FIXME: [rfeng] We should consider to use javax.jws.soap.SOAPBinding +@Target({TYPE, METHOD}) +@Retention(RUNTIME) +public @interface DataBinding { + + /** + * Indicate the effective databinding that controls the WSDL/Java mapping of the + * interface/operation + * + * @return the data binding with the MIME media type syntax + */ + String value(); + + /** + * Indicate if the operation is mapped using WRAPPED or BARE style. Originated from + * javax.jws.soap.SOAPBinding.ParameterStyle: Determines whether method parameters + * represent the entire message body, or whether the parameters are elements wrapped + * inside a top-level element named after the operation + * + * @return true if the parameter style is WRAPPED, false if BARE + */ + boolean wrapped() default false; + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/annotation/DataType.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/annotation/DataType.java new file mode 100644 index 0000000000..650e909c61 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/annotation/DataType.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.databinding.annotation; + +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.ElementType.PARAMETER; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +/** + * Used to demarcate expected data types for parameters and return type + * + * @version $Rev$ $Date$ + */ +@Target( {METHOD, PARAMETER}) +@Retention(RUNTIME) +public @interface DataType { + + /** + * Returns the data binding configuration in MIME media type syntax + * @return the data binding + */ + String value(); + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/externalizable/ExternalizableDataBinding.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/externalizable/ExternalizableDataBinding.java new file mode 100644 index 0000000000..2c14d4c380 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/externalizable/ExternalizableDataBinding.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.databinding.externalizable; + +import org.apache.tuscany.sca.databinding.BaseDataBinding; + +/** + * DataNinding for Externalizable objects. + * + * @version $Rev$ $Date$ + */ +public class ExternalizableDataBinding extends BaseDataBinding { + + public static final String NAME = java.io.Externalizable.class.getName(); + + public ExternalizableDataBinding() { + super(NAME, java.io.Externalizable.class); + } + + + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/DirectedGraph.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/DirectedGraph.java new file mode 100644 index 0000000000..a551671452 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/DirectedGraph.java @@ -0,0 +1,469 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * 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.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.logging.Logger; + +/** + * Directed, weighted graph + * + * @param The type of vertex object + * @param The type of edge object + * + * @version $Rev$ $Date$ + */ +public class DirectedGraph implements Cloneable { + private final static Logger logger = Logger.getLogger(DirectedGraph.class.getName()); + private final Map vertices = new HashMap(); + + /** + * Key for the shortest path cache + */ + private final class VertexPair { + private Vertex source; + + private Vertex target; + + /** + * @param source + * @param target + */ + private VertexPair(Vertex source, Vertex target) { + super(); + this.source = source; + this.target = target; + } + + @Override + public boolean equals(Object object) { + if (!VertexPair.class.isInstance(object)) { + return false; + } + VertexPair pair = (VertexPair)object; + return source == pair.source && target == pair.target; + } + + @Override + public int hashCode() { + int x = source == null ? 0 : source.hashCode(); + int y = target == null ? 0 : target.hashCode(); + return x ^ y; + } + + } + + // Fix for TUSCANY-2069, making the map concurrent + private final Map paths = new ConcurrentHashMap(); + private final Path NULL_PATH = new Path(); + + /** + * Vertex of a graph + */ + public final class Vertex { + private V value; + + // TODO: Do we want to support multiple edges for a vertex pair? If so, + // we should use a List instead of Map + private Map outEdges = new HashMap(); + private Map inEdges = new HashMap(); + + private Vertex(V value) { + this.value = value; + } + + @Override + public String toString() { + return "(" + value + ")"; + } + + public V getValue() { + return value; + } + + public Map getOutEdges() { + return outEdges; + } + + public Map getInEdges() { + return inEdges; + } + + } + + /** + * An Edge connects two vertices in one direction + */ + public final class Edge { + private Vertex sourceVertex; + + private Vertex targetVertex; + + private E value; + + private int weight; + + private boolean pub = true; + + public Edge(Vertex source, Vertex target, E value, int weight, boolean pub) { + this.sourceVertex = source; + this.targetVertex = target; + this.value = value; + this.weight = weight; + this.pub = pub; + } + + @Override + public String toString() { + return sourceVertex + "->" + targetVertex + "[" + value + "," + weight + "]"; + } + + public E getValue() { + return value; + } + + public void setValue(E value) { + this.value = value; + } + + public Vertex getTargetVertex() { + return targetVertex; + } + + public void setTargetVertex(Vertex vertex) { + this.targetVertex = vertex; + } + + public int getWeight() { + return weight; + } + + public void setWeight(int weight) { + this.weight = weight; + } + + public Vertex getSourceVertex() { + return sourceVertex; + } + + public void setSourceVertex(Vertex sourceVertex) { + this.sourceVertex = sourceVertex; + } + + public boolean isPublic() { + return pub; + } + + public void setPublic(boolean pub) { + this.pub = pub; + } + } + + private final class Node implements Comparable { + + private long distance = Integer.MAX_VALUE; + + private Node previous; // NOPMD by rfeng on 9/26/06 9:17 PM + + private Vertex vertex; // NOPMD by rfeng on 9/26/06 9:17 PM + + private Node(Vertex vertex) { + this.vertex = vertex; + } + + public int compareTo(Node o) { + return (distance > o.distance) ? 1 : ((distance == o.distance) ? 0 : -1); + } + } + + public void addEdge(V source, V target, E edgeValue, int weight, boolean publicEdge) { + // Fix for TUSCANY-3456 + // First check if we already has an edge + Edge edge = getEdge(source, target); + if (edge != null) { + // An existing edge has higher weight, let's replace it + if (edge.weight > weight) { + logger.fine("An edge exists with higher weight: " + edge); + removeEdge(edge); + } else { + // Don't add this edge + logger.fine("An edge exists with lower weight: " + edge); + return; + } + } + + Vertex s = getVertex(source); + if (s == null) { + s = new Vertex(source); + vertices.put(source, s); + } + Vertex t = getVertex(target); + if (t == null) { + t = new Vertex(target); + vertices.put(target, t); + } + edge = new Edge(s, t, edgeValue, weight, publicEdge); + s.outEdges.put(t, edge); + t.inEdges.put(s, edge); + } + + public void addEdge(V soure, V target) { + addEdge(soure, target, null, 0, true); + } + + public Vertex getVertex(V source) { + Vertex s = vertices.get(source); + return s; + } + + public boolean removeEdge(V source, V target) { + Vertex s = getVertex(source); + if (s == null) { + return false; + } + + Vertex t = getVertex(target); + if (t == null) { + return false; + } + + return s.outEdges.remove(t) != null && t.inEdges.remove(s) != null; + + } + + public void removeEdge(Edge edge) { + edge.sourceVertex.outEdges.remove(edge.targetVertex); + edge.targetVertex.inEdges.remove(edge.sourceVertex); + } + + public void removeVertex(Vertex vertex) { + vertices.remove(vertex.getValue()); + for (Edge e : new ArrayList(vertex.outEdges.values())) { + removeEdge(e); + } + for (Edge e : new ArrayList(vertex.inEdges.values())) { + removeEdge(e); + } + } + + public Edge getEdge(Vertex source, Vertex target) { + return source.outEdges.get(target); + } + + public Edge getEdge(V source, V target) { + Vertex sv = getVertex(source); + if (sv == null) { + return null; + } + Vertex tv = getVertex(target); + if (tv == null) { + return null; + } + return getEdge(getVertex(source), getVertex(target)); + } + + /** + * Get the shortest path from the source vertex to the target vertex using + * Dijkstra's algorithm. If there's no path, null will be returned. If the + * source is the same as the target, it returns a path with empty edges with + * weight 0. + * + * @param sourceValue The value identifies the source + * @param targetValue The value identifies the target + * @return The shortest path + */ + public Path getShortestPath(V sourceValue, V targetValue) { + Vertex source = getVertex(sourceValue); + if (source == null) { + return null; + } + Vertex target = getVertex(targetValue); + if (target == null) { + return null; + } + + VertexPair pair = new VertexPair(source, target); + Path path = null; + if (paths.containsKey(pair)) { + path = paths.get(pair); + return path == NULL_PATH? null: path; + } + + // Check if there is a direct link, if yes, use it instead + Edge direct = getEdge(source, target); + path = new Path(); + if (direct != null) { + path.addEdge(direct); + paths.put(pair, path); + return path; + } + + Map nodes = new HashMap(); + for (Vertex v : vertices.values()) { + Node node = new Node(v); + if (v == source) { + node.distance = 0; + } + nodes.put(v, node); + } + + Set otherNodes = new HashSet(nodes.values()); + Set nodesOnPath = new HashSet(); + Node nextNode = null; + while (!otherNodes.isEmpty()) { + nextNode = extractMin(otherNodes); + if (nextNode.vertex == target) { + path = getPath(nextNode); + paths.put(pair, path); // Cache it + return path == NULL_PATH? null: path; + } + nodesOnPath.add(nextNode); + for (Edge edge : nextNode.vertex.outEdges.values()) { + Node adjacentNode = nodes.get(edge.targetVertex); + // The private edge can only be used if the edge connects to the target directly + if (edge.isPublic() || edge.getTargetVertex() == target) { + if (nextNode.distance + edge.weight < adjacentNode.distance) { + adjacentNode.distance = nextNode.distance + edge.weight; + adjacentNode.previous = nextNode; + } + } + } + } + paths.put(pair, NULL_PATH); // Cache it + return null; + } + + /** + * Searches for the vertex u in the vertex set Q that has the least d[u] + * value. That vertex is removed from the set Q and returned to the user. + * + * @param nodes + * @return + */ + private Node extractMin(Set nodes) { + Node node = Collections.min(nodes); + nodes.remove(node); + return node; + } + + /** + * The path between two vertices + */ + public final class Path { + private List edges = new LinkedList(); + + private int weight; + + public int getWeight() { + return weight; + } + + public List getEdges() { + return edges; + } + + public void addEdge(Edge edge) { + edges.add(0, edge); + weight += edge.weight; + } + + @Override + public String toString() { + return edges + ", " + weight; + } + } + + private Path getPath(Node t) { + if (t.distance == Integer.MAX_VALUE) { + return NULL_PATH; + } + Path path = new Path(); + Node u = t; + while (u.previous != null) { + Edge edge = getEdge(u.previous.vertex, u.vertex); + path.addEdge(edge); + u = u.previous; + } + return path; + } + + @Override + public String toString() { + StringBuffer sb = new StringBuffer(); + for (Vertex v : vertices.values()) { + sb.append(v.outEdges.values()).append("\n"); + } + return sb.toString(); + } + + public Map getVertices() { + return vertices; + } + + public void addGraph(DirectedGraph otherGraph) { + for (Vertex v : otherGraph.vertices.values()) { + for (Edge e : v.outEdges.values()) { + addEdge(e.sourceVertex.value, e.targetVertex.value, e.value, e.weight, true); + } + } + } + + private Vertex getFirst() { + for (Vertex v : vertices.values()) { + if (v.inEdges.isEmpty()) { + return v; + } + } + if (!vertices.isEmpty()) { + throw new IllegalArgumentException("Circular ordering has been detected: " + toString()); + } else { + return null; + } + } + + public List topologicalSort(boolean readOnly) { + DirectedGraph graph = (!readOnly) ? this : (DirectedGraph)clone(); + List list = new ArrayList(); + while (true) { + Vertex v = graph.getFirst(); + if (v == null) { + break; + } + list.add(v.getValue()); + graph.removeVertex(v); + } + + return list; + } + + @Override + public Object clone() { + DirectedGraph copy = new DirectedGraph(); + copy.addGraph(this); + return copy; + } +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/Group2GroupTransformer.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/Group2GroupTransformer.java new file mode 100644 index 0000000000..d4d0312bc0 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/Group2GroupTransformer.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.impl; + +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.core.UtilityExtensionPoint; +import org.apache.tuscany.sca.databinding.BaseTransformer; +import org.apache.tuscany.sca.databinding.Mediator; +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.interfacedef.DataType; + +/** + * This is a special transformer to transform the output from one IDL to the + * other one + * + * @version $Rev$ $Date$ + */ +public class Group2GroupTransformer extends BaseTransformer implements + PullTransformer { + + protected Mediator mediator; + + /** + * @param wrapperHandler + */ + public Group2GroupTransformer(ExtensionPointRegistry registry) { + super(); + this.mediator = registry.getExtensionPoint(UtilityExtensionPoint.class).getUtility(Mediator.class); + } + + @Override + public String getSourceDataBinding() { + return GroupDataBinding.NAME; + } + + @Override + public String getTargetDataBinding() { + return GroupDataBinding.NAME; + } + + /** + * @see org.apache.tuscany.sca.databinding.BaseTransformer#getSourceType() + */ + @Override + protected Class getSourceType() { + return Object.class; + } + + /** + * @see org.apache.tuscany.sca.databinding.BaseTransformer#getTargetType() + */ + @Override + protected Class getTargetType() { + return Object.class; + } + + /** + * @see org.apache.tuscany.sca.databinding.Transformer#getWeight() + */ + @Override + public int getWeight() { + return 10; + } + + @SuppressWarnings("unchecked") + public Object transform(Object source, TransformationContext context) { + DataType sourceType = context.getSourceDataType(); + DataType targetType = context.getTargetDataType(); + + return mediator.mediate(source, sourceType.getLogical(), targetType.getLogical(), context.getMetadata()); + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/GroupDataBinding.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/GroupDataBinding.java new file mode 100644 index 0000000000..1c7220fa67 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/GroupDataBinding.java @@ -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. + */ + +package org.apache.tuscany.sca.databinding.impl; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; + +import org.apache.tuscany.sca.databinding.BaseDataBinding; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.interfacedef.util.XMLType; + +/** + * The base class for a special databinding which represents a group of other databindings + * + * @version $Rev$ $Date$ + */ +public abstract class GroupDataBinding extends BaseDataBinding { + public static final String NAME = "databinding:group"; + + /** + * Marker type is a java class or interface representing the data format. + */ + protected Class[] markerTypes; + + public GroupDataBinding(Class[] types) { + super(NAME, GroupDataBinding.class); + this.markerTypes = types; + } + + @SuppressWarnings("unchecked") + @Override + public boolean introspect(DataType type, Operation operation) { + if (markerTypes == null) { + return false; + } + Type physical = type.getPhysical(); + if (physical instanceof ParameterizedType) { + physical = ((ParameterizedType)physical).getRawType(); + } + if (!(physical instanceof Class)) { + return false; + } + Class cls = (Class)physical; + for (Class c : markerTypes) { + if (isTypeOf(c, cls)) { + type.setDataBinding(getDataBinding(c)); + Object logical = getLogical(cls, null); + if (logical != null) { + type.setLogical(getLogical(cls, null)); + } else { + type.setLogical(XMLType.UNKNOWN); + } + return true; + } + } + return false; + } + + /** + * Test if the given type is a subtype of the base type + * @param markerType + * @param type + * @return + */ + protected boolean isTypeOf(Class markerType, Class type) { + return markerType.isAssignableFrom(type); + } + + /** + * Derive the databinding name from a base class + * @param baseType + * @return + */ + protected String getDataBinding(Class baseType) { + return baseType.getName(); + } + + /** + * Get the logical type + * @param type The java type + * @param operation TODO + * @return + */ + protected abstract Object getLogical(Class type, Operation operation); + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/Java2SimpleTypeTransformer.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/Java2SimpleTypeTransformer.java new file mode 100644 index 0000000000..f6e8e53459 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/Java2SimpleTypeTransformer.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.impl; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.databinding.BaseTransformer; +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.SimpleTypeMapper; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.javabeans.SimpleJavaDataBinding; +import org.apache.tuscany.sca.interfacedef.util.XMLType; + +/** + * Transformer to convert data from a simple java object to a databinding's representation + * + * @version $Rev$ $Date$ + * @tuscany.spi.extension.inheritfrom + */ +public abstract class Java2SimpleTypeTransformer extends BaseTransformer implements + PullTransformer { + + protected SimpleTypeMapper mapper; + + public Java2SimpleTypeTransformer() { + this.mapper = new SimpleTypeMapperImpl(); + } + + public Java2SimpleTypeTransformer(SimpleTypeMapper mapper) { + this.mapper = (mapper != null) ? mapper : new SimpleTypeMapperImpl(); + } + + public T transform(Object source, TransformationContext context) { + XMLType xmlType = (XMLType) context.getTargetDataType().getLogical(); + String text = mapper.toXMLLiteral(xmlType.getTypeName(), source, context); + return createElement(xmlType.getElementName(), text, context); + } + + @Override + public Class getSourceType() { + return Object.class; + } + + @Override + public int getWeight() { + return 10000; + } + + protected abstract T createElement(QName element, String literal, TransformationContext context); + + @Override + public String getSourceDataBinding() { + return SimpleJavaDataBinding.NAME; + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/MediatorImpl.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/MediatorImpl.java new file mode 100644 index 0000000000..20c6c2b9e2 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/MediatorImpl.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.databinding.impl; + +import static org.apache.tuscany.sca.interfacedef.Operation.IDL_FAULT; +import static org.apache.tuscany.sca.interfacedef.Operation.IDL_OUTPUT; + +import java.io.Serializable; +import java.lang.reflect.Array; +import java.lang.reflect.InvocationTargetException; +import java.net.URI; +import java.util.HashMap; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.core.UtilityExtensionPoint; +import org.apache.tuscany.sca.databinding.DataBinding; +import org.apache.tuscany.sca.databinding.DataBindingExtensionPoint; +import org.apache.tuscany.sca.databinding.DataPipe; +import org.apache.tuscany.sca.databinding.DataPipeTransformer; +import org.apache.tuscany.sca.databinding.Mediator; +import org.apache.tuscany.sca.databinding.PullTransformer; +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.Transformer; +import org.apache.tuscany.sca.databinding.TransformerExtensionPoint; +import org.apache.tuscany.sca.databinding.javabeans.JavaBeansDataBinding; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.FaultExceptionMapper; +import org.apache.tuscany.sca.interfacedef.InterfaceContractMapper; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.interfacedef.ParameterMode; +import org.apache.tuscany.sca.interfacedef.impl.DataTypeImpl; +import org.apache.tuscany.sca.interfacedef.util.FaultException; +import org.apache.tuscany.sca.interfacedef.util.XMLType; +import org.oasisopen.sca.ServiceRuntimeException; + + +/** + * Default Mediator implementation + * + * @version $Rev$ $Date$ + * @tuscany.spi.extension.asclient + */ +public class MediatorImpl implements Mediator { + + private ExtensionPointRegistry registry; + private DataBindingExtensionPoint dataBindings; + private TransformerExtensionPoint transformers; + private InterfaceContractMapper interfaceContractMapper; + private FaultExceptionMapper faultExceptionMapper; + + MediatorImpl(DataBindingExtensionPoint dataBindings, TransformerExtensionPoint transformers) { + this.dataBindings = dataBindings; + this.transformers = transformers; + } + + public MediatorImpl(ExtensionPointRegistry registry) { + this.registry = registry; + this.dataBindings = registry.getExtensionPoint(DataBindingExtensionPoint.class); + this.transformers = registry.getExtensionPoint(TransformerExtensionPoint.class); + UtilityExtensionPoint utilities = registry.getExtensionPoint(UtilityExtensionPoint.class); + this.interfaceContractMapper = utilities.getUtility(InterfaceContractMapper.class); + this.faultExceptionMapper = utilities.getUtility(FaultExceptionMapper.class); + + } + + @SuppressWarnings("unchecked") + public Object mediate(Object source, DataType sourceDataType, DataType targetDataType, Map metadata) { + if (sourceDataType == null || sourceDataType.getDataBinding() == null) { + if (source != null) { + Operation operation = (Operation)metadata.get(SOURCE_OPERATION); + sourceDataType = dataBindings.introspectType(source, operation); + } + } + if (sourceDataType == null || targetDataType == null) { + return source; + } else if (sourceDataType.equals(targetDataType)) { + return source; + } + + List path = getTransformerChain(sourceDataType, targetDataType); + + Object result = source; + int size = path.size(); + int i = 0; + while (i < size) { + Transformer transformer = path.get(i); + TransformationContext context = + createTransformationContext(sourceDataType, targetDataType, size, i, transformer, metadata); + // the source and target type + if (transformer instanceof PullTransformer) { + // For intermediate node, set data type to null + result = ((PullTransformer)transformer).transform(result, context); + } else if (transformer instanceof PushTransformer) { + DataPipeTransformer dataPipeFactory = (i < size - 1) ? (DataPipeTransformer)path.get(++i) : null; + DataPipe dataPipe = dataPipeFactory == null ? null : dataPipeFactory.newInstance(); + ((PushTransformer)transformer).transform(result, dataPipe.getSink(), context); + result = dataPipe.getResult(); + } + i++; + } + + return result; + } + + private TransformationContext createTransformationContext(DataType sourceDataType, + DataType targetDataType, + int size, + int index, + Transformer transformer, + Map metadata) { + DataType sourceType = + (index == 0) ? sourceDataType : new DataTypeImpl(transformer.getSourceDataBinding(), Object.class, + sourceDataType.getLogical()); + DataType targetType = + (index == size - 1) ? targetDataType : new DataTypeImpl(transformer.getTargetDataBinding(), + Object.class, targetDataType.getLogical()); + + Map copy = new HashMap(); + if (metadata != null) { + copy.putAll(metadata); + } + copy.put(ExtensionPointRegistry.class.getName(), registry); + + TransformationContext context = new TransformationContextImpl(sourceType, targetType, copy); + return context; + } + + @SuppressWarnings("unchecked") + public void mediate(Object source, + Object target, + DataType sourceDataType, + DataType targetDataType, + Map metadata) { + if (source == null) { + // Shortcut for null value + return; + } + if (sourceDataType == null || sourceDataType.getDataBinding() == null) { + Operation operation = (Operation)metadata.get(SOURCE_OPERATION); + sourceDataType = dataBindings.introspectType(source, operation); + } + if (sourceDataType == null) { + return; + } else if (sourceDataType.equals(targetDataType)) { + return; + } + + List path = getTransformerChain(sourceDataType, targetDataType); + Object result = source; + int size = path.size(); + for (int i = 0; i < size; i++) { + Transformer transformer = path.get(i); + TransformationContext context = + createTransformationContext(sourceDataType, targetDataType, size, i, transformer, metadata); + + if (transformer instanceof PullTransformer) { + result = ((PullTransformer)transformer).transform(result, context); + } else if (transformer instanceof PushTransformer) { + DataPipeTransformer dataPipeFactory = (i < size - 1) ? (DataPipeTransformer)path.get(++i) : null; + DataPipe dataPipe = dataPipeFactory == null ? null : dataPipeFactory.newInstance(); + Object sink = dataPipe != null ? dataPipe.getSink() : target; + ((PushTransformer)transformer).transform(result, sink, context); + result = (dataPipe != null) ? dataPipe.getResult() : null; + } + } + } + + private List getTransformerChain(DataType sourceDataType, DataType targetDataType) { + String sourceId = sourceDataType.getDataBinding(); + String targetId = targetDataType.getDataBinding(); + List path = transformers.getTransformerChain(sourceId, targetId); + if (path == null) { + TransformationException ex = + new TransformationException("No path found for the transformation: " + sourceId + "->" + targetId); + ex.setSourceDataBinding(sourceId); + ex.setTargetDataBinding(targetId); + throw ex; + } + return path; + } + + public DataBindingExtensionPoint getDataBindings() { + return dataBindings; + } + + public TransformerExtensionPoint getTransformers() { + return transformers; + } + + /** + * Find the fault data type behind the exception data type + * @param exceptionType The exception data type + * @return The fault data type + */ + private DataType getFaultType(DataType exceptionType) { + return exceptionType == null ? null : (DataType)exceptionType.getLogical(); + } + + /** + * @param qn1 + * @param qn2 + */ + private boolean matches(QName qn1, QName qn2) { + if (qn1 == qn2) { + return true; + } + if (qn1 == null || qn2 == null) { + return false; + } + String ns1 = qn1.getNamespaceURI(); + String ns2 = qn2.getNamespaceURI(); + String e1 = qn1.getLocalPart(); + String e2 = qn2.getLocalPart(); + if (e1.equals(e2) && (ns1.equals(ns2) || ns1.equals(ns2 + "/") || ns2.equals(ns1 + "/"))) { + // Tolerating the trailing / which is required by JAX-WS java package --> xml ns mapping + return true; + } + return false; + } + + /** + * @param source The source exception + * @param sourceExType The data type for the source exception + * @param targetExType The data type for the target exception + * @param sourceType The fault type for the source + * @param targetType The fault type for the target + * @return + */ + private Object transformException(Object source, + DataType sourceExType, + DataType targetExType, + DataType sourceType, + DataType targetType, + Map metadata) { + + if (sourceType == targetType || (sourceType != null && sourceType.equals(targetType))) { + return source; + } + + DataType eSourceDataType = + new DataTypeImpl(IDL_FAULT, sourceExType.getPhysical(), sourceType); + DataType eTargetDataType = + new DataTypeImpl(IDL_FAULT, targetExType.getPhysical(), targetType); + + return mediate(source, eSourceDataType, eTargetDataType, metadata); + } + + // + // Assumes we're going from target->source, knowing that we're throwing BACK an exception, rather than the more + // obvious source->target + // + public Object mediateFault(Object result, + Operation sourceOperation, + Operation targetOperation, + Map metadata) { + + // FIXME: How to match fault data to a fault type for the + // operation? + + // If the result is from an InvocationTargetException look at + // the actual cause. + if (result instanceof InvocationTargetException) { + result = ((InvocationTargetException)result).getCause(); + } + + DataType targetDataType = findFaultDataType(targetOperation, result); + DataType targetFaultType = getFaultType(targetDataType); + + + if (targetFaultType == null) { + // No matching fault type, it's a system exception + Throwable cause = (Throwable)result; + throw new ServiceRuntimeException(cause); + } + + // FIXME: How to match a source fault type to a target fault + // type? + DataType sourceDataType = null; + DataType sourceFaultType = null; + for (DataType exType : sourceOperation.getFaultTypes()) { + DataType faultType = getFaultType(exType); + // Match by the QName (XSD element) of the fault type + if (faultType != null && typesMatch(targetFaultType.getLogical(), faultType.getLogical())) { + sourceDataType = exType; + sourceFaultType = faultType; + break; + } + } + + if (sourceFaultType == null) { + // No matching fault type, it's a system exception + Throwable cause = (Throwable)result; + throw new ServiceRuntimeException(cause); + } + + Map context = new HashMap(); + if (metadata != null) { + context.putAll(metadata); + } + if (targetOperation != null) { + context.put(SOURCE_OPERATION, targetOperation); + } + if (sourceOperation != null) { + context.put(TARGET_OPERATION, sourceOperation); + } + if (context.get(BODY_TYPE) == null) { + context.put(BODY_TYPE, BODY_TYPE_FAULT); + } + + + Object newResult = + transformException(result, targetDataType, sourceDataType, targetFaultType, sourceFaultType, context); + + return newResult; + + } + + /** + * Look up the fault data type that matches the fault or exception instance + * @param operation The operation + * @param faultOrException The fault or exception + * @return The matching fault data type + */ + private DataType findFaultDataType(Operation operation, Object faultOrException) { + DataType targetDataType = null; + for (DataType exType : operation.getFaultTypes()) { + if (((Class)exType.getPhysical()).isInstance(faultOrException)) { + if (faultOrException instanceof FaultException) { + DataType faultType = (DataType)exType.getLogical(); + if (((FaultException)faultOrException).isMatchingType(faultType.getLogical())) { + targetDataType = exType; + break; + } + } else { + targetDataType = exType; + break; + } + } + } + return targetDataType; + } + + private boolean typesMatch(Object first, Object second) { + if (first.equals(second)) { + return true; + } + if (first instanceof XMLType && second instanceof XMLType) { + XMLType t1 = (XMLType)first; + XMLType t2 = (XMLType)second; + // TUSCANY-2113, we should compare element names only + return matches(t1.getElementName(), t2.getElementName()); + } + return false; + } + + /** + * Assumes we're going from target-to-source, knowing that we're sending BACK an output response, rather than the more + * obvious source-to-target. + * + * @param output + * @param sourceOperation + * @param targetOperation + * @return + */ + public Object mediateOutput(Object output, + Operation sourceOperation, + Operation targetOperation, + Map metadata) { + + DataType sourceType = sourceOperation.getOutputType(); + DataType targetType = targetOperation.getOutputType(); + + if (sourceType == targetType || (sourceType != null && sourceType.equals(targetType))) { + return output; + } + Map context = new HashMap(); + if (metadata != null) { + context.putAll(metadata); + } + if (targetOperation != null) { + context.put(SOURCE_OPERATION, targetOperation); + } + if (sourceOperation != null) { + context.put(TARGET_OPERATION, sourceOperation); + } + if (context.get(BODY_TYPE) == null) { + context.put(BODY_TYPE, BODY_TYPE_OUTPUT); + } + + return mediate(output, targetType, sourceType, context); + } + + public Object mediateInput(Object input, + Operation sourceOperation, + Operation targetOperation, + Map metadata) { + // Get the data type to represent the input passed in by the source operation + DataType sourceType = sourceOperation.getInputType(); + + // Get the data type to represent the input expected by the target operation + DataType targetType = targetOperation.getInputType(); + + if (sourceType == targetType || (sourceType != null && sourceType.equals(targetType))) { + return input; + } + Map context = new HashMap(); + if (metadata != null) { + context.putAll(metadata); + } + if (sourceOperation != null) { + context.put(SOURCE_OPERATION, sourceOperation); + } + if (targetOperation != null) { + context.put(TARGET_OPERATION, targetOperation); + } + if (context.get(BODY_TYPE) == null) { + context.put(BODY_TYPE, BODY_TYPE_INPUT); + } + + return mediate(input, sourceType, targetType, context); + } + + public TransformationContext createTransformationContext() { + return new TransformationContextImpl(); + } + + public TransformationContext createTransformationContext(DataType sourceDataType, + DataType targetDataType, + Map metadata) { + return new TransformationContextImpl(sourceDataType, targetDataType, metadata); + } + + public Object copy(Object data, DataType dataType) { + return copy(data, dataType, dataType, null, null); + } + + public Object copy(Object data, DataType sourceDataType, DataType targetDataType) { + return copy(data, sourceDataType, targetDataType, null, null); + } + + /** + * Copy data using the specified databinding. + * @param data input data + * @param sourceDataType + * @return a copy of the data + */ + public Object copy(Object data, + DataType sourceDataType, + DataType targetDataType, + Operation sourceOperation, + Operation targetOperation) { + if (data == null) { + return null; + } + Class clazz = data.getClass(); + if (String.class == clazz || clazz.isPrimitive() + || Number.class.isAssignableFrom(clazz) + || Boolean.class.isAssignableFrom(clazz) + || Character.class.isAssignableFrom(clazz) + || Byte.class.isAssignableFrom(clazz) + || URI.class == clazz + || UUID.class == clazz + || QName.class == clazz) { + // Immutable classes + return data; + } + + DataBinding javaBeansDataBinding = dataBindings.getDataBinding(JavaBeansDataBinding.NAME); + // FIXME: The JAXB databinding is hard-coded here + DataBinding jaxbDataBinding = dataBindings.getDataBinding("javax.xml.bind.JAXBElement"); + DataBinding dataBinding = dataBindings.getDataBinding(sourceDataType.getDataBinding()); + // If no databinding was specified, introspect the given arg to + // determine its databinding + if (dataBinding == null) { + if (!"java:array".equals(sourceDataType.getDataBinding())) { + sourceDataType = dataBindings.introspectType(data, sourceOperation); + if (sourceDataType != null) { + String db = sourceDataType.getDataBinding(); + dataBinding = dataBindings.getDataBinding(db); + if (dataBinding == null && db != null) { + return data; + } + } + } + if (dataBinding == null) { + + // Default to the JavaBean databinding + dataBinding = dataBindings.getDataBinding(JavaBeansDataBinding.NAME); + } + } + + // Use the JAXB databinding to copy non-Serializable data + if (dataBinding == javaBeansDataBinding) { + + // If the input data is an array containing non Serializable elements + // use JAXB + clazz = data.getClass(); + if (clazz.isArray()) { + if (Array.getLength(data) != 0) { + Object element = Array.get(data, 0); + if (element != null && !(element instanceof Serializable)) { + dataBinding = jaxbDataBinding; + } + } + } else { + + // If the input data is not Serializable use JAXB + if (!((data instanceof Serializable) || (data instanceof Cloneable))) { + dataBinding = jaxbDataBinding; + } + } + } + + if (dataBinding == null) { + return data; + } + + return dataBinding.copy(data, sourceDataType, targetDataType, sourceOperation, targetOperation); + } + + /** + * Copy an array of data objects passed to an operation + * @param data array of objects to copy + * @return the copy + */ + public Object copyInput(Object input, Operation operation) { + return copyInput(input, operation, operation); + } + public Object copyInput(Object input, Operation sourceOperation, Operation targetOperation) { + if (input == null) { + return null; + } + Object[] data = (input instanceof Object[]) ? (Object[])input : new Object[] {input}; + List inputTypes = sourceOperation.getInputType().getLogical(); + List inputTypesTarget = targetOperation == null ? null : targetOperation.getInputType().getLogical(); + Object[] copy = new Object[data.length]; + Map map = new IdentityHashMap(); + + // OUT-only parameters have already been filtered out of the inputTypes List. + for (int i = 0; i < inputTypes.size(); i++) { + Object arg = data[i]; + if (arg == null) { + copy[i] = null; + } else { + Object copiedArg = map.get(arg); + if (copiedArg != null) { + copy[i] = copiedArg; + } else { + copiedArg = + copy(arg, + inputTypes.get(i), + inputTypesTarget == null ? null : inputTypesTarget.get(i), + sourceOperation, + targetOperation); + map.put(arg, copiedArg); + copy[i] = copiedArg; + } + } + } + return copy; + } + + public Object copyOutput(Object data, Operation operation) { + return copyOutput(data, operation, operation); + } + + public Object copyOutput(Object data, Operation sourceOperation, Operation targetOperation) { + + // Rename the parameters so we can more easily remember which direction we're going in. + Operation fromOperation = targetOperation; + Operation toOperation = sourceOperation; + + if ( data == null ) + return null; + Object[] output = null; + + if ( !fromOperation.hasArrayWrappedOutput() ) { + output = new Object[] {data}; + } else { + output = (Object[])data; + } + + List outputTypes = fromOperation.getOutputType().getLogical(); + List outputTypesTarget = toOperation == null ? null : toOperation.getOutputType().getLogical(); + Object[] copy = new Object[output.length]; + Map map = new IdentityHashMap(); + for (int i = 0, size = output.length; i < size; i++) { + Object arg = output[i]; + if (arg == null) { + copy[i] = null; + } else { + Object copiedArg = map.get(arg); + if (copiedArg != null) { + copy[i] = copiedArg; + } else { + copiedArg = + copy(arg, + outputTypes.get(i), + outputTypesTarget == null ? null : outputTypesTarget.get(i), + fromOperation, + toOperation); + map.put(arg, copiedArg); + copy[i] = copiedArg; + } + } + } + if ( !toOperation.hasArrayWrappedOutput()) { + return copy[0]; + } else { + return copy; + } + } + + public Object copyFault(Object fault, Operation operation) { + return copyFault(fault, operation, operation); + } + + public Object copyFault(Object fault, Operation sourceOperation, Operation targetOperation) { + + // Rename the parameters so we can more easily remember which direction we're going in. + Operation fromOperation = targetOperation; + Operation toOperation = sourceOperation; + + if (faultExceptionMapper == null) { + return fault; + } + List fts = fromOperation.getFaultTypes(); + for (int i = 0; i < fts.size(); i++) { + DataType et = fts.get(i); + if (et.getPhysical().isInstance(fault)) { + Throwable ex = (Throwable)fault; + DataType exType = findFaultDataType(fromOperation, fault); + DataType faultType = getFaultType(exType); + Object faultInfo = faultExceptionMapper.getFaultInfo(ex, faultType.getPhysical(), fromOperation); + DataType targetExType = findSourceFaultDataType(toOperation, exType); + DataType targetFaultType = getFaultType(targetExType); + faultInfo = copy(faultInfo, faultType, targetFaultType, fromOperation, toOperation); + fault = faultExceptionMapper.wrapFaultInfo(targetExType, ex.getMessage(), faultInfo, ex.getCause(), toOperation); + return fault; + } + } + return fault; + } + + /** + * Lookup a fault data type from the source operation which matches the target fault data type + * @param sourceOperation The source operation + * @param targetExceptionType The target fault data type + * @return The matching source target fault type + */ + private DataType findSourceFaultDataType(Operation sourceOperation, DataType targetExceptionType) { + boolean remotable = sourceOperation.getInterface().isRemotable(); + DataType targetFaultType = getFaultType(targetExceptionType); + for (DataType dt : sourceOperation.getFaultTypes()) { + DataType sourceFaultType = getFaultType(dt); + if (interfaceContractMapper.isCompatible(targetFaultType, sourceFaultType, remotable)) { + return dt; + } + } + return null; + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/PipedTransformer.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/PipedTransformer.java new file mode 100644 index 0000000000..a1a89005b3 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/PipedTransformer.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.impl; + +import org.apache.tuscany.sca.databinding.DataPipe; +import org.apache.tuscany.sca.databinding.DataPipeTransformer; +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.PushTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; + +/** + * A utility class to connect PushTransformer and DataPipe to create a + * PullTransformer + * + * @param Source type + * @param Intermediate type + * @param Result type + * + * @version $Rev$ $Date$ + */ +public class PipedTransformer implements PullTransformer { + private PushTransformer pusher; + + private DataPipeTransformer pipe; + + /** + * @param pumper + * @param pipe + */ + public PipedTransformer(PushTransformer pumper, DataPipeTransformer pipe) { + super(); + this.pusher = pumper; + this.pipe = pipe; + } + + public R transform(S source, TransformationContext context) { + DataPipe dataPipe = pipe.newInstance(); + pusher.transform(source, dataPipe.getSink(), context); + return dataPipe.getResult(); + } + + public String getSourceDataBinding() { + return pusher.getSourceDataBinding(); + } + + public String getTargetDataBinding() { + return pipe.getTargetDataBinding(); + } + + public int getWeight() { + return pusher.getWeight() + pipe.getWeight(); + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/SimpleType2JavaTransformer.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/SimpleType2JavaTransformer.java new file mode 100644 index 0000000000..a7849498b4 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/SimpleType2JavaTransformer.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.impl; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.databinding.BaseTransformer; +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.SimpleTypeMapper; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.javabeans.SimpleJavaDataBinding; +import org.apache.tuscany.sca.interfacedef.util.XMLType; + +/** + * Transformer to convert data from a databinding's representation of simple + * types to Java Objects + * + * @version $Rev$ $Date$ + * @tuscany.spi.extension.inheritfrom + */ +public abstract class SimpleType2JavaTransformer extends BaseTransformer implements + PullTransformer { + + protected SimpleTypeMapper mapper; + + public SimpleType2JavaTransformer() { + this.mapper = new SimpleTypeMapperImpl(); + } + + public SimpleType2JavaTransformer(SimpleTypeMapper mapper) { + this.mapper = (mapper != null) ? mapper : new SimpleTypeMapperImpl(); + } + + public Object transform(T source, TransformationContext context) { + XMLType xmlType = (XMLType)context.getSourceDataType().getLogical(); + QName type = (xmlType != null) ? xmlType.getTypeName() : null; + if (type == null) { + xmlType = (XMLType)context.getTargetDataType().getLogical(); + type = (xmlType != null) ? xmlType.getTypeName() : null; + } + Object result = mapper.toJavaObject(type, getText(source), context); + close(source); + return result; + } + + @Override + protected Class getTargetType() { + return Object.class; + } + + @Override + public int getWeight() { + // Cannot be used for intermediate + return 10000; + } + + /** + * Get the string value from the source + * @param source + * @return A string + */ + protected abstract String getText(T source); + + /** + * To be overrided by the subclass + * @param source + */ + protected void close(T source) { + } + + @Override + public String getTargetDataBinding() { + return SimpleJavaDataBinding.NAME; + } +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/SimpleTypeMapperImpl.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/SimpleTypeMapperImpl.java new file mode 100644 index 0000000000..16eb4b42ed --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/SimpleTypeMapperImpl.java @@ -0,0 +1,402 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * 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.impl; + +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.Map; + +import javax.xml.datatype.DatatypeConfigurationException; +import javax.xml.datatype.DatatypeFactory; +import javax.xml.datatype.XMLGregorianCalendar; +import javax.xml.namespace.NamespaceContext; +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.databinding.SimpleTypeMapper; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.interfacedef.util.TypeInfo; + +/** + * Simple type mapper that maps from XSD types to Java Classes and Java Classes to XSD types. + * + * @version $Rev$ $Date$ + * @tuscany.spi.extension.asclient + */ +public class SimpleTypeMapperImpl extends XSDDataTypeConverter implements SimpleTypeMapper { + + public static final Map JAVA2XML = new HashMap(); + + 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 Map XSD_SIMPLE_TYPES = new HashMap(); + + 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"); + + private static final String[] XSD_TYPE_NAMES = + {"string", "boolean", "double", "float", "int", "integer", "long", "short", "byte", "decimal", "base64Binary", + "hexBinary", "anySimpleType", "anyType", "any", "QName", "dateTime", "date", "time", "normalizedString", + "token", "unsignedLong", "unsignedInt", "unsignedShort", "unsignedByte", "positiveInteger", "negativeInteger", + "nonNegativeInteger", "nonPositiveInteger", "gYearMonth", "gMonthDay", "gYear", "gMonth", "gDay", "duration", + "Name", "NCName", "NMTOKEN", "NMTOKENS", "NOTATION", "ENTITY", "ENTITIES", "IDREF", "IDREFS", "anyURI", + "language", "ID"}; + + static { + for (String type : XSD_TYPE_NAMES) { + TypeInfo simpleType = new TypeInfo(new QName(URI_2001_SCHEMA_XSD, type), true, null); + XSD_SIMPLE_TYPES.put(type, simpleType); + } + } + + 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("string", java.lang.String.class); + XML2JAVA.put("integer", java.math.BigInteger.class); + XML2JAVA.put("int", int.class); + XML2JAVA.put("long", long.class); + XML2JAVA.put("short", short.class); + XML2JAVA.put("decimal", java.math.BigDecimal.class); + XML2JAVA.put("float", float.class); + XML2JAVA.put("double", double.class); + XML2JAVA.put("boolean", boolean.class); + XML2JAVA.put("byte", byte.class); + XML2JAVA.put("QName", javax.xml.namespace.QName.class); + XML2JAVA.put("dateTime", javax.xml.datatype.XMLGregorianCalendar.class); + XML2JAVA.put("base64Binary", byte[].class); + XML2JAVA.put("hexBinary", byte[].class); + XML2JAVA.put("unsignedInt", long.class); + XML2JAVA.put("unsignedShort", int.class); + XML2JAVA.put("unsignedByte", short.class); + XML2JAVA.put("time", javax.xml.datatype.XMLGregorianCalendar.class); + XML2JAVA.put("date", javax.xml.datatype.XMLGregorianCalendar.class); + XML2JAVA.put("gDay", javax.xml.datatype.XMLGregorianCalendar.class); + XML2JAVA.put("gMonth", javax.xml.datatype.XMLGregorianCalendar.class); + XML2JAVA.put("gYear", javax.xml.datatype.XMLGregorianCalendar.class); + XML2JAVA.put("gYearMonth", javax.xml.datatype.XMLGregorianCalendar.class); + XML2JAVA.put("gMonthDay", javax.xml.datatype.XMLGregorianCalendar.class); + XML2JAVA.put("anySimpleType", java.lang.Object.class); // For elements + // XML2JAVA.put("anySimpleType", java.lang.String.class); // For + // attributes + XML2JAVA.put("duration", javax.xml.datatype.Duration.class); + XML2JAVA.put("NOTATION", javax.xml.namespace.QName.class); + } + + private DatatypeFactory factory; + + public SimpleTypeMapperImpl() { + super(); + try { + this.factory = DatatypeFactory.newInstance(); + } catch (DatatypeConfigurationException e) { + throw new IllegalArgumentException(e); + } + } + + public Class getJavaType(QName xmlType) { + if (xmlType != null && URI_2001_SCHEMA_XSD.equals(xmlType.getNamespaceURI())) { + return XML2JAVA.get(xmlType.getLocalPart()); + } else { + return null; + } + } + + public TypeInfo getXMLType(Class javaType) { + return XSD_SIMPLE_TYPES.get(JAVA2XML.get(javaType)); + } + + public Object toJavaObject(QName simpleType, String literal, TransformationContext context) { + /** + *
    + *
  • xsd:string --- java.lang.String + *
  • xsd:integer --- java.math.BigInteger + *
  • xsd:int --- int + *
  • xsd:long --- long + *
  • xsd:short --- short + *
  • xsd:decimal --- java.math.BigDecimal + *
  • xsd:float --- float + *
  • xsd:double --- double + *
  • xsd:boolean --- boolean + *
  • xsd:byte --- byte + *
  • xsd:QName --- javax.xml.namespace.QName + *
  • xsd:dateTime --- javax.xml.datatype.XMLGregorianCalendar + *
  • xsd:base64Binary --- byte[] + *
  • xsd:hexBinary --- byte[] + *
  • xsd:unsignedInt --- long + *
  • xsd:unsignedShort --- int + *
  • xsd:unsignedByte --- short + *
  • xsd:time --- javax.xml.datatype.XMLGregorianCalendar + *
  • xsd:date --- javax.xml.datatype.XMLGregorianCalendar + *
  • xsd:g* --- javax.xml.datatype.XMLGregorianCalendar + *
  • xsd:anySimpleType (for xsd:element of this type)a + * java.lang.Object + *
  • xsd:anySimpleType (for xsd:attribute of this type) + * java.lang.String + *
  • xsd:duration javax.xml.datatype.Duration + *
  • xsd:NOTATION javax.xml.namespace.QName + *
+ */ + + if (literal == null) { + return null; + } + String value = literal.trim(); + + QName type = simpleType; + if (type.equals(XSD_STRING)) { + return parseString(value); + } else if (type.equals(XSD_INT)) { + return parseInt(value); + } else if (type.equals(XSD_INTEGER)) { + return parseInteger(value); + } else if (type.equals(XSD_INT)) { + return parseInt(value); + } else if (type.equals(XSD_FLOAT)) { + return parseFloat(value); + } else if (type.equals(XSD_DOUBLE)) { + return parseDouble(value); + } else if (type.equals(XSD_SHORT)) { + return parseShort(value); + } else if (type.equals(XSD_DECIMAL)) { + return parseDecimal(value); + } else if (type.equals(XSD_BOOLEAN)) { + return parseBoolean(value); + } else if (type.equals(XSD_BYTE)) { + return parseByte(value); + } else if (type.equals(XSD_LONG)) { + return parseLong(value); + } else if (type.equals(XSD_UNSIGNEDBYTE)) { + return parseUnsignedShort(value); + } else if (type.equals(XSD_UNSIGNEDSHORT)) { + return parseUnsignedShort(value); + } else if (type.equals(XSD_UNSIGNEDINT)) { + return parseUnsignedInt(value); + } else if (type.equals(XSD_UNSIGNEDLONG)) { + return parseUnsignedInt(value); + } else if (type.equals(XSD_DATETIME)) { + return parseDateTime(value); + } else if (type.equals(XSD_DATE)) { + return parseDate(value); + } else if (type.equals(XSD_TIME)) { + return parseTime(value); + } else if (type.equals(XSD_DURATION)) { + return parseDuration(value); + } else if (type.equals(XSD_HEXBIN)) { + return parseHexBinary(value); + } else if (type.equals(XSD_BASE64)) { + return parseBase64Binary(value); + } else if (type.equals(XSD_QNAME)) { + NamespaceContext namespaceContext = + (NamespaceContext)((context != null) ? context.getMetadata().get(NamespaceContext.class.getName()) : null); + return parseQName(value, namespaceContext); + } else if (type.equals(XSD_NOTATION)) { + NamespaceContext namespaceContext = + (NamespaceContext)((context != null) ? context.getMetadata().get(NamespaceContext.class.getName()) : null); + return parseQName(value, namespaceContext); + } else if (type.equals(XSD_YEAR)) { + return factory.newXMLGregorianCalendar(value); + } else if (type.equals(XSD_MONTH)) { + return factory.newXMLGregorianCalendar(value); + } else if (type.equals(XSD_DAY)) { + return factory.newXMLGregorianCalendar(value); + } else if (type.equals(XSD_YEARMONTH)) { + return factory.newXMLGregorianCalendar(value); + } else if (type.equals(XSD_MONTHDAY)) { + return factory.newXMLGregorianCalendar(value); + } else { + return value; + } + } + + @SuppressWarnings("deprecation") + private XMLGregorianCalendar toXMLGregorianCalendar(Date date) { + GregorianCalendar c = + new GregorianCalendar(date.getYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), + date.getSeconds()); + return factory.newXMLGregorianCalendar(c); + } + + private XMLGregorianCalendar toXMLGregorianCalendar(GregorianCalendar calendar) { + return factory.newXMLGregorianCalendar(calendar); + } + + public String toXMLLiteral(QName simpleType, Object obj, TransformationContext context) { + if(obj == null) { + // It could be null if nilable=true + return null; + } + if (obj instanceof Float || obj instanceof Double) { + if (obj instanceof Float) { + return printDouble(((Float)obj).floatValue()); + } else { + return printDouble(((Double)obj).doubleValue()); + } + } else if (obj instanceof GregorianCalendar) { + GregorianCalendar calendar = (GregorianCalendar)obj; + return toXMLGregorianCalendar(calendar).toXMLFormat(); + } else if (obj instanceof Date) { + return toXMLGregorianCalendar((Date)obj).toXMLFormat(); + } else if (obj instanceof XMLGregorianCalendar) { + return ((XMLGregorianCalendar)obj).toXMLFormat(); + } else if (obj instanceof byte[]) { + if (simpleType != null) { + if (simpleType.equals(XSD_BASE64)) { + return printBase64Binary((byte[])obj); + } else if (simpleType.equals(XSD_HEXBIN)) { + return printHexBinary((byte[])obj); + } + } + } else if (obj instanceof QName) { + NamespaceContext namespaceContext = + (NamespaceContext)((context != null) ? context.getMetadata().get(NamespaceContext.class.getName()) : null); + return printQName((QName)obj, namespaceContext); + } + return obj.toString(); + } + + public boolean isSimpleXSDType(QName typeName) { + if (typeName == null) { + return false; + } + return typeName.getNamespaceURI().equals(URI_2001_SCHEMA_XSD) + && XSD_SIMPLE_TYPES.get(typeName.getLocalPart()) != null; + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/TransformationContextImpl.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/TransformationContextImpl.java new file mode 100644 index 0000000000..e8b1ac3c01 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/TransformationContextImpl.java @@ -0,0 +1,101 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * 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.impl; + +import java.util.HashMap; +import java.util.Map; + +import static org.apache.tuscany.sca.databinding.Mediator.SOURCE_OPERATION; +import static org.apache.tuscany.sca.databinding.Mediator.TARGET_OPERATION; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.Operation; + +public class TransformationContextImpl implements TransformationContext { + + private DataType sourceDataType; + + private DataType targetDataType; + + private final Map metadata = new HashMap(); + + public TransformationContextImpl() { + super(); + } + + public TransformationContextImpl(DataType sourceDataType, + DataType targetDataType, + Map metadata) { + super(); + this.sourceDataType = sourceDataType; + this.targetDataType = targetDataType; + if (metadata != null) { + this.metadata.putAll(metadata); + } + } + + public DataType getSourceDataType() { + return sourceDataType; + } + + public DataType getTargetDataType() { + return targetDataType; + } + + public void setSourceDataType(DataType sourceDataType) { + this.sourceDataType = sourceDataType; + } + + public void setTargetDataType(DataType targetDataType) { + this.targetDataType = targetDataType; + } + + public Map getMetadata() { + return metadata; + } + + /** + * @return the sourceOperation + */ + public Operation getSourceOperation() { + return (Operation) metadata.get(SOURCE_OPERATION); + } + + /** + * @param sourceOperation the sourceOperation to set + */ + public void setSourceOperation(Operation sourceOperation) { + this.metadata.put(SOURCE_OPERATION, sourceOperation); + } + + /** + * @return the targetOperation + */ + public Operation getTargetOperation() { + return (Operation) metadata.get(TARGET_OPERATION); + } + + /** + * @param targetOperation the targetOperation to set + */ + public void setTargetOperation(Operation targetOperation) { + this.metadata.put(TARGET_OPERATION, targetOperation); + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/XSDDataTypeConverter.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/XSDDataTypeConverter.java new file mode 100644 index 0000000000..aeb63ce02f --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/impl/XSDDataTypeConverter.java @@ -0,0 +1,970 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * 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.impl; + +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 java.util.logging.Logger; + +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$ + * @tuscany.spi.extension.asclient + */ +public class XSDDataTypeConverter { + private static final Logger logger = Logger.getLogger(XSDDataTypeConverter.class.getName(), + "org.apache.tuscany.sca.databinding.databinding-validation-messages"); + /** + * + * @tuscany.spi.extension.asclient + * + */ + 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(logger.getResourceBundle().getString("NotBase64Encoded")); + } + } + + /** + * 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(logger.getResourceBundle().getString("HexBinaryUnevenLength")); + } + 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(logger.getResourceBundle().getString("InvalidHexDigit") + " " + 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(logger.getResourceBundle().getString("InvalidHexDigit") + " " + 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) { + String message = logger.getResourceBundle().getString("BadDate"); + message = message.replace("{0}", value); + message = message.replace("{1}", value.substring(pos.getErrorIndex())); + throw new IllegalArgumentException(message); + } + 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) { + String message = logger.getResourceBundle().getString("BadDateTime"); + message = message.replace("{0}", value); + message = message.replace("{1}", value.substring(pos.getErrorIndex())); + throw new IllegalArgumentException(message); + } + 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(logger.getResourceBundle().getString("DefaultPrefixNotBound")); + } + break; + case 0: + throw new IllegalArgumentException(logger.getResourceBundle().getString("NoColonForPrefix") + + " " + + value); + default: + String prefix = value.substring(0, offset); + localName = value.substring(offset + 1); + uri = context.getNamespaceURI(prefix); + if (uri == null) { + String message = logger.getResourceBundle().getString("PrefixNotBound"); + message = message.replace("{0}", prefix); + throw new IllegalArgumentException(message); + } + } + 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) { + String message = logger.getResourceBundle().getString("BadTime"); + message = message.replace("{0}", value); + message = message.replace("{1}", value.substring(pos.getErrorIndex())); + throw new IllegalArgumentException(message); + } + return cal; + } + + public long parseUnsignedInt(String value) { + long l = Long.parseLong(value); + if (l < 0) { + String message = logger.getResourceBundle().getString("BadUnsignedIntNegative"); + message = message.replace("{0}", value); + throw new IllegalArgumentException(message); + } + if (l > MAX_UNSIGNED_INT) { + String message = logger.getResourceBundle().getString("BadUnsignedIntMax"); + message = message.replace("{0}", value); + message = message.replace("{1}", String.valueOf(MAX_UNSIGNED_INT)); + throw new IllegalArgumentException(message); + } + return l; + } + + public int parseUnsignedShort(String value) { + int i = Integer.parseInt(value); + if (i < 0) { + String message = logger.getResourceBundle().getString("BadUnsignedShortNegative"); + message = message.replace("{0}", value); + throw new IllegalArgumentException(message); + } + if (i > MAX_UNSIGNED_SHORT) { + String message = logger.getResourceBundle().getString("BadUnsignedShortMax"); + message = message.replace("{0}", value); + message = message.replace("{1}", String.valueOf(MAX_UNSIGNED_SHORT)); + throw new IllegalArgumentException(message); + } + 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) { + String message = logger.getResourceBundle().getString("NamespaceNotBound"); + message = message.replace("{0}", value.getNamespaceURI()); + throw new IllegalArgumentException(message); + } 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/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/DOMNode2JavaBeanTransformer.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/DOMNode2JavaBeanTransformer.java new file mode 100644 index 0000000000..fbca9b0444 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/DOMNode2JavaBeanTransformer.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.databinding.javabeans; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +/** + * Transformer to convert data from DOM Node to JavaBean + * + * @version $Rev$ $Date$ + */ +public class DOMNode2JavaBeanTransformer extends XML2JavaBeanTransformer { + + @Override + public Node getRootElement(Node element) throws XML2JavaMapperException { + if (element instanceof Document) { + return ((Document)element).getDocumentElement(); + } else { + return element; + } + + } + + @Override + public Iterator getChildElements(Node parent) throws XML2JavaMapperException { + NodeList nodeList = parent.getChildNodes(); + List nodeArrayList = new ArrayList(nodeList.getLength()); + for (int count = 0; count < nodeList.getLength(); ++count) { + nodeArrayList.add(nodeList.item(count)); + } + + return nodeArrayList.iterator(); + } + + @Override + public String getElementName(Node element) throws XML2JavaMapperException { + return element.getLocalName(); + } + + @Override + public String getText(Node element) throws XML2JavaMapperException { + if (element instanceof Document) { + element = ((Document)element).getDocumentElement(); + } + return element.getTextContent(); + } + + @Override + public boolean isTextElement(Node element) throws XML2JavaMapperException { + return element.getNodeType() == Node.TEXT_NODE; + } + + @Override + public boolean isTextOnly(Node element) throws XML2JavaMapperException { + NodeList childNodes = element.getChildNodes(); + return childNodes.getLength() == 1 && isTextElement(childNodes.item(0)); + } + + @Override + public Node getFirstChildWithName(Node element, QName name) throws XML2JavaMapperException { + Node child; + for (child = element.getFirstChild(); + child != null && !(child.getNodeName() == name.getLocalPart() + && child.getNamespaceURI() == name.getNamespaceURI()) ; + child = child.getNextSibling()) { + } + return child; + } + + @Override + public Class getSourceType() { + return Node.class; + } +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/Java2XMLMapperException.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/Java2XMLMapperException.java new file mode 100644 index 0000000000..5dc13bd60b --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/Java2XMLMapperException.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.javabeans; + +import javax.xml.namespace.QName; + +/** + * This exception is used to encapsulate and rethrow exceptions that arise out + * of converting JavaBean objects to XML + * + * @version $Rev$ $Date$ + */ +public class Java2XMLMapperException extends RuntimeException { + private static final long serialVersionUID = 6811924384399578686L; + + private QName xmlElementName; + private String javaFieldName; + private Class javaType; + + public Java2XMLMapperException(String message) { + super(message); + } + + public Java2XMLMapperException(Throwable cause) { + super(cause); + } + + public String getJavaFieldName() { + return javaFieldName; + } + + public void setJavaFieldName(String javaFieldName) { + this.javaFieldName = javaFieldName; + } + + public Class getJavaType() { + return javaType; + } + + public void setJavaType(Class javaType) { + this.javaType = javaType; + } + + public QName getXmlElementName() { + return xmlElementName; + } + + public void setXmlElementName(QName xmlElementName) { + this.xmlElementName = xmlElementName; + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/JavaBean2DOMNodeTransformer.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/JavaBean2DOMNodeTransformer.java new file mode 100644 index 0000000000..f582499b70 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/JavaBean2DOMNodeTransformer.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.javabeans; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.common.xml.dom.DOMHelper; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.Node; + +/** + * Transformer to convert data from a JavaBean object to DOM Node + * + * @version $Rev$ $Date$ + */ +public class JavaBean2DOMNodeTransformer extends JavaBean2XMLTransformer { + + public static final String COLON = ":"; + private DOMHelper helper; + + public JavaBean2DOMNodeTransformer(ExtensionPointRegistry registry) { + super(); + helper = DOMHelper.getInstance(registry); + } + + @Override + public void appendChild(Node parentElement, Node childElement) throws Java2XMLMapperException { + parentElement.appendChild(childElement); + } + + @Override + public Node createElement(QName qName) throws Java2XMLMapperException { + String qualifedName = + (qName.getPrefix() == null || qName.getPrefix().length() <= 0) ? qName.getLocalPart() + : qName.getPrefix() + COLON + qName.getLocalPart(); + return helper.newDocument().createElementNS(qName.getNamespaceURI(), qualifedName); + } + + @Override + public void appendText(Node parentElement, String textData) throws Java2XMLMapperException { + Document document = helper.newDocument(); + Node textNode; + if (textData != null) { + textNode = document.createTextNode(textData); + } else { + Attr nil = document.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "xsi:nil"); + nil.setValue("true"); + textNode = nil; + } + appendChild(parentElement, textNode); + } + + @Override + public Class getTargetType() { + return Node.class; + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/JavaBean2XMLStreamReaderTransformer.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/JavaBean2XMLStreamReaderTransformer.java new file mode 100644 index 0000000000..43bda3d769 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/JavaBean2XMLStreamReaderTransformer.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.javabeans; + +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sca.databinding.BaseTransformer; +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.xml.BeanXMLStreamReaderImpl; +import org.apache.tuscany.sca.interfacedef.util.XMLType; + +/** + * Transformer to convert data from a JavaBean object to XMLStreamReader. + * + * @version $Rev$ $Date$ + */ +public class JavaBean2XMLStreamReaderTransformer extends BaseTransformer implements + PullTransformer { + + public XMLStreamReader transform(Object source, TransformationContext context) { + try { + javax.xml.namespace.QName name = null; + if (context != null) { + Object logical = context.getSourceDataType().getLogical(); + if (logical instanceof XMLType) { + name = ((XMLType)logical).getElementName(); + } + } + return new BeanXMLStreamReaderImpl(name, source); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + protected Class getSourceType() { + return Object.class; + } + + @Override + protected Class getTargetType() { + return XMLStreamReader.class; + } + + @Override + public int getWeight() { + return 50; + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/JavaBean2XMLTransformer.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/JavaBean2XMLTransformer.java new file mode 100644 index 0000000000..28d716e4f7 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/JavaBean2XMLTransformer.java @@ -0,0 +1,262 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * 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.javabeans; + +import java.lang.reflect.Array; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.Date; +import java.util.GregorianCalendar; + +import javax.xml.datatype.XMLGregorianCalendar; +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.databinding.BaseTransformer; +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.impl.SimpleTypeMapperImpl; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.util.XMLType; + +/** + * Transformer to convert data from a JavaBean object to xml + * + * @version $Rev$ $Date$ + */ +public abstract class JavaBean2XMLTransformer extends BaseTransformer implements + PullTransformer { + + public static final String GET = "get"; + public static final String PREFIX = "n"; + public static final String PERIOD = "."; + public static final String FWD_SLASH = "/"; + public static final String HTTP = "http://"; + private static int prefixCount = 1; + + protected SimpleTypeMapperImpl mapper; + + public JavaBean2XMLTransformer() { + this.mapper = new SimpleTypeMapperImpl(); + } + + public T transform(Object source, TransformationContext context) { + QName rootElement = null; + if (context != null) { + DataType type = context.getTargetDataType(); + if (type != null) { + Object logical = type.getLogical(); + if (logical instanceof XMLType) { + rootElement = ((XMLType)logical).getElementName(); + } + } + } + //FIXME See how/if we still need to get the metadata here + //QName rootElementName = (QName)context.getTargetDataType().getMetadata("RootElementName"); + //if (rootElementName == null) { + QName rootElementName = new QName(resolveRootElementName(source.getClass())); + //} + + T root = createElement(rootElementName); + appendChildElements(root, resolveElementName(source.getClass()), source.getClass(), source, context); + return root; + } + + private void appendChildElements(T parent, + QName elementName, + Class javaType, + Object javaObject, + TransformationContext context) { + T element = null; + if (javaObject != null) { + if (javaType.isPrimitive() || isSimpleJavaType(javaObject)) { + appendText(parent, mapper.toXMLLiteral(null, javaObject, context)); + } else if (javaType.isArray()) { + int size = Array.getLength(javaObject); + for (int count = 0; count < size; ++count) { + Object item = Array.get(javaObject, count); + element = createElement(elementName); + appendChild(parent, element); + appendChildElements(element, elementName, javaType.getComponentType(), item, context); + } + } else { + Field[] javaFields = javaType.getFields(); + for (Field aField : javaFields) { + try { + QName fieldElementName = new QName(aField.getName()); + if (!aField.getType().isArray()) { + element = createElement(fieldElementName); + appendChild(parent, element); + appendChildElements(element, + fieldElementName, + aField.getType(), + aField.get(javaObject), + context); + } else { + appendChildElements(parent, + fieldElementName, + aField.getType(), + aField.get(javaObject), + context); + } + } catch (IllegalAccessException e) { + Java2XMLMapperException java2xmlEx = new Java2XMLMapperException(e); + java2xmlEx.setJavaFieldName(aField.getName()); + java2xmlEx.setJavaType(javaType); + throw java2xmlEx; + } + } + + Method[] methods = javaType.getMethods(); + String fieldName = null; + for (Method aMethod : methods) { + try { + if (Modifier.isPublic(aMethod.getModifiers()) && aMethod.getName().startsWith(GET) + && aMethod.getParameterTypes().length == 0 + && isMappedGetter(aMethod.getName())) { + fieldName = resolveFieldFromMethod(aMethod.getName()); + try { + javaType.getField(fieldName); + } catch (NoSuchFieldException e) { + QName fieldElementName = new QName(fieldName); + if (aMethod.getReturnType().isArray()) { + appendChildElements(parent, fieldElementName, aMethod.getReturnType(), aMethod + .invoke(javaObject, new Object[0]), context); + } else { + element = createElement(fieldElementName); + appendChild(parent, element); + appendChildElements(element, fieldElementName, aMethod.getReturnType(), aMethod + .invoke(javaObject, new Object[0]), context); + } + } + } + } catch (IllegalAccessException e) { + Java2XMLMapperException java2xmlEx = new Java2XMLMapperException(e); + java2xmlEx.setJavaFieldName(fieldName); + java2xmlEx.setJavaType(javaType); + throw java2xmlEx; + } catch (InvocationTargetException e) { + Java2XMLMapperException java2xmlEx = new Java2XMLMapperException(e); + java2xmlEx.setJavaFieldName(fieldName); + java2xmlEx.setJavaType(javaType); + throw java2xmlEx; + } + } + } + } + } + + /* + * Subclasses can override this method to prevent some getter methods + * from being mapped. The default implementation provided by this class + * maps all getter methods. + */ + protected boolean isMappedGetter(String methodName) { + return true; + } + + @Override + public String getSourceDataBinding() { + return JavaBeansDataBinding.NAME; + } + + @Override + public Class getSourceType() { + return Object.class; + } + + private boolean isSimpleJavaType(Object javaObject) { + if (javaObject instanceof String) { + return true; + } + if (javaObject instanceof Byte || javaObject instanceof Character + || javaObject instanceof Short + || javaObject instanceof Integer + || javaObject instanceof Long + || javaObject instanceof Float + || javaObject instanceof Double + || javaObject instanceof Boolean) { + return true; + } + if (javaObject instanceof GregorianCalendar || javaObject instanceof Date + || javaObject instanceof XMLGregorianCalendar + || javaObject instanceof byte[] + || javaObject instanceof QName) { + return true; + } + return false; + } + + private String resolveRootElementName(Class javaType) { + if (javaType.isArray()) { + return javaType.getComponentType().getSimpleName() + "_collection"; + } else { + return javaType.getSimpleName() + "_instance"; + } + } + + private QName resolveElementName(Class javaType) { + if (javaType.isArray()) { + return new QName(javaType.getComponentType().getSimpleName()); + } else { + return new QName(javaType.getSimpleName()); + } + } + + private String resolveFieldFromMethod(String methodName) { + StringBuffer fieldName = new StringBuffer(); + fieldName.append(Character.toLowerCase(methodName.charAt(GET.length()))); + fieldName.append(methodName.substring(GET.length() + 1)); + return fieldName.toString(); + } + + public String getNexPrefix() { + return PREFIX + prefixCount++; + } + + @Override + public int getWeight() { + return JavaBeansDataBinding.HEAVY_WEIGHT; + } + + /** + * Create an element with the given name + * @param qName + * @return + * @throws Java2XMLMapperException + */ + public abstract T createElement(QName qName) throws Java2XMLMapperException; + + /** + * Create a text node and add it to the parent + * @param parentElement + * @param textData + * @throws Java2XMLMapperException + */ + public abstract void appendText(T parentElement, String textData) throws Java2XMLMapperException; + + /** + * Add the child element to the parent + * @param parentElement + * @param childElement + * @throws Java2XMLMapperException + */ + public abstract void appendChild(T parentElement, T childElement) throws Java2XMLMapperException; +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/JavaBeansDataBinding.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/JavaBeansDataBinding.java new file mode 100644 index 0000000000..3721fb7e63 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/JavaBeansDataBinding.java @@ -0,0 +1,178 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * 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.javabeans; + + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.ObjectStreamClass; +import java.io.OutputStream; +import java.io.Serializable; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.logging.Logger; + +import org.apache.tuscany.sca.databinding.BaseDataBinding; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.Operation; + +/** + * DataBinding for JavaBeans + * + * @version $Rev$ $Date$ + */ +public class JavaBeansDataBinding extends BaseDataBinding { + private final static Logger logger = Logger.getLogger(JavaBeansDataBinding.class.getName()); + /** + * Defining a weight to a very high number so that the transformer won't be picked + * up by other paths unless it's the only available path + */ + public static final int HEAVY_WEIGHT = 10000; + public static final String NAME = "java:complexType"; + + public JavaBeansDataBinding() { + super(NAME, Object.class); + } + + protected JavaBeansDataBinding(String name, Class baseType) { + super(name, baseType); + } + + @Override + public Object copy(Object arg, DataType sourceDataType, DataType targetDataType, Operation sourceOperation, Operation targetOperation) { + if (arg == null) { + return null; + } + final Class clazz = arg.getClass(); + if (String.class == clazz || clazz.isPrimitive() + || Number.class.isAssignableFrom(clazz) + || Boolean.class.isAssignableFrom(clazz) + || Character.class.isAssignableFrom(clazz) + || Byte.class.isAssignableFrom(clazz)) { + // Immutable classes + return arg; + } + try { + if (arg instanceof Serializable) { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + ObjectOutputStream oos = getObjectOutputStream(bos); + oos.writeObject(arg); + oos.close(); + bos.close(); + + // Work out which ClassLoader to use for deserializing arg + // We want to use: + // * The ClassLoader of the targetDataType if it is not the System ClassLoader + // * The ClassLoader of arg if it is not the System ClassLoader + // * The ThreadContext ClassLoader if the ClassLoader of arg is the System ClassLoader + // because Collection classes are loaded by the System ClassLoader but their contents + // may be loaded from another ClassLoader + // + final DataType fTargetDataType = targetDataType; + ClassLoader classLoaderToUse = AccessController.doPrivileged(new PrivilegedAction() { + public ClassLoader run() { + ClassLoader cl = fTargetDataType.getPhysical().getClassLoader(); + return cl; + } + }); + + + + if (classLoaderToUse == null) { + classLoaderToUse = clazz.getClassLoader(); + } + if (classLoaderToUse == null) + { + // ClassLoader of arg is the System ClassLoader so we will use the ThreadContext ClassLoader + // instead + classLoaderToUse = Thread.currentThread().getContextClassLoader(); + } + + ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); + ObjectInputStream ois = getObjectInputStream(bis, classLoaderToUse); + Object objectCopy = ois.readObject(); + ois.close(); + bis.close(); + return objectCopy; + } else if (arg instanceof Cloneable) { + Method clone; + try { + clone = arg.getClass().getMethod("clone"); + try { + return clone.invoke(arg, (Object[])null); + } catch (InvocationTargetException e) { + if (e.getTargetException() instanceof CloneNotSupportedException) { + // Ignore + } else { + throw new IllegalArgumentException(e); + } + } catch (Exception e) { + throw new IllegalArgumentException(e); + } + } catch (NoSuchMethodException e) { + // Ignore it + } + } + // return arg; + logger.warning("Argument type '" + arg.getClass().getName() + + "' is not Serializable or Cloneable. Pass-by-value is skipped."); + return arg; + } catch (Exception e) { + throw new IllegalArgumentException("Pass-by-value is not supported for the given object: " + arg.getClass() + .getName(), e); + } + } + + protected ObjectOutputStream getObjectOutputStream(OutputStream os) throws IOException { + return new ObjectOutputStream(os); + } + + protected ObjectInputStream getObjectInputStream(InputStream is, final ClassLoader cl) throws IOException { + ObjectInputStream ois = new ObjectInputStream(is) { + @Override + protected Class resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { + try { + return Class.forName(desc.getName(), false, cl); + } catch (ClassNotFoundException e) { + try { + // For OSGi, use context ClassLoader if the bundle ClassLoader cannot load the class + if (cl != Thread.currentThread().getContextClassLoader()) { + return Class.forName(desc.getName(), false, Thread.currentThread().getContextClassLoader()); + } + } catch (ClassNotFoundException e1) { + // ignore + } catch (NoClassDefFoundError e1) { + // ignore + } + return super.resolveClass(desc); + } + } + + }; + return ois; + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/JavaExceptionDataBinding.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/JavaExceptionDataBinding.java new file mode 100644 index 0000000000..6886462ac8 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/JavaExceptionDataBinding.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.databinding.javabeans; + + +/** + * DataBinding for Java Exceptions + * + * @version $Rev$ $Date$ + */ +public class JavaExceptionDataBinding extends JavaBeansDataBinding { + + public static final String NAME = "java:exception"; + + public JavaExceptionDataBinding() { + super(NAME, null); + } +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/SimpleJavaDataBinding.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/SimpleJavaDataBinding.java new file mode 100644 index 0000000000..a1bb7e6235 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/SimpleJavaDataBinding.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.javabeans; + + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.databinding.BaseDataBinding; +import org.apache.tuscany.sca.databinding.SimpleTypeMapper; +import org.apache.tuscany.sca.databinding.impl.SimpleTypeMapperImpl; +import org.apache.tuscany.sca.databinding.xml.XMLStringDataBinding; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.interfacedef.util.TypeInfo; +import org.apache.tuscany.sca.interfacedef.util.XMLType; + +/** + * DataBinding for Java simple types + * + * @version $Rev$ $Date$ + * @tuscany.spi.extension.asclient + */ +public class SimpleJavaDataBinding extends BaseDataBinding { + public static final String NAME = "java:simpleType"; + private SimpleTypeMapper simpleTypeMapper = new SimpleTypeMapperImpl(); + + public SimpleJavaDataBinding(ExtensionPointRegistry registry) { + super(NAME, Object.class); +// UtilityExtensionPoint utilityExtensionPoint = registry.getExtensionPoint(UtilityExtensionPoint.class); +// this.simpleTypeMapper = utilityExtensionPoint.getUtility(SimpleTypeMapper.class); + } + + @Override + public Object copy(Object arg, + DataType sourceDataType, + DataType targetDataType, + Operation sourceOperation, + Operation targetOperation) { + if (arg instanceof byte[]) { + return ((byte[])arg).clone(); + } + return arg; + } + + @Override + public boolean introspect(DataType type, Operation operation) { + Class cls = type.getPhysical(); + if (cls == Object.class) { + return false; + } + // HACK: [rfeng] By pass the one know to XMLString + String db = type.getDataBinding(); + if (db != null && (XMLStringDataBinding.NAME.equals(db))) { + return false; + } + if (SimpleTypeMapperImpl.JAVA2XML.keySet().contains(cls)) { + type.setDataBinding(NAME); + QName elementName = null; + Object logical = type.getLogical(); + if (logical instanceof XMLType) { + elementName = ((XMLType)logical).getElementName(); + } + TypeInfo typeInfo = simpleTypeMapper.getXMLType(cls); + type.setLogical(new XMLType(elementName, typeInfo == null ? null : typeInfo.getQName())); + return true; + } else { + return false; + } + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/XML2JavaBeanTransformer.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/XML2JavaBeanTransformer.java new file mode 100644 index 0000000000..6881ec6038 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/XML2JavaBeanTransformer.java @@ -0,0 +1,329 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * 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.javabeans; + +import java.lang.reflect.Array; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Hashtable; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.databinding.BaseTransformer; +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.impl.SimpleTypeMapperImpl; +import org.apache.tuscany.sca.interfacedef.util.XMLType; + +/** + * Transformer to convert data from XML to JavaBean + * + * @version $Rev$ $Date$ + */ +public abstract class XML2JavaBeanTransformer extends BaseTransformer implements + PullTransformer { + + public static final String SET = "set"; + public static final QName QNAME_MESSAGE = new QName("message"); + + protected SimpleTypeMapperImpl mapper; + + public XML2JavaBeanTransformer() { + this.mapper = new SimpleTypeMapperImpl(); + } + + @Override + public int getWeight() { + return JavaBeansDataBinding.HEAVY_WEIGHT; + } + + public Object transform(T source, TransformationContext context) { + //FIXME why is the logical type sometimes a Class instead of an XMLType? + if (context.getSourceDataType().getLogical() instanceof XMLType) { + XMLType xmlType = (XMLType) context.getSourceDataType().getLogical(); + return toJavaObject(xmlType.getTypeName(), getRootElement(source), context); + } else { + return toJavaObject(null, getRootElement(source), context); + } + } + + public Object toJavaObject(QName xmlType, T xmlElement, TransformationContext context) { + if (xmlType != null && mapper.isSimpleXSDType(xmlType)) { + return mapper.toJavaObject(xmlType, getText(xmlElement), context); + } else { + Class javaType = (Class)context.getTargetDataType().getPhysical(); + return createJavaObject(xmlElement, javaType, context); + } + } + + @SuppressWarnings("unchecked") + private L createJavaObject(T element, Class javaType, TransformationContext context) + throws XML2JavaMapperException { + if (isTextOnly(element)) { + return (L) mapper.toJavaObject(mapper.getXMLType(javaType).getQName(), + getText(element), + context); + } else { + String fieldName = null; + try { + L javaInstance; + T detailMsg = null; + if (Throwable.class.isAssignableFrom(javaType)) { + T msgElement = getFirstChildWithName(element, QNAME_MESSAGE); + if (msgElement != null && isTextOnly(msgElement)) { + detailMsg = msgElement; // skip this when handling child elements + Constructor constructor = javaType.getConstructor(new Class[] {String.class}); + javaInstance = (L)constructor.newInstance(new Object[] {getText(detailMsg)}); + } else { + javaInstance = javaType.newInstance(); + } + } else { + javaInstance = javaType.newInstance(); + } + Map> arrayFields = new Hashtable>(); + Map> arraySetters = new Hashtable>(); + + for (Iterator childElements = getChildElements(element); childElements.hasNext(); ) { + T childElement = childElements.next(); + if (!isTextElement(childElement) && childElement != detailMsg) { + fieldName = getElementName(childElement); + try { + Field javaField = javaType.getField(fieldName); + setFieldValue(javaInstance, + javaField, + childElement, + arrayFields, + context); + + } catch (NoSuchFieldException e1) { + setFieldValueUsingSetter(javaType, + javaInstance, + fieldName, + childElement, + arraySetters, + context); + } + } + } + + setArrayValues(javaInstance, arrayFields, arraySetters); + return javaInstance; + } catch (Exception e2) { + XML2JavaMapperException xml2JavaEx = new XML2JavaMapperException(e2); + xml2JavaEx.setJavaType(javaType); + xml2JavaEx.setJavaFieldName(fieldName); + throw xml2JavaEx; + } + } + } + + private void setFieldValue(Object javaInstance, + Field javaField, + T fieldValue, + Map> arrayFields, + TransformationContext context) throws IllegalAccessException { + Class javaFieldType = (Class) javaField.getType(); + + if (javaFieldType.isArray()) { + Class componentType = javaFieldType.getComponentType(); + List fldValueArray = arrayFields.get(javaField); + if (fldValueArray == null) { + fldValueArray = new ArrayList(); + arrayFields.put(javaField, fldValueArray); + } + fldValueArray.add(createJavaObject(fieldValue, componentType, context)); + } else { + javaField.setAccessible(true); + javaField.set(javaInstance, createJavaObject(fieldValue, javaFieldType, context)); + } + } + + private void setFieldValueUsingSetter(Class javaType, + Object javaInstance, + String fieldName, + T fieldValue, + Map> arraySetters, + TransformationContext context) throws IllegalAccessException, + InvocationTargetException { + char firstChar = Character.toUpperCase(fieldName.charAt(0)); + StringBuilder methodName = new StringBuilder(SET + fieldName); + methodName.setCharAt(SET.length(), firstChar); + boolean methodNotFound = true; + + for (int methodCount = 0; methodNotFound && methodCount < javaType.getMethods().length; ++methodCount) { + Method aMethod = javaType.getMethods()[methodCount]; + if (aMethod.getName().equals(methodName.toString()) + && aMethod.getParameterTypes().length == 1) { + Class paramType = aMethod.getParameterTypes()[0]; + + if (paramType.isArray()) { + Class componentType = paramType.getComponentType(); + List setterValueArray = arraySetters.get(aMethod); + if (setterValueArray == null) { + setterValueArray = new ArrayList(); + arraySetters.put(aMethod, setterValueArray); + } + setterValueArray.add(createJavaObject(fieldValue, componentType, context)); + } else { + aMethod.invoke(javaInstance, new Object[] {createJavaObject(fieldValue, + paramType, + context)}); + } + methodNotFound = false; + } + } + + if (methodNotFound) { + XML2JavaMapperException xml2JavaEx = + new XML2JavaMapperException("No field or setter method to configure xml data"); + xml2JavaEx.setJavaFieldName(fieldName); + xml2JavaEx.setJavaType(javaType); + throw xml2JavaEx; + } + } + + private void setArrayValues(Object javaInstance, + Map> arrayFields, + Map> arraySetters) throws IllegalAccessException, + InvocationTargetException { + if (arrayFields.size() > 0) { + for (Field javaField : arrayFields.keySet()) { + javaField.setAccessible(true); + + if (javaField.getType().getComponentType().isPrimitive()) { + javaField.set(javaInstance, createPrimitiveArray(javaField.getType() + .getComponentType(), + arrayFields.get(javaField))); + } else { + javaField.set(javaInstance, + createNonPrimitiveArray(javaField.getType().getComponentType(), + arrayFields.get(javaField))); + } + } + } + + if (arraySetters.size() > 0) { + for (Method aMethod : arraySetters.keySet()) { + Class paramType = aMethod.getParameterTypes()[0]; + if (paramType.getComponentType().isPrimitive()) { + aMethod.invoke(javaInstance, + new Object[] {createPrimitiveArray(paramType.getComponentType(), + arraySetters.get(aMethod))}); + } else { + aMethod.invoke(javaInstance, + new Object[] {createNonPrimitiveArray(paramType.getComponentType(), + arraySetters.get(aMethod))}); + } + } + } + } + + private Object createNonPrimitiveArray(Class fieldType, List values) { + Object objectArray = Array.newInstance(fieldType, values.size()); + for (int count = 0; count < values.size(); ++count) { + Array.set(objectArray, count, values.get(count)); + } + return objectArray; + } + + private Object createPrimitiveArray(Class fieldType, List values) { + if (fieldType.isPrimitive()) { + if (fieldType.getName().equals("int")) { + int[] primitiveValues = new int[values.size()]; + for (int count = 0; count < values.size(); ++count) { + primitiveValues[count] = ((Integer) values.get(count)).intValue(); + } + return primitiveValues; + } else if (fieldType.getName().equals("float")) { + float[] primitiveValues = new float[values.size()]; + for (int count = 0; count < values.size(); ++count) { + primitiveValues[count] = ((Float) values.get(count)).floatValue(); + } + return primitiveValues; + } else if (fieldType.getName().equals("boolean")) { + boolean[] primitiveValues = new boolean[values.size()]; + for (int count = 0; count < values.size(); ++count) { + primitiveValues[count] = ((Boolean) values.get(count)).booleanValue(); + } + return primitiveValues; + } else if (fieldType.getName().equals("char")) { + char[] primitiveValues = new char[values.size()]; + for (int count = 0; count < values.size(); ++count) { + primitiveValues[count] = ((Character) values.get(count)).charValue(); + } + return primitiveValues; + } else if (fieldType.getName().equals("byte")) { + byte[] primitiveValues = new byte[values.size()]; + for (int count = 0; count < values.size(); ++count) { + primitiveValues[count] = ((Byte) values.get(count)).byteValue(); + } + return primitiveValues; + } else if (fieldType.getName().equals("short")) { + short[] primitiveValues = new short[values.size()]; + for (int count = 0; count < values.size(); ++count) { + primitiveValues[count] = ((Short) values.get(count)).shortValue(); + } + return primitiveValues; + } else if (fieldType.getName().equals("long")) { + long[] primitiveValues = new long[values.size()]; + for (int count = 0; count < values.size(); ++count) { + primitiveValues[count] = ((Long) values.get(count)).longValue(); + } + return primitiveValues; + } else if (fieldType.getName().equals("double")) { + double[] primitiveValues = new double[values.size()]; + for (int count = 0; count < values.size(); ++count) { + primitiveValues[count] = ((Double) values.get(count)).doubleValue(); + } + return primitiveValues; + } + } + return values; + } + + public abstract String getText(T source) throws XML2JavaMapperException; + + public abstract Iterator getChildElements(T parent) throws XML2JavaMapperException; + + public abstract String getElementName(T element) throws XML2JavaMapperException; + + public abstract boolean isTextElement(T element) throws XML2JavaMapperException; + + public abstract boolean isTextOnly(T element) throws XML2JavaMapperException; + + public abstract T getFirstChildWithName(T element, QName name) throws XML2JavaMapperException; + + public abstract T getRootElement(T element) throws XML2JavaMapperException; + + @Override + public Class getTargetType() { + return Object.class; + } + + @Override + public String getTargetDataBinding() { + return JavaBeansDataBinding.NAME; + } +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/XML2JavaMapperException.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/XML2JavaMapperException.java new file mode 100644 index 0000000000..ae06d68e67 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/javabeans/XML2JavaMapperException.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.javabeans; + +import javax.xml.namespace.QName; + +/** + * This exception is used to encapsulate and rethrow exceptions that arise out + * of converting XML Data to Java Objects. + * + * @version $Rev$ $Date$ + */ +public class XML2JavaMapperException extends RuntimeException { + private static final long serialVersionUID = 6596530102591630642L; + + private QName xmlElementName; + private String javaFieldName; + private Class javaType; + + public XML2JavaMapperException(String message) { + super(message); + } + + public XML2JavaMapperException(Throwable cause) { + super(cause); + } + + public QName getXmlElementName() { + return xmlElementName; + } + + public void setXmlElementName(QName xmlElementName) { + this.xmlElementName = xmlElementName; + } + + public String getJavaFieldName() { + return javaFieldName; + } + + public void setJavaFieldName(String javaFieldName) { + this.javaFieldName = javaFieldName; + } + + public Class getJavaType() { + return javaType; + } + + public void setJavaType(Class javaType) { + this.javaType = javaType; + } + + @Override + public String getMessage() { + return super.getMessage() + " <" + getJavaFieldName() + "> " + " in <" + getJavaType() + ">"; + } + + + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/servicereference/ServiceReferenceDataBinding.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/servicereference/ServiceReferenceDataBinding.java new file mode 100644 index 0000000000..2117d2c3cf --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/servicereference/ServiceReferenceDataBinding.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.databinding.servicereference; + +import org.apache.tuscany.sca.databinding.BaseDataBinding; +import org.apache.tuscany.sca.databinding.XMLTypeHelper; +import org.oasisopen.sca.ServiceReference; + +public class ServiceReferenceDataBinding extends BaseDataBinding { + + public static final String NAME = ServiceReference.class.getName(); + + private ServiceReferenceTypeHelper xmlTypeHelper; + + public ServiceReferenceDataBinding() { + super(NAME, ServiceReference.class); + this.xmlTypeHelper = new ServiceReferenceTypeHelper(); + } + + @Override + public XMLTypeHelper getXMLTypeHelper() { + return xmlTypeHelper; + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/servicereference/ServiceReferenceTypeHelper.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/servicereference/ServiceReferenceTypeHelper.java new file mode 100644 index 0000000000..57da596d24 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/servicereference/ServiceReferenceTypeHelper.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.servicereference; + +import java.beans.Introspector; +import java.util.ArrayList; +import java.util.List; +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.util.JavaXMLMapper; +import org.apache.tuscany.sca.interfacedef.util.TypeInfo; +import org.apache.tuscany.sca.interfacedef.util.XMLType; +import org.apache.tuscany.sca.xsd.XSDFactory; +import org.apache.tuscany.sca.xsd.XSDefinition; + +/** + * Maps ServiceReference interfaces to AnyType + */ +public class ServiceReferenceTypeHelper implements XMLTypeHelper { + private static final String SCHEMA_NS = "http://www.w3.org/2001/XMLSchema"; + private static final String ANYTYPE_NAME = "anyType"; + private static final QName ANYTYPE_QNAME = new QName(SCHEMA_NS, ANYTYPE_NAME); + + public ServiceReferenceTypeHelper() { + super(); + } + + public TypeInfo getTypeInfo(Class javaType, Object logical) { + QName xmlType = JavaXMLMapper.getXMLType(javaType); + if (xmlType != null) { + return new TypeInfo(xmlType, true, null); + } else if (javaType.isInterface()) { + return new TypeInfo(ANYTYPE_QNAME, true, null); + } else { + if (logical instanceof XMLType) { + xmlType = ((XMLType)logical).getTypeName(); + } + if (xmlType == null) { + xmlType = new QName(Introspector.decapitalize(javaType.getSimpleName())); + } + return new TypeInfo(xmlType, false, null); + } + } + + public List getSchemaDefinitions(XSDFactory factory, ModelResolver resolver, Interface intf) { + return new ArrayList(); + } + + public List getSchemaDefinitions(XSDFactory factory, ModelResolver resolver, List dataTypes) { + return new ArrayList(); + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/util/DataTypeHelper.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/util/DataTypeHelper.java new file mode 100644 index 0000000000..8a0789c673 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/util/DataTypeHelper.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.databinding.util; + +import java.lang.reflect.GenericArrayType; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.lang.reflect.TypeVariable; +import java.lang.reflect.WildcardType; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +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; + +/** + * + * @version $Rev$ $Date$ + */ +public final class DataTypeHelper { + private DataTypeHelper() { + } + + /** + * Find all classes referenced by this data type though java generics + * @param d + * @return + */ + public static Set> findClasses(DataType d) { + Set> classes = new HashSet>(); + Set visited = new HashSet(); + findClasses(d, classes, visited); + return classes; + } + + private static void findClasses(DataType d, Set> classes, Set visited) { + if (d == null) { + return; + } + classes.add(d.getPhysical()); + if (d.getPhysical() != d.getGenericType()) { + findClasses(d.getGenericType(), classes, visited); + } + } + + /** + * Find referenced classes in the generic type + * @param type + * @param classSet + * @param visited + */ + private static void findClasses(Type type, Set> classSet, Set visited) { + if (visited.contains(type) || type == null) { + return; + } + visited.add(type); + if (type instanceof Class) { + Class cls = (Class)type; + if (!cls.isInterface()) { + classSet.add(cls); + } + return; + } else if (type instanceof ParameterizedType) { + ParameterizedType pType = (ParameterizedType)type; + findClasses(pType.getRawType(), classSet, visited); + for (Type t : pType.getActualTypeArguments()) { + findClasses(t, classSet, visited); + } + } else if (type instanceof TypeVariable) { + TypeVariable tv = (TypeVariable)type; + for (Type t : tv.getBounds()) { + findClasses(t, classSet, visited); + } + } else if (type instanceof GenericArrayType) { + GenericArrayType gType = (GenericArrayType)type; + findClasses(gType, classSet, visited); + } else if (type instanceof WildcardType) { + WildcardType wType = (WildcardType)type; + for (Type t : wType.getLowerBounds()) { + findClasses(t, classSet, visited); + } + for (Type t : wType.getUpperBounds()) { + findClasses(t, classSet, visited); + } + } + } + + /** + * Get all the data types in the interface + * @param intf The interface + * @param useWrapper Use wrapper classes? + * @return A list of DataTypes + */ + public static List getDataTypes(Interface intf, boolean useWrapper) { + List dataTypes = new ArrayList(); + for (Operation op : intf.getOperations()) { + getDataTypes(dataTypes, op, useWrapper); + } + return dataTypes; + } + + /** + * Get all the data types in the operation + * @param op The operation + * @param useWrapper Use wrapper classes? + * @return A list of DataTypes + */ + public static List getDataTypes(Operation op, boolean useWrapper) { + List dataTypes = new ArrayList(); + getDataTypes(dataTypes, op, useWrapper); + return dataTypes; + } + + private static void getDataTypes(List dataTypes, Operation op, boolean useWrapper) { + WrapperInfo inputWrapper = op.getInputWrapper(); + WrapperInfo outputWrapper = op.getOutputWrapper(); + + if (useWrapper && (inputWrapper != null) && (outputWrapper != null)) { + DataType dt1 = inputWrapper.getWrapperType(); + if (dt1 != null) { + dataTypes.add(dt1); + } + DataType dt2 = outputWrapper.getWrapperType(); + if (dt2 != null) { + dataTypes.add(dt2); + } + } + // FIXME: [rfeng] We may need to find the referenced classes in the child types + // 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); + } + } + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/util/OperationDataBindingHelper.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/util/OperationDataBindingHelper.java new file mode 100644 index 0000000000..8ecd0ffb7f --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/util/OperationDataBindingHelper.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.databinding.util; + +import java.util.List; + +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.Operation; + +/** +* +* @version $Rev$ $Date$ +*/ +public class OperationDataBindingHelper { + + private static boolean isTransformationRequired(DataType source, DataType target) { + if (source == null || target == null) { // void return type + return false; + } + if (source == target) { + return false; + } + + String sourceDataBinding = source.getDataBinding(); + String targetDataBinding = target.getDataBinding(); + if (sourceDataBinding == targetDataBinding) { + return false; + } + if (sourceDataBinding == null || targetDataBinding == null) { + // TODO: If any of the databinding is null, then no transformation + return false; + } + return !sourceDataBinding.equals(targetDataBinding); + } + + public static boolean isTransformationRequired(Operation source, Operation target) { + if (source == target) { + return false; + } + + if (source.isInputWrapperStyle() != target.isInputWrapperStyle()) { + return true; + } + + if (source.isOutputWrapperStyle() != target.isOutputWrapperStyle()) { + return true; + } + + // Check output type + List sourceOutputType = source.getOutputType().getLogical(); + List targetOutputType = target.getOutputType().getLogical(); + + int outputSize = sourceOutputType.size(); + if ( outputSize != targetOutputType.size() ) { + return true; + } + + for (int i = 0; i < outputSize; i++) { + if (isTransformationRequired(sourceOutputType.get(i), targetOutputType.get(i))) { + return true; + } + } + + List sourceInputType = source.getInputType().getLogical(); + List targetInputType = target.getInputType().getLogical(); + + int size = sourceInputType.size(); + if (size != targetInputType.size()) { + // TUSCANY-1682: The wrapper style may have different arguments + return true; + } + for (int i = 0; i < size; i++) { + if (isTransformationRequired(sourceInputType.get(i), targetInputType.get(i))) { + return true; + } + } + + return false; + } +} + diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/BeanXMLStreamReaderImpl.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/BeanXMLStreamReaderImpl.java new file mode 100644 index 0000000000..ed59911a0b --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/BeanXMLStreamReaderImpl.java @@ -0,0 +1,300 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * 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.xml; + +import java.beans.BeanInfo; +import java.beans.Introspector; +import java.beans.PropertyDescriptor; +import java.lang.reflect.Array; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.common.xml.stax.reader.SimpleXmlNodeImpl; +import org.apache.tuscany.sca.common.xml.stax.reader.XmlNode; +import org.apache.tuscany.sca.common.xml.stax.reader.XmlTreeStreamReaderImpl; +import org.apache.tuscany.sca.databinding.SimpleTypeMapper; +import org.apache.tuscany.sca.databinding.impl.SimpleTypeMapperImpl; +import org.apache.tuscany.sca.interfacedef.util.TypeInfo; + +/** + * @version $Rev$ $Date$ + */ +public class BeanXMLStreamReaderImpl extends XmlTreeStreamReaderImpl { + private static final Comparator COMPARATOR = new Comparator() { + public int compare(Accessor o1, Accessor o2) { + return o1.getName().compareTo(o2.getName()); + } + }; + + public static class BeanXmlNodeImpl extends SimpleXmlNodeImpl implements XmlNode { + private static final Object[] NULL = null; + private static final SimpleTypeMapper MAPPER = new SimpleTypeMapperImpl(); + + public BeanXmlNodeImpl(Object bean) { + super(getName(bean == null ? null : bean.getClass()), bean); + } + + public BeanXmlNodeImpl(QName name, Object bean) { + super(name, bean); + } + + private static boolean isSimpleType(Class javaType) { + return MAPPER.getXMLType(javaType) != null; + } + + private static String getStringValue(Object o) { + if (o == null) { + return null; + } + TypeInfo info = MAPPER.getXMLType(o.getClass()); + if (info != null) { + return MAPPER.toXMLLiteral(info.getQName(), o, null); + } else { + return String.valueOf(o); + } + } + + @Override + public Iterator children() { + if (name == null) { + return null; + } + if (value == null) { + return super.children(); + } + if (isSimpleType(value.getClass())) { + XmlNode textNode = new BeanXmlNodeImpl(null, value); + return Arrays.asList(textNode).iterator(); + } + if (Map.class.isAssignableFrom(value.getClass())) { + List entries = new ArrayList(); + QName entryName = new QName(name.getNamespaceURI(), "entry"); + Map map = (Map)value; + if (map != null) { + for (Object e : map.entrySet()) { + Map.Entry entry = (Map.Entry)e; + entries.add(new BeanXmlNodeImpl(entryName, entry)); + } + } + return entries.iterator(); + } + try { + Map accessorMap = getAccessors(value); + List accessorList = new ArrayList(accessorMap.values()); + Collections.sort(accessorList, COMPARATOR); + + List props = new ArrayList(); + for (Accessor accessor : accessorList) { + Class pType = accessor.getType(); + + QName pName = new QName(name.getNamespaceURI(), accessor.getName()); + Object pValue = accessor.getValue(); + if (pType.isArray()) { + if (pValue != null) { + int i1 = Array.getLength(pValue); + for (int j = 0; j < i1; j++) { + Object o = Array.get(pValue, j); + props.add(new BeanXmlNodeImpl(pName, o)); + } + } else { + // TODO: How to handle null? + } + } else if (Collection.class.isAssignableFrom(pType)) { + Collection objList = (Collection)pValue; + if (objList != null && objList.size() > 0) { + for (Iterator j = objList.iterator(); j.hasNext();) { + Object o = j.next(); + props.add(new BeanXmlNodeImpl(pName, o)); + } + + } else { + // How to handle null + } + } else { + props.add(new BeanXmlNodeImpl(pName, pValue)); + } + } + return props.iterator(); + } catch (Exception e) { + throw new IllegalArgumentException(e); + } + } + + @Override + public QName getName() { + return name; + } + + @Override + public String getValue() { + return getStringValue(value); + } + + private static String getPackageName(Class cls) { + String name = cls.getName(); + int index = name.lastIndexOf('.'); + return index == -1 ? "" : name.substring(0, index); + } + + public static QName getName(Class cls) { + if (cls == null) { + return null; + } + + String packageName = getPackageName(cls); + + if ("".equals(packageName)) { + return new QName("", cls.getSimpleName()); + } + StringBuffer ns = new StringBuffer("http://"); + String[] names = packageName.split("\\."); + for (int i = names.length - 1; i >= 0; i--) { + ns.append(names[i]); + if (i != 0) { + ns.append('.'); + } + } + ns.append('/'); + return new QName(ns.toString(), cls.getSimpleName()); + } + + } + + public BeanXMLStreamReaderImpl(QName name, Object bean) { + super(getXmlNode(name, bean)); + } + + private static BeanXmlNodeImpl getXmlNode(QName name, Object bean) { + BeanXmlNodeImpl root = null; + if (name != null) { + root = new BeanXmlNodeImpl(name, bean); + } else { + root = new BeanXmlNodeImpl(bean); + } + return root; + } + + public static interface Accessor { + String getName(); + + Class getType(); + + Object getValue() throws Exception; + + void setValue(Object value) throws Exception; + } + + private static class FieldAccessor implements Accessor { + private Object target; + private Field field; + + public FieldAccessor(Object target, Field field) { + super(); + this.target = target; + this.field = field; + this.field.setAccessible(true); + } + + public String getName() { + return field.getName(); + } + + public Object getValue() throws Exception { + return field.get(target); + } + + public void setValue(Object value) throws Exception { + field.set(target, value); + } + + public Class getType() { + return field.getType(); + } + + } + + private static class PropertyAccessor implements Accessor { + private Object target; + private PropertyDescriptor prop; + + public PropertyAccessor(Object target, PropertyDescriptor prop) { + super(); + this.target = target; + this.prop = prop; + } + + public String getName() { + return prop.getName(); + } + + public Class getType() { + return prop.getPropertyType(); + } + + public Object getValue() throws Exception { + Method getter = prop.getReadMethod(); + if (getter != null) { + getter.setAccessible(true); + return getter.invoke(target); + } + throw new IllegalAccessException("The property cannot be read: " + getName()); + } + + public void setValue(Object value) throws Exception { + Method setter = prop.getWriteMethod(); + if (setter != null) { + setter.setAccessible(true); + setter.invoke(target); + } + throw new IllegalAccessException("The property cannot be written: " + getName()); + } + + } + + private static Map getAccessors(Object target) throws Exception { + if (target == null) { + return Collections.emptyMap(); + } + Map map = new HashMap(); + Class type = target.getClass(); + for (Field f : type.getFields()) { + map.put(f.getName(), new FieldAccessor(target, f)); + } + BeanInfo info = Introspector.getBeanInfo(type, Object.class); + for (PropertyDescriptor p : info.getPropertyDescriptors()) { + // if (p.getReadMethod() != null && p.getWriteMethod() != null) { + map.put(p.getName(), new PropertyAccessor(target, p)); + // } + } + return map; + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/DOMDataBinding.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/DOMDataBinding.java new file mode 100644 index 0000000000..b21a531c53 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/DOMDataBinding.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.databinding.xml; + + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.common.xml.dom.DOMHelper; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.databinding.BaseDataBinding; +import org.apache.tuscany.sca.databinding.TransformationContext; +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.XMLType; +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; + +/** + * DOM DataBinding + * + * @version $Rev$ $Date$ + * @tuscany.spi.extension.asclient + */ +public class DOMDataBinding extends BaseDataBinding { + public static final String NAME = Node.class.getName(); + + public static final String ROOT_NAMESPACE = "http://tuscany.apache.org/xmlns/sca/databinding/dom/1.0"; + public static final QName ROOT_ELEMENT = new QName(ROOT_NAMESPACE, "root"); + + private DOMHelper domHelper; + + public DOMDataBinding(ExtensionPointRegistry registry) { + super(NAME, Node.class); + this.domHelper = DOMHelper.getInstance(registry); + } + + @Override + public WrapperHandler getWrapperHandler() { + return new DOMWrapperHandler(domHelper); + } + + @Override + public Object copy(Object source, + DataType dataType, + DataType targetDataType, + Operation operation, + Operation targetOperation) { + if (Node.class.isAssignableFrom(source.getClass())) { + Node nodeSource = (Node)source; + return nodeSource.cloneNode(true); + } + return super.copy(source, dataType, targetDataType, operation, targetOperation); + } + + @Override + public boolean introspect(DataType type, Operation operation) { + if (Node.class.isAssignableFrom(type.getPhysical())) { + if (type.getLogical() == null) { + type.setLogical(new XMLType(ROOT_ELEMENT, null)); + } + type.setDataBinding(NAME); + return true; + } + return false; + } + + /** + * @param context + * @param element + */ + public static Element adjustElementName(TransformationContext context, Element element) { + if (context != null) { + DataType dataType = context.getTargetDataType(); + Object logical = dataType == null ? null : dataType.getLogical(); + if (!(logical instanceof XMLType)) { + return element; + } + XMLType xmlType = (XMLType)logical; + QName name = new QName(element.getNamespaceURI(), element.getLocalName()); + if (xmlType.isElement() && !xmlType.getElementName().equals(name)) { + QName newName = xmlType.getElementName(); + String prefix = newName.getPrefix(); + String qname = newName.getLocalPart(); + if (prefix != null && !prefix.equals("")) { + qname = prefix + ":" + qname; + } + Document doc = element.getOwnerDocument(); + Element newElement = doc.createElementNS(newName.getNamespaceURI(), qname); + // Copy the attributes to the new element + NamedNodeMap attrs = element.getAttributes(); + for (int i = 0; i < attrs.getLength(); i++) { + Attr attr = (Attr)doc.importNode(attrs.item(i), true); + newElement.getAttributes().setNamedItem(attr); + } + + // Move all the children + while (element.hasChildNodes()) { + newElement.appendChild(element.getFirstChild()); + } + + // Replace the old node with the new node + if (element.getParentNode() != null) { + element.getParentNode().replaceChild(newElement, element); + } + + return newElement; + } + } + return element; + } +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/DOMWrapperHandler.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/DOMWrapperHandler.java new file mode 100644 index 0000000000..6736888b0e --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/DOMWrapperHandler.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.databinding.xml; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.common.xml.dom.DOMHelper; +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.WrapperInfo; +import org.apache.tuscany.sca.interfacedef.util.XMLType; +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +public class DOMWrapperHandler implements WrapperHandler { + private DOMHelper domHelper; + + public DOMWrapperHandler(DOMHelper domHelper) { + super(); + this.domHelper = domHelper; + } + + public Node create(Operation operation, boolean input) { + WrapperInfo inputWrapperInfo = operation.getInputWrapper(); + WrapperInfo outputWrapperInfo = operation.getOutputWrapper(); + + ElementInfo element = input ? inputWrapperInfo.getWrapperElement() : outputWrapperInfo.getWrapperElement(); + + Document document = domHelper.newDocument(); + QName name = element.getQName(); + return DOMHelper.createElement(document, name); + } + + public void setChildren(Node wrapper, + Object[] childObjects, + Operation operation, boolean input) { + WrapperInfo inputWrapperInfo = operation.getInputWrapper(); + WrapperInfo outputWrapperInfo = operation.getOutputWrapper(); + + List childElements = input? inputWrapperInfo.getChildElements(): + outputWrapperInfo.getChildElements(); + for (int i = 0; i < childElements.size(); i++) { + setChild(wrapper, i, childElements.get(i), childObjects[i]); + } + + } + public void setChild(Node wrapper, int i, ElementInfo childElement, Object value) { + Node node = (Node)value; + if (node.getNodeType() == Node.DOCUMENT_NODE) { + node = ((Document)node).getDocumentElement(); + } + wrapper.appendChild(wrapper.getOwnerDocument().importNode(node, true)); + } + + public List getChildren(Node wrapper, Operation operation, boolean input) { + assert wrapper != null; + + WrapperInfo inputWrapperInfo = operation.getInputWrapper(); + WrapperInfo outputWrapperInfo = operation.getOutputWrapper(); + + List childElements = input? inputWrapperInfo.getChildElements(): + outputWrapperInfo.getChildElements(); + + if (wrapper.getNodeType() == Node.DOCUMENT_NODE) { + wrapper = ((Document)wrapper).getDocumentElement(); + } + List elements = new ArrayList(); + NodeList nodes = wrapper.getChildNodes(); + for (int j = 0; j < nodes.getLength(); j++) { + Node node = nodes.item(j); + if (node.getNodeType() == Node.ELEMENT_NODE) { + elements.add(node); + } + } + return elements; + } + + /** + * @see org.apache.tuscany.sca.databinding.WrapperHandler#getWrapperType(Operation, boolean) + */ + public DataType getWrapperType(Operation operation, boolean input) { + WrapperInfo inputWrapperInfo = operation.getInputWrapper(); + WrapperInfo outputWrapperInfo = operation.getOutputWrapper(); + + ElementInfo element = input? inputWrapperInfo.getWrapperElement(): outputWrapperInfo.getWrapperElement(); + DataType wrapperType = + new DataTypeImpl(DOMDataBinding.NAME, Node.class, new XMLType(element)); + return wrapperType; + } + + public boolean isInstance(Object wrapperObj, + Operation operation, + boolean input) { + WrapperInfo inputWrapperInfo = operation.getInputWrapper(); + WrapperInfo outputWrapperInfo = operation.getOutputWrapper(); + + ElementInfo element = input ? inputWrapperInfo.getWrapperElement() : outputWrapperInfo.getWrapperElement(); + List childElements = input ? inputWrapperInfo.getChildElements() : outputWrapperInfo.getChildElements(); + + Node wrapper = (Node)wrapperObj; + if (wrapper.getNodeType() == Node.DOCUMENT_NODE) { + wrapper = ((Document)wrapper).getDocumentElement(); + } + QName elementName = new QName(wrapper.getNamespaceURI(), wrapper.getLocalName()); + if (!element.getQName().equals(elementName)) { + return false; + } + Set names = new HashSet(); + for (ElementInfo e : childElements) { + names.add(e.getQName()); + } + NodeList nodes = wrapper.getChildNodes(); + for (int j = 0; j < nodes.getLength(); j++) { + Node node = nodes.item(j); + if (node.getNodeType() == Node.ELEMENT_NODE) { + elementName = new QName(node.getNamespaceURI(), node.getLocalName()); + if (!names.contains(elementName)) { + return false; + } + } + } + return true; + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/InputSource2Node.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/InputSource2Node.java new file mode 100644 index 0000000000..0bb0513011 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/InputSource2Node.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.xml; + +import javax.xml.transform.Source; +import javax.xml.transform.dom.DOMResult; +import javax.xml.transform.stream.StreamSource; + +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.databinding.BaseTransformer; +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.w3c.dom.Node; +import org.xml.sax.InputSource; + +/** + * Push DOM InputSource to Node + * + * @version $Rev$ $Date$ + */ +public class InputSource2Node extends BaseTransformer implements + PullTransformer { + + private final Source2ResultTransformer TRANSFORMER; + + public InputSource2Node(ExtensionPointRegistry registry) { + super(); + this.TRANSFORMER = new Source2ResultTransformer(registry); + } + + public Node transform(InputSource source, TransformationContext context) { + try { + Source streamSource = new StreamSource(source.getCharacterStream()); + DOMResult result = new DOMResult(); + TRANSFORMER.transform(streamSource, result, context); + return result.getNode(); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + public Class getSourceType() { + return InputSource.class; + } + + @Override + public Class getTargetType() { + return Node.class; + } + + @Override + public int getWeight() { + return 40; + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/InputSource2SAX.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/InputSource2SAX.java new file mode 100644 index 0000000000..b0b5d336f0 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/InputSource2SAX.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.xml; + +import org.apache.tuscany.sca.databinding.BaseTransformer; +import org.apache.tuscany.sca.databinding.PushTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.xml.sax.ContentHandler; +import org.xml.sax.InputSource; +import org.xml.sax.XMLReader; +import org.xml.sax.helpers.XMLReaderFactory; + +/** + * Push InputSource to SAX + * + * @version $Rev$ $Date$ + */ +public class InputSource2SAX extends BaseTransformer implements + PushTransformer { + + public void transform(InputSource source, ContentHandler target, TransformationContext context) { + try { + XMLReader reader = XMLReaderFactory.createXMLReader(); + reader.setFeature("http://xml.org/sax/features/namespaces", true); + reader.setFeature("http://xml.org/sax/features/namespace-prefixes", false); + reader.setContentHandler(target); + reader.parse(source); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + public Class getSourceType() { + return InputSource.class; + } + + @Override + public Class getTargetType() { + return ContentHandler.class; + } + + @Override + public int getWeight() { + return 40; + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/InputStream2Node.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/InputStream2Node.java new file mode 100644 index 0000000000..c9183c4cbf --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/InputStream2Node.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.xml; + +import java.io.InputStream; + +import javax.xml.transform.Source; +import javax.xml.transform.dom.DOMResult; +import javax.xml.transform.sax.SAXSource; + +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.databinding.BaseTransformer; +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.w3c.dom.Node; +import org.xml.sax.InputSource; + +/** + * Push DOM InputSource to Node + * + * @version $Rev$ $Date$ + */ +public class InputStream2Node extends BaseTransformer implements + PullTransformer { + private final Source2ResultTransformer TRANSFORMER; + + public InputStream2Node(ExtensionPointRegistry registry) { + super(); + this.TRANSFORMER = new Source2ResultTransformer(registry); + } + + + public Node transform(InputStream source, TransformationContext context) { + try { + Source streamSource = new SAXSource(new InputSource(source)); + DOMResult result = new DOMResult(); + TRANSFORMER.transform(streamSource, result, context); + return result.getNode(); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + public Class getSourceType() { + return InputStream.class; + } + + @Override + public Class getTargetType() { + return Node.class; + } + + @Override + public int getWeight() { + return 40; + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/InputStream2SAX.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/InputStream2SAX.java new file mode 100644 index 0000000000..f762122350 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/InputStream2SAX.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.xml; + +import java.io.InputStream; + +import org.apache.tuscany.sca.databinding.BaseTransformer; +import org.apache.tuscany.sca.databinding.PushTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.xml.sax.ContentHandler; +import org.xml.sax.InputSource; +import org.xml.sax.XMLReader; +import org.xml.sax.helpers.XMLReaderFactory; + +/** + * Push InputStream to SAX + * + * @version $Rev$ $Date$ + */ +public class InputStream2SAX extends BaseTransformer implements + PushTransformer { + public void transform(InputStream source, ContentHandler target, TransformationContext context) { + try { + XMLReader reader = XMLReaderFactory.createXMLReader(); + reader.setContentHandler(target); + reader.parse(new InputSource(source)); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + public Class getSourceType() { + return InputStream.class; + } + + @Override + public Class getTargetType() { + return ContentHandler.class; + } + + @Override + public int getWeight() { + return 40; + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Node2OutputStream.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Node2OutputStream.java new file mode 100644 index 0000000000..25ed70dda5 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Node2OutputStream.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.xml; + +import java.io.OutputStream; + +import javax.xml.transform.Result; +import javax.xml.transform.Source; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.databinding.BaseTransformer; +import org.apache.tuscany.sca.databinding.PushTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.w3c.dom.Node; + +/** + * Push DOM Node to OutputStream + * + * @version $Rev$ $Date$ + */ +public class Node2OutputStream extends BaseTransformer implements + PushTransformer { + + private final Source2ResultTransformer TRANSFORMER; + + public Node2OutputStream(ExtensionPointRegistry registry) { + super(); + this.TRANSFORMER = new Source2ResultTransformer(registry); + } + + public void transform(Node source, OutputStream writer, TransformationContext context) { + try { + Source domSource = new DOMSource(source); + Result result = new StreamResult(writer); + TRANSFORMER.transform(domSource, result, context); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + protected Class getSourceType() { + return Node.class; + } + + @Override + protected Class getTargetType() { + return OutputStream.class; + } + + @Override + public int getWeight() { + return 40; + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Node2SimpleJavaType.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Node2SimpleJavaType.java new file mode 100644 index 0000000000..d5bf7e76b5 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Node2SimpleJavaType.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.databinding.xml; + +import org.apache.tuscany.sca.databinding.impl.SimpleType2JavaTransformer; +import org.w3c.dom.Document; +import org.w3c.dom.Node; + +/** + * Transformer to convert data from a simple java Object to OMElement. + * + * @version $Rev$ $Date$ + */ +public class Node2SimpleJavaType extends SimpleType2JavaTransformer { + + @Override + protected String getText(Node source) { + if (source instanceof Document) { + source = ((Document)source).getDocumentElement(); + } + return source.getTextContent(); + + } + + @Override + public Class getSourceType() { + return Node.class; + } +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Node2SourceTransformer.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Node2SourceTransformer.java new file mode 100644 index 0000000000..cb33d3548a --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Node2SourceTransformer.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.xml; + +import javax.xml.transform.Source; +import javax.xml.transform.dom.DOMSource; + +import org.apache.tuscany.sca.databinding.BaseTransformer; +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.w3c.dom.Node; + +/** + * Transform TrAX Node to Source + * + * @version $Rev$ $Date$ + */ +public class Node2SourceTransformer extends BaseTransformer implements + PullTransformer { + + public Source transform(Node source, TransformationContext context) { + try { + return new DOMSource(source); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + protected Class getSourceType() { + return Node.class; + } + + @Override + protected Class getTargetType() { + return Source.class; + } + + @Override + public int getWeight() { + return 40; + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Node2String.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Node2String.java new file mode 100644 index 0000000000..fb3023345c --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Node2String.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.xml; + +import java.io.StringWriter; + +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.databinding.BaseTransformer; +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.w3c.dom.Node; + +/** + * Transform DOM Node to XML String + * + * @version $Rev$ $Date$ + */ +public class Node2String extends BaseTransformer implements PullTransformer { + private final Node2Writer TRANSFORMER; + + public Node2String(ExtensionPointRegistry registry) { + super(); + this.TRANSFORMER = new Node2Writer(registry); + } + + public String transform(Node source, TransformationContext context) { + try { + StringWriter writer = new StringWriter(); + TRANSFORMER.transform(source, writer, context); + return writer.toString(); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + public Class getSourceType() { + return Node.class; + } + + @Override + public Class getTargetType() { + return String.class; + } + + @Override + public int getWeight() { + return 40; + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Node2Writer.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Node2Writer.java new file mode 100644 index 0000000000..6c1d241ce9 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Node2Writer.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.xml; + +import java.io.Writer; + +import javax.xml.transform.Result; +import javax.xml.transform.Source; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.databinding.BaseTransformer; +import org.apache.tuscany.sca.databinding.PushTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.w3c.dom.Node; + +/** + * Push DOM Node to Writer + * + * @version $Rev$ $Date$ + */ +public class Node2Writer extends BaseTransformer implements PushTransformer { + + private final Source2ResultTransformer TRANSFORMER; + + public Node2Writer(ExtensionPointRegistry registry) { + super(); + this.TRANSFORMER = new Source2ResultTransformer(registry); + } + + public void transform(Node source, Writer writer, TransformationContext context) { + try { + Source domSource = new DOMSource(source); + Result result = new StreamResult(writer); + TRANSFORMER.transform(domSource, result, context); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + protected Class getSourceType() { + return Node.class; + } + + @Override + protected Class getTargetType() { + return Writer.class; + } + + @Override + public int getWeight() { + return 40; + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Node2XMLStreamReader.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Node2XMLStreamReader.java new file mode 100644 index 0000000000..2e0612b9b7 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Node2XMLStreamReader.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.xml; + +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sca.common.xml.stax.reader.DOMXMLStreamReader; +import org.apache.tuscany.sca.databinding.BaseTransformer; +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.w3c.dom.Node; + +/** + * Transform DOM Node to XML XMLStreamReader + * + * @version $Rev$ $Date$ + */ +public class Node2XMLStreamReader extends BaseTransformer implements + PullTransformer { + + public XMLStreamReader transform(Node source, TransformationContext context) { + if (source == null) { + return null; + } + try { + DOMXMLStreamReader reader = new DOMXMLStreamReader(source); + return reader; + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + protected Class getSourceType() { + return Node.class; + } + + @Override + protected Class getTargetType() { + return XMLStreamReader.class; + } + + @Override + public int getWeight() { + return 40; + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Reader2Node.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Reader2Node.java new file mode 100644 index 0000000000..1866f3864a --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Reader2Node.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.xml; + +import java.io.Reader; + +import javax.xml.transform.Source; +import javax.xml.transform.dom.DOMResult; +import javax.xml.transform.stream.StreamSource; + +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.databinding.BaseTransformer; +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.w3c.dom.Node; + +/** + * Push DOM Reader to Node + * + * @version $Rev$ $Date$ + */ +public class Reader2Node extends BaseTransformer implements PullTransformer { + private final Source2ResultTransformer TRANSFORMER; + + public Reader2Node(ExtensionPointRegistry registry) { + super(); + this.TRANSFORMER = new Source2ResultTransformer(registry); + } + + public Node transform(Reader source, TransformationContext context) { + try { + Source streamSource = new StreamSource(source); + DOMResult result = new DOMResult(); + TRANSFORMER.transform(streamSource, result, context); + return result.getNode(); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + protected Class getSourceType() { + return Reader.class; + } + + @Override + protected Class getTargetType() { + return Node.class; + } + + @Override + public int getWeight() { + return 40; + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Reader2SAX.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Reader2SAX.java new file mode 100644 index 0000000000..396038ec08 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Reader2SAX.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.xml; + +import java.io.Reader; + +import org.apache.tuscany.sca.databinding.BaseTransformer; +import org.apache.tuscany.sca.databinding.PushTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.xml.sax.ContentHandler; +import org.xml.sax.InputSource; + +/** + * Transform XML string to SAX + * + * @version $Rev$ $Date$ + */ +public class Reader2SAX extends BaseTransformer implements + PushTransformer { + public void transform(Reader source, ContentHandler target, TransformationContext context) { + try { + new InputSource2SAX().transform(new InputSource(source), target, context); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + protected Class getSourceType() { + return Reader.class; + } + + @Override + protected Class getTargetType() { + return ContentHandler.class; + } + + @Override + public int getWeight() { + return 40; + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/SAX2DOMPipe.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/SAX2DOMPipe.java new file mode 100644 index 0000000000..9bc5f99304 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/SAX2DOMPipe.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.xml; + +import org.apache.tuscany.sca.common.xml.dom.DOMHelper; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.databinding.BaseTransformer; +import org.apache.tuscany.sca.databinding.DataPipe; +import org.apache.tuscany.sca.databinding.DataPipeTransformer; +import org.w3c.dom.Node; +import org.xml.sax.ContentHandler; + +public class SAX2DOMPipe extends BaseTransformer implements DataPipeTransformer { + private DOMHelper domHelper; + /** + * + */ + public SAX2DOMPipe(ExtensionPointRegistry registry) { + super(); + domHelper = DOMHelper.getInstance(registry); + } + + /** + * @see org.apache.tuscany.sca.databinding.DataPipeTransformer#newInstance() + */ + public DataPipe newInstance() { + return new Pipe(); + } + + @Override + protected Class getTargetType() { + return Node.class; + } + + @Override + protected Class getSourceType() { + return ContentHandler.class; + } + + @Override + public int getWeight() { + return 30; + } + + private class Pipe implements DataPipe { + private DOMHelper.NodeContentHandler pipe; + + public Pipe() { + super(); + this.pipe = domHelper.createContentHandler(null); + } + + public Node getResult() { + return pipe.getNode(); + } + + public ContentHandler getSink() { + return pipe; + } + + } +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/SimpleJavaType2Node.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/SimpleJavaType2Node.java new file mode 100644 index 0000000000..0bb13bb3ea --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/SimpleJavaType2Node.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.xml; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.common.xml.dom.DOMHelper; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.impl.Java2SimpleTypeTransformer; +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.Node; + +/** + * Transformer to convert data from an simple OMElement to Java Object + * + * @version $Rev$ $Date$ + */ +public class SimpleJavaType2Node extends Java2SimpleTypeTransformer { + private DOMHelper helper; + + public SimpleJavaType2Node(ExtensionPointRegistry registry) { + super(); + helper = DOMHelper.getInstance(registry); + } + + @Override + protected Node createElement(QName element, String text, TransformationContext context) { + if (element == null) { + element = DOMDataBinding.ROOT_ELEMENT; + } + Document factory = helper.newDocument(); + Node root = DOMHelper.createElement(factory, element); + if (text != null) { + root.appendChild(factory.createTextNode(text)); + } else { + Attr nil = factory.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "xsi:nil"); + nil.setValue("true"); + root.appendChild(nil); + } + return root; + } + + @Override + public Class getTargetType() { + return Node.class; + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Source2NodeTransformer.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Source2NodeTransformer.java new file mode 100644 index 0000000000..d2fb8305e8 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Source2NodeTransformer.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.xml; + +import javax.xml.transform.Source; + +import org.apache.tuscany.sca.common.xml.dom.DOMHelper; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.databinding.BaseTransformer; +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.w3c.dom.Document; +import org.w3c.dom.Node; + +/** + * Transform TrAX Source to Node + * + * @version $Rev$ $Date$ + */ +public class Source2NodeTransformer extends BaseTransformer implements + PullTransformer { + private DOMHelper helper; + + public Source2NodeTransformer(ExtensionPointRegistry registry) { + super(); + helper = DOMHelper.getInstance(registry); + } + + public Node transform(Source source, TransformationContext context) { + try { + Document doc = helper.load(source); + return DOMDataBinding.adjustElementName(context, doc.getDocumentElement()); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + protected Class getSourceType() { + return Source.class; + } + + @Override + protected Class getTargetType() { + return Node.class; + } + + @Override + public int getWeight() { + return 40; + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Source2ResultTransformer.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Source2ResultTransformer.java new file mode 100644 index 0000000000..dd69e3ea66 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Source2ResultTransformer.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.xml; + +import javax.xml.transform.Result; +import javax.xml.transform.Source; +import javax.xml.transform.TransformerFactory; + +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.core.FactoryExtensionPoint; +import org.apache.tuscany.sca.databinding.BaseTransformer; +import org.apache.tuscany.sca.databinding.PushTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; + +/** + * Transform TrAX Source to Result + * + * @version $Rev$ $Date$ + */ +public class Source2ResultTransformer extends BaseTransformer implements + PushTransformer { + private final TransformerFactory factory; + + public Source2ResultTransformer(ExtensionPointRegistry registry) { + super(); + FactoryExtensionPoint factories = registry.getExtensionPoint(FactoryExtensionPoint.class); + factory = factories.getFactory(TransformerFactory.class); + } + + public void transform(Source source, Result result, TransformationContext context) { + try { + javax.xml.transform.Transformer transformer = factory.newTransformer(); + transformer.transform(source, result); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + protected Class getSourceType() { + return Source.class; + } + + @Override + protected Class getTargetType() { + return Result.class; + } + + @Override + public int getWeight() { + return 40; + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Source2StringTransformer.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Source2StringTransformer.java new file mode 100644 index 0000000000..0c3db2a477 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Source2StringTransformer.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.xml; + +import java.io.StringWriter; + +import javax.xml.transform.Source; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.stream.StreamResult; + +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.core.FactoryExtensionPoint; +import org.apache.tuscany.sca.databinding.BaseTransformer; +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; + +/** + * Transform TrAX Source to String + * + * @version $Rev$ $Date$ + */ +public class Source2StringTransformer extends BaseTransformer implements + PullTransformer { + private final TransformerFactory factory; + + public Source2StringTransformer(ExtensionPointRegistry registry) { + super(); + FactoryExtensionPoint factories = registry.getExtensionPoint(FactoryExtensionPoint.class); + factory = factories.getFactory(TransformerFactory.class); + } + + public String transform(Source source, TransformationContext context) { + try { + javax.xml.transform.Transformer transformer = factory.newTransformer(); + StringWriter sw = new StringWriter(); + StreamResult result = new StreamResult(sw); + transformer.transform(source, result); + return sw.toString(); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + protected Class getSourceType() { + return Source.class; + } + + @Override + protected Class getTargetType() { + return String.class; + } + + @Override + public int getWeight() { + return 40; + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/StAXDataBinding.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/StAXDataBinding.java new file mode 100644 index 0000000000..f8ae31b96c --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/StAXDataBinding.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.xml; + + +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sca.databinding.BaseDataBinding; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.interfacedef.util.XMLType; + +/** + * A DataBinding for the StAX + * + * @version $Rev$ $Date$ + */ +public class StAXDataBinding extends BaseDataBinding { + public static final String NAME = XMLStreamReader.class.getName(); + + public StAXDataBinding() { + super(NAME, XMLStreamReader.class); + } + + @Override + public boolean introspect(DataType type, Operation operation) { + if (super.introspect(type, operation)) { + type.setLogical(XMLType.UNKNOWN); + type.setDataBinding(NAME); + return true; + } else { + return false; + } + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/StreamDataPipe.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/StreamDataPipe.java new file mode 100644 index 0000000000..38f8327ae4 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/StreamDataPipe.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.xml; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.OutputStream; + +import org.apache.tuscany.sca.databinding.BaseTransformer; +import org.apache.tuscany.sca.databinding.DataPipe; +import org.apache.tuscany.sca.databinding.DataPipeTransformer; + +public class StreamDataPipe extends BaseTransformer implements + DataPipeTransformer { + + public DataPipe newInstance() { + return new Pipe(); + } + + @Override + protected Class getTargetType() { + return InputStream.class; + } + + @Override + public int getWeight() { + return 50; + } + + @Override + protected Class getSourceType() { + return OutputStream.class; + } + + public static class Pipe implements DataPipe { + private ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + + public InputStream getResult() { + return new ByteArrayInputStream(outputStream.toByteArray()); + } + + public OutputStream getSink() { + return outputStream; + } + + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/String2Node.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/String2Node.java new file mode 100644 index 0000000000..cfcbce2e12 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/String2Node.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.xml; + +import org.apache.tuscany.sca.common.xml.dom.DOMHelper; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.databinding.BaseTransformer; +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.w3c.dom.Node; + +public class String2Node extends BaseTransformer implements PullTransformer { + private DOMHelper helper; + + public String2Node(ExtensionPointRegistry registry) { + super(); + helper = DOMHelper.getInstance(registry); + } + + public Node transform(String source, TransformationContext context) { + try { + return helper.load(source); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + protected Class getSourceType() { + return String.class; + } + + @Override + protected Class getTargetType() { + return Node.class; + } + + @Override + public int getWeight() { + return 50; + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/String2SAX.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/String2SAX.java new file mode 100644 index 0000000000..461adbe938 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/String2SAX.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.xml; + +import java.io.StringReader; + +import org.apache.tuscany.sca.databinding.BaseTransformer; +import org.apache.tuscany.sca.databinding.PushTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.xml.sax.ContentHandler; +import org.xml.sax.InputSource; + +/** + * Transform XML string to SAX + * + * @version $Rev$ $Date$ + */ +public class String2SAX extends BaseTransformer implements + PushTransformer { + + public void transform(String source, ContentHandler target, TransformationContext context) { + try { + new InputSource2SAX().transform(new InputSource(new StringReader(source)), target, context); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + protected Class getSourceType() { + return String.class; + } + + @Override + protected Class getTargetType() { + return ContentHandler.class; + } + + @Override + public int getWeight() { + return 40; + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/String2SourceTransformer.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/String2SourceTransformer.java new file mode 100644 index 0000000000..31093b8587 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/String2SourceTransformer.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.xml; + +import java.io.StringReader; + +import javax.xml.transform.Source; +import javax.xml.transform.stream.StreamSource; + +import org.apache.tuscany.sca.databinding.BaseTransformer; +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; + +/** + * Transform XML String to Source + * + * @version $Rev$ $Date$ + */ +public class String2SourceTransformer extends BaseTransformer implements + PullTransformer { + + public Source transform(String source, TransformationContext context) { + try { + return new StreamSource(new StringReader(source)); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + protected Class getSourceType() { + return String.class; + } + + @Override + protected Class getTargetType() { + return Source.class; + } + + @Override + public int getWeight() { + return 40; + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/String2XMLStreamReader.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/String2XMLStreamReader.java new file mode 100644 index 0000000000..156e15d8c5 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/String2XMLStreamReader.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.xml; + +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sca.common.xml.stax.StAXHelper; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.databinding.BaseTransformer; +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; + +public class String2XMLStreamReader extends BaseTransformer implements + PullTransformer { + private StAXHelper helper; + + public String2XMLStreamReader(ExtensionPointRegistry registry) { + helper = StAXHelper.getInstance(registry); + } + + public XMLStreamReader transform(String source, TransformationContext context) { + try { + return helper.createXMLStreamReader(source); + } catch (XMLStreamException e) { + throw new TransformationException(e); + } + } + + @Override + protected Class getSourceType() { + return String.class; + } + + @Override + protected Class getTargetType() { + return XMLStreamReader.class; + } + + @Override + public int getWeight() { + return 50; + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Writer2ReaderDataPipe.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Writer2ReaderDataPipe.java new file mode 100644 index 0000000000..0544631a73 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/Writer2ReaderDataPipe.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.xml; + +import java.io.Reader; +import java.io.StringReader; +import java.io.StringWriter; +import java.io.Writer; + +import org.apache.tuscany.sca.databinding.BaseTransformer; +import org.apache.tuscany.sca.databinding.DataPipe; +import org.apache.tuscany.sca.databinding.DataPipeTransformer; + +public class Writer2ReaderDataPipe extends BaseTransformer implements DataPipeTransformer { + + public DataPipe newInstance() { + return new Pipe(); + } + + @Override + protected Class getTargetType() { + return Reader.class; + } + + @Override + public int getWeight() { + return 50; + } + + @Override + protected Class getSourceType() { + return Writer.class; + } + + private static class Pipe implements DataPipe { + private StringWriter writer = new StringWriter(); + + public Reader getResult() { + return new StringReader(writer.toString()); + } + + public Writer getSink() { + return writer; + } + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLGroupDataBinding.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLGroupDataBinding.java new file mode 100644 index 0000000000..f7c895db1e --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLGroupDataBinding.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.xml; + +import java.io.InputStream; +import java.io.OutputStream; +import java.io.Reader; +import java.io.Writer; + +import javax.xml.stream.XMLEventReader; +import javax.xml.stream.XMLEventWriter; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; + +import org.apache.tuscany.sca.databinding.impl.GroupDataBinding; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.interfacedef.util.XMLType; +import org.xml.sax.ContentHandler; +import org.xml.sax.InputSource; + +/** + * A Group DataBinding + * + * @version $Rev$ $Date$ + */ +public class XMLGroupDataBinding extends GroupDataBinding { + + public XMLGroupDataBinding() { + super(new Class[] {InputStream.class, OutputStream.class, Reader.class, Writer.class, + // Source.class, Result.class, + InputSource.class, ContentHandler.class, XMLStreamReader.class, + XMLStreamWriter.class, XMLEventReader.class, XMLEventWriter.class}); + } + + @Override + protected Object getLogical(Class markerType, Operation operation) { + return XMLType.UNKNOWN; + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLStreamReader2Node.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLStreamReader2Node.java new file mode 100644 index 0000000000..a7b179b93c --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLStreamReader2Node.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.databinding.xml; + +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.databinding.BaseTransformer; +import org.apache.tuscany.sca.databinding.DataPipe; +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.xml.sax.ContentHandler; + +/** + * Transform DOM Node to XML XMLStreamReader + * + * @version $Rev$ $Date$ + */ +public class XMLStreamReader2Node extends BaseTransformer implements + PullTransformer { + + private XMLStreamReader2SAX stax2sax; + private SAX2DOMPipe sax2domPipe; + + public XMLStreamReader2Node(ExtensionPointRegistry registry) { + stax2sax = new XMLStreamReader2SAX(registry); + sax2domPipe = new SAX2DOMPipe(registry); + } + + public Node transform(XMLStreamReader source, TransformationContext context) { + try { + if (source == null) { + return null; + } + DataPipe pipe = sax2domPipe.newInstance(); + stax2sax.transform(source, pipe.getSink(), context); + Node node = pipe.getResult(); + source.close(); + if (node instanceof Document) { + Document doc = (Document)node; + return DOMDataBinding.adjustElementName(context, doc.getDocumentElement()); + } else { + return node; + } + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + protected Class getSourceType() { + return XMLStreamReader.class; + } + + @Override + protected Class getTargetType() { + return Node.class; + } + + @Override + public int getWeight() { + return 40; + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLStreamReader2SAX.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLStreamReader2SAX.java new file mode 100644 index 0000000000..11dc23e4b6 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLStreamReader2SAX.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.xml; + +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sca.common.xml.stax.StAXHelper; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.databinding.BaseTransformer; +import org.apache.tuscany.sca.databinding.PushTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.xml.sax.ContentHandler; + +/** + * XMLStreamReader to SAX events + * + * @version $Rev$ $Date$ + */ +public class XMLStreamReader2SAX extends BaseTransformer implements + PushTransformer { + + private StAXHelper helper; + + public XMLStreamReader2SAX(ExtensionPointRegistry registry) { + helper = StAXHelper.getInstance(registry); + } + + @Override + protected Class getTargetType() { + return ContentHandler.class; + } + + @Override + protected Class getSourceType() { + return XMLStreamReader.class; + } + + /** + * @see org.apache.tuscany.sca.databinding.PushTransformer#getWeight() + */ + @Override + public int getWeight() { + return 20; + } + + /** + * @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, ContentHandler sink, TransformationContext context) { + try { + helper.saveAsSAX(source, sink); + source.close(); + } catch (Exception e) { + throw new TransformationException(e); + } + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLStreamReader2String.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLStreamReader2String.java new file mode 100644 index 0000000000..64c93d74a0 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLStreamReader2String.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.xml; + +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sca.common.xml.stax.StAXHelper; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.databinding.BaseTransformer; +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; + +public class XMLStreamReader2String extends BaseTransformer implements + PullTransformer { + private StAXHelper helper; + + public XMLStreamReader2String(ExtensionPointRegistry registry) { + helper = StAXHelper.getInstance(registry); + } + + public String transform(XMLStreamReader source, TransformationContext context) { + try { + String str = helper.saveAsString(source); + source.close(); + return str; + } catch (XMLStreamException e) { + throw new TransformationException(e); + } + } + + @Override + protected Class getSourceType() { + return XMLStreamReader.class; + } + + @Override + protected Class getTargetType() { + return String.class; + } + + @Override + public int getWeight() { + return 40; + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLStringDataBinding.java b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLStringDataBinding.java new file mode 100644 index 0000000000..b360b5b9a8 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/java/org/apache/tuscany/sca/databinding/xml/XMLStringDataBinding.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.databinding.xml; + + +import org.apache.tuscany.sca.databinding.BaseDataBinding; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.Operation; +import org.apache.tuscany.sca.interfacedef.util.XMLType; + +/** + * A DataBinding for the XML string + * + * @version $Rev$ $Date$ + * @tuscany.spi.extension.asclient + */ +public class XMLStringDataBinding extends BaseDataBinding { + public static final String NAME = String.class.getName(); + + public XMLStringDataBinding() { + super(NAME, String.class); + } + + @Override + public boolean introspect(DataType type, Operation operation) { + if (type.getPhysical() == String.class && NAME.equals(type.getDataBinding())) { + type.setDataBinding(NAME); + type.setLogical(XMLType.UNKNOWN); + return true; + } else { + return false; + } + } +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.DataBinding b/sca-java-2.x/branches/2.0/modules/databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.DataBinding new file mode 100644 index 0000000000..3c0dce0492 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.DataBinding @@ -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 databindings +org.apache.tuscany.sca.databinding.xml.DOMDataBinding;name=org.w3c.dom.Node +org.apache.tuscany.sca.databinding.xml.XMLStringDataBinding;name=java.lang.String +org.apache.tuscany.sca.databinding.xml.XMLGroupDataBinding;name=databinding:group +org.apache.tuscany.sca.databinding.javabeans.JavaBeansDataBinding;name=java:complexType +org.apache.tuscany.sca.databinding.javabeans.SimpleJavaDataBinding;name=java:simpleType +org.apache.tuscany.sca.databinding.javabeans.JavaExceptionDataBinding;name=java:exception +org.apache.tuscany.sca.databinding.externalizable.ExternalizableDataBinding;name=java.io.Externalizable +org.apache.tuscany.sca.databinding.servicereference.ServiceReferenceDataBinding;name=org.oasisopen.sca.ServiceReference + diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.DataBindingExtensionPoint b/sca-java-2.x/branches/2.0/modules/databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.DataBindingExtensionPoint new file mode 100644 index 0000000000..4cad1181b7 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.DataBindingExtensionPoint @@ -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.databinding.DefaultDataBindingExtensionPoint + diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.Mediator b/sca-java-2.x/branches/2.0/modules/databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.Mediator new file mode 100644 index 0000000000..c91908e630 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.Mediator @@ -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.databinding.impl.MediatorImpl diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PullTransformer b/sca-java-2.x/branches/2.0/modules/databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PullTransformer new file mode 100644 index 0000000000..9f609be7e2 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PullTransformer @@ -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. + +# Implementation classes for the transformers +org.apache.tuscany.sca.databinding.xml.InputSource2Node;source=org.xml.sax.InputSource,target=org.w3c.dom.Node,weight=80 +org.apache.tuscany.sca.databinding.xml.InputStream2Node;source=java.io.InputStream,target=org.w3c.dom.Node,weight=80 +# org.apache.tuscany.sca.databinding.javabeans.DOMNode2JavaBeanTransformer;source=org.w3c.dom.Node,target=java:complexType,weight=80000 +org.apache.tuscany.sca.databinding.xml.Node2String;source=org.w3c.dom.Node,target=java.lang.String,weight=80 +org.apache.tuscany.sca.databinding.xml.Node2XMLStreamReader;source=org.w3c.dom.Node,target=javax.xml.stream.XMLStreamReader,weight=80 +# org.apache.tuscany.sca.databinding.javabeans.JavaBean2DOMNodeTransformer;source=java:complexType,target=org.w3c.dom.Node,weight=80000 +# org.apache.tuscany.sca.databinding.javabeans.JavaBean2XMLStreamReaderTransformer;source=java:complexType,target=javax.xml.stream.XMLStreamReader,weight=79000 +org.apache.tuscany.sca.databinding.xml.Reader2Node;source=java.io.Reader,target=org.w3c.dom.Node,weight=80 +org.apache.tuscany.sca.databinding.xml.SAX2DOMPipe;source=org.xml.sax.ContentHandler,target=org.w3c.dom.Node,weight=70 +org.apache.tuscany.sca.databinding.xml.StreamDataPipe;source=java.io.OutputStream,target=java.io.InputStream,weight=90 +org.apache.tuscany.sca.databinding.xml.String2Node;source=java.lang.String,target=org.w3c.dom.Node,weight=90 +org.apache.tuscany.sca.databinding.xml.String2XMLStreamReader;source=java.lang.String,target=javax.xml.stream.XMLStreamReader,weight=90 +org.apache.tuscany.sca.databinding.xml.Writer2ReaderDataPipe;source=java.io.Writer,target=java.io.Reader,weight=90 +org.apache.tuscany.sca.databinding.xml.XMLStreamReader2Node;source=javax.xml.stream.XMLStreamReader,target=org.w3c.dom.Node,weight=80 +org.apache.tuscany.sca.databinding.xml.XMLStreamReader2String;source=javax.xml.stream.XMLStreamReader,target=java.lang.String,weight=80 +org.apache.tuscany.sca.databinding.xml.Node2SimpleJavaType;source=org.w3c.dom.Node,target=java:simpleType,weight=95000 +org.apache.tuscany.sca.databinding.xml.SimpleJavaType2Node;source=java:simpleType,target=org.w3c.dom.Node,weight=95000 +org.apache.tuscany.sca.databinding.xml.Source2NodeTransformer;source=javax.xml.transform.Source,target=org.w3c.dom.Node,weight=80 +org.apache.tuscany.sca.databinding.xml.Source2StringTransformer;source=javax.xml.transform.Source,target=java.lang.String,weight=80 + +org.apache.tuscany.sca.databinding.xml.Node2SourceTransformer;source=org.w3c.dom.Node,target=javax.xml.transform.Source,weight=80 +org.apache.tuscany.sca.databinding.xml.String2SourceTransformer;source=java.lang.String,target=javax.xml.transform.Source,weight=80 + diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PushTransformer b/sca-java-2.x/branches/2.0/modules/databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PushTransformer new file mode 100644 index 0000000000..6c04591a1f --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PushTransformer @@ -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.xml.InputSource2SAX;source=org.xml.sax.InputSource,target=org.xml.sax.ContentHandler,weight=80 +org.apache.tuscany.sca.databinding.xml.InputStream2SAX;source=java.io.InputStream,target=org.xml.sax.ContentHandler,weight=80 +org.apache.tuscany.sca.databinding.xml.Node2OutputStream;source=org.w3c.dom.Node,target=java.io.OutputStream,weight=80 +org.apache.tuscany.sca.databinding.xml.Node2Writer;source=org.w3c.dom.Node,target=java.io.Writer,weight=80 +org.apache.tuscany.sca.databinding.xml.Reader2SAX;source=java.io.Reader,target=org.xml.sax.ContentHandler,weight=80 +org.apache.tuscany.sca.databinding.xml.Source2ResultTransformer;source=javax.xml.transform.Source,target=javax.xml.transform.Result,weight=80 +org.apache.tuscany.sca.databinding.xml.String2SAX;source=java.lang.String,target=org.xml.sax.ContentHandler,weight=80 +org.apache.tuscany.sca.databinding.xml.XMLStreamReader2SAX;source=javax.xml.stream.XMLStreamReader,target=org.xml.sax.ContentHandler,weight=70 + diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.SimpleTypeMapper b/sca-java-2.x/branches/2.0/modules/databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.SimpleTypeMapper new file mode 100644 index 0000000000..f905a9aa7b --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.SimpleTypeMapper @@ -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.databinding.impl.SimpleTypeMapperImpl diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.TransformerExtensionPoint b/sca-java-2.x/branches/2.0/modules/databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.TransformerExtensionPoint new file mode 100644 index 0000000000..07762a14b8 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.TransformerExtensionPoint @@ -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.databinding.DefaultTransformerExtensionPoint + diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/main/resources/org/apache/tuscany/sca/databinding/databinding-validation-messages.properties b/sca-java-2.x/branches/2.0/modules/databinding/src/main/resources/org/apache/tuscany/sca/databinding/databinding-validation-messages.properties new file mode 100644 index 0000000000..0697b8b346 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/main/resources/org/apache/tuscany/sca/databinding/databinding-validation-messages.properties @@ -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. +# +# +NotBase64Encoded = The character sequence is not base64 encoded +HexBinaryUnevenLength = A HexBinary string must have even length +InvalidHexDigit = Invalid hex digit: +BadDate = Failed to parse date {0} at {1} +BadDateTime = Failed to parse dateTime {0} at {1} +DefaultPrefixNotBound = The default prefix is not bound +NoColonForPrefix = Default prefix must be indicated by not using a colon: +PrefixNotBound = The prefix {0} is not bound. +BadTime = Failed to parse time {0} at {1} +BadUnsignedIntNegative = Failed to parse UnsignedInt {0} result is negative" +BadUnsignedIntMax = "Failed to parse UnsignedInt {0} result exceeds maximum value {1} +BadUnsignedShortNegative = Failed to parse UnsignedShort {0} result is negative" +BadUnsignedShortMax = "Failed to parse UnsignedShort {0} result exceeds maximum value {1} +NamespaceNotBound = The namespace URI {0} is not bound + diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/extension/DataBindingExtensionTestCase.java b/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/extension/DataBindingExtensionTestCase.java new file mode 100644 index 0000000000..defa62a49e --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/extension/DataBindingExtensionTestCase.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.extension; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import org.apache.tuscany.sca.core.DefaultExtensionPointRegistry; +import org.apache.tuscany.sca.databinding.BaseDataBinding; +import org.apache.tuscany.sca.databinding.DataBindingExtensionPoint; +import org.apache.tuscany.sca.databinding.DefaultDataBindingExtensionPoint; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.impl.DataTypeImpl; +import org.junit.Test; +import org.w3c.dom.Element; +import org.w3c.dom.Node; + +/** + * + * @version $Rev$ $Date$ + */ +public class DataBindingExtensionTestCase { + + @Test + @SuppressWarnings("unchecked") + public void testExtension() { + DataBinding1 binding1 = new DataBinding1(Node.class); + assertEquals(Node.class.getName(), binding1.getName()); + DataType dt1 = new DataTypeImpl(Element.class, null); + assertTrue(binding1.introspect(dt1, null)); + DataType dt2 = new DataTypeImpl(String.class, null); + assertFalse(binding1.introspect(dt2, null)); + assertNull(binding1.getWrapperHandler()); + + DataBindingExtensionPoint registry = new DefaultDataBindingExtensionPoint(new DefaultExtensionPointRegistry()); + registry.addDataBinding(binding1); + + assertNotNull(registry.getDataBinding(Node.class.getName())); + + DataBinding1 binding2 = new DataBinding1("dom", Node.class); + assertEquals("dom", binding2.getName()); + } + + private static class DataBinding1 extends BaseDataBinding { + + /** + * @param baseType + */ + public DataBinding1(Class baseType) { + super(baseType); + } + + /** + * @param name + * @param baseType + */ + public DataBinding1(String name, Class baseType) { + super(name, baseType); + } + + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/extension/SimpleTypeMapperExtensionTestCase.java.fixme b/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/extension/SimpleTypeMapperExtensionTestCase.java.fixme new file mode 100644 index 0000000000..562c22354c --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/extension/SimpleTypeMapperExtensionTestCase.java.fixme @@ -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.databinding.extension; + +import java.util.HashMap; +import java.util.Map; + +import javax.xml.namespace.NamespaceContext; + +import junit.framework.TestCase; + +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.impl.SimpleTypeMapperImpl; +import org.apache.tuscany.sca.interfacedef.util.TypeInfo; +import org.easymock.EasyMock; + +/** + * + * @version $Rev$ $Date$ + */ +public class SimpleTypeMapperExtensionTestCase extends TestCase { + + private static final Map SAMPLE_VALUES = new HashMap(); + + static { + SAMPLE_VALUES.put("anyURI", "http://www.w3.com"); + SAMPLE_VALUES.put("boolean", new String[] {"true", "false", "1", "0"}); + SAMPLE_VALUES.put("byte", new String[] {"-128", "127"}); + SAMPLE_VALUES.put("date", new String[] {"2004-03-15", "2002-09-24-06:00"}); + SAMPLE_VALUES.put("dateTime", "2003-12-25T08:30:00"); + SAMPLE_VALUES.put("decimal", "3.1415292"); + SAMPLE_VALUES.put("double", new String[] {"3.1415292", "INF", "NaN"}); + SAMPLE_VALUES.put("duration", new String[] {"P8M3DT7H33M2S", "P5Y2M10DT15H"}); + SAMPLE_VALUES.put("float", new String[] {"3.1415292", "INF", "NaN"}); + SAMPLE_VALUES.put("gDay", "---11"); + if (System.getProperty("java.vendor").toUpperCase().contains("SUN") && System.getProperty("java.version").contains("1.5.0") + || + System.getProperty("java.vendor").toUpperCase().contains("APPLE INC.") && System.getProperty("java.version").contains("1.5.0")) { + + // Work around a bug in SUN JDK (including Mac OS JDK) + SAMPLE_VALUES.put("gMonth", "--02--"); + } else { + SAMPLE_VALUES.put("gMonth", "--02"); + } + SAMPLE_VALUES.put("gMonthDay", "--02-14"); + SAMPLE_VALUES.put("gYear", "1999"); + SAMPLE_VALUES.put("gYearMonth", "1972-08"); + SAMPLE_VALUES.put("ID", "id-102"); + SAMPLE_VALUES.put("IDREF", "id-102"); + SAMPLE_VALUES.put("IDREFS", "id-102 id-103 id-100"); + SAMPLE_VALUES.put("int", "77"); + SAMPLE_VALUES.put("integer", "77"); + SAMPLE_VALUES.put("long", "214"); + SAMPLE_VALUES.put("negativeInteger", "-123"); + SAMPLE_VALUES.put("nonNegativeInteger", "2"); + SAMPLE_VALUES.put("nonPositiveInteger", "0"); + SAMPLE_VALUES.put("positiveInteger", "500"); + SAMPLE_VALUES.put("short", "476"); + SAMPLE_VALUES.put("string", "Joeseph"); + SAMPLE_VALUES.put("time", "13:02:00"); + SAMPLE_VALUES.put("base64Binary", "TWFu"); + SAMPLE_VALUES.put("hexBinary", "2CDB5F"); + SAMPLE_VALUES.put("QName", "f:foo"); + SAMPLE_VALUES.put("NOTATION", "f:bar"); + } + + /** + * @see junit.framework.TestCase#setUp() + */ + @Override + protected void setUp() throws Exception { + super.setUp(); + } + + public void testMap() throws Exception { + SimpleTypeMapperImpl extension = new SimpleTypeMapperImpl(); + TransformationContext context = EasyMock.createMock(TransformationContext.class); + Map metaData = new HashMap(); + EasyMock.expect(context.getMetadata()).andReturn(metaData).anyTimes(); + EasyMock.replay(context); + + NamespaceContext namespaceContext = EasyMock.createMock(NamespaceContext.class); + EasyMock.expect(namespaceContext.getNamespaceURI(EasyMock.eq("f"))).andReturn("http://foo").anyTimes(); + EasyMock.expect(namespaceContext.getPrefix(EasyMock.eq("http://foo"))).andReturn("f").anyTimes(); + EasyMock.replay(namespaceContext); + context.getMetadata().put(NamespaceContext.class.getName(), namespaceContext); + for (TypeInfo simpleType : SimpleTypeMapperImpl.XSD_SIMPLE_TYPES.values()) { + String name = simpleType.getQName().getLocalPart(); + Object value = SAMPLE_VALUES.get(name); + if (value instanceof String[]) { + for (String s : (String[])value) { + Object obj = extension.toJavaObject(simpleType.getQName(), s, context); + String str = extension.toXMLLiteral(simpleType.getQName(), obj, context); + assertNotNull(str); + // assertTrue("[" + name + "] " + s + " " + str, + // str.contains((String) s)); + } + } else if (value instanceof String) { + Object obj = extension.toJavaObject(simpleType.getQName(), (String)value, context); + String str = extension.toXMLLiteral(simpleType.getQName(), obj, context); + assertNotNull(str); + // assertTrue("[" + name + "] " + value + " " + str, + // str.contains((String) value)); + } + } + } +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/extension/TransformerExtensionTestCase.java.fixme b/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/extension/TransformerExtensionTestCase.java.fixme new file mode 100644 index 0000000000..243ac71201 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/extension/TransformerExtensionTestCase.java.fixme @@ -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.extension; + +import javax.xml.stream.XMLStreamReader; + +import junit.framework.TestCase; + +import org.apache.tuscany.sca.databinding.Transformer; +import org.apache.tuscany.sca.databinding.TransformerExtensionPoint; +import org.apache.tuscany.sca.databinding.impl.BaseTransformer; +import org.easymock.EasyMock; +import org.w3c.dom.Node; + +/** + * Test case for TransformerExtension + * + * @version $Rev$ $Date$ + */ +public class TransformerExtensionTestCase extends TestCase { + + /** + * @see junit.framework.TestCase#setUp() + */ + @Override + protected void setUp() throws Exception { + super.setUp(); + } + + public void testExtension() { + MyTransformer transformer = new MyTransformer(); + assertEquals(Node.class.getName(), transformer.getSourceDataBinding()); + assertEquals(XMLStreamReader.class.getName(), transformer.getTargetDataBinding()); + assertEquals(50, transformer.getWeight()); + TransformerExtensionPoint registry = EasyMock.createMock(TransformerExtensionPoint.class); + registry.addTransformer(EasyMock.isA(Transformer.class), EasyMock.eq(true)); + EasyMock + .expect(registry.getTransformer(transformer.getSourceDataBinding(), transformer.getTargetDataBinding())) + .andReturn(transformer); + EasyMock.replay(registry); + registry.addTransformer(transformer, true); + assertSame(transformer, registry.getTransformer(transformer.getSourceDataBinding(), transformer + .getTargetDataBinding())); + } + + private static class MyTransformer extends BaseTransformer { + + @Override + protected Class getSourceType() { + return Node.class; + } + + @Override + protected Class getTargetType() { + return XMLStreamReader.class; + } + + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/extension/XSDDataTypeConverterTestCase.java b/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/extension/XSDDataTypeConverterTestCase.java new file mode 100644 index 0000000000..a337dc113c --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/extension/XSDDataTypeConverterTestCase.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.databinding.extension; + +import static org.junit.Assert.assertEquals; + +import java.math.BigInteger; +import java.util.Calendar; +import java.util.GregorianCalendar; + +import org.apache.tuscany.sca.databinding.impl.XSDDataTypeConverter; +import org.junit.Test; + +/** + * + * @version $Rev$ $Date$ + */ +public class XSDDataTypeConverterTestCase { + + @Test + public void testConvert() throws Exception { + XSDDataTypeConverter c = new XSDDataTypeConverter(); + assertEquals("123", c.parseAnySimpleType(c.printAnySimpleType("123"))); + assertEquals(true, c.parseBoolean(c.printBoolean(true))); + assertEquals(false, c.parseBoolean(c.printBoolean(false))); + assertEquals(123.0, c.parseDouble(c.printDouble(123.0)), 0); + assertEquals(123.0f, c.parseFloat(c.printFloat(123.0f)), 0); + assertEquals(64, c.parseByte(c.printByte((byte)64))); + assertEquals(123, c.parseInt(c.printInt(123))); + assertEquals(new BigInteger("123456"), c.parseInteger(c.printInteger(new BigInteger("123456")))); + assertEquals(123456L, c.parseLong(c.printLong(123456L))); + assertEquals((short)123, c.parseShort(c.printShort((short)123))); + + Calendar calendar = new GregorianCalendar(); + String s = c.printDate(calendar); + calendar = c.parseDate(s); + assertEquals(s, c.printDate(calendar)); + + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/impl/DataBindingTestCase.java b/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/impl/DataBindingTestCase.java new file mode 100644 index 0000000000..c5d6dbbcc1 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/impl/DataBindingTestCase.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.databinding.impl; + +import static org.junit.Assert.assertEquals; + +import java.lang.reflect.Method; + +import org.apache.tuscany.sca.databinding.annotation.DataBinding; + +/** + * + * @version $Rev$ $Date$ + */ +public class DataBindingTestCase { + @org.junit.Test + public void testDataType() throws Exception { + Class testClass = Test.class; + DataBinding d = testClass.getAnnotation(DataBinding.class); + assertEquals(d.value(), "sdo"); + + Method method = testClass.getMethod("test", new Class[] {Object.class}); + DataBinding d2 = method.getAnnotation(DataBinding.class); + assertEquals(d2.value(), "jaxb"); + } + + @DataBinding("sdo") + private static interface Test { + @DataBinding("jaxb") + Object test(Object object); + } +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/impl/DirectedGraphTestCase.java b/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/impl/DirectedGraphTestCase.java new file mode 100644 index 0000000000..9ab2b51c95 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/impl/DirectedGraphTestCase.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.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.List; + +import org.apache.tuscany.sca.databinding.impl.DirectedGraph.Edge; +import org.apache.tuscany.sca.databinding.impl.DirectedGraph.Vertex; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * + * @version $Rev$ $Date$ + */ +public class DirectedGraphTestCase { + private DirectedGraph graph; + + @Before + public void setUp() throws Exception { + graph = new DirectedGraph(); + } + + @Test + public void testGraph() { + graph.addEdge("a", "b", null, 4, true); + graph.addEdge("a", "b", null, 5, true); + Assert.assertEquals(4, graph.getEdge("a", "b").getWeight()); + graph.addEdge("a", "b", null, 3, true); + Assert.assertEquals(3, graph.getEdge("a", "b").getWeight()); + graph.addEdge("b", "c", null, 1, true); + // graph.addEdge("a", "c", null, 8, true); + graph.addEdge("a", "d", null, 3, true); + graph.addEdge("b", "d", null, 2, true); + graph.addEdge("d", "c", null, 3, true); + graph.addEdge("c", "b", null, 1, true); + graph.addEdge("c", "d", null, 2, true); + graph.addEdge("d", "b", null, 1, true); + graph.addEdge("a", "e", null, 8, true); + graph.addEdge("c", "c", null, 2, true); + graph.addEdge("f", "g", null, 2, false); + graph.addEdge("f", "h", null, 8, true); + graph.addEdge("g", "j", null, 2, false); + graph.addEdge("j", "i", null, 2, true); + graph.addEdge("h", "i", null, 8, true); + + Vertex vertex = graph.getVertex("a"); + Assert.assertNotNull(vertex); + Assert.assertEquals(vertex.getValue(), "a"); + + Assert.assertNull(graph.getVertex("1")); + + Edge edge = graph.getEdge("a", "b"); + Assert.assertNotNull(edge); + Assert.assertEquals(edge.getWeight(), 3); + + edge = graph.getEdge("b", "a"); + Assert.assertNull(edge); + + DirectedGraph.Path path = graph.getShortestPath("a", "c"); + + List.Edge> edges = path.getEdges(); + Assert.assertEquals(edges.size(), 2); + Assert.assertEquals(edges.get(0), graph.getEdge("a", "b")); + Assert.assertEquals(edges.get(1), graph.getEdge("b", "c")); + + Assert.assertEquals(path.getWeight(), 4); + + DirectedGraph.Path path2 = graph.getShortestPath("b", "e"); + Assert.assertNull(path2); + + DirectedGraph.Path path3 = graph.getShortestPath("a", "a"); + Assert.assertTrue(path3.getWeight() == 0 && path3.getEdges().isEmpty()); + + DirectedGraph.Path path4 = graph.getShortestPath("c", "c"); + Assert.assertTrue(path4.getWeight() == 2 && path4.getEdges().size() == 1); + + DirectedGraph.Path path5 = graph.getShortestPath("f", "i"); + Assert.assertTrue(path5.getWeight() == 16 && path5.getEdges().size() == 2); + + } + + @Test + public void testSort() { + graph.addEdge("a", "b"); + graph.addEdge("a", "c"); + graph.addEdge("c", "d"); + graph.addEdge("b", "c"); + List order = graph.topologicalSort(true); + assertEquals(Arrays.asList("a", "b", "c", "d"), order); + assertTrue(!graph.getVertices().isEmpty()); + + graph.addEdge("d", "a"); + try { + order = graph.topologicalSort(true); + assertTrue("Should have failed", false); + } catch (IllegalArgumentException e) { + assertTrue(true); + } + + graph.removeEdge("d", "a"); + order = graph.topologicalSort(false); + assertEquals(Arrays.asList("a", "b", "c", "d"), order); + assertTrue(graph.getVertices().isEmpty()); + } +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/impl/MediatorImplTestCase.java b/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/impl/MediatorImplTestCase.java new file mode 100644 index 0000000000..953e539dd1 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/impl/MediatorImplTestCase.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.databinding.impl; + +import java.io.StringWriter; +import java.io.Writer; + +import org.apache.tuscany.sca.core.DefaultExtensionPointRegistry; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.databinding.DataBindingExtensionPoint; +import org.apache.tuscany.sca.databinding.DefaultDataBindingExtensionPoint; +import org.apache.tuscany.sca.databinding.DefaultTransformerExtensionPoint; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformerExtensionPoint; +import org.apache.tuscany.sca.databinding.xml.Node2String; +import org.apache.tuscany.sca.databinding.xml.Node2Writer; +import org.apache.tuscany.sca.databinding.xml.SAX2DOMPipe; +import org.apache.tuscany.sca.databinding.xml.String2SAX; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.impl.DataTypeImpl; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; + +/** + * Test case for MediatorImpl + * + * @version $Rev$ $Date$ + */ +public class MediatorImplTestCase { + 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 MediatorImpl mediator; + + @Before + public void setUp() throws Exception { + ExtensionPointRegistry extensionPointRegistry = new DefaultExtensionPointRegistry(); + DataBindingExtensionPoint dataBindingRegistry = new DefaultDataBindingExtensionPoint(extensionPointRegistry); + TransformerExtensionPoint registry = new DefaultTransformerExtensionPoint(extensionPointRegistry); + + registry.addTransformer(new String2SAX(), true); + registry.addTransformer(new SAX2DOMPipe(extensionPointRegistry), true); + registry.addTransformer(new Node2String(extensionPointRegistry), true); + registry.addTransformer(new Node2Writer(extensionPointRegistry), true); + + mediator = new MediatorImpl(dataBindingRegistry, registry); + } + + private TransformationContext createTransformationContext(Class sourceType, Class targetType) { + TransformationContext context = new TransformationContextImpl(); + DataType sourceDataType = new DataTypeImpl(sourceType.getName(), sourceType, sourceType); + DataType targetDataType = new DataTypeImpl(targetType.getName(), targetType, targetType); + context.setSourceDataType(sourceDataType); + context.setTargetDataType(targetDataType); + return context; + } + + @Test + public void testTransform1() { + TransformationContext context = createTransformationContext(String.class, Node.class); + Object node = + mediator.mediate(IPO_XML, context.getSourceDataType(), context.getTargetDataType(), null); + Assert.assertTrue(node instanceof Document); + Element root = ((Document)node).getDocumentElement(); + Assert.assertEquals(root.getNamespaceURI(), "http://www.example.com/IPO"); + Assert.assertEquals(root.getLocalName(), "purchaseOrder"); + } + + @Test + public void testTransform2() { + TransformationContext context = createTransformationContext(String.class, Writer.class); + Writer writer = new StringWriter(); + mediator.mediate(IPO_XML, writer, context.getSourceDataType(), context.getTargetDataType(), null); + String str = writer.toString(); + Assert.assertTrue(str != null && str.indexOf("1999-12-05") != -1); + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/impl/XMLDocumentStreamReaderTestCase.java b/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/impl/XMLDocumentStreamReaderTestCase.java new file mode 100644 index 0000000000..e240592adf --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/impl/XMLDocumentStreamReaderTestCase.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.impl; + +import java.io.StringReader; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamConstants; +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sca.common.xml.stax.StAXHelper; +import org.apache.tuscany.sca.common.xml.stax.reader.XMLDocumentStreamReader; +import org.apache.tuscany.sca.core.DefaultExtensionPointRegistry; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.databinding.xml.XMLStreamReader2String; +import org.junit.Assert; + +/** + * @version $Rev$ $Date$ + */ +public class XMLDocumentStreamReaderTestCase { + private static final String xml = "E4"; + + @org.junit.Test + public void testReader() throws Exception { + ExtensionPointRegistry extensionPointRegistry = new DefaultExtensionPointRegistry(); + + StAXHelper helper = StAXHelper.getInstance(extensionPointRegistry); + XMLStreamReader r1 = helper.createXMLStreamReader(new StringReader(xml)); + XMLDocumentStreamReader r2 = new XMLDocumentStreamReader(r1); + XMLStreamReader2String t1 = new XMLStreamReader2String(extensionPointRegistry); + String result = t1.transform(r2, null); + System.out.println(result); + XMLStreamReader r3 = helper.createXMLStreamReader(new StringReader(xml)); + r3.nextTag(); + r3.nextTag(); + Assert.assertEquals(XMLStreamConstants.START_ELEMENT, r3.getEventType()); + Assert.assertEquals(new QName(null, "e2"), r3.getName()); + XMLDocumentStreamReader r4 = new XMLDocumentStreamReader(r3); + result = t1.transform(r4, null); + System.out.println(result); + } +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/BeanXMLStreamReaderTestCase.java b/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/BeanXMLStreamReaderTestCase.java new file mode 100644 index 0000000000..95f21ff4c9 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/BeanXMLStreamReaderTestCase.java @@ -0,0 +1,188 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * 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.xml; + +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sca.core.DefaultExtensionPointRegistry; +import org.custommonkey.xmlunit.Diff; +import org.junit.Test; + +/** + * + * @version $Rev$ $Date$ + */ +public class BeanXMLStreamReaderTestCase { + private static final String XML_RESULT = + "" + "" + + "123Name1" + + "Item1Item2" + + "key1value1" + + "key2value2" + + "" + + "ABC"; + + // The map entries can come in a different order + private static final String XML_RESULT1 = + "" + "" + + "123Name1" + + "Item1Item2" + + "key2value2" + + "key1value1" + + "" + + "ABC"; + + + @Test + public void testTransformation() throws Exception { + MyBean bean = new MyBean(); + bean.str = "ABC"; + bean.i = 1; + bean.arr = new long[] {1, 2, 3}; + bean.bean = new AnotherBean(); + bean.bean.setName("Name"); + bean.list.add("Item1"); + bean.list.add("Item2"); + bean.map.put("key1", "value1"); + bean.map.put("key2", "value2"); + XMLStreamReader reader = new BeanXMLStreamReaderImpl(null, bean); + XMLStreamReader2String t3 = new XMLStreamReader2String(new DefaultExtensionPointRegistry()); + String xml = t3.transform(reader, null); + Diff diff = new Diff(XML_RESULT, xml); + Diff diff1 = new Diff(XML_RESULT1, xml); + assertTrue(diff.similar() || diff1.similar()); + } + + private static class MyBean { + private long arr[]; + private String str; + private int i; + private String nil; + private List list = new ArrayList(); + private AnotherBean bean; + private Map map = new HashMap(); + + /** + * @return the i + */ + public int getI() { + return i; + } + + /** + * @param i the i to set + */ + public void setI(int i) { + this.i = i; + } + + /** + * @return the arr + */ + public long[] getArr() { + return arr; + } + + /** + * @param arr the arr to set + */ + public void setArr(long[] arr) { + this.arr = arr; + } + + /** + * @return the str + */ + public String getStr() { + return str; + } + + /** + * @param str the str to set + */ + public void setStr(String str) { + this.str = str; + } + + /** + * @return the bean + */ + public AnotherBean getBean() { + return bean; + } + + /** + * @param bean the bean to set + */ + public void setBean(AnotherBean bean) { + this.bean = bean; + } + + public List getList() { + return list; + } + + public void setList(List list) { + this.list = list; + } + + public String getNil() { + return nil; + } + + public void setNil(String nil) { + this.nil = nil; + } + + public Map getMap() { + return map; + } + + public void setMap(Map map) { + this.map = map; + } + + } + + private static class AnotherBean { + private String name; + + /** + * @return the name + */ + public String getName() { + return name; + } + + /** + * @param name the name to set + */ + public void setName(String name) { + this.name = name; + } + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/DOM2StAXTestCase.java b/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/DOM2StAXTestCase.java new file mode 100644 index 0000000000..27d111374a --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/DOM2StAXTestCase.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.databinding.xml; + +import static org.junit.Assert.assertTrue; + +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sca.common.xml.stax.reader.DOMXmlNodeImpl; +import org.apache.tuscany.sca.common.xml.stax.reader.XmlTreeStreamReaderImpl; +import org.apache.tuscany.sca.core.DefaultExtensionPointRegistry; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.custommonkey.xmlunit.XMLAssert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.w3c.dom.Node; + +/** + * + * @version $Rev$ $Date$ + */ +public class DOM2StAXTestCase { + 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 CRAZY_XML = + "" + "E4"; + + private static ExtensionPointRegistry registry; + + @BeforeClass + public static void init() { + registry = new DefaultExtensionPointRegistry(); + } + + @Test + public void testTransformation() throws Exception { + String2Node t1 = new String2Node(registry); + Node node = t1.transform(IPO_XML, null); + Node2XMLStreamReader t2 = new Node2XMLStreamReader(); + XMLStreamReader reader = t2.transform(node, null); + XMLStreamReader2String t3 = new XMLStreamReader2String(registry); + String xml = t3.transform(reader, null); + XMLAssert.assertXMLEqual(IPO_XML, xml); + // assertTrue(xml != null && xml.indexOf("1999-12-05") != -1); + } + + @Test + public void testTransformation2() throws Exception { + String2Node t1 = new String2Node(registry); + Node node = t1.transform(CRAZY_XML, null); + Node2XMLStreamReader t2 = new Node2XMLStreamReader(); + XMLStreamReader reader = t2.transform(node, null); + XMLStreamReader2String t3 = new XMLStreamReader2String(registry); + String xml = t3.transform(reader, null); + // System.out.println(xml); + XMLAssert.assertXMLEqual(CRAZY_XML, xml); + assertTrue(xml.contains("1999-12-05") != -1); + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/DOMWrapperHandlerTestCase.java b/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/DOMWrapperHandlerTestCase.java new file mode 100644 index 0000000000..08ec98fca9 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/DOMWrapperHandlerTestCase.java @@ -0,0 +1,163 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * 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.xml; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; + +import org.apache.tuscany.sca.common.xml.dom.DOMHelper; +import org.apache.tuscany.sca.core.DefaultExtensionPointRegistry; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +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.junit.Assert; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.SAXException; + + +/** + * Test case for DOMWrapperHandler + * + * @version $Rev: 1101239 $ $Date: 2011-05-09 17:54:07 -0400 (Mon, 09 May 2011) $ + */ +@Ignore +public class DOMWrapperHandlerTestCase { + + private static final QName INPUT1 = new QName("http://ns1", "input1"); + private static final QName INPUT2 = new QName("http://ns2", "input2"); + private static final QName INPUT3 = new QName("http://ns3", "input3"); + private static final QName INPUT4 = new QName("http://ns4", "input4"); + private String WRAPPER_XML = + "" + "" + + " " + // Eliminating whitespace within the quotes allows us to have a simple compare. + + "input1ContentsA" + + "" + + " " + + " " + + "input1ContentsB" + + "" + + " " + + "input3ContentsA" + + "" + + " " + + "input4ContentsA" + + " " + + " "; + + private DOMHelper domHelper; + private DOMWrapperHandler handler; + private Operation op; + + @Before + public void setUp() throws Exception { + ExtensionPointRegistry registry = new DefaultExtensionPointRegistry(); + this.domHelper = DOMHelper.getInstance(registry); + this.handler = new DOMWrapperHandler(domHelper); + + List elements = new ArrayList(); + for (QName inQName : new QName[] { INPUT1, INPUT2, INPUT3, INPUT4 }) { + ElementInfo e = new ElementInfo(inQName, null); + e.setNillable(true); + elements.add(e); + } + // INPUT1,4 are like maxOccurs="unbounded" + elements.get(0).setMany(true); + elements.get(3).setMany(true); + // INPUT2 is like minOccurs="0", nillable="false" + elements.get(1).setOmissible(true); + elements.get(1).setNillable(false); + + WrapperInfo wrapperInfo = new WrapperInfo(DOMDataBinding.NAME, null, elements); + this.op = new OperationImpl(); + op.setInputWrapper(wrapperInfo); + } + + @Test + public void testGetChildren() { + try { + Element wrapperElem = domHelper.load(WRAPPER_XML).getDocumentElement(); + List children = handler.getChildren(wrapperElem, op, true); + Assert.assertEquals(4, children.size()); + Object[] firstChild = (Object[])children.get(0); + Assert.assertEquals(3, firstChild.length); + Assert.assertEquals("input1ContentsB", ((Element)firstChild[2]).getTextContent()); + Object secondChild = children.get(1); + Assert.assertNull(secondChild); + Element thirdChild = (Element)children.get(2); + Assert.assertEquals("input3ContentsA", thirdChild.getTextContent()); + Object[] fourthChild = (Object[])children.get(3); + Assert.assertEquals(1, fourthChild.length); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + + @Test + public void testSetChildren() { + Document document = domHelper.newDocument(); + + QName wrapperQName = new QName("myNamespace", "wrapper", "myns"); + Element wrapper = DOMHelper.createElement(document, wrapperQName); + + Element[] in1 = new Element[2]; + in1[0] = DOMHelper.createElement(document, INPUT1); + in1[1] = DOMHelper.createElement(document, INPUT1); + Element in2 = null; + Element in3 = DOMHelper.createElement(document, INPUT3); + Element[] in4 = new Element[1]; + in4[0] = DOMHelper.createElement(document, INPUT4); + Object[] parms = new Object[] {in1, in2, in3, in4}; + + handler.setChildren(wrapper, parms, op, true); + + NodeList iter = wrapper.getChildNodes(); + Assert.assertEquals(4, iter.getLength()); + Element elem1 = (Element)iter.item(0); + Element elem2 = (Element)iter.item(1); + Element elem3 = (Element)iter.item(2); + Element elem4 = (Element)iter.item(3); + + Assert.assertEquals(INPUT1, DOMHelper.getQName(elem1)); + Assert.assertEquals(INPUT1, DOMHelper.getQName(elem2)); + Assert.assertEquals(INPUT3, DOMHelper.getQName(elem3)); + Assert.assertEquals(INPUT4, DOMHelper.getQName(elem4)); + } + +} + diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/DataPipeTestCase.java b/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/DataPipeTestCase.java new file mode 100644 index 0000000000..da18a4f89c --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/DataPipeTestCase.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.databinding.xml; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.Reader; +import java.io.Writer; + +import org.apache.tuscany.sca.common.xml.dom.DOMHelper; +import org.apache.tuscany.sca.core.DefaultExtensionPointRegistry; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.databinding.DataPipe; +import org.apache.tuscany.sca.databinding.DataPipeTransformer; +import org.apache.tuscany.sca.databinding.impl.PipedTransformer; +import org.junit.Assert; +import org.junit.Test; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; + +/** + * Test case for DataPipe + * + * @version $Rev$ $Date$ + */ +public class DataPipeTestCase { + + @Test + public final void testStreamPipe() throws IOException { + byte[] bytes = new byte[] {1, 2, 3}; + DataPipeTransformer pipe = new StreamDataPipe(); + DataPipe dataPipe = pipe.newInstance(); + OutputStream os = dataPipe.getSink(); + os.write(bytes); + byte[] newBytes = new byte[16]; + int count = dataPipe.getResult().read(newBytes); + Assert.assertEquals(3, count); + for (int i = 0; i < bytes.length; i++) { + Assert.assertEquals(bytes[i], newBytes[i]); + } + } + + @Test + public final void testWriter2ReaderPipe() throws IOException { + String str = "ABC"; + Writer2ReaderDataPipe pipe = new Writer2ReaderDataPipe(); + Assert.assertSame(Writer.class, pipe.getSourceType()); + Assert.assertSame(Reader.class, pipe.getTargetType()); + DataPipe dataPipe = pipe.newInstance(); + dataPipe.getSink().write(str); + char[] buf = new char[16]; + int count = dataPipe.getResult().read(buf); + Assert.assertEquals(3, count); + for (int i = 0; i < str.length(); i++) { + Assert.assertEquals(str.charAt(i), buf[i]); + } + } + + @Test + public final void testPiped() throws Exception { + ExtensionPointRegistry registry = new DefaultExtensionPointRegistry(); + Node2Writer node2Writer = new Node2Writer(registry); + Writer2ReaderDataPipe pipe = new Writer2ReaderDataPipe(); + PipedTransformer transformer = + new PipedTransformer(node2Writer, pipe); + Document document = DOMHelper.getInstance(registry).newDocument(); + Element element = document.createElementNS("http://ns1", "root"); + document.appendChild(element); + Reader reader = transformer.transform(document, null); + Assert.assertEquals(transformer.getWeight(), node2Writer.getWeight() + pipe.getWeight()); + Assert.assertEquals(transformer.getSourceDataBinding(), node2Writer.getSourceDataBinding()); + Assert.assertEquals(transformer.getTargetDataBinding(), pipe.getTargetDataBinding()); + char[] buf = new char[120]; + int count = reader.read(buf); + String xml = new String(buf, 0, count); + Assert.assertTrue(xml.contains("")); + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/JavaBean2XMLStreamReaderTestCase.java b/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/JavaBean2XMLStreamReaderTestCase.java new file mode 100644 index 0000000000..8919453731 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/JavaBean2XMLStreamReaderTestCase.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.databinding.xml; + +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sca.core.DefaultExtensionPointRegistry; +import org.apache.tuscany.sca.databinding.javabeans.JavaBean2XMLStreamReaderTransformer; +import org.custommonkey.xmlunit.XMLAssert; +import org.junit.Test; + +/** + * + * @version $Rev$ $Date$ + */ +public class JavaBean2XMLStreamReaderTestCase { + private static final String XML_RESULT = + "" + + "" + + "123Name1ABC" + + ""; + + @Test + public void testTransformation() throws Exception { + JavaBean2XMLStreamReaderTransformer t2 = new JavaBean2XMLStreamReaderTransformer(); + MyBean bean = new MyBean(); + bean.str = "ABC"; + bean.i = 1; + bean.arr = new long[] {1, 2, 3}; + bean.bean = new AnotherBean(); + bean.bean.setName("Name"); + XMLStreamReader reader = t2.transform(bean, null); + XMLStreamReader2String t3 = new XMLStreamReader2String(new DefaultExtensionPointRegistry()); + String xml = t3.transform(reader, null); + XMLAssert.assertXMLEqual(XML_RESULT, xml); + + } + + private static class MyBean { + private String str; + private int i; + private long arr[]; + private AnotherBean bean; + + /** + * @return the arr + */ + public long[] getArr() { + return arr; + } + + /** + * @param arr the arr to set + */ + public void setArr(long[] arr) { + this.arr = arr; + } + + /** + * @return the i + */ + public int getI() { + return i; + } + + /** + * @param i the i to set + */ + public void setI(int i) { + this.i = i; + } + + /** + * @return the str + */ + public String getStr() { + return str; + } + + /** + * @param str the str to set + */ + public void setStr(String str) { + this.str = str; + } + + /** + * @return the bean + */ + public AnotherBean getBean() { + return bean; + } + + /** + * @param bean the bean to set + */ + public void setBean(AnotherBean bean) { + this.bean = bean; + } + + } + + private static class AnotherBean { + private String name; + + /** + * @return the name + */ + public String getName() { + return name; + } + + /** + * @param name the name to set + */ + public void setName(String name) { + this.name = name; + } + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/Node2StringTestCase.java b/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/Node2StringTestCase.java new file mode 100644 index 0000000000..75c43dbf79 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/Node2StringTestCase.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.databinding.xml; + +import org.apache.tuscany.sca.common.xml.dom.DOMHelper; +import org.apache.tuscany.sca.core.DefaultExtensionPointRegistry; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.junit.Test; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * + * @version $Rev$ $Date$ + */ +public class Node2StringTestCase { + + @Test + public void testTransformation() throws Exception { + ExtensionPointRegistry registry = new DefaultExtensionPointRegistry(); + Document document = DOMHelper.getInstance(registry).newDocument(); + Element element = document.createElementNS("http://ns1", "test"); + document.appendChild(element); + + new Node2String(registry).transform(document, null); + } +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/PushTransformationTestCase.java b/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/PushTransformationTestCase.java new file mode 100644 index 0000000000..5027f64f01 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/PushTransformationTestCase.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.databinding.xml; + +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sca.core.DefaultExtensionPointRegistry; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.databinding.impl.PipedTransformer; +import org.junit.Assert; +import org.junit.Test; +import org.w3c.dom.Node; +import org.xml.sax.ContentHandler; + +/** + * + * @version $Rev$ $Date$ + */ +public class PushTransformationTestCase { + 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" + + " " + + " " + + ""; + + @Test + public void testTransformation() { + ExtensionPointRegistry registry = new DefaultExtensionPointRegistry(); + String2XMLStreamReader t1 = new String2XMLStreamReader(registry); + XMLStreamReader reader = t1.transform(IPO_XML, null); + XMLStreamReader2SAX t2 = new XMLStreamReader2SAX(registry); + PipedTransformer t3 = + new PipedTransformer(t2, new SAX2DOMPipe(registry)); + Node node = t3.transform(reader, null); + Assert.assertNotNull(node); + Node2String t4 = new Node2String(registry); + String xml = t4.transform(node, null); + Assert.assertTrue(xml != null && xml.indexOf("1999-12-05") != -1); + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/TraxTransformerTestCase.java b/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/TraxTransformerTestCase.java new file mode 100644 index 0000000000..6fd8ce2e8b --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/test/java/org/apache/tuscany/sca/databinding/xml/TraxTransformerTestCase.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.databinding.xml; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringReader; +import java.io.StringWriter; +import java.io.Writer; +import java.net.URL; + +import org.apache.tuscany.sca.core.DefaultExtensionPointRegistry; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.junit.Before; +import org.junit.Test; +import org.w3c.dom.Node; +import org.xml.sax.Attributes; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.DefaultHandler; + +/** + * + * @version $Rev$ $Date$ + */ +public class TraxTransformerTestCase { + private URL url; + + @Before + public void setUp() throws Exception { + url = getClass().getResource("foo.xml"); + } + + @Test + public void testTransformDOM() throws IOException { + ExtensionPointRegistry registry = new DefaultExtensionPointRegistry(); + InputStream is = url.openStream(); + InputStream2Node t1 = new InputStream2Node(registry); + Node node = t1.transform(is, null); + is.close(); + Writer writer = new StringWriter(); + Node2Writer t2 = new Node2Writer(registry); + t2.transform(node, writer, null); + String str = writer.toString(); + StringReader reader = new StringReader(str); + Reader2Node t3 = new Reader2Node(registry); + node = t3.transform(reader, null); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + Node2OutputStream t4 = new Node2OutputStream(registry); + t4.transform(node, os, null); + InputSource inputSource = new InputSource(new ByteArrayInputStream(os.toByteArray())); + InputSource2Node t5 = new InputSource2Node(registry); + node = t5.transform(inputSource, null); + } + + @Test + public void testTransformSAX() throws IOException { + MyContentHandler handler = new MyContentHandler(); + InputStream is = url.openStream(); + InputStream2SAX t1 = new InputStream2SAX(); + t1.transform(is, handler, null); + is.close(); + + String xml = "bar"; + + InputSource inputSource = new InputSource(new StringReader(xml)); + InputSource2SAX t2 = new InputSource2SAX(); + MyContentHandler handler2 = new MyContentHandler(); + t2.transform(inputSource, handler2, null); + + } + + private static class MyContentHandler extends DefaultHandler { + + @Override + public void startElement(String namespaceURI, String localName, String qName, Attributes atts) + throws SAXException { + super.startElement(namespaceURI, localName, qName, atts); + } + + } + +} diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/test/resources/org/apache/tuscany/sca/databinding/impl/ipo.xsd b/sca-java-2.x/branches/2.0/modules/databinding/src/test/resources/org/apache/tuscany/sca/databinding/impl/ipo.xsd new file mode 100644 index 0000000000..92a576fb98 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/test/resources/org/apache/tuscany/sca/databinding/impl/ipo.xsd @@ -0,0 +1,136 @@ + + + + + + International Purchase order schema for Example.com + Copyright 2000 Example.com. All rights reserved. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/test/resources/org/apache/tuscany/sca/databinding/impl/order.wsdl b/sca-java-2.x/branches/2.0/modules/databinding/src/test/resources/org/apache/tuscany/sca/databinding/impl/order.wsdl new file mode 100644 index 0000000000..f011ca9f32 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/test/resources/org/apache/tuscany/sca/databinding/impl/order.wsdl @@ -0,0 +1,76 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/sca-java-2.x/branches/2.0/modules/databinding/src/test/resources/org/apache/tuscany/sca/databinding/xml/foo.xml b/sca-java-2.x/branches/2.0/modules/databinding/src/test/resources/org/apache/tuscany/sca/databinding/xml/foo.xml new file mode 100644 index 0000000000..0ba8ade1e0 --- /dev/null +++ b/sca-java-2.x/branches/2.0/modules/databinding/src/test/resources/org/apache/tuscany/sca/databinding/xml/foo.xml @@ -0,0 +1,22 @@ + + + + bar + \ No newline at end of file -- cgit v1.2.3