Example usage for javax.xml.transform.sax TransformerHandler getTransformer

List of usage examples for javax.xml.transform.sax TransformerHandler getTransformer

Introduction

In this page you can find the example usage for javax.xml.transform.sax TransformerHandler getTransformer.

Prototype

public Transformer getTransformer();

Source Link

Document

Get the Transformer associated with this handler, which is needed in order to set parameters and output properties.

Usage

From source file:Main.java

public static void serialize(Node n, StreamResult sr) throws IOException, TransformerException {
    TransformerHandler hd = newTransformerHandler();
    Transformer serializer = hd.getTransformer();

    serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    serializer.setOutputProperty(OutputKeys.INDENT, "yes");

    DOMSource source = new DOMSource(n);
    serializer.transform(source, sr);/*from w  w  w. ja v  a2 s . c om*/
}

From source file:Main.java

/**
 * Creates a {@link TransformerHandler}.
 * /*from  ww  w  . j  a va  2  s.  c  o  m*/
 * @param commentHeader the comment header
 * @param rootTag the root tag
 * @param streamResult stream result
 */
public static TransformerHandler createTransformerHandler(String commentHeader, String rootTag,
        StreamResult streamResult, Charset charset)
        throws TransformerFactoryConfigurationError, TransformerConfigurationException, SAXException {
    SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance();
    try {
        tf.setAttribute("indent-number", new Integer(2));
    } catch (Exception e) {
        // ignore, workaround for JDK 1.5 bug, see http://forum.java.sun.com/thread.jspa?threadID=562510
    }
    TransformerHandler transformerHandler = tf.newTransformerHandler();
    Transformer serializer = transformerHandler.getTransformer();
    serializer.setOutputProperty(OutputKeys.ENCODING, charset.name());
    serializer.setOutputProperty(OutputKeys.METHOD, "xml");
    serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformerHandler.setResult(streamResult);
    transformerHandler.startDocument();
    String newline = System.getProperty("line.separator");
    if (newline == null) {
        newline = "\n";
    }
    commentHeader = (newline + commentHeader).replaceAll("\\n--", newline + " ");
    transformerHandler.characters("\n".toCharArray(), 0, 1);
    transformerHandler.comment(commentHeader.toCharArray(), 0, commentHeader.toCharArray().length);
    transformerHandler.characters("\n".toCharArray(), 0, 1);
    if (rootTag.length() > 0) {
        transformerHandler.startElement("", "", rootTag, null);
    }
    return transformerHandler;
}

From source file:Main.java

public static String map2Xml(Map<String, String> content, String root_elem_id, String item_elem_id)
        throws Exception {
    DocumentBuilder b = documentBuilder();
    Document doc = b.newDocument();
    String str = null;/*from  w w w.j  a  va 2 s.  com*/
    SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    Element root = doc.createElement(root_elem_id);
    doc.appendChild(root);

    // Now, add all the children
    for (Entry<String, String> e : content.entrySet()) {
        Element item = doc.createElement(item_elem_id);
        item.setAttribute("id", e.getKey());
        CDATASection data = doc.createCDATASection(e.getValue());
        item.appendChild(data);
        root.appendChild(item);
    }

    try {
        DOMSource ds = new DOMSource(doc);
        StreamResult sr = new StreamResult(out);
        TransformerHandler th = tf.newTransformerHandler();
        th.getTransformer().setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

        Properties format = new Properties();
        format.put(OutputKeys.METHOD, "xml");
        //         format.put("{http://xml. customer .org/xslt}indent-amount", "4");
        //         format.put("indent-amount", "4");
        //         format.put(OutputKeys.DOCTYPE_SYSTEM, "myfile.dtd");
        format.put(OutputKeys.ENCODING, "UTF-8");
        format.put(OutputKeys.INDENT, "yes");

        th.getTransformer().setOutputProperties(format);
        th.setResult(sr);
        th.getTransformer().transform(ds, sr);

        str = out.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return str;
}

From source file:Main.java

/** Set up transformer to output full XML doc.
 *
 * @param tf see {@link #saxTransformerFactory()}
 * @return Transformer that is fully set up. But here we get TransformerHandler first from TransformerFactory.
 *///  w w  w.j ava2  s .c o  m
public static TransformerHandler newTransformerHandler(final SAXTransformerFactory tf)
        throws TransformerConfigurationException {
    final TransformerHandler resultHandler = tf.newTransformerHandler();
    final Transformer transformer = resultHandler.getTransformer();
    setUtfEncoding(transformer);
    setIndentFlag(transformer);
    setTransformerIndent(transformer);
    return resultHandler;
}

From source file:Main.java

/** Set up transformer to output a standalone "fragment" - suppressing xml declaration.
 *
 * @param tf see {@link #saxTransformerFactory()}
 * @return Transformer that is fully set up. But here we get TransformerHandler first from TransformerFactory.
 *//*from  ww  w . j ava 2s  . c o m*/
public static TransformerHandler newFragmentTransformerHandler(final SAXTransformerFactory tf)
        throws TransformerConfigurationException {
    final TransformerHandler resultHandler = tf.newTransformerHandler();
    final Transformer transformer = resultHandler.getTransformer();
    setUtfEncoding(transformer);
    setIndentFlag(transformer);
    setTransformerIndent(transformer);
    outputStandaloneFragment(transformer);
    return resultHandler;
}

From source file:IOUtils.java

/**
 * Checks if the used Trax implementation correctly handles namespaces set using
 * <code>startPrefixMapping()</code>, but wants them also as 'xmlns:' attributes.
 * <p>//from   w w  w . j  av  a2 s . com
 * The check consists in sending SAX events representing a minimal namespaced document
 * with namespaces defined only with calls to <code>startPrefixMapping</code> (no
 * xmlns:xxx attributes) and check if they are present in the resulting text.
 */
protected static boolean needsNamespacesAsAttributes(Properties format)
        throws TransformerException, SAXException {
    // Serialize a minimal document to check how namespaces are handled.
    final StringWriter writer = new StringWriter();

    final String uri = "namespaceuri";
    final String prefix = "nsp";
    final String check = "xmlns:" + prefix + "='" + uri + "'";

    final TransformerHandler handler = FACTORY.newTransformerHandler();

    handler.getTransformer().setOutputProperties(format);
    handler.setResult(new StreamResult(writer));

    // Output a single element
    handler.startDocument();
    handler.startPrefixMapping(prefix, uri);
    handler.startElement(uri, "element", "element", new AttributesImpl());
    handler.endElement(uri, "element", "element");
    handler.endPrefixMapping(prefix);
    handler.endDocument();

    final String text = writer.toString();

    // Check if the namespace is there (replace " by ' to be sure of what we search in)
    boolean needsIt = (text.replace('"', '\'').indexOf(check) == -1);

    return needsIt;
}

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  ww w .  j  av  a2  s.c om
        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:com.benchmark.TikaCLI.java

/**
 * Returns a transformer handler that serializes incoming SAX events
 * to XHTML or HTML (depending the given method) using the given output
 * encoding.//ww  w  . j a v  a2s  .  c  om
 *
 * @see <a href="https://issues.apache.org/jira/browse/TIKA-277">TIKA-277</a>
 * @param output output stream
 * @param method "xml" or "html"
 * @param encoding output encoding,
 *                 or <code>null</code> for the platform default
 * @return {@link System#out} transformer handler
 * @throws TransformerConfigurationException
 *         if the transformer can not be created
 */
private static TransformerHandler getTransformerHandler(OutputStream output, String method, String encoding,
        boolean prettyPrint) throws TransformerConfigurationException {
    SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
    TransformerHandler handler = factory.newTransformerHandler();
    handler.getTransformer().setOutputProperty(OutputKeys.METHOD, method);
    handler.getTransformer().setOutputProperty(OutputKeys.INDENT, prettyPrint ? "yes" : "no");
    if (encoding != null) {
        handler.getTransformer().setOutputProperty(OutputKeys.ENCODING, encoding);
    }
    handler.setResult(new StreamResult(output));
    return handler;
}

From source file:com.mindquarry.search.serializer.IndexPostSerializer.java

/**
 * Set the {@link OutputStream} where the requested resource should be
 * serialized./*w  ww . j a  v  a2s .  com*/
 */
public void setOutputStream(OutputStream out) throws IOException {
    super.setOutputStream(out);
    try {
        TransformerHandler handler = this.getTransformerHandler();
        handler.getTransformer().setOutputProperties(this.format);
        res = new DOMResult();
        handler.setResult(res);
        // handler.setResult(new StreamResult(this.output));
        this.setContentHandler(handler);
        this.setLexicalHandler(handler);
    } catch (Exception e) {
        final String message = "Cannot set XMLSerializer outputstream";
        throw new CascadingIOException(message, e);
    }
}

From source file:com.ikanow.infinit.e.harvest.extraction.document.file.FileHarvester.java

private static TransformerHandler getTransformerHandler(String method, StringWriter sw) {
    try {/*from   ww  w . j  a  v  a  2  s  .c  om*/
        SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
        TransformerHandler handler = factory.newTransformerHandler();
        handler.getTransformer().setOutputProperty(OutputKeys.METHOD, method);
        handler.getTransformer().setOutputProperty(OutputKeys.INDENT, "yes");
        handler.setResult(new StreamResult(sw));
        return handler;
    } catch (Exception e) {
        return null;
    }
}