├── .gitignore ├── Dockerfile ├── LICENSE.md ├── README.md ├── pom.xml ├── release.sh └── src ├── main └── java │ └── com │ └── atomgraph │ └── etl │ └── json │ ├── JSON2XML.java │ └── JsonStreamXMLWriter.java └── test └── java └── com └── atomgraph └── etl └── json └── JsonStreamXMLWriterTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM maven:3.8.4-openjdk-17 2 | 3 | LABEL maintainer="martynas@atomgraph.com" 4 | 5 | COPY . /usr/src/JSON2XML 6 | 7 | WORKDIR /usr/src/JSON2XML 8 | 9 | RUN mvn clean install 10 | 11 | ### entrypoint 12 | 13 | ENTRYPOINT ["java", "-jar", "target/json2xml-jar-with-dependencies.jar"] -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2019 Martynas Jusevičius 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # JSON2XML 2 | Streaming JSON to XML converter 3 | 4 | Reads any JSON data and produces [XML Representation of JSON](https://www.w3.org/TR/xslt-30/#json-to-xml-mapping) specified in XSLT 3.0. 5 | 6 | JSON2XML enables JSON transformation with XSLT even without having an XSLT 3.0 processor. You can simply pre-process the data by having JSON2XML before the transformation, and pipeline it into an XSLT 2.0 stylesheet, for example. That way your stylesheet stays forward compatible with XSLT 3.0, as the XML representation is exactly the same. 7 | 8 | ## Invalid characters 9 | 10 | The JSON input might contain characters (for example, form feed `\f`) which would be invalid in the XML output. The [`json-to-xml()` function](https://www.w3.org/TR/xslt-30/#func-json-to-xml) specifies character escape rules that apply in this case. 11 | 12 | JSON2XML currently implements only the default escape rule: 13 | > Any characters or codepoints that are not valid XML characters (for example, unpaired surrogates) are passed to the fallback function as described below; in the absence of a fallback function, they are replaced by the Unicode `REPLACEMENT CHARACTER (xFFFD)`. 14 | 15 | ## Build 16 | 17 | mvn clean install 18 | 19 | That should produce an executable JAR file `target/json2xml-jar-with-dependencies.jar` in which dependency libraries will be included. 20 | 21 | ## Maven 22 | 23 | Each version is released to the Maven central repository as [`com.atomgraph.etl.json/json2xml`](https://central.sonatype.com/artifact/com.atomgraph.etl.json/json2xml) 24 | 25 | ## Usage 26 | 27 | The JSON data is read from `stdin`, UTF-8 encoding is expected. The resulting XML data is written to `stdout`. 28 | 29 | JSON2XML is available as a `.jar` as well as a Docker image [atomgraph/json2xml](https://hub.docker.com/r/atomgraph/json2xml) (recommended). 30 | 31 | ## Example 32 | 33 | JSON data in `city-distances.json`: 34 | 35 | ```json 36 | { 37 | "desc" : "Distances between several cities, in kilometers.", 38 | "updated" : "2014-02-04T18:50:45", 39 | "uptodate": true, 40 | "author" : null, 41 | "cities" : { 42 | "Brussels": [ 43 | {"to": "London", "distance": 322}, 44 | {"to": "Paris", "distance": 265}, 45 | {"to": "Amsterdam", "distance": 173} 46 | ], 47 | "London": [ 48 | {"to": "Brussels", "distance": 322}, 49 | {"to": "Paris", "distance": 344}, 50 | {"to": "Amsterdam", "distance": 358} 51 | ], 52 | "Paris": [ 53 | {"to": "Brussels", "distance": 265}, 54 | {"to": "London", "distance": 344}, 55 | {"to": "Amsterdam", "distance": 431} 56 | ], 57 | "Amsterdam": [ 58 | {"to": "Brussels", "distance": 173}, 59 | {"to": "London", "distance": 358}, 60 | {"to": "Paris", "distance": 431} 61 | ] 62 | } 63 | } 64 | ``` 65 | 66 | Java execution from shell: 67 | 68 | cat city-distances.json | java -jar json2xml-jar-with-dependencies.jar > city-distances.xml 69 | 70 | Alternatively, Docker execution from shell: 71 | 72 | cat city-distances.json | docker run --rm -i -a stdin -a stdout -a stderr atomgraph/json2xml > city-distances.xml 73 | 74 | Note that you need to [bind](https://docs.docker.com/engine/reference/commandline/run/#attach-to-stdinstdoutstderr--a) `stdin`/`stdout`/`stderr` when running JSON2XML as a Docker container. 75 | 76 | Output in `city-distances.xml` (indented for clarity): 77 | 78 | ```xml 79 | 80 | 81 | Distances between several cities, in kilometers. 82 | 2014-02-04T18:50:45 83 | true 84 | 85 | 86 | 87 | 88 | London 89 | 322 90 | 91 | 92 | Paris 93 | 265 94 | 95 | 96 | Amsterdam 97 | 173 98 | 99 | 100 | 101 | 102 | Brussels 103 | 322 104 | 105 | 106 | Paris 107 | 344 108 | 109 | 110 | Amsterdam 111 | 358 112 | 113 | 114 | 115 | 116 | Brussels 117 | 265 118 | 119 | 120 | London 121 | 344 122 | 123 | 124 | Amsterdam 125 | 431 126 | 127 | 128 | 129 | 130 | Brussels 131 | 173 132 | 133 | 134 | London 135 | 358 136 | 137 | 138 | Paris 139 | 431 140 | 141 | 142 | 143 | 144 | ``` 145 | 146 | ## Dependencies 147 | 148 | * [javax.json](https://mvnrepository.com/artifact/org.glassfish/javax.json) 149 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | 5 | com.atomgraph.etl.json 6 | json2xml 7 | 1.0.8-SNAPSHOT 8 | jar 9 | 10 | JSON2XML 11 | Streaming JSON converter to XSLT 3.0 XML representation 12 | https://github.com/AtomGraph/JSON2XML 13 | 2019 14 | 15 | 16 | 17 | namedgraph 18 | martynas@atomgraph.com 19 | 20 | Developer 21 | Founder 22 | 23 | AtomGraph 24 | https://atomgraph.com 25 | 26 | 27 | 28 | 29 | 30 | Apache License 2.0 31 | http://www.apache.org/licenses/LICENSE-2.0.html 32 | repo 33 | 34 | 35 | 36 | 37 | https://github.com/AtomGraph/JSON2XML 38 | scm:git:git://github.com/AtomGraph/JSON2XML.git 39 | scm:git:git@github.com:AtomGraph/JSON2XML.git 40 | HEAD 41 | 42 | 43 | 44 | UTF-8 45 | apache20 46 | 17 47 | 17 48 | 49 | 50 | 51 | 52 | javax.json 53 | javax.json-api 54 | 1.1.4 55 | 56 | 57 | org.glassfish 58 | javax.json 59 | 1.1.4 60 | 61 | 62 | junit 63 | junit 64 | 4.13.1 65 | test 66 | 67 | 68 | 69 | 70 | 71 | ossrh 72 | https://oss.sonatype.org/content/repositories/snapshots 73 | 74 | 75 | 76 | 77 | json2xml 78 | 79 | 80 | org.apache.maven.plugins 81 | maven-assembly-plugin 82 | 83 | 84 | create-my-bundle 85 | package 86 | 87 | single 88 | 89 | 90 | 91 | jar-with-dependencies 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | true 100 | com.atomgraph.etl.json.JSON2XML 101 | 102 | 103 | 104 | 105 | 106 | org.apache.maven.plugins 107 | maven-release-plugin 108 | 2.5.3 109 | 110 | release 111 | 112 | 113 | 114 | org.sonatype.plugins 115 | nexus-staging-maven-plugin 116 | 1.6.12 117 | true 118 | 119 | ossrh 120 | https://oss.sonatype.org/ 121 | true 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | release 130 | 131 | jar 132 | 133 | 134 | 135 | 136 | org.apache.maven.plugins 137 | maven-source-plugin 138 | 3.1.0 139 | 140 | 141 | attach-sources 142 | 143 | jar-no-fork 144 | 145 | 146 | 147 | 148 | 149 | org.apache.maven.plugins 150 | maven-gpg-plugin 151 | 1.6 152 | 153 | 154 | sign-artifacts 155 | verify 156 | 157 | sign 158 | 159 | 160 | 161 | 162 | --pinentry-mode 163 | loopback 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | -------------------------------------------------------------------------------- /release.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | mvn release:clean release:prepare 4 | 5 | mvn release:perform -------------------------------------------------------------------------------- /src/main/java/com/atomgraph/etl/json/JSON2XML.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Martynas Jusevičius . 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.atomgraph.etl.json; 17 | 18 | import java.io.BufferedReader; 19 | import java.io.BufferedWriter; 20 | import java.io.IOException; 21 | import java.io.InputStream; 22 | import java.io.InputStreamReader; 23 | import java.io.OutputStreamWriter; 24 | import java.io.Reader; 25 | import java.nio.charset.StandardCharsets; 26 | import javax.xml.stream.XMLStreamException; 27 | 28 | /** 29 | * Main entry point to the conversion. 30 | * 31 | * @author Martynas Jusevičius {@literal } 32 | */ 33 | public class JSON2XML 34 | { 35 | 36 | public static void main(String[] args) throws IOException, XMLStreamException 37 | { 38 | InputStream json = System.in; 39 | 40 | if (json.available() == 0) 41 | { 42 | System.err.println("JSON input: stdin"); 43 | System.err.println("Example: cat sample.json | java -jar json2xml-jar-with-dependencies.jar > sample.xml"); 44 | System.exit(1); 45 | } 46 | 47 | try (Reader reader = new BufferedReader(new InputStreamReader(json, StandardCharsets.UTF_8))) 48 | { 49 | new JsonStreamXMLWriter(reader, new BufferedWriter(new OutputStreamWriter(System.out, StandardCharsets.UTF_8))). 50 | convert(StandardCharsets.UTF_8.name(), "1.0"); 51 | } 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/atomgraph/etl/json/JsonStreamXMLWriter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Martynas Jusevičius . 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.atomgraph.etl.json; 17 | 18 | import java.io.InputStream; 19 | import java.io.OutputStream; 20 | import java.io.Reader; 21 | import java.io.Writer; 22 | import javax.json.Json; 23 | import javax.json.stream.JsonParser; 24 | import javax.xml.stream.XMLOutputFactory; 25 | import javax.xml.stream.XMLStreamException; 26 | import javax.xml.stream.XMLStreamWriter; 27 | import javax.xml.transform.Result; 28 | 29 | /** 30 | * Converts JSON stream to XML stream. 31 | * Uses XML representation of JSON defined in XSLT 3.0. 32 | * 33 | * @see 22 Processing JSON Data 34 | * @author Martynas Jusevičius {@literal } 35 | */ 36 | public class JsonStreamXMLWriter 37 | { 38 | 39 | /** 40 | * XPath function namespace 41 | **/ 42 | public static final String XPATH_FUNCTIONS_NS = "http://www.w3.org/2005/xpath-functions"; 43 | /** 44 | * Fallback replacement character 45 | * @see json-to-xml 46 | */ 47 | public static final String REPLACEMENT_CHAR = "\uFFFD"; 48 | private static final XMLOutputFactory XOF = XMLOutputFactory.newInstance(); 49 | 50 | static 51 | { 52 | XOF.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true); 53 | } 54 | 55 | private final JsonParser parser; 56 | private final XMLStreamWriter writer; 57 | 58 | public JsonStreamXMLWriter(Reader reader, Writer stream) throws XMLStreamException 59 | { 60 | this(Json.createParser(reader), getXMLOutputFactory().createXMLStreamWriter(stream)); 61 | } 62 | 63 | public JsonStreamXMLWriter(Reader reader, OutputStream stream) throws XMLStreamException 64 | { 65 | this(Json.createParser(reader), getXMLOutputFactory().createXMLStreamWriter(stream)); 66 | } 67 | 68 | public JsonStreamXMLWriter(Reader reader, OutputStream stream, String encoding) throws XMLStreamException 69 | { 70 | this(Json.createParser(reader), getXMLOutputFactory().createXMLStreamWriter(stream, encoding)); 71 | } 72 | 73 | public JsonStreamXMLWriter(Reader reader, Result result) throws XMLStreamException 74 | { 75 | this(Json.createParser(reader), getXMLOutputFactory().createXMLStreamWriter(result)); 76 | } 77 | 78 | public JsonStreamXMLWriter(Reader reader, XMLStreamWriter writer) 79 | { 80 | this(Json.createParser(reader), writer); 81 | } 82 | 83 | public JsonStreamXMLWriter(InputStream is, Writer stream) throws XMLStreamException 84 | { 85 | this(Json.createParser(is), getXMLOutputFactory().createXMLStreamWriter(stream)); 86 | } 87 | 88 | public JsonStreamXMLWriter(InputStream is, OutputStream stream) throws XMLStreamException 89 | { 90 | this(Json.createParser(is), getXMLOutputFactory().createXMLStreamWriter(stream)); 91 | } 92 | 93 | public JsonStreamXMLWriter(InputStream is, OutputStream stream, String encoding) throws XMLStreamException 94 | { 95 | this(Json.createParser(is), getXMLOutputFactory().createXMLStreamWriter(stream, encoding)); 96 | } 97 | 98 | public JsonStreamXMLWriter(InputStream is, Result result) throws XMLStreamException 99 | { 100 | this(Json.createParser(is), getXMLOutputFactory().createXMLStreamWriter(result)); 101 | } 102 | 103 | public JsonStreamXMLWriter(InputStream is, XMLStreamWriter writer) 104 | { 105 | this(Json.createParser(is), writer); 106 | } 107 | 108 | public JsonStreamXMLWriter(JsonParser parser, Writer stream) throws XMLStreamException 109 | { 110 | this(parser, getXMLOutputFactory().createXMLStreamWriter(stream)); 111 | } 112 | 113 | public JsonStreamXMLWriter(JsonParser parser, OutputStream stream) throws XMLStreamException 114 | { 115 | this(parser, getXMLOutputFactory().createXMLStreamWriter(stream)); 116 | } 117 | 118 | public JsonStreamXMLWriter(JsonParser parser, OutputStream stream, String encoding) throws XMLStreamException 119 | { 120 | this(parser, getXMLOutputFactory().createXMLStreamWriter(stream, encoding)); 121 | } 122 | 123 | public JsonStreamXMLWriter(JsonParser parser, Result result) throws XMLStreamException 124 | { 125 | this(parser, getXMLOutputFactory().createXMLStreamWriter(result)); 126 | } 127 | 128 | public JsonStreamXMLWriter(JsonParser parser, XMLStreamWriter writer) 129 | { 130 | this.parser = parser; 131 | this.writer = writer; 132 | } 133 | 134 | public void convert(String encoding, String version) throws XMLStreamException 135 | { 136 | convert(getWriter(), encoding, version); 137 | } 138 | 139 | public void convert(XMLStreamWriter writer, String encoding, String version) throws XMLStreamException 140 | { 141 | convert(getParser(), writer, encoding, version); 142 | } 143 | 144 | public static void convert(JsonParser parser, XMLStreamWriter writer, String encoding, String version) throws XMLStreamException 145 | { 146 | try (parser) 147 | { 148 | writer.writeStartDocument(encoding, version); 149 | writer.setDefaultNamespace(XPATH_FUNCTIONS_NS); 150 | 151 | write(parser, writer); 152 | 153 | writer.writeEndDocument(); 154 | writer.flush(); 155 | } 156 | } 157 | 158 | /** 159 | * Parses JSON and writes XML into a stream. 160 | * 161 | * @param parser JSON parser 162 | * @param writer XML writer stream 163 | * @throws XMLStreamException 164 | */ 165 | public static void write(JsonParser parser, XMLStreamWriter writer) throws XMLStreamException 166 | { 167 | String keyName = null; 168 | while (parser.hasNext()) 169 | { 170 | JsonParser.Event event = parser.next(); 171 | 172 | switch(event) 173 | { 174 | case START_ARRAY -> { 175 | writer.writeStartElement(XPATH_FUNCTIONS_NS, "array"); 176 | if (keyName != null) 177 | { 178 | writer.writeAttribute("key", keyName); 179 | keyName = null; 180 | } 181 | } 182 | case END_ARRAY -> writer.writeEndElement(); 183 | case START_OBJECT -> { 184 | writer.writeStartElement(XPATH_FUNCTIONS_NS, "map"); 185 | if (keyName != null) 186 | { 187 | writer.writeAttribute("key", keyName); 188 | keyName = null; 189 | } 190 | } 191 | case END_OBJECT -> writer.writeEndElement(); 192 | case VALUE_FALSE -> { 193 | writer.writeStartElement(XPATH_FUNCTIONS_NS, "boolean"); 194 | if (keyName != null) 195 | { 196 | writer.writeAttribute("key", keyName); 197 | keyName = null; 198 | } 199 | writer.writeCharacters("false"); 200 | writer.writeEndElement(); 201 | } 202 | case VALUE_TRUE -> { 203 | writer.writeStartElement(XPATH_FUNCTIONS_NS, "boolean"); 204 | if (keyName != null) 205 | { 206 | writer.writeAttribute("key", keyName); 207 | keyName = null; 208 | } 209 | writer.writeCharacters("true"); 210 | writer.writeEndElement(); 211 | } 212 | case KEY_NAME -> keyName = replaceInvalidXMLChars(parser.getString(), REPLACEMENT_CHAR); 213 | case VALUE_STRING -> { 214 | writer.writeStartElement(XPATH_FUNCTIONS_NS, "string"); 215 | if (keyName != null) 216 | { 217 | writer.writeAttribute("key", keyName); 218 | keyName = null; 219 | } 220 | writer.writeCharacters(replaceInvalidXMLChars(parser.getString(), REPLACEMENT_CHAR)); 221 | writer.writeEndElement(); 222 | } 223 | case VALUE_NUMBER -> { 224 | writer.writeStartElement(XPATH_FUNCTIONS_NS, "number"); 225 | if (keyName != null) 226 | { 227 | writer.writeAttribute("key", keyName); 228 | keyName = null; 229 | } 230 | writer.writeCharacters(replaceInvalidXMLChars(parser.getString(), REPLACEMENT_CHAR)); 231 | writer.writeEndElement(); 232 | } 233 | case VALUE_NULL -> { 234 | writer.writeEmptyElement(XPATH_FUNCTIONS_NS, "null"); 235 | if (keyName != null) 236 | { 237 | writer.writeAttribute("key", keyName); 238 | keyName = null; 239 | } 240 | } 241 | } 242 | 243 | writer.flush(); 244 | } 245 | } 246 | 247 | public static String replaceInvalidXMLChars(String text, String replacement) 248 | { 249 | if (null == text || text.isEmpty()) return text; 250 | 251 | final int len = text.length(); 252 | char current = 0; 253 | int codePoint = 0; 254 | StringBuilder sb = new StringBuilder(); 255 | for (int i = 0; i < len; i++) 256 | { 257 | current = text.charAt(i); 258 | boolean surrogate = false; 259 | if (Character.isHighSurrogate(current) 260 | && i + 1 < len && Character.isLowSurrogate(text.charAt(i + 1))) 261 | { 262 | surrogate = true; 263 | codePoint = text.codePointAt(i++); 264 | } 265 | else codePoint = current; 266 | 267 | if ((codePoint == 0x9) || (codePoint == 0xA) || (codePoint == 0xD) 268 | || ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) 269 | || ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) 270 | || ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF))) 271 | { 272 | sb.append(current); 273 | if (surrogate) sb.append(text.charAt(i)); 274 | } 275 | else 276 | sb.append(replacement); 277 | } 278 | 279 | return sb.toString(); 280 | } 281 | 282 | protected JsonParser getParser() 283 | { 284 | return parser; 285 | } 286 | 287 | protected XMLStreamWriter getWriter() 288 | { 289 | return writer; 290 | } 291 | 292 | protected static XMLOutputFactory getXMLOutputFactory() 293 | { 294 | return XOF; 295 | } 296 | 297 | } 298 | -------------------------------------------------------------------------------- /src/test/java/com/atomgraph/etl/json/JsonStreamXMLWriterTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 Martynas Jusevičius . 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.atomgraph.etl.json; 17 | 18 | import java.io.BufferedReader; 19 | import java.io.BufferedWriter; 20 | import java.io.ByteArrayInputStream; 21 | import java.io.ByteArrayOutputStream; 22 | import java.io.IOException; 23 | import java.io.InputStream; 24 | import java.io.InputStreamReader; 25 | import java.io.OutputStreamWriter; 26 | import java.io.Reader; 27 | import java.nio.charset.StandardCharsets; 28 | import javax.xml.stream.XMLStreamException; 29 | import static org.junit.Assert.assertTrue; 30 | import org.junit.Test; 31 | 32 | /** 33 | * 34 | * @author Martynas Jusevičius 35 | */ 36 | public class JsonStreamXMLWriterTest 37 | { 38 | 39 | @Test 40 | public void testJsonKeyWithInvalidXMLChar() throws IOException, XMLStreamException 41 | { 42 | String jsonString = "{ \"a\\fb\": \"c\" }"; // form feed in the key (invalid in XML 1.0, valid in XML 1.1) 43 | InputStream json = new ByteArrayInputStream(jsonString.getBytes(StandardCharsets.UTF_8)); 44 | ByteArrayOutputStream xml = new ByteArrayOutputStream(); 45 | 46 | try (Reader reader = new BufferedReader(new InputStreamReader(json, StandardCharsets.UTF_8))) 47 | { 48 | new JsonStreamXMLWriter(reader, new BufferedWriter(new OutputStreamWriter(xml, StandardCharsets.UTF_8))). 49 | convert(StandardCharsets.UTF_8.name(), "1.0"); 50 | String xmlString = xml.toString(StandardCharsets.UTF_8.name()); 51 | assertTrue(xmlString.contains(JsonStreamXMLWriter.REPLACEMENT_CHAR)); // 52 | } 53 | } 54 | 55 | @Test 56 | public void testJsonValueWithInvalidXMLChar() throws IOException, XMLStreamException 57 | { 58 | String jsonString = "{ \"a\": \"b\\fc\" }"; // form feed in the value (invalid in XML 1.0, valid in XML 1.1) 59 | InputStream json = new ByteArrayInputStream(jsonString.getBytes(StandardCharsets.UTF_8)); 60 | ByteArrayOutputStream xml = new ByteArrayOutputStream(); 61 | 62 | try (Reader reader = new BufferedReader(new InputStreamReader(json, StandardCharsets.UTF_8))) 63 | { 64 | new JsonStreamXMLWriter(reader, new BufferedWriter(new OutputStreamWriter(xml, StandardCharsets.UTF_8))). 65 | convert(StandardCharsets.UTF_8.name(), "1.0"); 66 | String xmlString = xml.toString(StandardCharsets.UTF_8.name()); 67 | assertTrue(xmlString.contains(JsonStreamXMLWriter.REPLACEMENT_CHAR)); // form feed has been replaced 68 | } 69 | } 70 | 71 | } 72 | --------------------------------------------------------------------------------