Example usage for javax.xml.transform TransformerFactory newTransformer

List of usage examples for javax.xml.transform TransformerFactory newTransformer

Introduction

In this page you can find the example usage for javax.xml.transform TransformerFactory newTransformer.

Prototype

public abstract Transformer newTransformer() throws TransformerConfigurationException;

Source Link

Document

Create a new Transformer that performs a copy of the Source to the Result .

Usage

From source file:com.casewaresa.framework.util.LegacyJasperInputStream.java

public static String addDocTypeAndConvertDOMToString(final Document document) {

    TransformerFactory transfac = TransformerFactory.newInstance();
    Transformer trans = null;/* w w  w. j  a v  a  2 s.com*/
    try {
        trans = transfac.newTransformer();
    } catch (TransformerConfigurationException ex) {
        log.error(ex.getMessage(), ex);
    }

    trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    trans.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "//JasperReports//DTD Report Design//EN");
    trans.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,
            "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd");

    StringWriter sw = new StringWriter();
    StreamResult result = new StreamResult(sw);
    DOMSource source = new DOMSource(document);
    try {
        trans.transform(source, result);
    } catch (TransformerException ex) {
        log.error(ex.getMessage(), ex);
    }

    return sw.toString();
}

From source file:Main.java

public static String readSource(final Source sourceToRead) throws TransformerException {
    // Create transformer
    final TransformerFactory tff = TransformerFactory.newInstance();
    final Transformer tf = tff.newTransformer();

    final Writer resultWriter = new StringWriter();

    final Result result = new StreamResult(resultWriter);

    tf.transform(sourceToRead, result);//from w w w .j a  v a 2 s .co  m

    return resultWriter.toString();

}

From source file:Main.java

/**
 * @param xml/*from w  w w.j  ava  2 s  . c o m*/
 * @return pretty xml
 */
public static String prettyXml(String xml) {
    TransformerFactory tfactory = TransformerFactory.newInstance();
    Transformer serializer;
    try {
        Source source = new StreamSource(new StringReader(xml));
        StringWriter writer = new StringWriter();

        serializer = tfactory.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

public static Transformer getTransformer(boolean standalone, boolean indent, int indentNumber,
        boolean omitXmlDeclaration) throws TransformerException {
    TransformerFactory f = TransformerFactory.newInstance();
    f.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
    if (indent) {
        f.setAttribute("indent-number", indentNumber);
    }/*from  ww w.ja  va  2  s.  c  o  m*/

    Transformer t = f.newTransformer();
    if (standalone) {
        t.setOutputProperty(OutputKeys.STANDALONE, "yes");
    }
    if (indent) {
        t.setOutputProperty(OutputKeys.INDENT, "yes");
        t.setOutputProperty("{xml.apache.org/xslt}indent-amount", "" + indentNumber);
    }
    if (omitXmlDeclaration) {
        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    }

    return t;
}

From source file:Main.java

public static String formatXmlAsString(Document document) {

    StringWriter writer = new StringWriter();
    TransformerFactory factory = TransformerFactory.newInstance();

    try {/*from  w ww  . j  a v a 2 s . c om*/

        factory.setAttribute("indent-number", new Integer(2));
    } catch (IllegalArgumentException ex) {

    }

    try {

        Transformer transformer = factory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

        transformer.transform(new DOMSource(document), new StreamResult(writer));
    } catch (TransformerException ex) {

        throw new RuntimeException("Error formatting xml as pretty-printed string", ex);
    }

    return writer.toString();
}

From source file:Main.java

/**
 * potentially unsafe XML transformation.
 * @param source The XML input to transform.
 * @param out The Result of transforming the <code>source</code>.
 *///from   w  w w.  jav  a2s.co m
private static void _transform(Source source, Result out) throws TransformerException {
    TransformerFactory factory = TransformerFactory.newInstance();
    factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);

    // this allows us to use UTF-8 for storing data,
    // plus it checks any well-formedness issue in the submitted data.
    Transformer t = factory.newTransformer();
    t.transform(source, out);
}

From source file:com.omertron.traileraddictapi.tools.DOMHelper.java

/**
 * Write the Document out to a file using nice formatting
 *
 * @param doc The document to save/*from  w w  w . j a va2 s  .  com*/
 * @param localFile The file to write to
 * @return
 */
public static boolean writeDocumentToFile(Document doc, String localFile) {
    try {
        TransformerFactory transfact = TransformerFactory.newInstance();
        Transformer trans = transfact.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, YES);
        trans.setOutputProperty(OutputKeys.INDENT, YES);
        trans.transform(new DOMSource(doc), new StreamResult(new File(localFile)));
        return true;
    } catch (TransformerConfigurationException ex) {
        LOG.warn(ERROR_WRITING_DOC, localFile, ex);
        return false;
    } catch (TransformerException ex) {
        LOG.warn(ERROR_WRITING_DOC, localFile, ex);
        return false;
    }
}

From source file:Main.java

public static String toPrettyString(String xml) {
    int indent = 4;
    try {//  w w w  .  ja  v a  2s  .c o m
        // Turn xml string into a document
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8"))));

        // Remove whitespaces outside tags
        XPath xPath = XPathFactory.newInstance().newXPath();
        NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']", document,
                XPathConstants.NODESET);

        for (int i = 0; i < nodeList.getLength(); ++i) {
            Node node = nodeList.item(i);
            node.getParentNode().removeChild(node);
        }

        // Setup pretty print options
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setAttribute("indent-number", indent);
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");

        // Return pretty print xml string
        StringWriter stringWriter = new StringWriter();
        transformer.transform(new DOMSource(document), new StreamResult(stringWriter));
        return stringWriter.toString();
    } catch (Exception e) {
        System.out.println(xml);
        throw new RuntimeException(
                "Problems prettyfing xml content [" + Splitter.fixedLength(100).split(xml) + "]", e);
    }
}

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  w w.j a va 2s  . 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;
}

From source file:Main.java

public static void prettyPrintXml(Document doc, OutputStream out, int indent) {
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    TransformerFactory tfactory = TransformerFactory.newInstance();

    // set indent spaces on factory
    //        tfactory.setAttribute("indent-number", new Integer(indent));

    try {/*from  ww w  . ja  v  a 2  s  . com*/
        Transformer serializer = tfactory.newTransformer();

        // turn on indenting on transformer (serializer)
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount",
                //                  String.valueOf(indent));
                "2");

        serializer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(out, "utf-8")));
    } catch (Exception e) {

        // this is fatal, just dump stack and throw runtime exception
        e.printStackTrace();

        throw new RuntimeException(e);
    }
}