Search in sources :

Example 11 with XmlWriter

use of nl.nn.adapterframework.xml.XmlWriter in project iaf by ibissource.

the class MatchUtils method xmlPretty.

public static String xmlPretty(String xml, boolean removeNamespaces) {
    XmlWriter xmlWriter = new XmlWriter();
    xmlWriter.setIncludeComments(false);
    ContentHandler contentHandler = new PrettyPrintFilter(xmlWriter);
    if (removeNamespaces) {
        contentHandler = new NamespaceRemovingFilter(contentHandler);
    }
    try {
        XmlUtils.parseXml(xml, contentHandler);
        return xmlWriter.toString();
    } catch (IOException | SAXException e) {
        throw new RuntimeException("ERROR: could not prettify [" + xml + "]", e);
    }
}
Also used : IOException(java.io.IOException) XmlWriter(nl.nn.adapterframework.xml.XmlWriter) ContentHandler(org.xml.sax.ContentHandler) PrettyPrintFilter(nl.nn.adapterframework.xml.PrettyPrintFilter) NamespaceRemovingFilter(nl.nn.adapterframework.xml.NamespaceRemovingFilter) SAXException(org.xml.sax.SAXException)

Example 12 with XmlWriter

use of nl.nn.adapterframework.xml.XmlWriter in project iaf by ibissource.

the class XsltExceptionTest method testXsltException.

public void testXsltException(boolean expectChildThreads, int tailCount) throws Exception {
    String xpathExpression = "*/*";
    int xsltVersion = 1;
    TransformerPool tp = TransformerPool.configureTransformer0(null, null, null, xpathExpression, null, OutputType.XML, false, null, xsltVersion);
    XmlWriter writer = new XmlWriter();
    FullXmlFilter filter = new FullXmlFilter(writer) {

        @Override
        public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
            if (localName.equals("error")) {
                throw new SaxException("Found error");
            }
            super.startElement(uri, localName, qName, atts);
        }
    };
    try (ThreadConnector threadConnector = expectChildThreads ? new ThreadConnector(null, null, null, (PipeLineSession) null) : null) {
        TransformerFilter transformer = tp.getTransformerFilter(threadConnector, filter);
        try {
            try (SaxDocumentBuilder seb = new SaxDocumentBuilder("root", transformer)) {
                seb.addElement("elem");
                seb.addElement("error");
                for (int i = 0; i < tailCount; i++) {
                    seb.addElement("elem");
                }
            }
            fail("Expected exception to be caught while processing");
        } catch (Exception e) {
            System.out.println("Expected exception: " + e.getMessage());
        }
        System.out.println(writer);
    }
}
Also used : FullXmlFilter(nl.nn.adapterframework.xml.FullXmlFilter) TransformerFilter(nl.nn.adapterframework.xml.TransformerFilter) Attributes(org.xml.sax.Attributes) ThreadConnector(nl.nn.adapterframework.stream.ThreadConnector) SaxDocumentBuilder(nl.nn.adapterframework.xml.SaxDocumentBuilder) PipeLineSession(nl.nn.adapterframework.core.PipeLineSession) SaxException(nl.nn.adapterframework.xml.SaxException) TransformerPool(nl.nn.adapterframework.util.TransformerPool) XmlWriter(nl.nn.adapterframework.xml.XmlWriter) SaxException(nl.nn.adapterframework.xml.SaxException) SAXException(org.xml.sax.SAXException)

Example 13 with XmlWriter

use of nl.nn.adapterframework.xml.XmlWriter in project iaf by ibissource.

the class ConfigurationDigester method parseAndResolveEntitiesAndProperties.

/**
 * Performs an Identity-transform, which resolves entities with content from files found on the ClassPath.
 * Resolve all non-attribute properties
 */
public void parseAndResolveEntitiesAndProperties(ContentHandler digester, Configuration configuration, Resource resource, Properties appConstants) throws IOException, SAXException, TransformerConfigurationException {
    ContentHandler handler;
    XmlWriter loadedHiddenWriter = new XmlWriter();
    handler = new PrettyPrintFilter(loadedHiddenWriter);
    handler = new AttributePropertyResolver(handler, appConstants, getPropsToHide(appConstants));
    handler = new XmlTee(digester, handler);
    handler = getStub4TesttoolContentHandler(handler, appConstants);
    handler = getConfigurationCanonicalizer(handler);
    handler = new OnlyActiveFilter(handler, appConstants);
    handler = new ElementPropertyResolver(handler, appConstants);
    XmlWriter originalConfigWriter = new XmlWriter();
    handler = new XmlTee(handler, originalConfigWriter);
    XmlUtils.parseXml(resource, handler);
    configuration.setOriginalConfiguration(originalConfigWriter.toString());
    configuration.setLoadedConfiguration(loadedHiddenWriter.toString());
}
Also used : XmlTee(nl.nn.adapterframework.stream.xml.XmlTee) AttributePropertyResolver(nl.nn.adapterframework.xml.AttributePropertyResolver) ElementPropertyResolver(nl.nn.adapterframework.xml.ElementPropertyResolver) OnlyActiveFilter(nl.nn.adapterframework.configuration.filters.OnlyActiveFilter) ContentHandler(org.xml.sax.ContentHandler) XmlWriter(nl.nn.adapterframework.xml.XmlWriter) PrettyPrintFilter(nl.nn.adapterframework.xml.PrettyPrintFilter)

Example 14 with XmlWriter

use of nl.nn.adapterframework.xml.XmlWriter in project iaf by ibissource.

the class Json2XmlValidator method alignJson.

protected PipeRunResult alignJson(String messageToValidate, PipeLineSession session, boolean responseMode) throws PipeRunException, XmlValidatorException {
    ValidationContext context;
    ValidatorHandler validatorHandler;
    try {
        context = validator.createValidationContext(session, getJsonRootValidations(responseMode), getInvalidRootNamespaces());
        validatorHandler = validator.getValidatorHandler(session, context);
    } catch (ConfigurationException e) {
        throw new PipeRunException(this, "Cannot create ValidationContext", e);
    }
    String resultEvent;
    String out = null;
    try {
        Json2Xml aligner = new Json2Xml(validatorHandler, context.getXsModels(), isCompactJsonArrays(), getMessageRoot(responseMode), isStrictJsonArraySyntax());
        if (StringUtils.isNotEmpty(getTargetNamespace())) {
            aligner.setTargetNamespace(getTargetNamespace());
        }
        aligner.setDeepSearch(isDeepSearch());
        aligner.setErrorHandler(context.getErrorHandler());
        aligner.setFailOnWildcards(isFailOnWildcards());
        aligner.setIgnoreUndeclaredElements(isIgnoreUndeclaredElements());
        ParameterList parameterList = getParameterList();
        if (parameterList != null) {
            Map<String, Object> parametervalues = null;
            parametervalues = parameterList.getValues(new Message(messageToValidate), session).getValueMap();
            // remove parameters with null values, to support optional request parameters
            for (Iterator<String> it = parametervalues.keySet().iterator(); it.hasNext(); ) {
                String key = it.next();
                if (parametervalues.get(key) == null) {
                    it.remove();
                }
            }
            aligner.setOverrideValues(parametervalues);
        }
        JsonStructure jsonStructure = Json.createReader(new StringReader(messageToValidate)).read();
        // cannot build filter chain as usual backwardly, because it ends differently.
        // This will be fixed once an OutputStream can be provided to Xml2Json
        XMLFilterImpl sourceFilter = aligner;
        if (StringUtils.isNotEmpty(getRootElementSessionKey())) {
            XMLFilterImpl storeRootFilter = new RootElementToSessionKeyFilter(session, getRootElementSessionKey(), getRootNamespaceSessionKey(), null);
            aligner.setContentHandler(storeRootFilter);
            sourceFilter = storeRootFilter;
        }
        if (getOutputFormat(session, responseMode) == DocumentFormat.JSON) {
            Xml2Json xml2json = new Xml2Json(aligner, isCompactJsonArrays(), !isJsonWithRootElements());
            sourceFilter.setContentHandler(xml2json);
            aligner.startParse(jsonStructure);
            out = xml2json.toString();
        } else {
            XmlWriter xmlWriter = new XmlWriter();
            xmlWriter.setIncludeXmlDeclaration(true);
            ContentHandler handler = xmlWriter;
            if (isProduceNamespaceLessXml()) {
                handler = new NamespaceRemovingFilter(handler);
            }
            sourceFilter.setContentHandler(handler);
            aligner.startParse(jsonStructure);
            out = xmlWriter.toString();
        }
    } catch (Exception e) {
        resultEvent = validator.finalizeValidation(context, session, e);
    }
    resultEvent = validator.finalizeValidation(context, session, null);
    PipeForward forward = determineForward(resultEvent, session, responseMode);
    PipeRunResult result = new PipeRunResult(forward, out);
    return result;
}
Also used : RootElementToSessionKeyFilter(nl.nn.adapterframework.xml.RootElementToSessionKeyFilter) ValidatorHandler(javax.xml.validation.ValidatorHandler) Message(nl.nn.adapterframework.stream.Message) PipeForward(nl.nn.adapterframework.core.PipeForward) ContentHandler(org.xml.sax.ContentHandler) PipeRunException(nl.nn.adapterframework.core.PipeRunException) IOException(java.io.IOException) ConfigurationException(nl.nn.adapterframework.configuration.ConfigurationException) XmlValidatorException(nl.nn.adapterframework.validation.XmlValidatorException) ValidationContext(nl.nn.adapterframework.validation.ValidationContext) NamespaceRemovingFilter(nl.nn.adapterframework.xml.NamespaceRemovingFilter) PipeRunResult(nl.nn.adapterframework.core.PipeRunResult) ConfigurationException(nl.nn.adapterframework.configuration.ConfigurationException) XMLFilterImpl(org.xml.sax.helpers.XMLFilterImpl) PipeRunException(nl.nn.adapterframework.core.PipeRunException) StringReader(java.io.StringReader) ParameterList(nl.nn.adapterframework.parameters.ParameterList) JsonObject(javax.json.JsonObject) Xml2Json(nl.nn.adapterframework.align.Xml2Json) Json2Xml(nl.nn.adapterframework.align.Json2Xml) XmlWriter(nl.nn.adapterframework.xml.XmlWriter) JsonStructure(javax.json.JsonStructure)

Example 15 with XmlWriter

use of nl.nn.adapterframework.xml.XmlWriter in project iaf by ibissource.

the class XsltSender method createHandler.

protected ContentHandler createHandler(Message input, ThreadConnector threadConnector, PipeLineSession session, MessageOutputStream target) throws StreamingException {
    ContentHandler handler = null;
    try {
        ParameterValueList pvl = null;
        if (paramList != null) {
            pvl = paramList.getValues(input, session);
        }
        TransformerPool poolToUse = transformerPool;
        if (StringUtils.isNotEmpty(styleSheetNameSessionKey)) {
            Message styleSheetNameToUse = session.getMessage(styleSheetNameSessionKey);
            if (!Message.isEmpty(styleSheetNameToUse)) {
                String styleSheetNameFromSessionKey = styleSheetNameToUse.asString();
                if (!dynamicTransformerPoolMap.containsKey(styleSheetNameFromSessionKey)) {
                    dynamicTransformerPoolMap.put(styleSheetNameFromSessionKey, poolToUse = TransformerPool.configureTransformer(getLogPrefix(), this, null, null, styleSheetNameFromSessionKey, null, true, getParameterList()));
                    poolToUse.open();
                } else {
                    poolToUse = dynamicTransformerPoolMap.get(styleSheetNameFromSessionKey);
                }
            }
            if (poolToUse == null) {
                throw new SenderException("no XSLT stylesheet found from styleSheetNameSessionKey [" + styleSheetNameSessionKey + "], and neither one statically configured");
            }
        }
        OutputType outputType = getOutputType();
        if (log.isTraceEnabled())
            log.trace("Configured outputmethod [" + outputType + "]");
        if (outputType == null) {
            String parsedOutputType = poolToUse.getOutputMethod();
            if (StringUtils.isNotEmpty(parsedOutputType)) {
                outputType = EnumUtils.parse(OutputType.class, parsedOutputType);
            }
            if (log.isTraceEnabled())
                log.trace("Detected outputmethod [" + parsedOutputType + "]");
        }
        if (outputType == null) {
            outputType = DEFAULT_OUTPUT_METHOD;
            if (log.isTraceEnabled())
                log.trace("Default outputmethod [" + outputType + "]");
        }
        Object targetStream = target.asNative();
        Boolean indentXml = getIndentXml();
        if (log.isTraceEnabled())
            log.trace("Configured indentXml [" + indentXml + "]");
        if (indentXml == null) {
            indentXml = poolToUse.getIndent();
            if (log.isTraceEnabled())
                log.trace("Detected indentXml [" + indentXml + "]");
        }
        if (indentXml == null) {
            indentXml = DEFAULT_INDENT;
            if (log.isTraceEnabled())
                log.trace("Default indentXml [" + indentXml + "]");
        }
        Boolean omitXmlDeclaration = getOmitXmlDeclaration();
        if (targetStream instanceof ContentHandler) {
            handler = (ContentHandler) targetStream;
        } else {
            XmlWriter xmlWriter = new XmlWriter(target.asWriter());
            if (log.isTraceEnabled())
                log.trace("Configured omitXmlDeclaration [" + omitXmlDeclaration + "]");
            if (outputType == OutputType.XML) {
                if (omitXmlDeclaration == null) {
                    omitXmlDeclaration = poolToUse.getOmitXmlDeclaration();
                    if (log.isTraceEnabled())
                        log.trace("Detected omitXmlDeclaration [" + omitXmlDeclaration + "]");
                    if (omitXmlDeclaration == null) {
                        omitXmlDeclaration = DEFAULT_OMIT_XML_DECLARATION;
                        if (log.isTraceEnabled())
                            log.trace("Default omitXmlDeclaration [" + omitXmlDeclaration + "]");
                    }
                }
                xmlWriter.setIncludeXmlDeclaration(!omitXmlDeclaration);
                if (indentXml) {
                    xmlWriter.setNewlineAfterXmlDeclaration(true);
                }
            } else {
                xmlWriter.setTextMode(true);
            }
            handler = xmlWriter;
        }
        if (indentXml) {
            handler = new PrettyPrintFilter(handler);
        }
        if (isSkipEmptyTags()) {
            handler = new SkipEmptyTagsFilter(handler);
        }
        TransformerFilter mainFilter = poolToUse.getTransformerFilter(threadConnector, handler);
        if (pvl != null) {
            XmlUtils.setTransformerParameters(mainFilter.getTransformer(), pvl.getValueMap());
        }
        handler = filterInput(mainFilter, session);
        return handler;
    } catch (Exception e) {
        // log.warn(getLogPrefix()+"intermediate exception logging",e);
        throw new StreamingException(getLogPrefix() + "Exception on creating transformerHandler chain", e);
    }
}
Also used : TransformerFilter(nl.nn.adapterframework.xml.TransformerFilter) StreamingException(nl.nn.adapterframework.stream.StreamingException) ParameterValueList(nl.nn.adapterframework.parameters.ParameterValueList) Message(nl.nn.adapterframework.stream.Message) ContentHandler(org.xml.sax.ContentHandler) TransformerPool(nl.nn.adapterframework.util.TransformerPool) StreamingException(nl.nn.adapterframework.stream.StreamingException) ConfigurationException(nl.nn.adapterframework.configuration.ConfigurationException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException) SenderException(nl.nn.adapterframework.core.SenderException) SkipEmptyTagsFilter(nl.nn.adapterframework.xml.SkipEmptyTagsFilter) SenderException(nl.nn.adapterframework.core.SenderException) XmlWriter(nl.nn.adapterframework.xml.XmlWriter) OutputType(nl.nn.adapterframework.util.TransformerPool.OutputType) PrettyPrintFilter(nl.nn.adapterframework.xml.PrettyPrintFilter)

Aggregations

XmlWriter (nl.nn.adapterframework.xml.XmlWriter)33 Test (org.junit.Test)15 PrettyPrintFilter (nl.nn.adapterframework.xml.PrettyPrintFilter)11 ContentHandler (org.xml.sax.ContentHandler)11 SAXException (org.xml.sax.SAXException)9 Resource (nl.nn.adapterframework.core.Resource)7 IOException (java.io.IOException)6 StringWriter (java.io.StringWriter)6 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 Writer (java.io.Writer)4 XmlTee (nl.nn.adapterframework.stream.xml.XmlTee)4 OutputStream (java.io.OutputStream)3 OutputStreamWriter (java.io.OutputStreamWriter)3 URL (java.net.URL)3 ValidatorHandler (javax.xml.validation.ValidatorHandler)3 ConfigurationDigester (nl.nn.adapterframework.configuration.ConfigurationDigester)3 Message (nl.nn.adapterframework.stream.Message)3 JsonWriter (nl.nn.adapterframework.stream.json.JsonWriter)3 WriterOutputStream (org.apache.commons.io.output.WriterOutputStream)3 Properties (java.util.Properties)2