diff options
Diffstat (limited to 'sandbox/sebastien/java/wrapped/modules/databinding-json')
33 files changed, 3100 insertions, 0 deletions
diff --git a/sandbox/sebastien/java/wrapped/modules/databinding-json/LICENSE b/sandbox/sebastien/java/wrapped/modules/databinding-json/LICENSE new file mode 100644 index 0000000000..d645695673 --- /dev/null +++ b/sandbox/sebastien/java/wrapped/modules/databinding-json/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/sandbox/sebastien/java/wrapped/modules/databinding-json/META-INF/MANIFEST.MF b/sandbox/sebastien/java/wrapped/modules/databinding-json/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..940ecccd8a --- /dev/null +++ b/sandbox/sebastien/java/wrapped/modules/databinding-json/META-INF/MANIFEST.MF @@ -0,0 +1,40 @@ +Manifest-Version: 1.0
+Export-Package: org.apache.tuscany.sca.databinding.json;version="2.0.0",
+ org.apache.tuscany.sca.databinding.json.axiom;version="2.0.0"
+SCA-Version: 1.1
+Bundle-Name: Apache Tuscany SCA Data Binding for JSON
+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 Data Binding for JSON
+Import-Package: javax.xml.namespace,
+ javax.xml.stream,
+ org.apache.axiom.om,
+ org.apache.tuscany.sca.common.xml.stax;version="2.0.0",
+ org.apache.tuscany.sca.core;version="2.0.0",
+ org.apache.tuscany.sca.databinding;version="2.0.0",
+ org.apache.tuscany.sca.databinding.impl;version="2.0.0",
+ org.apache.tuscany.sca.databinding.javabeans;version="2.0.0",
+ org.apache.tuscany.sca.interfacedef;version="2.0.0",
+ org.apache.tuscany.sca.interfacedef.impl;version="2.0.0";resolution:=optional,
+ org.apache.tuscany.sca.interfacedef.util;version="2.0.0",
+ org.codehaus.jackson,
+ org.codehaus.jackson.map,
+ org.codehaus.jackson.map.annotate,
+ org.codehaus.jackson.map.deser,
+ org.codehaus.jackson.map.introspect,
+ org.codehaus.jackson.map.ser,
+ org.codehaus.jackson.map.type,
+ org.codehaus.jackson.type,
+ org.codehaus.jackson.xc;resolution:=optional,
+ org.codehaus.jettison.badgerfish,
+ org.codehaus.jettison.json,
+ org.codehaus.jettison.mapped,
+ org.jabsorb,
+ org.jabsorb.serializer,
+ org.json,
+ org.oasisopen.sca.annotation;version="2.0.0"
+Bundle-SymbolicName: org.apache.tuscany.sca.databinding.json
+Bundle-DocURL: http://www.apache.org/
+
diff --git a/sandbox/sebastien/java/wrapped/modules/databinding-json/NOTICE b/sandbox/sebastien/java/wrapped/modules/databinding-json/NOTICE new file mode 100644 index 0000000000..fdfa0e9faa --- /dev/null +++ b/sandbox/sebastien/java/wrapped/modules/databinding-json/NOTICE @@ -0,0 +1,6 @@ +${pom.name} +Copyright (c) 2005 - 2008 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + diff --git a/sandbox/sebastien/java/wrapped/modules/databinding-json/pom.xml b/sandbox/sebastien/java/wrapped/modules/databinding-json/pom.xml new file mode 100644 index 0000000000..793307bff3 --- /dev/null +++ b/sandbox/sebastien/java/wrapped/modules/databinding-json/pom.xml @@ -0,0 +1,171 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. +--> +<project> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>org.apache.tuscany.sca</groupId> + <artifactId>tuscany-modules</artifactId> + <version>2.0-SNAPSHOT</version> + <relativePath>../pom.xml</relativePath> + </parent> + <artifactId>tuscany-databinding-json</artifactId> + <name>Apache Tuscany SCA Data Binding for JSON</name> + + <dependencies> + <dependency> + <groupId>org.apache.tuscany.sca</groupId> + <artifactId>tuscany-core-runtime-pom</artifactId> + <type>pom</type> + <version>2.0-SNAPSHOT</version> + <scope>provided</scope> + </dependency> + + <dependency> + <groupId>org.codehaus.jackson</groupId> + <artifactId>jackson-core-asl</artifactId> + <version>1.6.3</version> + </dependency> + <dependency> + <groupId>org.codehaus.jackson</groupId> + <artifactId>jackson-mapper-asl</artifactId> + <version>1.6.3</version> + </dependency> + <dependency> + <groupId>org.codehaus.jackson</groupId> + <artifactId>jackson-xc</artifactId> + <version>1.6.3</version> + </dependency> + + <dependency> + <groupId>org.jabsorb</groupId> + <artifactId>jabsorb</artifactId> + <version>1.3.1</version> + </dependency> + + <dependency> + <groupId>org.slf4j</groupId> + <artifactId>slf4j-api</artifactId> + <version>1.6.1</version> + <scope>runtime</scope> + </dependency> + <dependency> + <groupId>org.slf4j</groupId> + <artifactId>slf4j-jdk14</artifactId> + <version>1.6.1</version> + <scope>runtime</scope> + </dependency> + + <dependency> + <groupId>org.codehaus.jettison</groupId> + <artifactId>jettison</artifactId> + <version>1.2</version> + <scope>compile</scope> + <exclusions> + <exclusion> + <groupId>stax</groupId> + <artifactId>stax-api</artifactId> + </exclusion> + </exclusions> + </dependency> + + <dependency> + <groupId>org.apache.ws.commons.axiom</groupId> + <artifactId>axiom-api</artifactId> + <version>1.2.10</version> + <exclusions> + <exclusion> + <groupId>xerces</groupId> + <artifactId>xercesImpl</artifactId> + </exclusion> + <exclusion> + <groupId>javax.mail</groupId> + <artifactId>mail</artifactId> + </exclusion> + <exclusion> + <groupId>commons-logging</groupId> + <artifactId>commons-logging</artifactId> + </exclusion> + <exclusion> + <groupId>stax</groupId> + <artifactId>stax-api</artifactId> + </exclusion> + <exclusion> + <groupId>org.apache.geronimo.specs</groupId> + <artifactId>geronimo-activation_1.1_spec</artifactId> + </exclusion> + <exclusion> + <groupId>org.apache.geronimo.specs</groupId> + <artifactId>geronimo-stax-api_1.0_spec</artifactId> + </exclusion> + </exclusions> + </dependency> + + <dependency> + <groupId>org.apache.ws.commons.axiom</groupId> + <artifactId>axiom-impl</artifactId> + <version>1.2.10</version> + <scope>runtime</scope> + <exclusions> + <exclusion> + <groupId>org.apache.geronimo.specs</groupId> + <artifactId>geronimo-activation_1.1_spec</artifactId> + </exclusion> + <exclusion> + <groupId>org.apache.geronimo.specs</groupId> + <artifactId>geronimo-stax-api_1.0_spec</artifactId> + </exclusion> + <exclusion> + <groupId>org.codehaus.woodstox</groupId> + <artifactId>wstx-asl</artifactId> + </exclusion> + </exclusions> + </dependency> + + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <version>4.8.1</version> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>commons-logging</groupId> + <artifactId>commons-logging</artifactId> + <version>1.1.1</version> + <exclusions> + <exclusion> + <groupId>commons-logging</groupId> + <artifactId>commons-logging</artifactId> + </exclusion> + <exclusion> + <groupId>javax.servlet</groupId> + <artifactId>servlet-api</artifactId> + </exclusion> + </exclusions> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.codehaus.woodstox</groupId> + <artifactId>wstx-asl</artifactId> + <version>3.2.6</version> + <scope>test</scope> + </dependency> + </dependencies> +</project> diff --git a/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JSON2JavaBean.java b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JSON2JavaBean.java new file mode 100644 index 0000000000..5cf48645b8 --- /dev/null +++ b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JSON2JavaBean.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.json; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.javabeans.JavaBeansDataBinding; +import org.jabsorb.JSONSerializer; +import org.jabsorb.serializer.SerializerState; + +/** + * @version $Rev$ $Date$ + */ +public class JSON2JavaBean implements PullTransformer<Object, Object> { + private JSONSerializer serializer; + + public JSON2JavaBean() { + super(); + serializer = new JSONSerializer(); + try { + serializer.registerDefaultSerializers(); + } catch (Exception e) { + throw new TransformationException(e); + } + serializer.setMarshallClassHints(true); + serializer.setMarshallNullAttributes(false); + } + + public Object transform(Object source, TransformationContext context) { + if (source == null) { + return null; + } + + try { + SerializerState state = new SerializerState(); + return serializer.unmarshall(state, context.getTargetDataType().getPhysical(), source); + } catch (Exception e) { + throw new TransformationException(e); + } + + } + + public String getSourceDataBinding() { + return JSONDataBinding.NAME; + } + + public String getTargetDataBinding() { + return JavaBeansDataBinding.NAME; + } + + public int getWeight() { + return 5000; + } +} diff --git a/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JSON2String.java b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JSON2String.java new file mode 100644 index 0000000000..4577e7260e --- /dev/null +++ b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JSON2String.java @@ -0,0 +1,61 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.databinding.json; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.BaseTransformer; + +/** + * @version $Rev$ $Date$ + */ +public class JSON2String extends BaseTransformer<Object, String> implements + PullTransformer<Object, String> { + + @Override + protected Class<Object> getSourceType() { + return Object.class; + } + + @Override + protected Class<String> getTargetType() { + return String.class; + } + + public String transform(Object source, TransformationContext context) { + try { + return source.toString(); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + public int getWeight() { + return 500; + } + + @Override + public String getSourceDataBinding() { + return JSONDataBinding.NAME; + } + +} diff --git a/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JSON2XMLStreamReader.java b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JSON2XMLStreamReader.java new file mode 100644 index 0000000000..4989f59143 --- /dev/null +++ b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JSON2XMLStreamReader.java @@ -0,0 +1,65 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.databinding.json; + +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.BaseTransformer; +import org.codehaus.jettison.badgerfish.BadgerFishXMLStreamReader; +import org.codehaus.jettison.json.JSONObject; + +/** + * @version $Rev$ $Date$ + */ +public class JSON2XMLStreamReader extends BaseTransformer<Object, XMLStreamReader> implements + PullTransformer<Object, XMLStreamReader> { + + @Override + protected Class<Object> getSourceType() { + return Object.class; + } + + @Override + protected Class<XMLStreamReader> getTargetType() { + return XMLStreamReader.class; + } + + public XMLStreamReader transform(Object source, TransformationContext context) { + try { + JSONObject json = JSONHelper.toJettison(source); + return new BadgerFishXMLStreamReader(json); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + public int getWeight() { + return 500; + } + @Override + public String getSourceDataBinding() { + return JSONDataBinding.NAME; + } + +} diff --git a/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JSONDataBinding.java b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JSONDataBinding.java new file mode 100644 index 0000000000..1557c90bce --- /dev/null +++ b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JSONDataBinding.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.json; + + +import javax.xml.namespace.QName; + +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; +import org.codehaus.jettison.json.JSONObject; + +/** + * JAXB DataBinding + * + * @version $Rev$ $Date$ + */ +public class JSONDataBinding extends BaseDataBinding { + public static final String NAME = "JSON"; + + public static final String ROOT_NAMESPACE = "http://tuscany.apache.org/xmlns/sca/databinding/json/1.0"; + public static final QName ROOT_ELEMENT = new QName(ROOT_NAMESPACE, "root"); + + public JSONDataBinding() { + super(NAME, org.json.JSONObject.class); + } + + @Override + public boolean introspect(DataType type, Operation operation) { + assert type != null; + Class cls = type.getPhysical(); + if (JSONObject.class.isAssignableFrom(cls) || org.json.JSONObject.class.isAssignableFrom(cls)) { + type.setDataBinding(getName()); + if (type.getLogical() == null) { + type.setLogical(XMLType.UNKNOWN); + } + return true; + } + return false; + } + + @SuppressWarnings("unchecked") + @Override + public Object copy(Object arg, + DataType sourceDataType, + DataType targetDataType, + Operation sourceOperation, + Operation targetOperation) { + if (arg == null) { + return null; + } + try { + Class type = arg != null ? arg.getClass() : null; + return JSONHelper.toJSON(arg.toString(), type); + } catch (Exception e) { + throw new IllegalArgumentException(e); + } + } + +} diff --git a/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JSONHelper.java b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JSONHelper.java new file mode 100644 index 0000000000..028690a789 --- /dev/null +++ b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JSONHelper.java @@ -0,0 +1,106 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.databinding.json; + +import java.util.Collection; + +import org.apache.tuscany.sca.databinding.json.jackson.JacksonHelper; +import org.codehaus.jackson.JsonNode; +import org.codehaus.jackson.JsonParser; +import org.codehaus.jettison.json.JSONException; +import org.codehaus.jettison.json.JSONObject; +import org.json.JSONArray; + +/** + * @version $Rev$ $Date$ + */ +public class JSONHelper { + private JSONHelper() { + + } + + /** + * Convert to Jettison JSONObject + * @param source + * @return + */ + public static JSONObject toJettison(Object source) { + JSONObject json = null; + if (source instanceof JSONObject) { + json = (JSONObject)source; + } else if (source instanceof org.json.JSONObject || source instanceof String) { + json = stringToJettision(source.toString()); + } else if (source instanceof JsonNode) { + json = stringToJettision(JacksonHelper.toString((JsonNode)source)); + } else if (source instanceof JsonParser) { + json = stringToJettision(JacksonHelper.toString((JsonParser)source)); + } + return json; + } + + private static JSONObject stringToJettision(String content) { + try { + return new JSONObject(content); + } catch (JSONException e) { + throw new IllegalArgumentException(e); + } + } + + /** + * Convert to org.json.JSONObject + * @param source + * @return + */ + public static org.json.JSONObject toJSONOrg(Object source) { + org.json.JSONObject json = null; + if (source instanceof JSONObject) { + try { + json = new org.json.JSONObject(((JSONObject)source).toString()); + } catch (org.json.JSONException e) { + throw new IllegalArgumentException(e); + } + } else if (source instanceof org.json.JSONObject) { + json = (org.json.JSONObject)source; + } + return json; + } + + public static Object toJSON(String json, Class<?> type) { + if (type == JSONObject.class) { + try { + return new JSONObject(json); + } catch (JSONException e) { + throw new IllegalArgumentException(e); + } + } else { + if (type == null) { + type = org.json.JSONObject.class; + } + try { + if (type == JSONArray.class || type.isArray() || Collection.class.isAssignableFrom(type)) { + return new JSONArray(json); + } + return new org.json.JSONObject(json); + } catch (org.json.JSONException e) { + throw new IllegalArgumentException(e); + } + } + } +} diff --git a/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JavaBean2JSON.java b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JavaBean2JSON.java new file mode 100644 index 0000000000..0c0683b16c --- /dev/null +++ b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JavaBean2JSON.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.json; + +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.javabeans.JavaBeansDataBinding; +import org.jabsorb.JSONSerializer; +import org.jabsorb.serializer.SerializerState; + +public class JavaBean2JSON extends BaseTransformer<Object, Object> implements PullTransformer<Object, Object> { + private JSONSerializer serializer; + + public JavaBean2JSON() { + serializer = new JSONSerializer(); + try { + serializer.registerDefaultSerializers(); + } catch (Exception e) { + throw new TransformationException(e); + } + serializer.setMarshallClassHints(true); + serializer.setMarshallNullAttributes(false); + } + + @Override + public String getSourceDataBinding() { + return JavaBeansDataBinding.NAME; + } + + @Override + protected Class<Object> getSourceType() { + return Object.class; + } + + @Override + public String getTargetDataBinding() { + return JSONDataBinding.NAME; + } + + @Override + protected Class<Object> getTargetType() { + return Object.class; + } + + public Object toJSON(Object source) throws Exception { + if (source == null) { + return org.json.JSONObject.NULL; + } + + SerializerState state = new SerializerState(); + return serializer.marshall(state, null, source, new Integer(0)); + } + + public Object transform(Object source, TransformationContext context) { + try { + return toJSON(source); + } catch (Exception e) { + throw new TransformationException(e); + } + } + +} diff --git a/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JavaBean2JSONObject.java b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JavaBean2JSONObject.java new file mode 100644 index 0000000000..9ec3bd7e19 --- /dev/null +++ b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/JavaBean2JSONObject.java @@ -0,0 +1,142 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.databinding.json; + +import java.beans.BeanInfo; +import java.beans.Introspector; +import java.beans.PropertyDescriptor; +import java.lang.reflect.Array; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.SimpleTypeMapper; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.BaseTransformer; +import org.apache.tuscany.sca.databinding.impl.SimpleTypeMapperImpl; +import org.apache.tuscany.sca.databinding.javabeans.JavaBeansDataBinding; +import org.apache.tuscany.sca.interfacedef.util.TypeInfo; +import org.codehaus.jettison.json.JSONArray; +import org.codehaus.jettison.json.JSONObject; + +public class JavaBean2JSONObject extends BaseTransformer<Object, Object> implements PullTransformer<Object, Object> { + private static final SimpleTypeMapper SIMPLE_TYPE_MAPPER = new SimpleTypeMapperImpl(); + + private static final Comparator<PropertyDescriptor> COMPARATOR = new Comparator<PropertyDescriptor>() { + public int compare(PropertyDescriptor o1, PropertyDescriptor o2) { + return o1.getName().compareTo(o2.getName()); + } + }; + + private static final SimpleTypeMapperImpl MAPPER = new SimpleTypeMapperImpl(); + private static final Object[] NULL = null; + + private static String getStringValue(Object o) { + if (o == null) { + return null; + } + TypeInfo info = SIMPLE_TYPE_MAPPER.getXMLType(o.getClass()); + if (info != null) { + return MAPPER.toXMLLiteral(info.getQName(), o, null); + } else { + return String.valueOf(o); + } + } + + private static boolean isSimpleType(Class<?> javaType) { + return SIMPLE_TYPE_MAPPER.getXMLType(javaType) != null; + } + + public JavaBean2JSONObject() { + } + + @Override + public String getSourceDataBinding() { + return JavaBeansDataBinding.NAME; + } + + @Override + protected Class<Object> getSourceType() { + return Object.class; + } + + @Override + public String getTargetDataBinding() { + return JSONDataBinding.NAME; + } + + @Override + protected Class<Object> getTargetType() { + return Object.class; + } + + public Object toJSON(Object source) throws Exception { + if (source == null) { + return JSONObject.NULL; + } + Class<?> type = source.getClass(); + if (isSimpleType(type)) { + return source; + } else if (type.isArray()) { + JSONArray array = new JSONArray(); + int i1 = Array.getLength(source); + for (int j = 0; j < i1; j++) { + Object o = Array.get(source, j); + array.put(toJSON(o)); + } + return array; + } else if (Collection.class.isAssignableFrom(type)) { + Collection c = (Collection)source; + JSONArray array = new JSONArray(); + for (Object element : c) { + array.put(toJSON(element)); + } + return array; + } + JSONObject json = new JSONObject(); + BeanInfo beanInfo = Introspector.getBeanInfo(type); + PropertyDescriptor[] propDescs = beanInfo.getPropertyDescriptors(); + Collections.sort(Arrays.asList(propDescs), COMPARATOR); + + for (int i = 0; i < propDescs.length; i++) { + PropertyDescriptor propDesc = propDescs[i]; + Class<?> pType = propDesc.getPropertyType(); + if ("class".equals(propDesc.getName())) { + continue; + } + Object pValue = propDesc.getReadMethod().invoke(source, NULL); + json.put(propDesc.getName(), toJSON(pValue)); + } + return json; + + } + + public Object transform(Object source, TransformationContext context) { + try { + return toJSON(source); + } catch (Exception e) { + throw new TransformationException(e); + } + } + +} diff --git a/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/String2JSON.java b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/String2JSON.java new file mode 100644 index 0000000000..7d89927f51 --- /dev/null +++ b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/String2JSON.java @@ -0,0 +1,64 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.databinding.json; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.BaseTransformer; + +/** + * @version $Rev$ $Date$ + */ +public class String2JSON extends BaseTransformer<String, Object> implements PullTransformer<String, Object> { + + @Override + protected Class<String> getSourceType() { + return String.class; + } + + @Override + protected Class<Object> getTargetType() { + return Object.class; + } + + public Object transform(String source, TransformationContext context) { + try { + Class type = null; + if (context != null && context.getTargetDataType() != null) { + type = context.getTargetDataType().getPhysical(); + } + return JSONHelper.toJSON(source, type); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + public int getWeight() { + return 500; + } + + @Override + public String getTargetDataBinding() { + return JSONDataBinding.NAME; + } + +} diff --git a/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/XMLStreamReader2JSON.java b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/XMLStreamReader2JSON.java new file mode 100644 index 0000000000..76ccc69c55 --- /dev/null +++ b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/XMLStreamReader2JSON.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.json; + +import java.io.StringWriter; + +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; + +import org.apache.tuscany.sca.common.xml.stax.StAXHelper; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +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.BaseTransformer; +import org.codehaus.jettison.badgerfish.BadgerFishXMLStreamWriter; + +/** + * @version $Rev$ $Date$ + */ +public class XMLStreamReader2JSON extends BaseTransformer<XMLStreamReader, Object> implements + PullTransformer<XMLStreamReader, Object> { + + private StAXHelper staxHelper; + + public XMLStreamReader2JSON(ExtensionPointRegistry registry) { + staxHelper = StAXHelper.getInstance(registry); + } + + @Override + protected Class<XMLStreamReader> getSourceType() { + return XMLStreamReader.class; + } + + @Override + protected Class<Object> getTargetType() { + return Object.class; + } + + public Object transform(XMLStreamReader source, TransformationContext context) { + try { + StringWriter writer = new StringWriter(); + XMLStreamWriter jsonWriter = new BadgerFishXMLStreamWriter(writer); + staxHelper.save(source, jsonWriter); + source.close(); + Class type = null; + if (context != null && context.getTargetDataType() != null) { + type = context.getTargetDataType().getPhysical(); + } + return JSONHelper.toJSON(writer.toString(), type); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + public int getWeight() { + return 500; + } + + @Override + public String getTargetDataBinding() { + return JSONDataBinding.NAME; + } + +} diff --git a/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/axiom/JSON2OMElement.java b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/axiom/JSON2OMElement.java new file mode 100644 index 0000000000..c7c9adc882 --- /dev/null +++ b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/axiom/JSON2OMElement.java @@ -0,0 +1,94 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.databinding.json.axiom; + + +import org.apache.axiom.om.OMAbstractFactory; +import org.apache.axiom.om.OMElement; +import org.apache.axiom.om.OMFactory; +import org.apache.axiom.om.OMNamespace; +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.Transformer; +import org.apache.tuscany.sca.databinding.BaseTransformer; +import org.apache.tuscany.sca.databinding.json.JSONDataBinding; +import org.apache.tuscany.sca.databinding.json.JSONHelper; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.util.XMLType; +import org.codehaus.jettison.json.JSONObject; +import org.oasisopen.sca.annotation.Service; + +/** + * @version $Rev$ $Date$ + */ +@Service(Transformer.class) +public class JSON2OMElement extends BaseTransformer<Object, OMElement> implements PullTransformer<Object, OMElement> { + + private OMFactory factory = OMAbstractFactory.getOMFactory(); + + @Override + protected Class<Object> getSourceType() { + return Object.class; + } + + @Override + protected Class<OMElement> getTargetType() { + return OMElement.class; + } + + public OMElement transform(Object source, TransformationContext context) { + try { + JSONObject json = JSONHelper.toJettison(source); + if (json == null) { + return null; + } + String ns = JSONDataBinding.ROOT_ELEMENT.getNamespaceURI(); + String name = JSONDataBinding.ROOT_ELEMENT.getLocalPart(); + if (context != null) { + DataType<?> dataType = context.getTargetDataType(); + Object logical = dataType.getLogical(); + if (logical instanceof XMLType) { + XMLType xmlType = (XMLType)logical; + if (xmlType.isElement()) { + ns = xmlType.getElementName().getNamespaceURI(); + name = xmlType.getElementName().getLocalPart(); + } + } + } + JSONBadgerfishDataSource ds = new JSONBadgerfishDataSource(json); + OMNamespace namespace = factory.createOMNamespace(ns, ""); + return factory.createOMElement(ds, name, namespace); + } catch (Exception e) { + throw new TransformationException(e); + } + } + + @Override + public int getWeight() { + return 500; + } + + @Override + public String getSourceDataBinding() { + return JSONDataBinding.NAME; + } + +} diff --git a/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/axiom/JSONBadgerfishDataSource.java b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/axiom/JSONBadgerfishDataSource.java new file mode 100644 index 0000000000..adc38772be --- /dev/null +++ b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/axiom/JSONBadgerfishDataSource.java @@ -0,0 +1,57 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.databinding.json.axiom; + +import javax.xml.stream.XMLStreamException; + +import org.codehaus.jettison.badgerfish.BadgerFishXMLStreamReader; +import org.codehaus.jettison.json.JSONException; +import org.codehaus.jettison.json.JSONObject; + +/** + * JSONDataSource keeps the JSON String inside and consumes it when needed. This is to be kept in the + * OMSourcedElementImpl and can be used either to expand the tree or get the JSON String directly without expanding. + * This uses the "Badgerfish" JSON convention. + * + * @version $Rev$ $Date$ + */ + +public class JSONBadgerfishDataSource extends JSONDataSource { + + public JSONBadgerfishDataSource(JSONObject json) { + super(json); + } + + /** + * Gives the StAX reader using the "Badgerfish" formatted input JSON String. + * + * @return The XMLStreamReader according to the JSON String. + * @throws javax.xml.stream.XMLStreamException if there is an error while making the StAX reader. + */ + @Override + public javax.xml.stream.XMLStreamReader getReader() throws XMLStreamException { + try { + return new BadgerFishXMLStreamReader(json); + } catch (JSONException e) { + throw new XMLStreamException(e); + } + + } +} diff --git a/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/axiom/JSONDataSource.java b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/axiom/JSONDataSource.java new file mode 100644 index 0000000000..5b0312056e --- /dev/null +++ b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/axiom/JSONDataSource.java @@ -0,0 +1,176 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.databinding.json.axiom; + +import java.io.IOException; +import java.io.OutputStream; +import java.io.Writer; +import java.util.HashMap; +import java.util.Map; + +import javax.xml.stream.XMLStreamConstants; +import javax.xml.stream.XMLStreamReader; + +import org.apache.axiom.om.OMDataSource; +import org.apache.axiom.om.OMException; +import org.apache.axiom.om.OMOutputFormat; +import org.codehaus.jettison.json.JSONObject; +import org.codehaus.jettison.json.JSONTokener; +import org.codehaus.jettison.mapped.MappedXMLInputFactory; + +/** + * JSONDataSource keeps the JSON String inside and consumes it when needed. This is to be kept in the + * OMSourcedElementImpl and can be used either to expand the tree or get the JSON String directly without expanding. + * This uses the "Mapped" JSON convention. + * + * @version $Rev$ $Date$ + */ + +public class JSONDataSource implements OMDataSource { + protected JSONObject json; + + public JSONDataSource(JSONObject json) { + this.json = json; + } + + /** + * Writes JSON into the output stream. As this should write JSON, it directly gets the JSON string and writes it + * without expanding the tree. + * + * @param outputStream the stream to be written into + * @param omOutputFormat format of the message, this is ignored. + * @throws javax.xml.stream.XMLStreamException if there is an error while writing the message in to the output + * stream. + */ + public void serialize(OutputStream outputStream, OMOutputFormat omOutputFormat) + throws javax.xml.stream.XMLStreamException { + try { + String encoding = omOutputFormat == null ? "UTF-8" : omOutputFormat.getCharSetEncoding(); + outputStream.write(getJSONString().getBytes(encoding)); + } catch (IOException e) { + throw new OMException(); + } + } + + /** + * Writes JSON through the writer. As this should write JSON, it directly gets the JSON string and writes it without + * expanding the tree. + * + * @param writer Writer to be written into + * @param omOutputFormat format of the message, this is ignored. + * @throws javax.xml.stream.XMLStreamException if there is an error while writing the message through the writer. + */ + public void serialize(Writer writer, OMOutputFormat omOutputFormat) throws javax.xml.stream.XMLStreamException { + try { + writer.write(getJSONString()); + } catch (IOException e) { + throw new OMException(); + } + } + + /** + * Writes XML through the XMLStreamWriter. As the input data source is JSON, this method needs to get a StAX reader + * from that JSON String. Therefore this uses the getReader() method to get the StAX reader writes the events into + * the XMLStreamWriter. + * + * @param xmlStreamWriter StAX writer to be written into + * @throws javax.xml.stream.XMLStreamException if there is an error while writing the message through the StAX + * writer. + */ + public void serialize(javax.xml.stream.XMLStreamWriter xmlStreamWriter) throws javax.xml.stream.XMLStreamException { + XMLStreamReader reader = getReader(); + xmlStreamWriter.writeStartDocument(); + while (reader.hasNext()) { + int x = reader.next(); + switch (x) { + case XMLStreamConstants.START_ELEMENT: + xmlStreamWriter.writeStartElement(reader.getPrefix(), reader.getLocalName(), reader + .getNamespaceURI()); + int namespaceCount = reader.getNamespaceCount(); + for (int i = namespaceCount - 1; i >= 0; i--) { + xmlStreamWriter.writeNamespace(reader.getNamespacePrefix(i), reader.getNamespaceURI(i)); + } + int attributeCount = reader.getAttributeCount(); + for (int i = 0; i < attributeCount; i++) { + xmlStreamWriter.writeAttribute(reader.getAttributePrefix(i), + reader.getAttributeNamespace(i), + reader.getAttributeLocalName(i), + reader.getAttributeValue(i)); + } + break; + case XMLStreamConstants.START_DOCUMENT: + break; + case XMLStreamConstants.CHARACTERS: + xmlStreamWriter.writeCharacters(reader.getText()); + break; + case XMLStreamConstants.CDATA: + xmlStreamWriter.writeCData(reader.getText()); + break; + case XMLStreamConstants.END_ELEMENT: + xmlStreamWriter.writeEndElement(); + break; + case XMLStreamConstants.END_DOCUMENT: + xmlStreamWriter.writeEndDocument(); + break; + case XMLStreamConstants.SPACE: + break; + case XMLStreamConstants.COMMENT: + xmlStreamWriter.writeComment(reader.getText()); + break; + case XMLStreamConstants.DTD: + xmlStreamWriter.writeDTD(reader.getText()); + break; + case XMLStreamConstants.PROCESSING_INSTRUCTION: + xmlStreamWriter.writeProcessingInstruction(reader.getPITarget(), reader.getPIData()); + break; + case XMLStreamConstants.ENTITY_REFERENCE: + xmlStreamWriter.writeEntityRef(reader.getLocalName()); + break; + default: + throw new OMException(); + } + } + xmlStreamWriter.writeEndDocument(); + } + + /** + * Gives the StAX reader using the "Mapped" formatted input JSON String. + * + * @return The XMLStreamReader according to the JSON String. + * @throws javax.xml.stream.XMLStreamException if there is an error while making the StAX reader. + */ + + public javax.xml.stream.XMLStreamReader getReader() throws javax.xml.stream.XMLStreamException { + + Map<String, String> nsMap = new HashMap<String, String>(); + nsMap.put("", ""); + + // input factory for "Mapped" convention + MappedXMLInputFactory inputFactory = new MappedXMLInputFactory(nsMap); + String jsonString = this.getJSONString(); + return inputFactory.createXMLStreamReader(new JSONTokener(jsonString)); + } + + // returns the json string by consuming the JSON input stream. + protected String getJSONString() { + return json.toString(); + } + +} diff --git a/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/jackson/InputStream2JSON.java b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/jackson/InputStream2JSON.java new file mode 100644 index 0000000000..57b9d55b44 --- /dev/null +++ b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/jackson/InputStream2JSON.java @@ -0,0 +1,49 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.databinding.json.jackson; + +import java.io.InputStream; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.json.JSONDataBinding; + +/** + * + */ +public class InputStream2JSON implements PullTransformer<InputStream, Object> { + + public String getSourceDataBinding() { + return "application/json" + "#" + InputStream.class.getName(); + } + + public String getTargetDataBinding() { + return JSONDataBinding.NAME; + } + + public int getWeight() { + return 10; + } + + public Object transform(InputStream source, TransformationContext context) { + return JacksonHelper.createJsonParser(source); + } + +} diff --git a/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/jackson/JSON2Object.java b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/jackson/JSON2Object.java new file mode 100644 index 0000000000..c7ae9d636d --- /dev/null +++ b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/jackson/JSON2Object.java @@ -0,0 +1,82 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.databinding.json.jackson; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.javabeans.JavaBeansDataBinding; +import org.apache.tuscany.sca.databinding.json.JSONDataBinding; +import org.codehaus.jackson.JsonNode; +import org.codehaus.jackson.JsonParser; +import org.codehaus.jackson.map.ObjectMapper; +import org.codehaus.jackson.map.type.TypeFactory; +import org.codehaus.jackson.type.JavaType; + +/** + * @version $Rev$ $Date$ + */ +public class JSON2Object implements PullTransformer<Object, Object> { + private ObjectMapper mapper; + + public JSON2Object() { + super(); + } + + public Object transform(Object source, TransformationContext context) { + if (source == null) { + return null; + } + + try { + Class<?> cls = context.getTargetDataType().getPhysical(); + ObjectMapper mapper = JacksonHelper.createObjectMapper(cls); + JavaType javaType = TypeFactory.type(context.getTargetDataType().getGenericType()); + if (source instanceof String) { + String sourceString = (String) source; + if(sourceString.isEmpty()) { + return sourceString; + } else { + return mapper.readValue((String)source, javaType); + } + } else if (source instanceof JsonNode) { + return mapper.treeToValue((JsonNode)source, context.getTargetDataType().getPhysical()); + } else if (source instanceof JsonParser) { + return mapper.readValue((JsonParser)source, javaType); + } else { + return mapper.readValue(source.toString(), javaType); + } + } catch (Exception e) { + throw new TransformationException(e); + } + } + + public String getSourceDataBinding() { + return JSONDataBinding.NAME; + } + + public String getTargetDataBinding() { + return JavaBeansDataBinding.NAME; + } + + public int getWeight() { + return 5000; + } +} diff --git a/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/jackson/JSON2OutputStream.java b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/jackson/JSON2OutputStream.java new file mode 100644 index 0000000000..920485a540 --- /dev/null +++ b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/jackson/JSON2OutputStream.java @@ -0,0 +1,65 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.databinding.json.jackson; + +import java.io.OutputStream; + +import org.apache.tuscany.sca.databinding.PushTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.json.JSONDataBinding; +import org.codehaus.jackson.JsonNode; +import org.codehaus.jackson.JsonParser; + +/** + * + */ +public class JSON2OutputStream implements PushTransformer<Object, OutputStream> { + + public String getSourceDataBinding() { + return JSONDataBinding.NAME; + } + + public String getTargetDataBinding() { + return "application/json" + "#" + OutputStream.class.getName(); + } + + public void transform(Object source, OutputStream sink, TransformationContext context) { + if (source == null) { + return; + } + if (source instanceof JsonNode) { + JacksonHelper.write((JsonNode)source, sink); + } else if (source instanceof JsonParser) { + JacksonHelper.write((JsonParser)source, sink); + } else { + try { + sink.write(source.toString().getBytes("UTF-8")); + } catch (Exception e) { + throw new TransformationException(e); + } + } + } + + public int getWeight() { + return 50; + } + +} diff --git a/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/jackson/JacksonHelper.java b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/jackson/JacksonHelper.java new file mode 100644 index 0000000000..459462fa97 --- /dev/null +++ b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/jackson/JacksonHelper.java @@ -0,0 +1,181 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.databinding.json.jackson; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.Reader; +import java.io.StringWriter; + +import javax.xml.bind.annotation.adapters.XmlAdapter; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapters; + +import org.codehaus.jackson.JsonEncoding; +import org.codehaus.jackson.JsonFactory; +import org.codehaus.jackson.JsonGenerator; +import org.codehaus.jackson.JsonNode; +import org.codehaus.jackson.JsonParser; +import org.codehaus.jackson.map.AnnotationIntrospector; +import org.codehaus.jackson.map.DeserializationConfig; +import org.codehaus.jackson.map.MappingJsonFactory; +import org.codehaus.jackson.map.ObjectMapper; +import org.codehaus.jackson.map.annotate.JsonSerialize; +import org.codehaus.jackson.map.deser.CustomDeserializerFactory; +import org.codehaus.jackson.map.deser.StdDeserializerProvider; +import org.codehaus.jackson.map.introspect.JacksonAnnotationIntrospector; +import org.codehaus.jackson.map.ser.CustomSerializerFactory; +import org.codehaus.jackson.xc.JaxbAnnotationIntrospector; +import org.codehaus.jackson.xc.XmlAdapterJsonDeserializer; +import org.codehaus.jackson.xc.XmlAdapterJsonSerializer; + +/** + * + */ +public class JacksonHelper { + private final static ObjectMapper MAPPER = createMapper(); + private final static JsonFactory FACTORY = new MappingJsonFactory(createMapper()); + + public static ObjectMapper createMapper() { + return createObjectMapper(null); + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + public static ObjectMapper createObjectMapper(Class<?> cls) { + ObjectMapper mapper = null; + if (cls != null) { + // Workaround for http://jira.codehaus.org/browse/JACKSON-413 + Package pkg = cls.getPackage(); + if (pkg != null) { + XmlJavaTypeAdapters adapters = pkg.getAnnotation(XmlJavaTypeAdapters.class); + if (adapters != null) { + CustomSerializerFactory serializerFactory = new CustomSerializerFactory(); + CustomDeserializerFactory deserializerFactory = new CustomDeserializerFactory(); + for (XmlJavaTypeAdapter a : adapters.value()) { + XmlAdapter xmlAdapter = null; + try { + xmlAdapter = a.value().newInstance(); + } catch (Throwable e) { + // Ignore + } + if (xmlAdapter != null) { + XmlAdapterJsonDeserializer deserializer = new XmlAdapterJsonDeserializer(xmlAdapter); + XmlAdapterJsonSerializer serializer = new XmlAdapterJsonSerializer(xmlAdapter); + deserializerFactory.addSpecificMapping(a.type(), deserializer); + serializerFactory.addGenericMapping(a.type(), serializer); + StdDeserializerProvider deserializerProvider = + new StdDeserializerProvider(deserializerFactory); + mapper = new ObjectMapper(); + mapper.setSerializerFactory(serializerFactory); + mapper.setDeserializerProvider(deserializerProvider); + } + } + } + } + } + if (mapper == null) { + mapper = new ObjectMapper(); + } + AnnotationIntrospector primary = new JaxbAnnotationIntrospector(); + AnnotationIntrospector secondary = new JacksonAnnotationIntrospector(); + AnnotationIntrospector pair = new AnnotationIntrospector.Pair(primary, secondary); + mapper.getDeserializationConfig().setAnnotationIntrospector(pair); + // [rfeng] To avoid complaints about javaClass + mapper.getDeserializationConfig().set(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, Boolean.FALSE); + mapper.getSerializationConfig().setAnnotationIntrospector(pair); + mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); + return mapper; + } + + public static JsonFactory getJsonFactory() { + return FACTORY; + } + + public static String toString(JsonNode node) { + try { + return MAPPER.writeValueAsString(node); + } catch (IOException e) { + throw new IllegalArgumentException(e); + } + } + + public static String toString(JsonParser parser) { + try { + JsonFactory jsonFactory = getJsonFactory(); + StringWriter sw = new StringWriter(); + JsonGenerator generator = jsonFactory.createJsonGenerator(sw); + JsonNode node = parser.readValueAs(JsonNode.class); + generator.writeTree(node); + return sw.toString(); + } catch (IOException e) { + throw new IllegalArgumentException(e); + } + } + + public static JsonParser createJsonParser(String content) { + JsonFactory jsonFactory = getJsonFactory(); + try { + return jsonFactory.createJsonParser(content); + } catch (IOException e) { + throw new IllegalArgumentException(e); + } + } + + public static JsonParser createJsonParser(InputStream content) { + JsonFactory jsonFactory = getJsonFactory(); + try { + return jsonFactory.createJsonParser(content); + } catch (IOException e) { + throw new IllegalArgumentException(e); + } + } + + public static JsonParser createJsonParser(Reader content) { + JsonFactory jsonFactory = getJsonFactory(); + try { + return jsonFactory.createJsonParser(content); + } catch (IOException e) { + throw new IllegalArgumentException(e); + } + } + + public static void write(JsonNode node, OutputStream out) { + try { + JsonFactory jsonFactory = getJsonFactory(); + JsonGenerator generator = jsonFactory.createJsonGenerator(out, JsonEncoding.UTF8); + generator.writeTree(node); + } catch (IOException e) { + throw new IllegalArgumentException(e); + } + } + + public static void write(JsonParser parser, OutputStream out) { + try { + JsonFactory jsonFactory = getJsonFactory(); + JsonGenerator generator = jsonFactory.createJsonGenerator(out, JsonEncoding.UTF8); + JsonNode node = parser.readValueAs(JsonNode.class); + generator.writeTree(node); + } catch (IOException e) { + throw new IllegalArgumentException(e); + } + } + +} diff --git a/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/jackson/Object2JSON.java b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/jackson/Object2JSON.java new file mode 100644 index 0000000000..38b826b202 --- /dev/null +++ b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/java/org/apache/tuscany/sca/databinding/json/jackson/Object2JSON.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.json.jackson; + +import java.math.BigDecimal; + +import org.apache.tuscany.sca.databinding.PullTransformer; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.TransformationException; +import org.apache.tuscany.sca.databinding.javabeans.JavaBeansDataBinding; +import org.apache.tuscany.sca.databinding.json.JSONDataBinding; +import org.apache.tuscany.sca.databinding.json.JSONHelper; +import org.codehaus.jackson.JsonNode; +import org.codehaus.jackson.JsonParser; +import org.codehaus.jackson.map.ObjectMapper; + +/** + * @version $Rev$ $Date$ + */ +public class Object2JSON implements PullTransformer<Object, Object> { + + public Object2JSON() { + super(); + } + + public Object transform(Object source, TransformationContext context) { + if (source == null) { + return null; + } + + Class<?> targetType = null; + if (context != null && context.getTargetDataType() != null) { + targetType = context.getTargetDataType().getPhysical(); + } + if (targetType == null) { + targetType = String.class; + } + try { + if (targetType != null && targetType.isPrimitive()) { + return source; + } + ObjectMapper mapper = JacksonHelper.createObjectMapper(targetType); + String value = mapper.writeValueAsString(source); + if (targetType == String.class || targetType == Object.class || targetType.isPrimitive()) { + return value; + } else if (targetType == BigDecimal.class) { + return value.toString(); + } else if (JsonNode.class.isAssignableFrom(targetType)) { + return JacksonHelper.createJsonParser(value).readValueAsTree(); + } + if (JsonParser.class.isAssignableFrom(targetType)) { + return JacksonHelper.createJsonParser(value); + } else { + return JSONHelper.toJSON(value, targetType); + } + } catch (Exception e) { + throw new TransformationException(e); + } + } + + public String getSourceDataBinding() { + return JavaBeansDataBinding.NAME; + } + + public String getTargetDataBinding() { + return JSONDataBinding.NAME; + } + + public int getWeight() { + return 5000; + } +} diff --git a/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.DataBinding b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.DataBinding new file mode 100644 index 0000000000..aec4184afa --- /dev/null +++ b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.DataBinding @@ -0,0 +1,20 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +# implementation classes for the databindings +org.apache.tuscany.sca.databinding.json.JSONDataBinding;name=JSON +
diff --git a/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PullTransformer b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PullTransformer new file mode 100644 index 0000000000..39426ce844 --- /dev/null +++ b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PullTransformer @@ -0,0 +1,34 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +# Implementation classes for the transformers +org.apache.tuscany.sca.databinding.json.JSON2XMLStreamReader;source=JSON,target=javax.xml.stream.XMLStreamReader,weight=5000 +org.apache.tuscany.sca.databinding.json.XMLStreamReader2JSON;source=javax.xml.stream.XMLStreamReader,target=JSON,weight=5000,public=false +org.apache.tuscany.sca.databinding.json.jackson.Object2JSON;source=java:complexType,target=JSON,weight=90000,public=true +org.apache.tuscany.sca.databinding.json.jackson.Object2JSON;source=java:simpleType,target=JSON,weight=90000,public=false +org.apache.tuscany.sca.databinding.json.axiom.JSON2OMElement;source=JSON,target=org.apache.axiom.om.OMElement,weight=500 +org.apache.tuscany.sca.databinding.json.jackson.Object2JSON;source=java:array,target=JSON,weight=90000,public=false +org.apache.tuscany.sca.databinding.json.jackson.Object2JSON;source=commonj.sdo.DataObject,target=JSON,weight=90000,public=false +org.apache.tuscany.sca.databinding.json.jackson.Object2JSON;source=javax.xml.bind.JAXBElement,target=JSON,weight=90000,public=true +org.apache.tuscany.sca.databinding.json.jackson.JSON2Object;source=JSON,target=java:complexType,weight=90000,public=false +org.apache.tuscany.sca.databinding.json.jackson.JSON2Object;source=JSON,target=java:simpleType,weight=90000,public=false +org.apache.tuscany.sca.databinding.json.jackson.JSON2Object;source=JSON,target=commonj.sdo.DataObject,weight=90000,public=false +org.apache.tuscany.sca.databinding.json.jackson.JSON2Object;source=JSON,target=javax.xml.bind.JAXBElement,weight=90000,public=false +org.apache.tuscany.sca.databinding.json.jackson.JSON2Object;source=JSON,target=java:array,weight=90000,public=false + +org.apache.tuscany.sca.databinding.json.jackson.InputStream2JSON;source=application/json#java.io.InputStream;target=JSON,weight=50,public=true +
diff --git a/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PushTransformer b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PushTransformer new file mode 100644 index 0000000000..c3272d1425 --- /dev/null +++ b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/main/resources/META-INF/services/org.apache.tuscany.sca.databinding.PushTransformer @@ -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.json.jackson.JSON2OutputStream;source=JSON;target=application/json#java.io.OutputStream,weight=50,public=true diff --git a/sandbox/sebastien/java/wrapped/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/JSONTransformerTestCase.java b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/JSONTransformerTestCase.java new file mode 100644 index 0000000000..1aa6cf3dab --- /dev/null +++ b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/JSONTransformerTestCase.java @@ -0,0 +1,140 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.databinding.json; + +import java.io.StringReader; +import java.io.StringWriter; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLOutputFactory; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; + +import junit.framework.Assert; + +import org.apache.axiom.om.OMElement; +import org.apache.tuscany.sca.common.xml.stax.StAXHelper; +import org.apache.tuscany.sca.core.DefaultExtensionPointRegistry; +import org.apache.tuscany.sca.core.ExtensionPointRegistry; +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.impl.TransformationContextImpl; +import org.apache.tuscany.sca.databinding.json.axiom.JSON2OMElement; +import org.apache.tuscany.sca.interfacedef.DataType; +import org.apache.tuscany.sca.interfacedef.impl.DataTypeImpl; +import org.apache.tuscany.sca.interfacedef.util.XMLType; +import org.json.JSONObject; +import org.junit.Test; + +public class JSONTransformerTestCase { + private static final String IPO_XML = + "<?xml version=\"1.0\"?>" + "<ipo:purchaseOrder" + + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + + " xmlns:ipo=\"http://www.example.com/IPO\"" + + " xsi:schemaLocation=\"http://www.example.com/IPO ipo.xsd\"" + + " orderDate=\"1999-12-01\">" + + " <shipTo exportCode=\"1\" xsi:type=\"ipo:UKAddress\">" + + " <name>Helen Zoe</name>" + + " <street>47 Eden Street</street>" + + " <city>Cambridge</city>" + + " <postcode>CB1 1JR</postcode>" + + " </shipTo>" + + " <billTo xsi:type=\"ipo:USAddress\">" + + " <name>Robert Smith</name>" + + " <street>8 Oak Avenue</street>" + + " <city>Old Town</city>" + + " <state>PA</state>" + + " <zip>95819</zip>" + + " </billTo>" + + " <items>" + + " <item partNum=\"833-AA\">" + + " <productName>Lapis necklace</productName>" + + " <quantity>1</quantity>" + + " <USPrice>99.95</USPrice>" + + " <ipo:comment>Want this for the holidays</ipo:comment>" + + " <shipDate>1999-12-05</shipDate>" + + " </item>" + + " </items>" + + "</ipo:purchaseOrder>"; + + private static final String JSON_STR = + "{\"xsl:root\":{\"@xmlns\":{\"xsl\":\"http://foo.com\"},\"data\":{\"$\":\"my json string\"}}}"; + + @Test + public void testXML2JSON() throws Exception { + ExtensionPointRegistry extensionPointRegistry = new DefaultExtensionPointRegistry(); + StAXHelper staxHelper = StAXHelper.getInstance(extensionPointRegistry); + + XMLStreamReader reader = staxHelper.createXMLStreamReader(new StringReader(IPO_XML)); + XMLStreamReader2JSON t1 = new XMLStreamReader2JSON(extensionPointRegistry); + JSONObject json = (JSONObject)t1.transform(reader, null); + Assert.assertNotNull(json); + + // Cannot round-trip as we hit a bug in Jettison: http://jira.codehaus.org/browse/JETTISON-93 + /* + JSON2XMLStreamReader t2 = new JSON2XMLStreamReader(); + XMLStreamReader reader2 = t2.transform(json, null); + StringWriter sw = new StringWriter(); + XMLStreamWriter streamWriter = staxHelper.createXMLStreamWriter(sw); + staxHelper.save(reader2, streamWriter); + streamWriter.flush(); + System.out.println(sw.toString()); + */ + + } + + @Test + public void testJSON2XML() throws Exception { + ExtensionPointRegistry extensionPointRegistry = new DefaultExtensionPointRegistry(); + StAXHelper helper = StAXHelper.getInstance(extensionPointRegistry); + + JSON2XMLStreamReader t2 = new JSON2XMLStreamReader(); + XMLStreamReader reader2 = t2.transform(new JSONObject(JSON_STR), null); + StringWriter sw = new StringWriter(); + XMLStreamWriter streamWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(sw); + helper.save(reader2, streamWriter); + Assert.assertTrue(sw.toString() + .contains("<xsl:root xmlns:xsl=\"http://foo.com\"><data>my json string</data></xsl:root>")); + } + + @Test + public void testJSON2OMElement() throws Exception { + JSON2OMElement t1 = new JSON2OMElement(); + TransformationContext context = new TransformationContextImpl(); + DataType dt = new DataTypeImpl(Object.class, new XMLType(new QName("http://foo.com", "root"), null)); + context.setTargetDataType(dt); + OMElement element = t1.transform(new JSONObject(JSON_STR), context); + StringWriter writer = new StringWriter(); + element.serialize(writer); + // System.out.println(writer.toString()); + } + + @Test + public void testString2JSON() throws Exception { + String json = "{\"name\":\"John\",\"age\":25}"; + String2JSON t1 = new String2JSON(); + JSONObject jsonObject = (JSONObject)t1.transform(json, null); + Assert.assertEquals(jsonObject.getString("name"), "John"); + Assert.assertEquals(jsonObject.getInt("age"), 25); + JSON2String t2 = new JSON2String(); + String str = t2.transform(jsonObject, null); + Assert.assertTrue(str.contains("\"name\":\"John\"")); + Assert.assertTrue(str.contains("\"age\":25")); + } +} diff --git a/sandbox/sebastien/java/wrapped/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/JavaBean2JSONTestCase.java b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/JavaBean2JSONTestCase.java new file mode 100644 index 0000000000..9ec9f21d7e --- /dev/null +++ b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/JavaBean2JSONTestCase.java @@ -0,0 +1,179 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.databinding.json; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.Assert; + +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.impl.TransformationContextImpl; +import org.apache.tuscany.sca.interfacedef.impl.DataTypeImpl; +import org.json.JSONObject; +import org.junit.Test; + +/** + * @version $Rev$ $Date$ + */ +public class JavaBean2JSONTestCase { + + public static class MyBean { + private String name; + private int age; + private boolean vip; + private String friends[]; + private List<String> books; + private YourBean you; + private String note; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public boolean isVip() { + return vip; + } + + public void setVip(boolean vip) { + this.vip = vip; + } + + public String[] getFriends() { + return friends; + } + + public void setFriends(String[] friends) { + this.friends = friends; + } + + public List<String> getBooks() { + return books; + } + + public void setBooks(List<String> books) { + this.books = books; + } + + public YourBean getYou() { + return you; + } + + public void setYou(YourBean you) { + this.you = you; + } + + public String getNote() { + return note; + } + + public void setNote(String note) { + this.note = note; + } + + } + + public static class YourBean { + private int id; + private String name; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + } + + @Test + public void testBean2JSON() throws Exception { + MyBean me = new MyBean(); + me.setAge(30); + me.setBooks(new ArrayList<String>()); + me.setFriends(new String[] {"John", "Mike"}); + me.setVip(true); + me.setName("Me"); + YourBean you = new YourBean(); + you.setId(123); + you.setName(null); + me.setYou(you); + JavaBean2JSON t1 = new JavaBean2JSON(); + Object result = t1.transform(me, null); + System.out.println(result); + JSON2JavaBean t2 = new JSON2JavaBean(); + TransformationContext context = new TransformationContextImpl(); + context.setTargetDataType(new DataTypeImpl(MyBean.class, null)); + Object v = t2.transform(new JSONObject(result.toString()), context); + Assert.assertTrue(v instanceof MyBean); + // String json = + // "{\"age\":30,\"books\":[],\"friends\":[\"John\",\"Mike\"],\"name\":\"Me\",\"vip\":true,\"you\":{\"id\":123,\"name\":null}}"; + // Assert.assertEquals(json, result.toString()); + } + + @Test + public void testString2JSON() throws Exception { + JavaBean2JSONObject t1 = new JavaBean2JSONObject(); + Object result = t1.transform("ABC", null); + System.out.println(result); + JSON2JavaBean t2 = new JSON2JavaBean(); + TransformationContext context = new TransformationContextImpl(); + context.setTargetDataType(new DataTypeImpl(String.class, null)); + Object v = t2.transform(result, context); + Assert.assertTrue(v instanceof String); + Assert.assertEquals("ABC", v); + } + + @Test + public void testStringArray2JSON() throws Exception { + JavaBean2JSON t1 = new JavaBean2JSON(); + Object result = t1.transform(new String[] {"ABC", "DF"}, null); + System.out.println(result); + JSON2JavaBean t2 = new JSON2JavaBean(); + TransformationContext context = new TransformationContextImpl(); + context.setTargetDataType(new DataTypeImpl(String[].class, null)); + Object v = t2.transform(result, context); + Assert.assertTrue(v instanceof String[]); + String[] strs = (String[])v; + Assert.assertEquals("ABC", strs[0]); + Assert.assertEquals("DF", strs[1]); + } + +} diff --git a/sandbox/sebastien/java/wrapped/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/MyBean.java b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/MyBean.java new file mode 100644 index 0000000000..60b293c1d4 --- /dev/null +++ b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/MyBean.java @@ -0,0 +1,158 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.databinding.json; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class MyBean { + private int age; + private String name; + private float[] rates = new float[] {1.0f, 2.0f}; + private List<String> notes = new ArrayList<String>(); + private Map<String, Integer> map = new HashMap<String, Integer>(); + private Object service; + private Object otherService; + private boolean good; + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List<String> getNotes() { + return notes; + } + + public void setNotes(List<String> notes) { + this.notes = notes; + } + + public float[] getRates() { + return rates; + } + + public void setRates(float[] rates) { + this.rates = rates; + } + + public Map<String, Integer> getMap() { + return map; + } + + public void setMap(Map<String, Integer> map) { + this.map = map; + } + + public Object getService() { + return service; + } + + public void setService(Object service) { + this.service = service; + } + + public Object getOtherService() { + return otherService; + } + + public void setOtherService(Object otherService) { + this.otherService = otherService; + } + + public boolean isGood() { + return good; + } + + public void setGood(boolean good) { + this.good = good; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + age; + result = prime * result + (good ? 1231 : 1237); + result = prime * result + ((map == null) ? 0 : map.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + ((notes == null) ? 0 : notes.hashCode()); + result = prime * result + ((otherService == null) ? 0 : otherService.hashCode()); + result = prime * result + Arrays.hashCode(rates); + result = prime * result + ((service == null) ? 0 : service.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final MyBean other = (MyBean)obj; + if (age != other.age) + return false; + if (good != other.good) + return false; + if (map == null) { + if (other.map != null) + return false; + } else if (!map.equals(other.map)) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + if (notes == null) { + if (other.notes != null) + return false; + } else if (!notes.equals(other.notes)) + return false; + if (otherService == null) { + if (other.otherService != null) + return false; + } else if (!otherService.equals(other.otherService)) + return false; + if (!Arrays.equals(rates, other.rates)) + return false; + if (service == null) { + if (other.service != null) + return false; + } else if (!service.equals(other.service)) + return false; + return true; + } +} diff --git a/sandbox/sebastien/java/wrapped/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/MyInterface.java b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/MyInterface.java new file mode 100644 index 0000000000..d32e0763c7 --- /dev/null +++ b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/MyInterface.java @@ -0,0 +1,29 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.databinding.json; + +/** + * @version $Rev$ $Date$ + */ +public interface MyInterface { + void setId(String id); + + String getId(); +} diff --git a/sandbox/sebastien/java/wrapped/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/MyInterfaceImpl.java b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/MyInterfaceImpl.java new file mode 100644 index 0000000000..3a2b95a4e2 --- /dev/null +++ b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/MyInterfaceImpl.java @@ -0,0 +1,67 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.databinding.json; + +/** + * @version $Rev$ $Date$ + */ +public class MyInterfaceImpl implements MyInterface { + private String id; + + /** + * @see org.apache.tuscany.databinding.jaxb.MyInterface#getId() + */ + public String getId() { + return id; + } + + /** + * @see org.apache.tuscany.databinding.jaxb.MyInterface#setId(java.lang.String) + */ + public void setId(String id) { + this.id = id; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final MyInterfaceImpl other = (MyInterfaceImpl)obj; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + return true; + } + +} diff --git a/sandbox/sebastien/java/wrapped/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/POJOTestCase.java b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/POJOTestCase.java new file mode 100644 index 0000000000..fd0557d0a2 --- /dev/null +++ b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/POJOTestCase.java @@ -0,0 +1,92 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.databinding.json; + +import java.lang.reflect.Array; + +import junit.framework.Assert; + +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.impl.TransformationContextImpl; +import org.apache.tuscany.sca.interfacedef.impl.DataTypeImpl; +import org.junit.Test; + +public class POJOTestCase { + public void testPOJO() throws Exception { + MyBean bean = new MyBean(); + bean.setName("Test"); + bean.setAge(20); + bean.getNotes().add("1"); + bean.getNotes().add("2"); + bean.getMap().put("1", 1); + MyInterface service = new MyInterfaceImpl(); + service.setId("ID001"); + bean.setService(service); + bean.setOtherService(service); + + roundTrip(bean); + } + + private <T> void roundTrip(T bean) { + JavaBean2JSON t1 = new JavaBean2JSON(); + + Object json = t1.transform(bean, null); + System.out.println(json); + JSON2JavaBean t2 = new JSON2JavaBean(); + + TransformationContext context = new TransformationContextImpl(); + context.setTargetDataType(new DataTypeImpl(bean == null ? Object.class : bean.getClass(), null)); + Object newBean = t2.transform(json, context); + + if (newBean != null && newBean.getClass().isArray()) { + int len = Array.getLength(newBean); + Assert.assertEquals(Array.getLength(bean), len); + for (int i = 0; i < len; i++) { + Assert.assertEquals(Array.get(bean, i), Array.get(newBean, i)); + } + return; + } + Assert.assertEquals(bean, newBean); + } + + @Test + public void testString() throws Exception { + roundTrip("ABC"); + } + + @Test + public void testNull() throws Exception { + roundTrip(null); + } + + @Test + public void testArray() throws Exception { + roundTrip(new String[] {"123", "ABC"}); + } + + @Test + public void testByteArray() throws Exception { + roundTrip("ABC".getBytes()); + } + + @Test + public void testPrimitive() throws Exception { + roundTrip(123); + } +} diff --git a/sandbox/sebastien/java/wrapped/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/jackson/JacksonTestCase.java b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/jackson/JacksonTestCase.java new file mode 100644 index 0000000000..5254ca7742 --- /dev/null +++ b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/jackson/JacksonTestCase.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.json.jackson; + +import java.lang.reflect.Array; + +import junit.framework.Assert; + +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.impl.TransformationContextImpl; +import org.apache.tuscany.sca.databinding.json.MyBean; +import org.apache.tuscany.sca.databinding.json.MyInterface; +import org.apache.tuscany.sca.databinding.json.MyInterfaceImpl; +import org.apache.tuscany.sca.interfacedef.impl.DataTypeImpl; +import org.junit.Test; + +public class JacksonTestCase { + public void testPOJO() throws Exception { + MyBean bean = new MyBean(); + bean.setName("Test"); + bean.setAge(20); + bean.getNotes().add("1"); + bean.getNotes().add("2"); + bean.getMap().put("1", 1); + MyInterface service = new MyInterfaceImpl(); + service.setId("ID001"); + bean.setService(service); + bean.setOtherService(service); + + roundTrip(bean); + } + + private <T> void roundTrip(T bean) { + Object2JSON t1 = new Object2JSON(); + + Object json = t1.transform(bean, null); + System.out.println(json); + JSON2Object t2 = new JSON2Object(); + + TransformationContext context = new TransformationContextImpl(); + context.setTargetDataType(new DataTypeImpl(bean == null ? Object.class : bean.getClass(), null)); + Object newBean = t2.transform(json, context); + + if (newBean != null && newBean.getClass().isArray()) { + int len = Array.getLength(newBean); + Assert.assertEquals(Array.getLength(bean), len); + for (int i = 0; i < len; i++) { + Assert.assertEquals(Array.get(bean, i), Array.get(newBean, i)); + } + return; + } + Assert.assertEquals(bean, newBean); + } + + @Test + public void testString() throws Exception { + roundTrip("ABC"); + } + + @Test + public void testNull() throws Exception { + roundTrip(null); + } + + @Test + public void testArray() throws Exception { + roundTrip(new String[] {"123", "ABC"}); + } + + @Test + public void testByteArray() throws Exception { + roundTrip("ABC".getBytes()); + } + + @Test + public void testPrimitive() throws Exception { + roundTrip(123); + } +} diff --git a/sandbox/sebastien/java/wrapped/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/jackson/Object2JSONTestCase.java b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/jackson/Object2JSONTestCase.java new file mode 100644 index 0000000000..b401e7012d --- /dev/null +++ b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/test/java/org/apache/tuscany/sca/databinding/json/jackson/Object2JSONTestCase.java @@ -0,0 +1,169 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.databinding.json.jackson; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.Assert; + +import org.apache.tuscany.sca.databinding.TransformationContext; +import org.apache.tuscany.sca.databinding.impl.TransformationContextImpl; +import org.apache.tuscany.sca.interfacedef.impl.DataTypeImpl; +import org.junit.Test; + +/** + * @version $Rev$ $Date$ + */ +public class Object2JSONTestCase { + + public static class MyBean { + private String name; + private int age; + private boolean vip; + private String friends[]; + private List<String> books; + private YourBean you; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public boolean isVip() { + return vip; + } + + public void setVip(boolean vip) { + this.vip = vip; + } + + public String[] getFriends() { + return friends; + } + + public void setFriends(String[] friends) { + this.friends = friends; + } + + public List<String> getBooks() { + return books; + } + + public void setBooks(List<String> books) { + this.books = books; + } + + public YourBean getYou() { + return you; + } + + public void setYou(YourBean you) { + this.you = you; + } + + } + + public static class YourBean { + private int id; + private String name; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + } + + @Test + public void testBean2JSON() throws Exception { + MyBean me = new MyBean(); + me.setAge(30); + me.setBooks(new ArrayList<String>()); + me.setFriends(new String[] {"John", "Mike"}); + me.setVip(true); + me.setName("Me"); + YourBean you = new YourBean(); + you.setId(123); + you.setName(null); + me.setYou(you); + Object2JSON t1 = new Object2JSON(); + Object result = t1.transform(me, null); + System.out.println(result); + JSON2Object t2 = new JSON2Object(); + TransformationContext context = new TransformationContextImpl(); + context.setTargetDataType(new DataTypeImpl(MyBean.class, null)); + Object v = t2.transform(result.toString(), context); + Assert.assertTrue(v instanceof MyBean); + // String json = + // "{\"age\":30,\"books\":[],\"friends\":[\"John\",\"Mike\"],\"name\":\"Me\",\"vip\":true,\"you\":{\"id\":123,\"name\":null}}"; + // Assert.assertEquals(json, result.toString()); + } + + @Test + public void testString2JSON() throws Exception { + Object2JSON t1 = new Object2JSON(); + Object result = t1.transform("ABC", null); + System.out.println(result); + JSON2Object t2 = new JSON2Object(); + TransformationContext context = new TransformationContextImpl(); + context.setTargetDataType(new DataTypeImpl(String.class, null)); + Object v = t2.transform(result, context); + Assert.assertTrue(v instanceof String); + Assert.assertEquals("ABC", v); + } + + @Test + public void testStringArray2JSON() throws Exception { + Object2JSON t1 = new Object2JSON(); + Object result = t1.transform(new String[] {"ABC", "DF"}, null); + System.out.println(result); + JSON2Object t2 = new JSON2Object(); + TransformationContext context = new TransformationContextImpl(); + context.setTargetDataType(new DataTypeImpl(String[].class, null)); + Object v = t2.transform(result, context); + Assert.assertTrue(v instanceof String[]); + String[] strs = (String[])v; + Assert.assertEquals("ABC", strs[0]); + Assert.assertEquals("DF", strs[1]); + } + +} diff --git a/sandbox/sebastien/java/wrapped/modules/databinding-json/src/test/resources/ipo.xsd b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/test/resources/ipo.xsd new file mode 100644 index 0000000000..5a493e1746 --- /dev/null +++ b/sandbox/sebastien/java/wrapped/modules/databinding-json/src/test/resources/ipo.xsd @@ -0,0 +1,136 @@ +<!-- + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. +--> +<schema targetNamespace="http://www.example.com/IPO" + xmlns="http://www.w3.org/2001/XMLSchema" + xmlns:ipo="http://www.example.com/IPO"> + + <annotation> + <documentation xml:lang="en"> + International Purchase order schema for Example.com + Copyright 2000 Example.com. All rights reserved. + </documentation> + </annotation> + + + <element name="purchaseOrder" type="ipo:PurchaseOrderType" /> + + <element name="comment" type="string" /> + + <complexType name="PurchaseOrderType"> + <sequence> + <element name="shipTo" type="ipo:Address" /> + <element name="billTo" type="ipo:Address" /> + <element ref="ipo:comment" minOccurs="0" /> + <element name="items" type="ipo:Items" /> + </sequence> + <attribute name="orderDate" type="date" /> + </complexType> + + <complexType name="Items"> + <sequence> + <element name="item" minOccurs="0" maxOccurs="unbounded"> + <complexType> + <sequence> + <element name="productName" type="string" /> + <element name="quantity"> + <simpleType> + <restriction base="positiveInteger"> + <maxExclusive value="100" /> + </restriction> + </simpleType> + </element> + <element name="USPrice" type="decimal" /> + <element ref="ipo:comment" minOccurs="0" /> + <element name="shipDate" type="date" + minOccurs="0" /> + </sequence> + <attribute name="partNum" type="ipo:SKU" + use="required" /> + </complexType> + </element> + </sequence> + </complexType> + + <simpleType name="SKU"> + <restriction base="string"> + <pattern value="\d{3}-[A-Z]{2}" /> + </restriction> + </simpleType> + + <complexType name="Address"> + <sequence> + <element name="name" type="string" /> + <element name="street" type="string" /> + <element name="city" type="string" /> + </sequence> + </complexType> + + <complexType name="USAddress"> + <complexContent> + <extension base="ipo:Address"> + <sequence> + <element name="state" type="ipo:USState" /> + <element name="zip" type="positiveInteger" /> + </sequence> + </extension> + </complexContent> + </complexType> + + <complexType name="UKAddress"> + <complexContent> + <extension base="ipo:Address"> + <sequence> + <element name="postcode" type="ipo:UKPostcode" /> + </sequence> + <attribute name="exportCode" type="positiveInteger" + fixed="1" /> + </extension> + </complexContent> + </complexType> + + <!-- other Address derivations for more countries --> + + <simpleType name="USState"> + <restriction base="string"> + <enumeration value="AK" /> + <enumeration value="AL" /> + <enumeration value="AR" /> + <enumeration value="CA" /> + <enumeration value="PA" /> + <!-- and so on ... --> + </restriction> + </simpleType> + + <simpleType name="Postcode"> + <restriction base="string"> + <length value="7" fixed="true" /> + </restriction> + </simpleType> + + + <simpleType name="UKPostcode"> + <restriction base="ipo:Postcode"> + <pattern value="[A-Z]{2}\d\s\d[A-Z]{2}" /> + </restriction> + </simpleType> + + + +</schema> + |