Search in sources :

Example 16 with JsonStructure

use of javax.json.JsonStructure in project iaf by ibissource.

the class XmlTypeToJsonSchemaConverter method handleElementDeclaration.

private void handleElementDeclaration(JsonObjectBuilder builder, XSElementDeclaration elementDeclaration, boolean multiOccurring, boolean shouldCreateReferences) {
    String elementName = elementDeclaration.getName();
    // if (log.isTraceEnabled()) log.trace("XSElementDeclaration name ["+elementName+"]");
    if (log.isTraceEnabled())
        log.trace("XSElementDeclaration element [" + elementName + "][" + ToStringBuilder.reflectionToString(elementDeclaration, ToStringStyle.MULTI_LINE_STYLE) + "]");
    XSTypeDefinition elementTypeDefinition = elementDeclaration.getTypeDefinition();
    JsonStructure definition;
    if (elementTypeDefinition.getAnonymous() || XML_SCHEMA_NS.equals(elementTypeDefinition.getNamespace())) {
        definition = getDefinition(elementTypeDefinition, shouldCreateReferences);
    } else {
        definition = Json.createObjectBuilder().add("$ref", definitionsPath + elementTypeDefinition.getName()).build();
    }
    if (elementDeclaration.getNillable()) {
        definition = nillable(definition);
    }
    if (multiOccurring) {
        JsonObjectBuilder arrayBuilder = Json.createObjectBuilder();
        arrayBuilder.add("type", "array");
        arrayBuilder.add("items", definition);
        builder.add(elementName, arrayBuilder.build());
    } else {
        if (definition != null) {
            builder.add(elementName, definition);
        }
    }
}
Also used : XSTypeDefinition(org.apache.xerces.xs.XSTypeDefinition) JsonObjectBuilder(javax.json.JsonObjectBuilder) JsonStructure(javax.json.JsonStructure)

Example 17 with JsonStructure

use of javax.json.JsonStructure in project iaf by ibissource.

the class TestXml2Json method testXml2Json.

public void testXml2Json(String schemaFile, String xml, String rootElement, boolean compactArrays, boolean skipJsonRootElements, boolean expectValidRoundTrip, String expectedFailureReason) throws Exception {
    URL schemaUrl = getSchemaURL(schemaFile);
    String xmlString = getTestFile(xml + ".xml");
    boolean expectValid = expectedFailureReason == null;
    // check the validity of the input XML
    if (expectValid) {
        assertEquals("valid XML", expectValid, Utils.validate(schemaUrl, xmlString));
    }
    System.out.println("input xml:" + xmlString);
    JsonStructure json;
    String jsonOut;
    try {
        jsonOut = Xml2Json.translate(xmlString, schemaUrl, compactArrays, skipJsonRootElements).toString(true);
        System.out.println("result compactArrays [" + compactArrays + "] skipJsonRootElements [" + skipJsonRootElements + "] json:\n" + jsonOut);
        if (!expectValid) {
            fail("expected to fail with reason [" + expectedFailureReason + "]");
        }
        json = Utils.string2Json(jsonOut);
    } catch (Exception e) {
        if (expectValid) {
            e.printStackTrace();
            System.out.println("exception compactArrays [" + compactArrays + "] skipJsonRootElements [" + skipJsonRootElements + "]");
            fail(e.getMessage());
        }
        return;
    }
    if (expectValidRoundTrip) {
        String backToXml1 = Json2Xml.translate(json, schemaUrl, compactArrays, skipJsonRootElements ? rootElement : null, null);
        // System.out.println("back to xml compactArrays ["+compactArrays+"] xml:\n" +backToXml1);
        String backToXml2 = Json2Xml.translate(json, schemaUrl, !compactArrays, skipJsonRootElements ? rootElement : null, null);
        // System.out.println("back to xml compactArrays ["+!compactArrays+"] xml:\n" +backToXml2);
        String jsonCompactExpected = getTestFile(xml + "-compact.json");
        String jsonFullExpected = getTestFile(xml + "-full.json");
        if (jsonCompactExpected != null && compactArrays && skipJsonRootElements) {
            assertEquals(jsonCompactExpected, jsonOut);
        }
        if (jsonFullExpected != null && !compactArrays && !skipJsonRootElements) {
            assertEquals(jsonFullExpected, jsonOut);
        }
    }
// 
// // setup the chain
// XMLReader parser = new SAXParser();
// ValidatorHandler validator = schema.newValidatorHandler();
// XmlAligner aligner = new XmlAligner(validator);
// Xml2Json xml2json = new Xml2Json(aligner, false);
// 
// parser.setContentHandler(validator);
// aligner.setContentHandler(xml2json);
// 
// System.out.println();
// System.out.println("start aligning "+xml);
// 
// InputSource is = new InputSource(new StringReader(xmlString));
// try {
// parser.parse(is);
// String jsonOut=xml2json.toString();
// System.out.println("jsonOut="+jsonOut);
// if (!expectValid) {
// fail("expected to fail");
// }
// } catch (Exception e) {
// if (expectValid) {
// e.printStackTrace();
// fail(e.getMessage());
// }
// }
// 
// assertTrue("valid aligned XML", Utils.validate(namespace, xsdUri, dom)); // only if dom  itself is modified...
// 
// testXmlAligner(instance, dom.getDocumentElement(), namespace, xsdUri);
// JSONObject json=Utils.xml2Json(xmlString);
// System.out.println("JSON:"+json);
// String jsonString = json.toString();
// 
// jsonString=jsonString.replaceAll(",\"xmlns\":\"[^\"]*\"", "");
// System.out.println("JSON with fixed xmlns:"+jsonString);
// 
// String xmlFromJson = Utils.json2Xml(Utils.string2Json(jsonString));
// if (StringUtils.isNotEmpty(namespace)) {
// xmlFromJson=xmlFromJson.replaceFirst(">", " xmlns=\""+namespace+"\">");
// }
// System.out.println("start aligning xml from json "+xmlFromJson);
// Document domFromJson = Utils.string2Dom(xmlFromJson);
// instance.startParse(domFromJson.getDocumentElement());
}
Also used : URL(java.net.URL) JsonStructure(javax.json.JsonStructure)

Example 18 with JsonStructure

use of javax.json.JsonStructure in project iaf by ibissource.

the class TestXmlSchema2JsonSchema method testXml2JsonSchema.

public void testXml2JsonSchema(String schemaFile, String namespace, String xml, String rootElement, boolean compactArrays, boolean skipJsonRootElements, boolean expectValidRoundTrip, String expectedFailureReason) throws Exception {
    URL schemaUrl = getSchemaURL(schemaFile);
    String jsonSchemaFile = schemaFile.replace(".xsd", (skipJsonRootElements ? "-compact-" : "-full-") + rootElement + ".jsd");
    URL jsonSchemaUrl = getSchemaURL(jsonSchemaFile);
    String expectedJsonSchema = jsonSchemaUrl == null ? null : StreamUtil.streamToString(jsonSchemaUrl.openStream(), "\n", "utf-8");
    String xmlString = getTestFile(xml + ".xml");
    String jsonString = getTestFile(xml + (skipJsonRootElements ? "-compact" : "-full") + ".json");
    Json2XmlValidator validator = new Json2XmlValidator();
    validator.registerForward(new PipeForward("success", null));
    validator.setThrowException(true);
    if (StringUtils.isNotEmpty(namespace)) {
        validator.setSchemaLocation(namespace + " " + BASEDIR + schemaFile);
    } else {
        validator.setSchema(BASEDIR + schemaFile);
    }
    validator.setJsonWithRootElements(!skipJsonRootElements);
    validator.setCompactJsonArrays(compactArrays);
    validator.setRoot(rootElement);
    validator.configure();
    validator.start();
    boolean expectValid = expectedFailureReason == null;
    // // check the validity of the input XML
    // if (expectValid) {
    // assertEquals("valid XML", expectValid, Utils.validate(schemaUrl, xmlString));
    // }
    // 
    JsonStructure jsonschema = validator.createJsonSchema(rootElement);
    if (jsonschema == null) {
        fail("no schema generated for [" + rootElement + "]");
    }
    String jsonSchemaContent = Misc.jsonPretty(jsonschema.toString());
    System.out.println("result compactArrays [" + compactArrays + "] skipJsonRootElements [" + skipJsonRootElements + "] json:\n" + jsonSchemaContent);
    if (StringUtils.isEmpty(jsonSchemaContent)) {
        fail("json schema is empty");
    }
    // compare generated schema to reference
    if (compactArrays == skipJsonRootElements) {
        // String schemaPretty = jsonPrettyPrint("{" + jsonSchemaContent + "}");
        // schemaPretty = schemaPretty.substring(1, schemaPretty.length() - 1).trim();
        // System.out.println("expected [" + expectedJsonSchema + "]");
        // System.out.println("actual   [" + jsonSchemaContent + "]");
        assertEquals("generated does not match [" + jsonSchemaFile + "]", expectedJsonSchema, jsonSchemaContent);
    // if (!expectValid) {
    // fail("expected to fail with reason ["+ expectedFailureReason +"]");
    // }
    }
    // validate the json against the generated schema
    if (compactArrays == skipJsonRootElements) {
        if (StringUtils.isNotEmpty(jsonString)) {
            JsonSchemaFactory factory = JsonSchemaFactory.getInstance();
            JsonSchema schema = factory.getSchema(jsonSchemaContent);
            ObjectMapper mapper = new ObjectMapper();
            JsonNode node = mapper.readTree(jsonString);
            Set<ValidationMessage> errors = schema.validate(node);
            System.out.println(jsonString);
            System.out.println(errors);
            assertEquals(errors.toString(), 0, errors.size());
        }
    }
}
Also used : ValidationMessage(com.networknt.schema.ValidationMessage) Json2XmlValidator(nl.nn.adapterframework.pipes.Json2XmlValidator) JsonSchema(com.networknt.schema.JsonSchema) JsonSchemaFactory(com.networknt.schema.JsonSchemaFactory) JsonNode(com.fasterxml.jackson.databind.JsonNode) PipeForward(nl.nn.adapterframework.core.PipeForward) URL(java.net.URL) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) JsonStructure(javax.json.JsonStructure)

Example 19 with JsonStructure

use of javax.json.JsonStructure in project iaf by ibissource.

the class TestJson2Xml method testJson.

public void testJson(String jsonIn, Map<String, Object> properties, boolean deepSearch, URL schemaUrl, String targetNamespace, String rootElement, boolean compactConversion, boolean strictSyntax, String resultJsonExpected, String expectedFailureReason, String description) throws Exception {
    Object json = Utils.string2Json(jsonIn);
    try {
        JsonStructure jsonStructure = Json.createReader(new StringReader(jsonIn)).read();
        String xmlAct = Json2Xml.translate(jsonStructure, schemaUrl, compactConversion, rootElement, strictSyntax, deepSearch, targetNamespace, properties);
        System.out.println("xml out=" + xmlAct);
        if (expectedFailureReason != null) {
            fail("Expected to fail: " + description);
        }
        if (xmlAct == null) {
            fail("could not convert to xml: " + description);
        }
        assertTrue("converted XML is not aligned: " + description, Utils.validate(schemaUrl, xmlAct));
        if (resultJsonExpected != null) {
            String roundTrippedJson = Xml2Json.translate(xmlAct, schemaUrl, compactConversion, rootElement != null).toString(true);
            assertEquals("roundTrippedJson", resultJsonExpected, roundTrippedJson);
        }
    } catch (Exception e) {
        if (expectedFailureReason == null) {
            e.printStackTrace();
            fail("Expected conversion to succeed: " + description);
        }
        String msg = e.getMessage();
        if (msg == null) {
            e.printStackTrace();
            fail("msg==null (" + e.getClass().getSimpleName() + ")");
        }
        if (!msg.contains(expectedFailureReason)) {
            e.printStackTrace();
            fail("expected reason [" + expectedFailureReason + "] in msg [" + msg + "]");
        }
    }
}
Also used : StringReader(java.io.StringReader) JsonObject(javax.json.JsonObject) JsonStructure(javax.json.JsonStructure)

Example 20 with JsonStructure

use of javax.json.JsonStructure in project iaf by ibissource.

the class TestJson2Xml method testStrings.

public void testStrings(String xmlIn, String jsonIn, URL schemaUrl, String targetNamespace, String rootElement, boolean compactInput, boolean potentialCompactionProblems, boolean checkRoundTrip, String expectedFailureReason) throws Exception {
    System.out.println("schemaUrl [" + schemaUrl + "]");
    if (StringUtils.isNotEmpty(xmlIn))
        assertTrue("Expected XML is not valid to XSD", Utils.validate(schemaUrl, xmlIn));
    JsonStructure json = Utils.string2Json(jsonIn);
    System.out.println("jsonIn [" + json + "]");
    Map<String, Object> overrideMap = new HashMap<String, Object>();
    overrideMap.put("Key not expected", "value of unexpected key");
    if (json instanceof JsonObject) {
        JsonObject jo = (JsonObject) json;
        for (String key : jo.keySet()) {
            if (overrideMap.containsKey(key)) {
                System.out.println("multiple occurrences in object for element [" + key + "]");
            }
            overrideMap.put(key, null);
        }
    }
    testJson(jsonIn, null, false, schemaUrl, targetNamespace, rootElement, compactInput, false, checkRoundTrip ? jsonIn : null, expectedFailureReason, "(compact in and conversion) [" + compactInput + "], relaxed");
    testJson(jsonIn, null, false, schemaUrl, targetNamespace, rootElement, compactInput, true, checkRoundTrip ? jsonIn : null, expectedFailureReason, "(compact in and conversion) [" + compactInput + "], strict");
    testJson(jsonIn, overrideMap, false, schemaUrl, targetNamespace, rootElement, compactInput, false, checkRoundTrip ? jsonIn : null, expectedFailureReason, "(compact in and conversion) [" + compactInput + "], relaxed, parameters");
    testJson(jsonIn, overrideMap, false, schemaUrl, targetNamespace, rootElement, compactInput, true, checkRoundTrip ? jsonIn : null, expectedFailureReason, "(compact in and conversion) [" + compactInput + "], strict, parameters");
    // testJson(jsonIn, overrideMap, true, schemaUrl, targetNamespace, rootElement, compactInput, true, checkRoundTrip?jsonIn:null,expectedFailureReason,"(compact in and conversion) ["+compactInput+"], strict, parameters");
    if (expectedFailureReason == null) {
        if (potentialCompactionProblems) {
            if (compactInput) {
                testJsonNoRoundTrip(jsonIn, schemaUrl, targetNamespace, rootElement, !compactInput, false, expectedFailureReason, "compact input, full expected, relaxed, potentialCompactionProblems");
                testJson(jsonIn, null, false, schemaUrl, targetNamespace, rootElement, !compactInput, true, checkRoundTrip ? jsonIn : null, Json2Xml.MSG_EXPECTED_SINGLE_ELEMENT, "compact input, full expected, strict, potentialCompactionProblems");
            } else {
                testJsonNoRoundTrip(jsonIn, schemaUrl, targetNamespace, rootElement, !compactInput, false, expectedFailureReason, "full input, compact expected, relaxed, potentialCompactionProblems");
                testJson(jsonIn, null, false, schemaUrl, targetNamespace, rootElement, !compactInput, true, checkRoundTrip ? jsonIn : null, Json2Xml.MSG_FULL_INPUT_IN_STRICT_COMPACTING_MODE, "full input, compact expected, strict, potentialCompactionProblems");
            }
        } else {
            testJson(jsonIn, null, false, schemaUrl, targetNamespace, rootElement, !compactInput, false, checkRoundTrip ? jsonIn : null, expectedFailureReason, "compact in [" + compactInput + "] and conversion not, relaxed, no potentialCompactionProblems");
            testJson(jsonIn, null, false, schemaUrl, targetNamespace, rootElement, !compactInput, true, checkRoundTrip ? jsonIn : null, expectedFailureReason, "compact in [" + compactInput + "] and conversion not, strict, no potentialCompactionProblems");
        }
    }
}
Also used : HashMap(java.util.HashMap) JsonObject(javax.json.JsonObject) JsonObject(javax.json.JsonObject) JsonStructure(javax.json.JsonStructure)

Aggregations

JsonStructure (javax.json.JsonStructure)37 JsonObject (javax.json.JsonObject)14 StringReader (java.io.StringReader)7 JsonObjectBuilder (javax.json.JsonObjectBuilder)5 Test (org.junit.Test)5 StringWriter (java.io.StringWriter)4 URL (java.net.URL)4 JsonArrayBuilder (javax.json.JsonArrayBuilder)4 IOException (java.io.IOException)3 Map (java.util.Map)3 JsonReader (javax.json.JsonReader)3 JsonString (javax.json.JsonString)3 PipeForward (nl.nn.adapterframework.core.PipeForward)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 HashMap (java.util.HashMap)2 List (java.util.List)2 JsonArray (javax.json.JsonArray)2 PipeRunResult (nl.nn.adapterframework.core.PipeRunResult)2 Message (nl.nn.adapterframework.stream.Message)2 JsonNode (com.fasterxml.jackson.databind.JsonNode)1