Example usage for javax.xml.transform Transformer setOutputProperties

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

Introduction

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

Prototype

public abstract void setOutputProperties(Properties oformat);

Source Link

Document

Set the output properties for the transformation.

Usage

From source file:fr.paris.lutece.plugins.calendar.service.XMLUtils.java

/**
 * This method performs XSL Transformation.
 * //from  ww w  .  ja  va2s .co m
 * @param strXml The input XML document
 * @param baSource The source input stream
 * @param params parameters to apply to the XSL Stylesheet
 * @param outputProperties properties to use for the xsl transform. Will
 *            overload the xsl output definition.
 * @return The output document transformed
 * @throws Exception The exception
 */
public static byte[] transformXMLToXSL(String strXml, InputStream baSource, Map<String, String> params,
        Properties outputProperties) throws Exception {
    Source stylesheet = new StreamSource(baSource);
    StringReader srInputXml = new StringReader(strXml);
    StreamSource source = new StreamSource(srInputXml);

    try {
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer(stylesheet);

        if (outputProperties != null) {
            transformer.setOutputProperties(outputProperties);
        }

        if (params != null) {
            transformer.clearParameters();

            Set<Entry<String, String>> entries = params.entrySet();

            for (Entry<String, String> entry : entries) {
                String name = entry.getKey();
                String value = entry.getValue();
                transformer.setParameter(name, value);
            }
        }

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Result result = new StreamResult(out);
        transformer.transform(source, result);

        return out.toByteArray();
    } catch (TransformerConfigurationException e) {
        String strMessage = e.getMessage();

        if (e.getLocationAsString() != null) {
            strMessage += ("- location : " + e.getLocationAsString());
        }

        throw new Exception("Error transforming document XSLT : " + strMessage, e.getCause());
    } catch (TransformerFactoryConfigurationError e) {
        throw new Exception("Error transforming document XSLT : " + e.getMessage(), e);
    } catch (TransformerException e) {
        String strMessage = e.getMessage();

        if (e.getLocationAsString() != null) {
            strMessage += ("- location : " + e.getLocationAsString());
        }

        throw new Exception("Error transforming document XSLT : " + strMessage, e.getCause());
    } catch (Exception e) {
        throw new Exception("Error transforming document XSLT : " + e.getMessage(), e);
    }
}

From source file:IOUtils.java

public static ContentHandler getSerializer(File file) throws IOException, TransformerException {
    final FileWriter writer = new FileWriter(file);

    final TransformerHandler transformerHandler = FACTORY.newTransformerHandler();
    final Transformer transformer = transformerHandler.getTransformer();

    final Properties format = new Properties();
    format.put(OutputKeys.METHOD, "xml");
    format.put(OutputKeys.OMIT_XML_DECLARATION, "no");
    format.put(OutputKeys.ENCODING, "UTF-8");
    format.put(OutputKeys.INDENT, "yes");
    transformer.setOutputProperties(format);

    transformerHandler.setResult(new StreamResult(writer));

    try {//from w  ww.  j  a  v a 2 s. co m
        if (needsNamespacesAsAttributes(format)) {
            return new NamespaceAsAttributes(transformerHandler);
        }
    } catch (SAXException se) {
        throw new TransformerException("Unable to detect of namespace support for sax works properly.", se);
    }
    return transformerHandler;
}

From source file:Examples.java

/**
 * Show how to override output properties.
 *//*from ww w  .  j a  va2 s. com*/
public static void exampleOutputProperties(String sourceID, String xslID)
        throws TransformerException, TransformerConfigurationException {

    TransformerFactory tfactory = TransformerFactory.newInstance();
    Templates templates = tfactory.newTemplates(new StreamSource(xslID));
    Properties oprops = templates.getOutputProperties();

    oprops.put(OutputKeys.INDENT, "yes");

    Transformer transformer = templates.newTransformer();

    transformer.setOutputProperties(oprops);
    transformer.transform(new StreamSource(sourceID), new StreamResult(new OutputStreamWriter(System.out)));
}

From source file:Examples.java

/**
 * A fuller example showing how the TrAX interface can be used 
 * to serialize a DOM tree./*from ww  w  .  j a va2s .  c o m*/
 */
public static void exampleAsSerializer(String sourceID, String xslID) throws TransformerException,
        TransformerConfigurationException, SAXException, IOException, ParserConfigurationException {
    DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = dfactory.newDocumentBuilder();
    org.w3c.dom.Document outNode = docBuilder.newDocument();
    Node doc = docBuilder.parse(new InputSource(sourceID));

    TransformerFactory tfactory = TransformerFactory.newInstance();

    // This creates a transformer that does a simple identity transform, 
    // and thus can be used for all intents and purposes as a serializer.
    Transformer serializer = tfactory.newTransformer();

    Properties oprops = new Properties();
    oprops.put("method", "html");
    serializer.setOutputProperties(oprops);
    serializer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(System.out)));
}

From source file:com.granule.json.utils.XML.java

/**
 * Method to do the transform from an JSON input stream to a XML stream.
 * Neither input nor output streams are closed.  Closure is left up to the caller.
 *
 * @param JSONStream The XML stream to convert to JSON
 * @param XMLStream The stream to write out JSON to.  The contents written to this stream are always in UTF-8 format.
 * @param verbose Flag to denote whether or not to render the XML text in verbose (indented easy to read), or compact (not so easy to read, but smaller), format.
 *
 * @throws IOException Thrown if an IO error occurs.
 *//*from ww  w . j  a v  a 2s.c om*/
public static void toXml(InputStream JSONStream, OutputStream XMLStream, boolean verbose) throws IOException {
    if (logger.isLoggable(Level.FINER)) {
        logger.entering(className, "toXml(InputStream, OutputStream)");
    }

    if (XMLStream == null) {
        throw new NullPointerException("XMLStream cannot be null");
    } else if (JSONStream == null) {
        throw new NullPointerException("JSONStream cannot be null");
    } else {

        if (logger.isLoggable(Level.FINEST)) {
            logger.logp(Level.FINEST, className, "transform", "Parsing the JSON and a DOM builder.");
        }

        try {
            //Get the JSON from the stream.
            JSONObject jObject = new JSONObject(JSONStream);

            //Create a new document

            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbf.newDocumentBuilder();
            Document doc = dBuilder.newDocument();

            if (logger.isLoggable(Level.FINEST)) {
                logger.logp(Level.FINEST, className, "transform", "Parsing the JSON content to XML");
            }

            convertJSONObject(doc, doc.getDocumentElement(), jObject, "jsonObject");

            //Serialize it.
            TransformerFactory tfactory = TransformerFactory.newInstance();
            Transformer serializer = null;
            if (verbose) {
                serializer = tfactory.newTransformer(new StreamSource(new StringReader(styleSheet)));
                ;
            } else {
                serializer = tfactory.newTransformer();
            }
            Properties oprops = new Properties();
            oprops.put(OutputKeys.METHOD, "xml");
            oprops.put(OutputKeys.OMIT_XML_DECLARATION, "yes");
            oprops.put(OutputKeys.VERSION, "1.0");
            oprops.put(OutputKeys.INDENT, "true");
            serializer.setOutputProperties(oprops);
            serializer.transform(new DOMSource(doc), new StreamResult(XMLStream));

        } catch (Exception ex) {
            IOException iox = new IOException("Problem during conversion");
            iox.initCause(ex);
            throw iox;
        }
    }

    if (logger.isLoggable(Level.FINER)) {
        logger.exiting(className, "toXml(InputStream, OutputStream)");
    }
}

From source file:ar.com.zauber.commons.web.transformation.processors.impl.XalanXSLTScraper.java

/**
 *
 * Propiedades que recibe un tranformer.
 * {@link javax.xml.transform.Transformer#setOutputProperties(Properties)}
 * utiliza estas opciones:/*from   w w  w.  jav  a2s . c o m*/
 *      javax.xml.transform.OutputKeys
 * @param node
 * @param model
 * @param writer
 * @param oformat siguiendo las specs linkeadas mas arriba
 *
 *
 * @throws TransformerFactoryConfigurationError
 */
public void scrap(final Node node, final Map<String, Object> model, final Writer writer, Properties oformat)
        throws TransformerFactoryConfigurationError {
    Validate.notNull(node);
    Validate.notNull(model);
    Validate.notNull(writer);
    try {
        final TransformerFactory factory = TransformerFactory.newInstance();
        final Transformer transformer = factory.newTransformer(xsltSource);
        Validate.notNull(transformer);
        for (final Entry<String, Object> entry : model.entrySet()) {
            transformer.setParameter(entry.getKey(), entry.getValue());
        }
        Properties options;
        if (oformat != null) {
            options = new Properties(oformat);
        } else {
            options = new Properties();
        }
        if (encoding != null) {
            options.setProperty(OutputKeys.ENCODING, encoding);
        }
        transformer.setOutputProperties(options);
        transformer.transform(new DOMSource(node), new StreamResult(writer));
    } catch (TransformerException e) {
        throw new UnhandledException(e);
    }
}

From source file:it.cnr.icar.eric.common.SOAPMessenger.java

StringReader domNode2StringReader(org.w3c.dom.Node node)
        throws TransformerConfigurationException, TransformerException {
    TransformerFactory tfactory = TransformerFactory.newInstance();
    StringWriter writer = null;/*from  www .  j  a v  a  2 s.c o m*/

    Transformer serializer = tfactory.newTransformer();
    Properties oprops = new Properties();
    oprops.put("method", "xml");
    oprops.put("indent", "yes");
    serializer.setOutputProperties(oprops);
    writer = new StringWriter();
    serializer.transform(new DOMSource(node), new StreamResult(writer));

    String outString = writer.toString();

    //log.trace("outString=" + outString);
    StringReader reader = new StringReader(outString);

    return reader;
}

From source file:nl.armatiek.xslweb.configuration.WebApp.java

public XsltExecutable trySchematronCache(String schematronPath, String phase, ErrorListener errorListener)
        throws Exception {
    String key = FilenameUtils.normalize(schematronPath) + (phase != null ? phase : "");
    XsltExecutable templates = templatesCache.get(key);
    if (templates == null) {
        logger.info("Compiling and caching schematron schema \"" + schematronPath + "\" ...");
        try {//from  w  w  w. ja v  a 2  s.c o m
            Source source = new StreamSource(new File(schematronPath));
            File schematronDir = new File(Context.getInstance().getHomeDir(), "common/xsl/system/schematron");

            ErrorListener listener = new TransformationErrorListener(null, developmentMode);
            MessageWarner messageWarner = new MessageWarner();

            Xslt30Transformer stage1 = tryTemplatesCache(
                    new File(schematronDir, "iso_dsdl_include.xsl").getAbsolutePath(), errorListener).load30();
            stage1.setErrorListener(listener);
            stage1.getUnderlyingController().setMessageEmitter(messageWarner);
            Xslt30Transformer stage2 = tryTemplatesCache(
                    new File(schematronDir, "iso_abstract_expand.xsl").getAbsolutePath(), errorListener)
                            .load30();
            stage2.setErrorListener(listener);
            stage2.getUnderlyingController().setMessageEmitter(messageWarner);
            Xslt30Transformer stage3 = tryTemplatesCache(
                    new File(schematronDir, "iso_svrl_for_xslt2.xsl").getAbsolutePath(), errorListener)
                            .load30();
            stage3.setErrorListener(listener);
            stage3.getUnderlyingController().setMessageEmitter(messageWarner);

            XdmDestination destStage1 = new XdmDestination();
            XdmDestination destStage2 = new XdmDestination();
            XdmDestination destStage3 = new XdmDestination();

            stage1.applyTemplates(source, destStage1);
            stage2.applyTemplates(destStage1.getXdmNode().asSource(), destStage2);
            stage3.applyTemplates(destStage2.getXdmNode().asSource(), destStage3);

            Source generatedXsltSource = destStage3.getXdmNode().asSource();

            if (this.developmentMode) {
                TransformerFactory factory = new TransformerFactoryImpl();
                Transformer transformer = factory.newTransformer();
                Properties props = new Properties();
                props.put(OutputKeys.INDENT, "yes");
                transformer.setOutputProperties(props);
                StringWriter sw = new StringWriter();
                transformer.transform(generatedXsltSource, new StreamResult(sw));
                logger.info("Generated Schematron XSLT for \"" + schematronPath + "\", phase \""
                        + (phase != null ? phase : "") + "\" [" + sw.toString() + "]");
            }

            XsltCompiler comp = processor.newXsltCompiler();
            comp.setErrorListener(errorListener);
            templates = comp.compile(generatedXsltSource);

        } catch (Exception e) {
            logger.error("Could not compile schematron schema \"" + schematronPath + "\"", e);
            throw e;
        }
        if (!developmentMode) {
            templatesCache.put(key, templates);
        }
    }
    return templates;
}

From source file:nl.armatiek.xslweb.saxon.functions.ExtensionFunctionCall.java

protected void serialize(NodeInfo nodeInfo, Result result, Properties outputProperties) throws XPathException {
    try {//ww  w  .  j  a v  a2s  .  c  om
        TransformerFactory factory = new TransformerFactoryImpl();
        Transformer transformer = factory.newTransformer();
        if (outputProperties != null) {
            transformer.setOutputProperties(outputProperties);
        }
        transformer.transform(nodeInfo, result);
    } catch (Exception e) {
        throw new XPathException(e);
    }
}

From source file:nl.b3p.ogc.utils.OGCResponse.java

protected String serializeNode(Node doc) throws TransformerConfigurationException, TransformerException {
    StringWriter outText = new StringWriter();
    StreamResult sr = new StreamResult(outText);
    Properties oprops = new Properties();
    oprops.put(OutputKeys.METHOD, "xml");
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer();
    t.setOutputProperties(oprops);
    t.transform(new DOMSource(doc), sr);
    return outText.toString();
}