Example usage for javax.xml.transform Transformer setOutputProperty

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

Introduction

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

Prototype

public abstract void setOutputProperty(String name, String value) throws IllegalArgumentException;

Source Link

Document

Set an output property that will be in effect for the transformation.

Usage

From source file:Main.java

/**
 * Transform./*  w w  w  .j a  v  a  2  s.  c  o m*/
 *
 * @param document
 *          the document
 * @param streamResult
 *          the stream result
 * @param xmlDeclaration
 *          the xml declaration
 */
public static void transform(final Document document, final StreamResult streamResult,
        final boolean xmlDeclaration) {
    if (document == null) {
        throw new IllegalArgumentException("document cannot be NULL!");
    }
    if (streamResult == null) {
        throw new IllegalArgumentException("streamResult cannot be NULL!");
    }
    Transformer transformer;
    try {
        transformer = TRANSFORMER_FACTORY.newTransformer();
    } catch (final TransformerConfigurationException e) {
        throw new RuntimeException(e);
    }
    transformer.setOutputProperty(OutputKeys.INDENT, "no");
    String strXmlDeclaration;
    if (xmlDeclaration) {
        strXmlDeclaration = "no";
    } else {
        strXmlDeclaration = "yes";
    }
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, strXmlDeclaration);
    final DOMSource source = new DOMSource(document);
    try {
        transformer.transform(source, streamResult);
    } catch (final TransformerException e) {
        throw new RuntimeException(e);
    }
}

From source file:XMLUtil.java

public static void write(Document doc, OutputStream out) throws IOException {
    // XXX note that this may fail to write out namespaces correctly if the
    // document// w  w  w.  jav  a 2 s.  c o m
    // is created with namespaces and no explicit prefixes; however no code in
    // this package is likely to be doing so
    try {
        Transformer t = TransformerFactory.newInstance().newTransformer();
        DocumentType dt = doc.getDoctype();
        if (dt != null) {
            String pub = dt.getPublicId();
            if (pub != null) {
                t.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, pub);
            }
            t.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, dt.getSystemId());
        }
        t.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // NOI18N
        t.setOutputProperty(OutputKeys.INDENT, "yes"); // NOI18N
        t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); // NOI18N
        Source source = new DOMSource(doc);
        Result result = new StreamResult(out);
        t.transform(source, result);
    } catch (Exception e) {
        throw (IOException) new IOException(e.toString()).initCause(e);
    } catch (TransformerFactoryConfigurationError e) {
        throw (IOException) new IOException(e.toString()).initCause(e);
    }
}

From source file:Main.java

public static StringBuffer transformToString(Source xmlSource, Source xslSource) {
    StringWriter writer = new StringWriter();
    Transformer transformer;
    try {//www .  j  a  v a 2s. com
        if (xslSource == null) {
            transformer = TransformerFactory.newInstance().newTransformer();
        } else {
            transformer = TransformerFactory.newInstance().newTransformer(xslSource);
        }
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.transform(xmlSource, new StreamResult(writer));
        return writer.getBuffer();
    } catch (Exception e) {
        e.printStackTrace();
        return writer.getBuffer();
    } finally {
        try {
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:Main.java

/**
 * @param xml/* ww w .  ja v a2  s.c  om*/
 * @return pretty xml
 */
public static String prettyXml(String xml) {
    Transformer serializer;
    try {
        Source source = new StreamSource(new StringReader(xml));
        StringWriter writer = new StringWriter();

        serializer = transFactory.newTransformer();
        // Setup indenting to "pretty print"
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

        serializer.transform(source, new StreamResult(writer));
        return writer.toString();
    } catch (Exception e) {
        return xml;
    }
}

From source file:Main.java

/**
 * DOCUMENT ME!//from   www.ja v  a  2s  . co m
 *
 * @return DOCUMENT ME!
 *
 * @throws TransformerConfigurationException DOCUMENT ME!
 * @throws TransformerException DOCUMENT ME!
 * @throws Exception DOCUMENT ME!
 */
public static byte[] writeToBytes(Document document)
        throws TransformerConfigurationException, TransformerException, Exception {
    byte[] ret = null;

    TransformerFactory tFactory = TransformerFactory.newInstance();
    tFactory.setAttribute("indent-number", new Integer(4));

    Transformer transformer = tFactory.newTransformer();
    DOMSource source = new DOMSource(document);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    StreamResult result = new StreamResult(bos);
    transformer.setOutputProperty(OutputKeys.METHOD, "xml"); // NOI18N
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // NOI18N
    transformer.setOutputProperty(OutputKeys.MEDIA_TYPE, "text/xml"); // NOI18N
    transformer.setOutputProperty(OutputKeys.STANDALONE, "yes"); // NOI18N

    // indent the output to make it more legible...
    try {
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); // NOI18N
        transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // NOI18N
    } catch (IllegalArgumentException e) {
        // the JAXP implementation doesn't support indentation, no big deal
        //e.printStackTrace();
    }

    try {
        transformer.transform(source, result);
        ret = bos.toByteArray();
    } finally {
        if (bos != null) {
            bos.flush();
            bos.close();
        }
    }

    return ret;
}

From source file:be.fedict.eid.idp.protocol.ws_federation.sts.SecurityTokenServicePortImpl.java

static String toString(Node dom) throws TransformerException {
    Source source = new DOMSource(dom);
    StringWriter stringWriter = new StringWriter();
    Result result = new StreamResult(stringWriter);
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.transform(source, result);
    return stringWriter.getBuffer().toString();
}

From source file:com.c4om.jschematronvalidator.JSchematronValidatorMain.java

/**
 * Prints a {@link org.w3c.dom.Document} to an {@link OutputStream}.
 * @param outputDocument The output document
 * @param outputStream The output stream
 * @param charset the charset./*from  w  w w.ja  v a  2  s  . co m*/
 * @throws TransformerFactoryConfigurationError
 * @throws TransformerConfigurationException
 * @throws TransformerException
 */
private static void printW3CDocumentToOutputStream(Document outputDocument, OutputStream outputStream,
        String charset)
        throws TransformerFactoryConfigurationError, TransformerConfigurationException, TransformerException {
    LOGGER.info("Printing W3C Document to an output stream with encoding '" + charset + "'");
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.ENCODING, charset);
    LOGGER.debug("XML output properties: " + transformer.getOutputProperties().toString());

    DOMSource source = new DOMSource(outputDocument);
    Writer outputWriter = new XmlStreamWriter(outputStream, charset);

    StreamResult result = new StreamResult(outputWriter);

    transformer.transform(source, result);
    LOGGER.info("Document printed");
}

From source file:Main.java

public static final void writeMalformedXml(Transformer transformer, OutputStream outputEntry, NodeList nodes) {
    Assert.notNull(transformer, "Transformer required");
    Assert.notNull(outputEntry, "Output entry required");
    Assert.notNull(nodes, "NodeList required");

    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

    try {//from ww w  .j  a  v  a  2 s . c  om
        for (int i = 0; i < nodes.getLength(); i++) {
            transformer.transform(new DOMSource(nodes.item(i)), createUnixStreamResultForEntry(outputEntry));
        }
    } catch (Exception ex) {
        throw new IllegalStateException(ex);
    }
}

From source file:Main.java

public static final void writeXml(Transformer transformer, OutputStream outputEntry, Document document) {
    Assert.notNull(transformer, "Transformer required");
    Assert.notNull(outputEntry, "Output entry required");
    Assert.notNull(document, "Document required");

    transformer.setOutputProperty(OutputKeys.METHOD, "xml");

    try {//from  www .  j  a  va 2s  .  co m
        transformer.transform(new DOMSource(document), createUnixStreamResultForEntry(outputEntry));
    } catch (Exception ex) {
        throw new IllegalStateException(ex);
    }
}

From source file:cz.muni.fi.webmias.TeXConverter.java

/**
 * Converts TeX formula to MathML using LaTeXML through a web service.
 *
 * @param query String containing one or more keywords and TeX formulae
 * (formulae enclosed in $ or $$)./*from  w  ww .java  2 s  . c  om*/
 * @return String containing formulae converted to MathML that replaced
 * original TeX forms. Non math tokens are connected at the end.
 */
public static String convertTexLatexML(String query) {
    query = query.replaceAll("\\$\\$", "\\$");
    if (query.matches(".*\\$.+\\$.*")) {
        try {
            HttpClient httpclient = HttpClients.createDefault();
            HttpPost httppost = new HttpPost(LATEX_TO_XHTML_CONVERSION_WS_URL);

            // Request parameters and other properties.
            List<NameValuePair> params = new ArrayList<>(1);
            params.add(new BasicNameValuePair("code", query));
            httppost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));

            // Execute and get the response.
            HttpResponse response = httpclient.execute(httppost);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    try (InputStream responseContents = resEntity.getContent()) {
                        DocumentBuilder dBuilder = MIaSUtils.prepareDocumentBuilder();
                        org.w3c.dom.Document doc = dBuilder.parse(responseContents);
                        NodeList ps = doc.getElementsByTagName("p");
                        String convertedMath = "";
                        for (int k = 0; k < ps.getLength(); k++) {
                            Node p = ps.item(k);
                            NodeList pContents = p.getChildNodes();
                            for (int j = 0; j < pContents.getLength(); j++) {
                                Node pContent = pContents.item(j);
                                if (pContent instanceof Text) {
                                    convertedMath += pContent.getNodeValue() + "\n";
                                } else {
                                    TransformerFactory transFactory = TransformerFactory.newInstance();
                                    Transformer transformer = transFactory.newTransformer();
                                    StringWriter buffer = new StringWriter();
                                    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                                    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                                    transformer.transform(new DOMSource(pContent), new StreamResult(buffer));
                                    convertedMath += buffer.toString() + "\n";
                                }
                            }
                        }
                        return convertedMath;
                    }
                }
            }

        } catch (TransformerException | SAXException | ParserConfigurationException | IOException ex) {
            Logger.getLogger(ProcessServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return query;
}