Example usage for javax.xml.transform OutputKeys METHOD

List of usage examples for javax.xml.transform OutputKeys METHOD

Introduction

In this page you can find the example usage for javax.xml.transform OutputKeys METHOD.

Prototype

String METHOD

To view the source code for javax.xml.transform OutputKeys METHOD.

Click Source Link

Document

method = "xml" | "html" | "text" | expanded name.

Usage

From source file:com.ingby.socbox.bischeck.configuration.DocManager.java

/**
 * Generate the display file of configuration file 
 * @param xmlconf the enum entry of the configuration file
 * @param outputdir the output directory where the generated files should
 * be generated/*  w ww  .  j  av  a2 s.  com*/
 * @param type the type of file to be generated, like html and text. This
 * control the xslt file to be used for the generation.
 * @throws TransformerFactoryConfigurationError
 * @throws TransformerException
 * @throws IOException
 * @throws Exception  
 */
private void genFile(XMLCONFIG xmlconf, File outputdir, String type)
        throws TransformerFactoryConfigurationError, TransformerException, IOException, Exception {

    URL xslUrl = DocManager.class.getClassLoader().getResource(xmlconf.nametag() + "2" + type + ".xsl");
    if (xslUrl == null) {
        throw new IOException("File " + xmlconf.nametag() + "2" + type + ".xsl does not exists");
    }

    TransformerFactory tFactory = TransformerFactory.newInstance();

    Transformer transformer = tFactory.newTransformer(new StreamSource(xslUrl.getFile()));

    if ("text".equalsIgnoreCase(type))
        transformer.setOutputProperty(OutputKeys.METHOD, "text");

    transformer.transform(new StreamSource(new File(ConfigFileManager.initConfigDir(), xmlconf.xml())),
            new javax.xml.transform.stream.StreamResult(
                    new FileOutputStream(outputdir + File.separator + xmlconf.nametag() + "." + type)));
}

From source file:com.alfaariss.oa.util.configuration.handler.jdbc.JDBCConfigurationHandler.java

/**
 * Saves the database configuration using the update query.
 * @see IConfigurationHandler#saveConfiguration(org.w3c.dom.Document)
 *//*from w  w w .  j  av  a2 s.c om*/
public void saveConfiguration(Document oConfigurationDocument) throws ConfigurationException {
    Connection oConnection = null;
    OutputStream os = null;
    PreparedStatement ps = null;

    try {
        os = new ByteArrayOutputStream();

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.VERSION, "1.0");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(new DOMSource(oConfigurationDocument), new StreamResult(os));

        //Save to DB
        oConnection = _oDataSource.getConnection();
        ps = oConnection.prepareStatement(_sUpdateQuery);
        ps.setString(1, os.toString());
        ps.setString(2, _sConfigId);
        ps.executeUpdate();
    } catch (SQLException e) {
        _logger.error("Database error while writing configuration, SQL eror", e);
        throw new ConfigurationException(SystemErrors.ERROR_CONFIG_WRITE);
    } catch (TransformerException e) {
        _logger.error("Error while transforming document", e);
        throw new ConfigurationException(SystemErrors.ERROR_CONFIG_WRITE);
    } catch (Exception e) {
        _logger.error("Internal error during during configuration save", e);
        throw new ConfigurationException(SystemErrors.ERROR_CONFIG_WRITE);
    } finally {

        try {
            if (os != null)
                os.close();
        } catch (IOException e) {
            _logger.debug("Error closing configuration outputstream", e);
        }

        try {
            if (ps != null)
                ps.close();
        } catch (SQLException e) {
            _logger.debug("Error closing statement", e);
        }

        try {
            if (oConnection != null)
                oConnection.close();
        } catch (SQLException e) {
            _logger.debug("Error closing connection", e);
        }
    }
}

From source file:com.mirth.connect.plugins.datatypes.xml.XMLBatchAdaptor.java

private String toXML(Node node) throws Exception {
    Writer writer = new StringWriter();

    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.transform(new DOMSource(node), new StreamResult(writer));

    return writer.toString();
}

From source file:com.twinsoft.convertigo.engine.util.XMLUtils.java

public static void prettyPrintDOMWithEncoding(Document doc, String defaultEncoding, Result result) {
    Node firstChild = doc.getFirstChild();
    boolean omitXMLDeclaration = false;
    String encoding = defaultEncoding; // default Encoding char set if non
    // is found in the PI

    if ((firstChild.getNodeType() == Document.PROCESSING_INSTRUCTION_NODE)
            && (firstChild.getNodeName().equals("xml"))) {
        omitXMLDeclaration = true;//  www.j ava2  s  .com
        String piValue = firstChild.getNodeValue();
        // extract from PI the encoding Char Set
        int encodingOffset = piValue.indexOf("encoding=\"");
        if (encodingOffset != -1) {
            encoding = piValue.substring(encodingOffset + 10);
            // remove the last "
            encoding = encoding.substring(0, encoding.length() - 1);
        }
    }

    try {
        Transformer t = getNewTransformer();
        t.setOutputProperty(OutputKeys.ENCODING, encoding);
        t.setOutputProperty(OutputKeys.INDENT, "yes");
        t.setOutputProperty(OutputKeys.METHOD, "xml"); // xml, html, text
        t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, omitXMLDeclaration ? "yes" : "no");
        t.transform(new DOMSource(doc), result);
    } catch (Exception e) {
        Engine.logEngine.error("Unexpected exception while pretty print DOM", e);
    }
}

From source file:org.alloy.metal.xml.merge.MergeContext.java

/**
* Merge 2 xml document streams together into a final resulting stream. During
* the merge, various merge business rules are followed based on configuration
* defined for various merge points.//  www.  j  a  v  a  2 s .c o m
*
* @param stream1
* @param stream2
* @return the stream representing the merged document
* @throws org.broadleafcommerce.common.extensibility.context.merge.exceptions.MergeException
*/
public ResourceInputStream merge(ResourceInputStream stream1, ResourceInputStream stream2)
        throws MergeException {
    try {
        Document doc1 = builder.parse(stream1);
        Document doc2 = builder.parse(stream2);

        List<Node> exhaustedNodes = new ArrayList<Node>();

        // process any defined handlers
        for (MergeHandler handler : this.handlers) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Processing handler: " + handler.getXPath());
            }
            MergePoint point = new MergePoint(handler, doc1, doc2);
            List<Node> list = point.merge(exhaustedNodes);
            exhaustedNodes.addAll(list);
        }

        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer xmlTransformer = tFactory.newTransformer();
        xmlTransformer.setOutputProperty(OutputKeys.VERSION, "1.0");
        xmlTransformer.setOutputProperty(OutputKeys.ENCODING, _String.CHARACTER_ENCODING.toString());
        xmlTransformer.setOutputProperty(OutputKeys.METHOD, "xml");
        xmlTransformer.setOutputProperty(OutputKeys.INDENT, "yes");

        if (doc1.getDoctype() != null && doc1.getDoctype().getSystemId() != null) {
            xmlTransformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, doc1.getDoctype().getSystemId());
        }

        DOMSource source = new DOMSource(doc1);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(baos));
        StreamResult result = new StreamResult(writer);
        xmlTransformer.transform(source, result);

        byte[] itemArray = baos.toByteArray();

        return new ResourceInputStream(new ByteArrayInputStream(itemArray), stream2.getName(),
                stream1.getNames());
    } catch (Exception e) {
        throw new MergeException(e);
    }
}

From source file:de.awtools.xml.XSLTransformer.java

/**
 * Liefert den Transformer./* ww w. java  2 s  . c o m*/
 * 
 * @return Ein <code>Transformer</code>
 */
private final Transformer getTransformer() {
    if ((transe == null) || (styleModified)) {
        InputStream xslt = null;
        try {
            xslt = getStyle();
            transe = TransformerUtils.getTransformer(xslt, getUriResolver());

            transe.setOutputProperty(OutputKeys.ENCODING, getEncoding());
            transe.setOutputProperty(OutputKeys.METHOD, getMethod());
            transe.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, getOmitXmlDeclaration());

            styleModified = false;
        } catch (IOException ex) {
            log.debug("IOException", ex);
            throw new RuntimeException(ex);
        } finally {
            IOUtils.closeQuietly(xslt);
        }
    }
    return transe;
}

From source file:com.ibm.xsp.webdav.DavXMLResponse.java

/**
 * Gets the transformer handler object where we write everything to
 * //from w w  w .j a v  a2s. c o  m
 * @param streamResult
 *            the place where we write the result to
 * @return the body object to append XML tags to
 */
private TransformerHandler getSAXOutputObject(StreamResult streamResult) {

    // Factory pattern at work
    SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance();
    // SAX2.0 ContentHandler that provides the append point and access to
    // serializing options
    TransformerHandler hd;
    try {
        hd = tf.newTransformerHandler();
        Transformer serializer = hd.getTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");// Suitable
        // for
        // all
        // languages
        serializer.setOutputProperty(OutputKeys.METHOD, "xml");
        if (this.extendedResult || true) {
            serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        }
        hd.setResult(streamResult);

        return hd;

    } catch (TransformerConfigurationException e) {
        LOGGER.error(e);
    }

    return null;

}

From source file:com.vmware.identity.samlservice.Shared.java

/**
 * Print out XML node to a stream/*from  w w  w .jav a 2s.  com*/
 *
 * @param xml
 * @param out
 * @throws TransformerConfigurationException
 * @throws TransformerFactoryConfigurationError
 * @throws TransformerException
 * @throws UnsupportedEncodingException
 */
private static final void prettyPrint(Node xml, OutputStream out) throws Exception {
    TransformerFactory tFactory = TransformerFactory.newInstance();
    // tFactory.setAttribute("indent-number", 4);
    Transformer tf = tFactory.newTransformer();
    tf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    tf.setOutputProperty(OutputKeys.INDENT, "yes");
    tf.setOutputProperty(OutputKeys.METHOD, "xml");
    tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "5");
    StreamResult result = new StreamResult(new OutputStreamWriter(out, "UTF-8"));
    tf.transform(new DOMSource(xml), result);
}

From source file:org.joy.config.Configuration.java

public void save() {
    try {//from w  w  w.  ja v a2s. com
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbf.newDocumentBuilder();
        Document doc = docBuilder.newDocument();
        Element root = doc.createElement("configuration");
        doc.appendChild(root);

        Element classpathEle = doc.createElement("classpath");
        root.appendChild(classpathEle);
        for (String s : classPathEntries) {
            Element e = doc.createElement("entry");
            e.appendChild(doc.createTextNode(s));
            classpathEle.appendChild(e);
        }

        Element connectionsEle = doc.createElement("connections");
        root.appendChild(connectionsEle);
        for (DatabaseElement d : connectionHistory) {
            writeDatabase(connectionsEle, d);
        }

        Element e = doc.createElement("tagertProject");
        e.appendChild(doc.createTextNode(tagertProject));
        root.appendChild(e);

        e = doc.createElement("basePackage");
        e.appendChild(doc.createTextNode(basePackage));
        root.appendChild(e);

        e = doc.createElement("moduleName");
        e.appendChild(doc.createTextNode(moduleName));
        root.appendChild(e);

        Element templatesEle = doc.createElement("templates");
        root.appendChild(templatesEle);
        for (TemplateElement t : templates) {
            writeTemplate(templatesEle, t);
        }

        // Write the file
        DOMSource ds = new DOMSource(doc);
        StreamResult sr = new StreamResult(new File(configurationFile));
        Transformer t = TransformerFactory.newInstance().newTransformer();
        t.setOutputProperty(OutputKeys.METHOD, "xml");
        t.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        t.setOutputProperty(OutputKeys.INDENT, "yes");
        t.setOutputProperty(OutputKeys.STANDALONE, "yes");
        t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        t.transform(ds, sr);
    } catch (Exception e) {
        LOGGER.info(e.getMessage(), e);
    }
}

From source file:com.mirth.connect.connectors.ws.WebServiceDispatcher.java

private String sourceToXmlString(Source source) throws TransformerConfigurationException, TransformerException {
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    Writer writer = new StringWriter();
    transformer.transform(source, new StreamResult(writer));
    return writer.toString();
}