Example usage for javax.xml.transform Transformer getOutputProperties

List of usage examples for javax.xml.transform Transformer getOutputProperties

Introduction

In this page you can find the example usage for javax.xml.transform Transformer getOutputProperties.

Prototype

public abstract Properties getOutputProperties();

Source Link

Document

<p>Get a copy of the output properties for the transformation.</p> <p>The properties returned should contain properties set by the user, and properties set by the stylesheet, and these properties are "defaulted" by default properties specified by <a href="http://www.w3.org/TR/xslt#output">section 16 of the XSL Transformations (XSLT) W3C Recommendation</a>.

Usage

From source file:org.docx4j.XmlUtils.java

/**
 * /*w w  w  .java2  s .c o  m*/
 * Transform an input document using XSLT
 * 
 * @param doc
 * @param xslt
 * @param transformParameters
 * @param result
 * @throws Docx4JException In case serious transformation errors occur
 */
public static void transform(javax.xml.transform.Source source, javax.xml.transform.Templates template,
        Map<String, Object> transformParameters, javax.xml.transform.Result result) throws Docx4JException {

    if (source == null) {
        Throwable t = new Throwable();
        throw new Docx4JException("Null Source doc", t);
    }

    // Use the template to create a transformer
    // A Transformer may not be used in multiple threads running concurrently. 
    // Different Transformers may be used concurrently by different threads.
    // A Transformer may be used multiple times. Parameters and output properties 
    // are preserved across transformations.      
    javax.xml.transform.Transformer xformer;
    try {
        xformer = template.newTransformer();
    } catch (TransformerConfigurationException e) {
        throw new Docx4JException("The Transformer is ill-configured", e);
    }

    log.info("Using " + xformer.getClass().getName());

    if (xformer.getClass().getName().equals("org.apache.xalan.transformer.TransformerImpl")) {

        if (Docx4jProperties.getProperty("docx4j.xalan.XALANJ-2419.workaround", false)) {
            // Use our patched serializer, which fixes Unicode astral character
            // issue. See https://issues.apache.org/jira/browse/XALANJ-2419

            log.info("Working around https://issues.apache.org/jira/browse/XALANJ-2419");

            Properties p = xformer.getOutputProperties();
            String method = p.getProperty("method");
            System.out.println("method: " + method);
            if (method == null || method.equals("xml")) {

                ((org.apache.xalan.transformer.TransformerImpl) xformer).setOutputProperty(
                        S_KEY_CONTENT_HANDLER, "org.docx4j.org.apache.xml.serializer.ToXMLStream");

            } else if (method.equals("html")) {

                ((org.apache.xalan.transformer.TransformerImpl) xformer).setOutputProperty(
                        S_KEY_CONTENT_HANDLER, "org.docx4j.org.apache.xml.serializer.ToHTMLStream");

            } else if (method.equals("text")) {

                ((org.apache.xalan.transformer.TransformerImpl) xformer).setOutputProperty(
                        S_KEY_CONTENT_HANDLER, "org.docx4j.org.apache.xml.serializer.ToTextStream");

            } else {

                log.warn("fallback for method: " + method);
                ((org.apache.xalan.transformer.TransformerImpl) xformer).setOutputProperty(
                        S_KEY_CONTENT_HANDLER, "org.docx4j.org.apache.xml.serializer.ToUnknownStream");

            }

            /* That wasn't quite enough:
             * 
               at org.docx4j.org.apache.xml.serializer.ToXMLStream.startDocumentInternal(ToXMLStream.java:143)
               at org.docx4j.org.apache.xml.serializer.SerializerBase.startDocument(SerializerBase.java:1190)
               at org.apache.xml.serializer.ToSAXHandler.startDocumentInternal(ToSAXHandler.java:97)
               at org.apache.xml.serializer.ToSAXHandler.flushPending(ToSAXHandler.java:273)
               at org.apache.xml.serializer.ToXMLSAXHandler.startPrefixMapping(ToXMLSAXHandler.java:350)
               at org.apache.xml.serializer.ToXMLSAXHandler.startPrefixMapping(ToXMLSAXHandler.java:320)
               at org.apache.xalan.templates.ElemLiteralResult.execute(ElemLiteralResult.java:1317)
             *
             * (TransformerImpl's createSerializationHandler makes a new org.apache.xml.serializer.ToXMLSAXHandler.ToXMLSAXHandler
             * and that's hard coded.)
             * 
             * But it seems to be enough now...
                        
             */
        }

    } else {

        log.error("Detected " + xformer.getClass().getName()
                + ", but require org.apache.xalan.transformer.TransformerImpl. "
                + "Ensure Xalan 2.7.x is on your classpath!");
    }
    LoggingErrorListener errorListener = new LoggingErrorListener(false);
    xformer.setErrorListener(errorListener);

    if (transformParameters != null) {
        Iterator parameterIterator = transformParameters.entrySet().iterator();
        while (parameterIterator.hasNext()) {
            Map.Entry pairs = (Map.Entry) parameterIterator.next();

            if (pairs.getKey() == null) {
                log.info("Skipped null key");
                // pairs = (Map.Entry)parameterIterator.next();
                continue;
            }

            if (pairs.getKey().equals("customXsltTemplates"))
                continue;

            if (pairs.getValue() == null) {
                log.warn("parameter '" + pairs.getKey() + "' was null.");
            } else {
                xformer.setParameter((String) pairs.getKey(), pairs.getValue());
            }
        }
    }

    /* SUPER DEBUGGING
    // http://xml.apache.org/xalan-j/usagepatterns.html#debugging
    // debugging
    // Set up a PrintTraceListener object to print to a file.
    java.io.FileWriter fw = new java.io.FileWriter("/tmp/xslt-events" + xsltCount++ + ".log");
    java.io.PrintWriter pw = new java.io.PrintWriter(fw);
    PrintTraceListener ptl = new PrintTraceListener(pw);
            
    // Print information as each node is 'executed' in the stylesheet.
    ptl.m_traceElements = true;
    // Print information after each result-tree generation event.
    ptl.m_traceGeneration = true;
    // Print information after each selection event.
    ptl.m_traceSelection = true;
    // Print information whenever a template is invoked.
    ptl.m_traceTemplates = true;
    // Print information whenever an extension is called.
    ptl.m_traceExtension = true;
    TransformerImpl transformerImpl = (TransformerImpl)xformer;
            
      // Register the TraceListener with the TraceManager associated
      // with the TransformerImpl.
      TraceManager trMgr = transformerImpl.getTraceManager();
      trMgr.addTraceListener(ptl);
            
    */
    // DEBUGGING
    // use the identity transform if you want to send wordDocument;
    // otherwise you'll get the XHTML
    // javax.xml.transform.Transformer xformer = tfactory.newTransformer();
    try {
        xformer.transform(source, result);
    } catch (TransformerException e) {
        throw new Docx4JException("Cannot perform the transformation", e);
    } finally {
        //pw.flush();
    }

}

From source file:org.geoserver.wfs.xslt.XSLTOutputFormat.java

@Override
protected void write(final FeatureCollectionResponse featureCollection, OutputStream output,
        Operation operation) throws IOException, ServiceException {
    // get the transformation we need
    TransformInfo info = locateTransformation(featureCollection, operation);
    Transformer transformer = repository.getTransformer(info);
    // force Xalan to indent the output
    if (transformer.getOutputProperties() != null
            && "yes".equals(transformer.getOutputProperties().getProperty("indent"))) {
        try {/*from w  w w. ja  va 2  s  . c  o  m*/
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        } catch (IllegalArgumentException e) {
            LOGGER.log(Level.FINE, "Could not set indent amount", e);
            // in case it's not Xalan
        }
    }

    // prepare the fake operation we're providing to the source output format
    final Operation sourceOperation = buildSourceOperation(operation, info);

    // lookup the operation we are going to use
    final Response sourceResponse = findSourceResponse(sourceOperation, info);
    if (sourceResponse == null) {
        throw new WFSException("Could not locate a response that can generate the desired source format '"
                + info.getSourceFormat() + "' for transformation '" + info.getName() + "'");

    }

    // prepare the stream connections, so that we can do the transformation on the fly
    PipedInputStream pis = new PipedInputStream();
    final PipedOutputStream pos = new PipedOutputStream(pis);

    // submit the source output format execution, tracking exceptions
    Future<Void> future = executor.submit(new Callable<Void>() {

        @Override
        public Void call() throws Exception {
            try {
                sourceResponse.write(featureCollection, pos, sourceOperation);
            } finally {
                // close the stream to make sure the transformation won't keep on waiting
                pos.close();
            }

            return null;
        }
    });

    // run the transformation
    TransformerException transformerException = null;
    try {
        transformer.transform(new StreamSource(pis), new StreamResult(output));
    } catch (TransformerException e) {
        transformerException = e;
    } finally {
        pis.close();
    }

    // now handle exceptions, starting from the source
    try {
        future.get();
    } catch (Exception e) {
        throw new WFSException(
                "Failed to run the output format generating the source for the XSTL transformation", e);
    }
    if (transformerException != null) {
        throw new WFSException("Failed to run the the XSTL transformation", transformerException);
    }

}

From source file:org.springframework.integration.xml.transformer.XsltPayloadTransformer.java

private Object transformSource(Source source, Object payload, Transformer transformer)
        throws TransformerException {
    Result result;/*from   w ww . j  a v  a  2 s .  c  o m*/
    if (!this.resultFactoryExplicitlySet
            && "text".equals(transformer.getOutputProperties().getProperty("method"))) {
        result = new StringResult();
    } else {
        result = this.resultFactory.createResult(payload);
    }
    transformer.transform(source, result);
    if (this.resultTransformer != null) {
        return this.resultTransformer.transformResult(result);
    }
    return result;
}