Example usage for javax.xml.transform OutputKeys ENCODING

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

Introduction

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

Prototype

String ENCODING

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

Click Source Link

Document

encoding = string.

Usage

From source file:com.sfs.jbtimporter.JBTImporter.java

/**
 * Transform the issues to the new XML format.
 *
 * @param jbt the jbt processor/*from w  w  w . j  a  v  a  2  s .c o  m*/
 * @param issues the issues
 */
private static void transformIssues(final JBTProcessor jbt, final List<JBTIssue> issues) {

    final File xsltFile = new File(jbt.getXsltFileName());

    final Source xsltSource = new StreamSource(xsltFile);
    final TransformerFactory transFact = TransformerFactory.newInstance();
    Transformer trans = null;

    try {
        final Templates cachedXSLT = transFact.newTemplates(xsltSource);
        trans = cachedXSLT.newTransformer();
    } catch (TransformerConfigurationException tce) {
        System.out.println("ERROR configuring XSLT engine: " + tce.getMessage());
    }
    // Enable indenting and UTF8 encoding
    trans.setOutputProperty(OutputKeys.INDENT, "yes");
    trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

    if (trans != null) {
        for (JBTIssue issue : issues) {
            System.out.println("Processing Issue ID: " + issue.getId());
            System.out.println("Filename: " + issue.getFullFileName());

            // Read the XML file
            final File xmlFile = new File(issue.getFullFileName());
            final File tempFile = new File(issue.getFullFileName() + ".tmp");
            final File originalFile = new File(issue.getFullFileName() + ".old");

            Source xmlSource = null;
            if (originalFile.exists()) {
                // The original file exists, use that as the XML source
                xmlSource = new StreamSource(originalFile);
            } else {
                // No backup exists, use the .xml file.
                xmlSource = new StreamSource(xmlFile);
            }

            // Transform the XML file
            try {
                trans.transform(xmlSource, new StreamResult(tempFile));

                if (originalFile.exists()) {
                    // Delete the .xml file as it needs to be replaced
                    xmlFile.delete();
                } else {
                    // Rename the existing file with the .old extension
                    xmlFile.renameTo(originalFile);
                }
            } catch (TransformerException te) {
                System.out.println("ERROR transforming XML: " + te.getMessage());
            }

            // Read the xmlFile and convert the special characters

            OutputStreamWriter out = null;
            try {

                final BufferedReader in = new BufferedReader(
                        new InputStreamReader(new FileInputStream(tempFile), "UTF8"));

                out = new OutputStreamWriter(new FileOutputStream(xmlFile), "UTF-8");

                int ch = -1;
                ch = in.read();
                while (ch != -1) {
                    final char c = (char) ch;

                    if (jbt.getSpecialCharacterMap().containsKey(c)) {
                        // System.out.println("Replacing character: " + c 
                        //        + ", " + jbt.getSpecialCharacterMap().get(c));
                        out.write(jbt.getSpecialCharacterMap().get(c));
                    } else {
                        out.write(c);
                    }
                    ch = in.read();
                }
            } catch (IOException ie) {
                System.out.println("ERROR converting special characters: " + ie.getMessage());
            } finally {
                try {
                    if (out != null) {
                        out.close();
                    }
                } catch (IOException ie) {
                    System.out.println("ERROR closing the XML file: " + ie.getMessage());
                }
                // Delete the temporary file
                tempFile.delete();
            }

            System.out.println("-------------------------------------");
        }
    }
}

From source file:com.sitewhere.configuration.ConfigurationMigrationSupport.java

/**
 * Format the given XML document./*from ww  w.  ja v a  2s.c  o  m*/
 * 
 * @param xml
 * @return
 * @throws SiteWhereException
 */
public static String format(Document xml) throws SiteWhereException {
    try {
        Transformer tf = TransformerFactory.newInstance().newTransformer();
        tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        tf.setOutputProperty(OutputKeys.INDENT, "yes");
        tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        Writer out = new StringWriter();
        tf.transform(new DOMSource(xml), new StreamResult(out));
        return out.toString();
    } catch (Exception e) {
        throw new SiteWhereException("Unable to format XML document.", e);
    }
}

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

/**
 * Gets the transformer handler object where we write everything to
 * // w ww. ja  v  a  2  s  .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 ww  . j a  va  2  s.c  o m
 *
 * @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:apiconnector.TestDataFunctionality.java

public static String toPrettyString(String xml, int indent) throws Exception {
    // 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);
    }//  ww w. ja v  a 2s . c o  m

    // 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, "yes");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    // Return pretty print xml string
    StringWriter stringWriter = new StringWriter();
    transformer.transform(new DOMSource(document), new StreamResult(stringWriter));
    return stringWriter.toString();
}

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

public void save() {
    try {/*from   w ww.  ja v a2 s.c  o m*/
        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:eidassaml.starterkit.EidasMetadataNode.java

/**
 * Creates a metadata.xml as byte array/*from  ww w. ja  va2s .co m*/
 * 
 * @param signer
 * @return metadata.xml byte array
 * @throws CertificateEncodingException
 * @throws IOException
 * @throws XMLParserException
 * @throws UnmarshallingException
 * @throws MarshallingException
 * @throws SignatureException
 * @throws TransformerFactoryConfigurationError
 * @throws TransformerException
 */
public byte[] generate(EidasSigner signer)
        throws CertificateEncodingException, IOException, XMLParserException, UnmarshallingException,
        MarshallingException, SignatureException, TransformerFactoryConfigurationError, TransformerException {
    byte[] result = null;
    String template = TemplateLoader.GetTemplateByName("metadatanode");
    template = template.replace("$Id", id);
    template = template.replace("$entityID", entityId);
    template = template.replace("$validUntil", Constants.SimpleSamlDf.format(validUntil));
    template = template.replace("$signCert",
            new String(Base64.encodeBase64(sigCert.getEncoded(), false), Constants.UTF8_CHARSET));
    template = template.replace("$encCert",
            new String(Base64.encodeBase64(encCert.getEncoded(), false), Constants.UTF8_CHARSET));
    template = template.replace("$landID", this.organisation.getLangId());

    template = template.replace("$orgName", organisation.getName());
    template = template.replace("$orgDisplayName", organisation.getDisplayName());
    template = template.replace("$orgUrl", organisation.getUrl());
    template = template.replace("$techPersonCompany", technicalcontact.getCompany());
    template = template.replace("$techPersonGivenName", technicalcontact.getGivenName());
    template = template.replace("$techPersonSurName", technicalcontact.getSurName());
    template = template.replace("$techPersonAddress", technicalcontact.getEmail());
    template = template.replace("$techPersonTel", supportcontact.getTel());
    template = template.replace("$supPersonCompany", supportcontact.getCompany());
    template = template.replace("$supPersonGivenName", supportcontact.getGivenName());
    template = template.replace("$supPersonSurName", supportcontact.getSurName());
    template = template.replace("$supPersonAddress", supportcontact.getEmail());
    template = template.replace("$supPersonTel", supportcontact.getTel());
    template = template.replace("$POST_ENDPOINT", postEndpoint);
    template = template.replace("$SPType", spType.NAME);

    StringBuilder sbSupportNameIDTypes = new StringBuilder();
    for (EidasNameIdType nameIDType : this.supportedNameIdTypes) {
        sbSupportNameIDTypes.append("<md:NameIDFormat>" + nameIDType.NAME + "</md:NameIDFormat>");
    }
    template = template.replace("$SUPPORTED_NAMEIDTYPES", sbSupportNameIDTypes.toString());

    List<Signature> sigs = new ArrayList<Signature>();
    BasicParserPool ppMgr = new BasicParserPool();
    ppMgr.setNamespaceAware(true);
    try (InputStream is = new ByteArrayInputStream(template.getBytes(Constants.UTF8_CHARSET))) {
        Document inCommonMDDoc = ppMgr.parse(is);
        Element metadataRoot = inCommonMDDoc.getDocumentElement();
        UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
        Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(metadataRoot);
        EntityDescriptor metaData = (EntityDescriptor) unmarshaller.unmarshall(metadataRoot);

        XMLSignatureHandler.addSignature(metaData, signer.getSigKey(), signer.getSigCert(), signer.getSigType(),
                signer.getSigDigestAlg());
        sigs.add(metaData.getSignature());

        EntityDescriptorMarshaller arm = new EntityDescriptorMarshaller();
        Element all = arm.marshall(metaData);
        if (sigs.size() > 0)
            Signer.signObjects(sigs);

        Transformer trans = TransformerFactory.newInstance().newTransformer();
        trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        try (ByteArrayOutputStream bout = new ByteArrayOutputStream()) {
            trans.transform(new DOMSource(all), new StreamResult(bout));
            result = bout.toByteArray();
        }
    }

    return result;
}

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();
}

From source file:eidassaml.starterkit.EidasMetadataService.java

public byte[] generate(List<EidasPersonAttributes> attributes, EidasSigner signer)
        throws CertificateEncodingException, IOException, XMLParserException, UnmarshallingException,
        MarshallingException, SignatureException, TransformerFactoryConfigurationError, TransformerException {
    byte[] result = null;
    String template = TemplateLoader.GetTemplateByName("metadataservice");
    template = template.replace("$Id", id);
    template = template.replace("$entityID", entityId);
    template = template.replace("$validUntil", Constants.SimpleSamlDf.format(validUntil));
    template = template.replace("$highestSupportedLoA", this.highestSupportedLoA.NAME);

    template = template.replace("$signCert",
            new String(Base64.encodeBase64(sigCert.getEncoded(), false), Constants.UTF8_CHARSET));
    template = template.replace("$encCert",
            new String(Base64.encodeBase64(encCert.getEncoded(), false), Constants.UTF8_CHARSET));
    template = template.replace("$landID", this.organisation.getLangId());

    template = template.replace("$orgName", organisation.getName());
    template = template.replace("$orgDisplayName", organisation.getDisplayName());
    template = template.replace("$orgUrl", organisation.getUrl());
    template = template.replace("$techPersonCompany", technicalcontact.getCompany());
    template = template.replace("$techPersonGivenName", technicalcontact.getGivenName());
    template = template.replace("$techPersonSurName", technicalcontact.getSurName());
    template = template.replace("$techPersonAddress", technicalcontact.getEmail());
    template = template.replace("$techPersonTel", technicalcontact.getTel());
    template = template.replace("$supPersonCompany", supportcontact.getCompany());
    template = template.replace("$supPersonGivenName", supportcontact.getGivenName());
    template = template.replace("$supPersonSurName", supportcontact.getSurName());
    template = template.replace("$supPersonAddress", supportcontact.getEmail());
    template = template.replace("$supPersonTel", supportcontact.getTel());
    template = template.replace("$POST_ENDPOINT", postEndpoint);
    template = template.replace("$REDIRECT_ENDPOINT", redirectEndpoint);

    StringBuilder sbSupportNameIDTypes = new StringBuilder();
    for (EidasNameIdType nameIDType : this.supportedNameIdTypes) {
        sbSupportNameIDTypes.append("<md:NameIDFormat>" + nameIDType.NAME + "</md:NameIDFormat>");
    }/*from   ww  w.j av a  2 s.c om*/
    template = template.replace("$SUPPORTED_NAMEIDTYPES", sbSupportNameIDTypes.toString());

    StringBuilder sB = new StringBuilder();
    for (EidasPersonAttributes att : attributes) {
        sB.append(attributeTemplate.replace("$ATTFriendlyNAME", att.getFriendlyName()).replace("$ATTName",
                att.getName()));
    }
    template = template.replace("$att", sB.toString());

    List<Signature> sigs = new ArrayList<Signature>();
    BasicParserPool ppMgr = new BasicParserPool();
    ppMgr.setNamespaceAware(true);
    try (InputStream is = new ByteArrayInputStream(template.getBytes(Constants.UTF8_CHARSET))) {
        Document inCommonMDDoc = ppMgr.parse(is);
        Element metadataRoot = inCommonMDDoc.getDocumentElement();
        UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
        Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(metadataRoot);
        EntityDescriptor metaData = (EntityDescriptor) unmarshaller.unmarshall(metadataRoot);

        XMLSignatureHandler.addSignature(metaData, signer.getSigKey(), signer.getSigCert(), signer.getSigType(),
                signer.getSigDigestAlg());
        sigs.add(metaData.getSignature());

        EntityDescriptorMarshaller arm = new EntityDescriptorMarshaller();
        Element all = arm.marshall(metaData);
        if (sigs.size() > 0)
            Signer.signObjects(sigs);

        Transformer trans = TransformerFactory.newInstance().newTransformer();
        trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        try (ByteArrayOutputStream bout = new ByteArrayOutputStream()) {
            trans.transform(new DOMSource(all), new StreamResult(bout));
            result = bout.toByteArray();
        }
    }

    return result;
}

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 ww  w  .j  a v  a 2s. c  om
 * @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");
}