Search in sources :

Example 21 with Templates

use of javax.xml.transform.Templates in project wso2-synapse by wso2.

the class XSLTMediator method createTemplate.

/**
 * Create a XSLT template object and assign it to the cachedTemplates variable
 * @param synCtx current message
 * @param synLog logger to use
 * @param generatedXsltKey evaluated xslt key(real key value) for dynamic or static key
 * @return cached template
 */
private Templates createTemplate(MessageContext synCtx, SynapseLog synLog, String generatedXsltKey) {
    // Assign created template
    Templates cachedTemplates = null;
    // Set an error listener (SYNAPSE-307).
    transFact.setErrorListener(new ErrorListenerImpl(synLog, STYLESHEET_PARSING_ACTIVITY));
    // Allow xsl:import and xsl:include resolution
    transFact.setURIResolver(new CustomJAXPURIResolver(resourceMap, synCtx.getConfiguration()));
    try {
        cachedTemplates = transFact.newTemplates(SynapseConfigUtils.getStreamSource(synCtx.getEntry(generatedXsltKey)));
        if (cachedTemplates == null) {
            // if cached template creation failed
            handleException("Error compiling the XSLT with key : " + xsltKey, synCtx);
        } else {
            if (useCache) {
                // if cached template is created then put it in to cachedTemplatesMap
                cachedTemplatesMap.put(generatedXsltKey, cachedTemplates);
            }
        }
    } catch (Exception e) {
        handleException("Error creating XSLT transformer using : " + xsltKey, e, synCtx);
    }
    return cachedTemplates;
}
Also used : Templates(javax.xml.transform.Templates) CustomJAXPURIResolver(org.apache.synapse.util.resolver.CustomJAXPURIResolver) TransformerException(javax.xml.transform.TransformerException) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) SynapseException(org.apache.synapse.SynapseException)

Example 22 with Templates

use of javax.xml.transform.Templates in project wso2-synapse by wso2.

the class XSLTMediator method performXSLT.

/**
 * Perform actual XSLT transformation
 * @param synCtx current message
 * @param synLog the logger to be used
 */
private void performXSLT(MessageContext synCtx, SynapseLog synLog) {
    OMNode sourceNode = source.selectOMNode(synCtx, synLog);
    boolean isSoapEnvelope = (sourceNode == synCtx.getEnvelope());
    boolean isSoapBody = (sourceNode == synCtx.getEnvelope().getBody());
    boolean isSoapHeader = (sourceNode == synCtx.getEnvelope().getHeader());
    // Derive actual key from message context
    String generatedXsltKey = xsltKey.evaluateValue(synCtx);
    // get templates from generatedXsltKey
    Templates cachedTemplates = null;
    if (synLog.isTraceTraceEnabled()) {
        synLog.traceTrace("Transformation source : " + sourceNode.toString());
    }
    // determine if it is needed to create or create the template
    if (isCreationOrRecreationRequired(synCtx)) {
        // many threads can see this and come here for acquiring the lock
        synchronized (transformerLock) {
            // only first thread should create the template
            if (isCreationOrRecreationRequired(synCtx)) {
                cachedTemplates = createTemplate(synCtx, synLog, generatedXsltKey);
            } else {
                cachedTemplates = cachedTemplatesMap.get(generatedXsltKey);
            }
        }
    } else {
        // If already cached template then load it from cachedTemplatesMap
        synchronized (transformerLock) {
            cachedTemplates = cachedTemplatesMap.get(generatedXsltKey);
        }
    }
    try {
        // perform transformation
        Transformer transformer = null;
        try {
            transformer = cachedTemplates.newTransformer();
        } catch (NullPointerException ex) {
            handleException("Unable to create Transformer using cached template", ex, synCtx);
        }
        if (!properties.isEmpty()) {
            // set the parameters which will pass to the Transformation
            applyProperties(transformer, synCtx, synLog);
        }
        transformer.setErrorListener(new ErrorListenerImpl(synLog, XSLT_TRANSFORMATION_ACTIVITY));
        String outputMethod = transformer.getOutputProperty(OutputKeys.METHOD);
        String encoding = transformer.getOutputProperty(OutputKeys.ENCODING);
        if (synLog.isTraceOrDebugEnabled()) {
            synLog.traceOrDebug("output method: " + outputMethod + "; encoding: " + encoding);
        }
        ResultBuilderFactory.Output output;
        if ("text".equals(outputMethod)) {
            synLog.traceOrDebug("Processing non SOAP/XML (text) transformation result");
            output = ResultBuilderFactory.Output.TEXT;
        } else if (isSoapEnvelope) {
            output = ResultBuilderFactory.Output.SOAP_ENVELOPE;
        } else {
            output = ResultBuilderFactory.Output.ELEMENT;
        }
        SynapseEnvironment synEnv = synCtx.getEnvironment();
        ResultBuilder resultBuilder = resultBuilderFactory.createResultBuilder(synEnv, output);
        SourceBuilder sourceBuilder = sourceBuilderFactory.createSourceBuilder(synEnv);
        if (synLog.isTraceOrDebugEnabled()) {
            synLog.traceOrDebug("Using " + sourceBuilder.getClass().getName());
            synLog.traceOrDebug("Using " + resultBuilder.getClass().getName());
        }
        try {
            transformer.transform(sourceBuilder.getSource((OMElement) sourceNode), resultBuilder.getResult());
        } finally {
            sourceBuilder.release();
        }
        synLog.traceOrDebug("Transformation completed - processing result");
        /**
         * If user have set transform.xslt.result.disableBuild property to true, we do not build the message to
         * OMElement,
         */
        if (targetPropertyName != null && resultBuilder instanceof StreamResultBuilder && synCtx.getProperty(TRANSFORM_XSLT_RESULT_DISABLE_BUILD) != null && synCtx.getProperty(TRANSFORM_XSLT_RESULT_DISABLE_BUILD) instanceof String && "true".equalsIgnoreCase((String) synCtx.getProperty(TRANSFORM_XSLT_RESULT_DISABLE_BUILD))) {
            // add result XML string as a message context property to the message
            if (synLog.isTraceOrDebugEnabled()) {
                synLog.traceOrDebug("Adding result string as message context property : " + targetPropertyName);
            }
            synCtx.setProperty(targetPropertyName, ((StreamResultBuilder) resultBuilder).getResultAsString());
            return;
        }
        // get the result OMElement
        OMElement result = null;
        try {
            result = resultBuilder.getNode(encoding == null ? null : Charset.forName(encoding));
        } catch (Exception e) {
            throw new SynapseException("Unable to create an OMElement using XSLT result ", e);
        }
        if (synLog.isTraceTraceEnabled()) {
            synLog.traceTrace("Transformation result : " + result.toString());
        }
        if (targetPropertyName != null) {
            // add result XML as a message context property to the message
            if (synLog.isTraceOrDebugEnabled()) {
                synLog.traceOrDebug("Adding result as message context property : " + targetPropertyName);
            }
            synCtx.setProperty(targetPropertyName, result);
        } else {
            if (synLog.isTraceOrDebugEnabled()) {
                synLog.traceOrDebug("Replace " + (isSoapEnvelope ? "SOAP envelope" : isSoapBody ? "SOAP body" : "node") + " with result");
            }
            if (isSoapEnvelope) {
                try {
                    synCtx.setEnvelope((SOAPEnvelope) result);
                } catch (AxisFault ex) {
                    handleException("Unable to replace SOAP envelope with result", ex, synCtx);
                }
            } else if (isSoapBody) {
                for (Iterator itr = synCtx.getEnvelope().getBody().getChildElements(); itr.hasNext(); ) {
                    OMElement child = (OMElement) itr.next();
                    child.detach();
                }
                for (Iterator itr = result.getChildElements(); itr.hasNext(); ) {
                    OMElement child = (OMElement) itr.next();
                    synCtx.getEnvelope().getBody().addChild(child);
                }
            } else if (isSoapHeader) {
                for (Iterator itr = synCtx.getEnvelope().getHeader().getChildElements(); itr.hasNext(); ) {
                    OMElement child = (OMElement) itr.next();
                    child.detach();
                }
                for (Iterator itr = result.getChildElements(); itr.hasNext(); ) {
                    OMElement child = (OMElement) itr.next();
                    synCtx.getEnvelope().getHeader().addChild(child);
                }
            } else {
                sourceNode.insertSiblingAfter(result);
                sourceNode.detach();
            }
        }
    } catch (TransformerException e) {
        handleException("Error performing XSLT transformation using : " + xsltKey, e, synCtx);
    }
}
Also used : AxisFault(org.apache.axis2.AxisFault) ResultBuilder(org.apache.synapse.util.jaxp.ResultBuilder) StreamResultBuilder(org.apache.synapse.util.jaxp.StreamResultBuilder) Transformer(javax.xml.transform.Transformer) StreamResultBuilder(org.apache.synapse.util.jaxp.StreamResultBuilder) SynapseException(org.apache.synapse.SynapseException) SynapseEnvironment(org.apache.synapse.core.SynapseEnvironment) SourceBuilder(org.apache.synapse.util.jaxp.SourceBuilder) Templates(javax.xml.transform.Templates) OMElement(org.apache.axiom.om.OMElement) TransformerException(javax.xml.transform.TransformerException) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) SynapseException(org.apache.synapse.SynapseException) OMNode(org.apache.axiom.om.OMNode) Iterator(java.util.Iterator) StreamResultBuilderFactory(org.apache.synapse.util.jaxp.StreamResultBuilderFactory) DOOMResultBuilderFactory(org.apache.synapse.util.jaxp.DOOMResultBuilderFactory) ResultBuilderFactory(org.apache.synapse.util.jaxp.ResultBuilderFactory) TransformerException(javax.xml.transform.TransformerException)

Example 23 with Templates

use of javax.xml.transform.Templates in project jvarkit by lindenb.

the class VcfEnsemblVepRest method doWork.

@Override
public int doWork(final List<String> args) {
    try {
        this.outputTags.addAll(Arrays.stream(this.tagListString.split("[, \t;]+")).filter(S -> !StringUtil.isBlank(S)).collect(Collectors.toSet()));
        for (final String tag : this.outputTags) {
            if (!tag.matches("[A-Za-z][A-Za-z0-9_]*")) {
                LOG.error("Bad tag name " + tag);
                return -1;
            }
        }
        if (this.outputTags.isEmpty()) {
            LOG.error("no output tag defined");
            return -1;
        }
        final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        this.documentBuilder = dbf.newDocumentBuilder();
        final TransformerFactory trf = TransformerFactory.newInstance();
        final Source stylesheetSource;
        if (this.xslTemplateFile != null) {
            stylesheetSource = new StreamSource(this.xslTemplateFile);
        } else {
            stylesheetSource = new StreamSource(new StringReader(DEFAULT_XSLT_TEMPLATE));
        }
        final Templates templates = trf.newTemplates(stylesheetSource);
        this.xsltTransformer = templates.newTransformer();
        /**
         * create http client
         */
        // createDefault();
        this.httpClient = HttpClients.createSystem();
        return doVcfToVcf(args, this.outputFile);
    } catch (final Exception err) {
        LOG.error(err);
        return -1;
    } finally {
        CloserUtil.close(this.httpClient);
        this.httpClient = null;
    }
}
Also used : DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) TransformerFactory(javax.xml.transform.TransformerFactory) StreamSource(javax.xml.transform.stream.StreamSource) StringReader(java.io.StringReader) Templates(javax.xml.transform.Templates) DOMSource(javax.xml.transform.dom.DOMSource) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) TransformerException(javax.xml.transform.TransformerException) RuntimeIOException(htsjdk.samtools.util.RuntimeIOException) IOException(java.io.IOException)

Example 24 with Templates

use of javax.xml.transform.Templates in project jvarkit by lindenb.

the class XsltStream method doWork.

@Override
public int doWork(final List<String> args) {
    if (this.targetQnames.isEmpty()) {
        LOG.error("No target name defined");
        return -1;
    }
    XMLEventReader xmlReader = null;
    OutputStream outputStream = null;
    try {
        final String inputSource = oneFileOrNull(args);
        final TransformerFactory transformerFactory = TransformerFactory.newInstance();
        final Templates template = transformerFactory.newTemplates(new StreamSource(this.templateFile));
        final Transformer transformer = template.newTransformer();
        outputStream = openFileOrStdoutAsStream(this.outputFile);
        final XMLInputFactory xif = XMLInputFactory.newFactory();
        xmlReader = (inputSource == null ? xif.createXMLEventReader(stdin()) : xif.createXMLEventReader(new StreamSource(new File(inputSource))));
        final Document dom = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        while (xmlReader.hasNext()) {
            final XMLEvent evt = xmlReader.nextEvent();
            if (!evt.isStartElement()) {
                continue;
            }
            final StartElement SE = evt.asStartElement();
            if (!this.targetQnames.contains(SE.getName())) {
                continue;
            }
            dom.appendChild(parseDocument(dom, SE, xmlReader));
            transformer.transform(new DOMSource(dom), new StreamResult(outputStream));
            while (dom.hasChildNodes()) dom.removeChild(dom.getFirstChild());
        }
        outputStream.flush();
        outputStream.close();
        outputStream = null;
        xmlReader.close();
        xmlReader = null;
        return 0;
    } catch (final Exception e) {
        LOG.error(e);
        return -1;
    } finally {
        CloserUtil.close(xmlReader);
        CloserUtil.close(outputStream);
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) OutputStream(java.io.OutputStream) StreamSource(javax.xml.transform.stream.StreamSource) Templates(javax.xml.transform.Templates) Document(org.w3c.dom.Document) XMLStreamException(javax.xml.stream.XMLStreamException) StartElement(javax.xml.stream.events.StartElement) XMLEvent(javax.xml.stream.events.XMLEvent) XMLEventReader(javax.xml.stream.XMLEventReader) File(java.io.File) XMLInputFactory(javax.xml.stream.XMLInputFactory)

Example 25 with Templates

use of javax.xml.transform.Templates in project nokogiri by sparklemotion.

the class XsltStylesheet method retryXsltTransformation.

private String retryXsltTransformation(ThreadContext context, IRubyObject[] args, DOMSource domSource, NokogiriXsltErrorListener elistener) throws TransformerException, IOException {
    Templates templates = getTemplatesFromStreamSource();
    Transformer transf = templates.newTransformer();
    transf.setErrorListener(elistener);
    if (args.length > 1) {
        addParametersToTransformer(context, transf, args[1]);
    }
    PipedWriter pwriter = new PipedWriter();
    PipedReader preader = new PipedReader();
    pwriter.connect(preader);
    StreamResult result = new StreamResult(pwriter);
    transf.transform(domSource, result);
    char[] cbuf = new char[1024];
    int len = preader.read(cbuf, 0, 1024);
    StringBuilder builder = new StringBuilder(len);
    builder.append(cbuf, 0, len);
    // judge from the first chunk
    htmlish = isHtml(builder);
    while (len == 1024) {
        len = preader.read(cbuf, 0, 1024);
        if (len > 0) {
            builder.append(cbuf, 0, len);
        }
    }
    preader.close();
    pwriter.close();
    return builder.toString();
}
Also used : PipedWriter(java.io.PipedWriter) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) Templates(javax.xml.transform.Templates) PipedReader(java.io.PipedReader)

Aggregations

Templates (javax.xml.transform.Templates)60 TransformerFactory (javax.xml.transform.TransformerFactory)25 StreamSource (javax.xml.transform.stream.StreamSource)25 Transformer (javax.xml.transform.Transformer)20 Source (javax.xml.transform.Source)19 TransformerConfigurationException (javax.xml.transform.TransformerConfigurationException)17 StreamResult (javax.xml.transform.stream.StreamResult)16 TransformerException (javax.xml.transform.TransformerException)10 InputStream (java.io.InputStream)8 IOException (java.io.IOException)7 OutputStream (java.io.OutputStream)7 DOMResult (javax.xml.transform.dom.DOMResult)7 DOMSource (javax.xml.transform.dom.DOMSource)7 File (java.io.File)5 Result (javax.xml.transform.Result)5 SAXSource (javax.xml.transform.sax.SAXSource)5 FileOutputStream (java.io.FileOutputStream)4 StringReader (java.io.StringReader)4 BufferedOutputStream (java.io.BufferedOutputStream)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3