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:org.wso2.carbon.identity.user.store.configuration.UserStoreConfigAdminService.java

private void writeUserMgtXMLFile(File userStoreConfigFile, UserStoreDTO userStoreDTO,
        boolean editSecondaryUserStore) throws IdentityUserStoreMgtException {
    StreamResult result = new StreamResult(userStoreConfigFile);
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();

    try {/*  ww w .jav a  2  s  .co  m*/
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.newDocument();

        //create UserStoreManager element
        Element userStoreElement = doc
                .createElement(UserCoreConstants.RealmConfig.LOCAL_NAME_USER_STORE_MANAGER);
        doc.appendChild(userStoreElement);

        Attr attrClass = doc.createAttribute("class");
        attrClass.setValue(userStoreDTO.getClassName());
        userStoreElement.setAttributeNode(attrClass);

        addProperties(userStoreDTO.getClassName(), userStoreDTO.getProperties(), doc, userStoreElement,
                editSecondaryUserStore);
        addProperty(UserStoreConfigConstants.DOMAIN_NAME, userStoreDTO.getDomainId(), doc, userStoreElement,
                false);
        addProperty(DESCRIPTION, userStoreDTO.getDescription(), doc, userStoreElement, false);
        DOMSource source = new DOMSource(doc);

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "6");
        transformer.transform(source, result);
    } catch (ParserConfigurationException e) {
        String errMsg = " Error occurred due to serious parser configuration exception of "
                + userStoreConfigFile;
        throw new IdentityUserStoreMgtException(errMsg, e);
    } catch (TransformerException e) {
        String errMsg = " Error occurred during the transformation process of " + userStoreConfigFile;
        throw new IdentityUserStoreMgtException(errMsg, e);
    }
}

From source file:org.wso2.carbon.mdm.mobileservices.windows.operations.util.SyncmlGenerator.java

private String transformDocument(Document document) throws SyncmlOperationException {
    DOMSource domSource = new DOMSource(document);
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer;/*from  w  ww  .j  a v a 2  s  . c  o m*/
    try {
        transformer = transformerFactory.newTransformer();
    } catch (TransformerConfigurationException e) {
        String message = "Error while retrieving a new transformer";
        log.error(message, e);
        throw new SyncmlOperationException(message, e);
    }
    transformer.setOutputProperty(OutputKeys.ENCODING, Constants.UTF_8);
    transformer.setOutputProperty(OutputKeys.INDENT, Constants.YES);

    StringWriter stringWriter = new StringWriter();
    StreamResult streamResult = new StreamResult(stringWriter);
    try {
        transformer.transform(domSource, streamResult);
    } catch (TransformerException e) {
        String message = "Error while transforming document to a string";
        log.error(message, e);
        throw new SyncmlOperationException(message, e);
    }
    return stringWriter.toString();
}

From source file:org.wso2.carbon.mdm.mobileservices.windows.SyncmlParserTest.java

public String convertToString(Document doc) throws TransformerException {

    DOMSource domSource = new DOMSource(doc);
    StringWriter stringWriter = new StringWriter();
    StreamResult streamResult = new StreamResult(stringWriter);
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.transform(domSource, streamResult);
    stringWriter.flush();//from  w  ww.ja  v a2s .com
    return stringWriter.toString();
}

From source file:org.wso2.carbon.ml.core.impl.MLModelHandler.java

/**
 * Append version attribute to pmml (temporary fix)
 *
 * @param pmmlString the pmml string to be appended
 * @return PMML with version as a String
 * @throws MLPmmlExportException//from  w  w w.jav a  2  s.  c  om
 */
private String appendVersionToPMML(String pmmlString) throws MLPmmlExportException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;
    StringWriter stringWriter = null;

    try {
        //convert the string to xml to append the version attribute
        builder = factory.newDocumentBuilder();
        Document document = builder.parse(new InputSource(new StringReader(pmmlString)));
        Element root = document.getDocumentElement();
        root.setAttribute("version", "4.2");

        // convert it back to string
        stringWriter = new StringWriter();
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

        transformer.transform(new DOMSource(document), new StreamResult(stringWriter));
        return stringWriter.toString();
    } catch (Exception e) {
        String msg = "Error while appending version attribute to pmml";
        log.error(msg, e);
        throw new MLPmmlExportException(msg);
    } finally {
        try {
            if (stringWriter != null) {
                stringWriter.close();
            }
        } catch (IOException e) {
            String msg = "Error while closing stringWriter stream resource";
            log.error(msg, e);
            throw new MLPmmlExportException(msg);
        }
    }
}

From source file:org.yamj.core.tools.xml.DOMHelper.java

/**
 * Write the Document out to a file using nice formatting
 *
 * @param doc The document to save//from w  ww.  j  a  va2  s . co  m
 * @param localFile The file to write to
 * @return
 */
public static boolean writeDocumentToFile(Document doc, File localFile) {
    try {
        Transformer trans = TransformerFactory.newInstance().newTransformer();

        // Define the output properties
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        trans.setOutputProperty(OutputKeys.INDENT, YES);
        trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        doc.setXmlStandalone(true);

        trans.transform(new DOMSource(doc), new StreamResult(localFile));
        return true;
    } catch (IllegalArgumentException | DOMException | TransformerException ex) {
        LOG.error("Error writing the document to {}", localFile);
        LOG.error("Error", ex);
        return false;
    }
}

From source file:pl.baczkowicz.spy.formatting.FormattingUtils.java

public static String prettyXml(final Document document, final int indent) throws TransformerException {
    final TransformerFactory transformerFactory = TransformerFactory.newInstance();

    final Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", Integer.toString(indent));

    final StringWriter writer = new StringWriter();
    final Result result = new StreamResult(writer);
    final Source source = new DOMSource(document);
    transformer.transform(source, result);

    return writer.getBuffer().toString();
}

From source file:pt.webdetails.cdf.dd.render.CdaRenderer.java

public String render() throws Exception {
    ByteArrayOutputStream result = new ByteArrayOutputStream();
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document cdaFile = builder.newDocument();
    Element root = cdaFile.createElement("CDADescriptor");
    cdaFile.appendChild(root);//from w w w . ja  v  a2  s . c o  m
    Element connections = cdaFile.createElement("DataSources");
    root.appendChild(connections);
    Iterator<Pointer> pointers = doc.iteratePointers(CDA_ELEMENTS_JXPATH);
    while (pointers.hasNext()) {
        Pointer pointer = pointers.next();
        JXPathContext context = JXPathContext.newContext(pointer.getNode());
        String connectionId = (String) context.getValue("properties/.[name='name']/value", String.class);
        Element conn;
        try {
            conn = exportConnection(cdaFile, context, connectionId);
            connections.appendChild(conn);
        } catch (Exception e) {
            // things without connections end up here. All is fine,
            // we just need to make sure exportDataAccess doesn't try to generate a connection link
            connectionId = null;
        }

        Element dataAccess = exportDataAccess(cdaFile, context, connectionId);
        if (dataAccess != null) {
            root.appendChild(dataAccess);
        }
    }

    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer();

    DOMSource source = new DOMSource(cdaFile);
    StreamResult res = new StreamResult(new OutputStreamWriter(result, CharsetHelper.getEncoding()));
    transformer.setOutputProperty(OutputKeys.ENCODING, CharsetHelper.getEncoding());
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "Query");
    transformer.transform(source, res);
    return result.toString();
}

From source file:ru.runa.common.web.HTMLUtils.java

public static String writeHtml(Document document) {
    try {/*from  w w  w.java 2  s.com*/
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "html");
        transformer.setOutputProperty(OutputKeys.ENCODING, Charsets.UTF_8.name());
        transformer.transform(new DOMSource(document), new StreamResult(outputStream));
        String string = new String(outputStream.toByteArray(), Charsets.UTF_8);
        // crunch to fix issue #646
        // setting xalan property
        // "{http://xml.apache.org/xalan}line-separator" to "\n" did not
        // work
        string = string.replaceAll("&#13;\r\n", "\n");
        return string;
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:xmlconverter.controller.logic.GetFileCount.java

/**
 * This method filters given pathName for proper pathname for OS not to be
 * confused by characters that are not supported. Also it provides names and
 * type of detectors that are in specific location.
 *
 * @param doc/*from  w w w  .  j  av a 2 s. c  om*/
 * @param out
 * @throws java.io.IOException
 * @throws javax.xml.transform.TransformerException
 */
//P.S should work well junit test could be to compare number of items that are present
//in the file to compare with number that has been readed my this function
//Is able to print org.w3c.dom.Document out.
public void printDocument(Document doc, OutputStream out) throws IOException, TransformerException {
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

    transformer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(out, "UTF-8")));
}

From source file:xmlconverter.controller.logic.GetFileCount.java

/**
 *
 * Writes Document object to specified path as file
 *
 * @param doc//from  w ww. j  a  v a2 s. c o m
 * @param path
 * @throws TransformerException
 * @throws IOException
 * @throws DOMException
 * @throws ParserConfigurationException
 * @throws SAXException
 */
private void writeDocument(Document doc, File path)
        throws TransformerException, IOException, DOMException, ParserConfigurationException, SAXException {
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "no");
    transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(new StringWriter());
    transformer.transform(source, result);

    File toCheck = path;
    if (!path.getAbsolutePath().endsWith(".xml")) {
        toCheck = new File(path.getAbsolutePath() + slash + path.getName() + ".xml");
    }

    try (FileOutputStream xmlfile = new FileOutputStream(toCheck);) {
        if (toCheck.exists()) {
            xmlfile.write(result.getWriter().toString().getBytes());
        } else {
            toCheck.createNewFile();
            xmlfile.write(result.getWriter().toString().getBytes());
        }
    }
}