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.bonitasoft.theme.builder.impl.AbstractXMLBuilder.java

public final File done(File targetFile) throws IOException {
    final File themeDescriptorDefinitionFile = createTempXMLFile();
    document.appendChild(rootElement);//  ww w  .jav a2s. c o m
    final Source source = new DOMSource(document);
    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    final Result resultat = new StreamResult(new OutputStreamWriter(outputStream, "UTF-8"));
    try {
        final Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.transform(source, resultat);

        final byte[] xmlContent = outputStream.toByteArray();
        outputStream.close();

        final FileOutputStream fileOutputStream = new FileOutputStream(themeDescriptorDefinitionFile);
        try {
            fileOutputStream.write(xmlContent);
            fileOutputStream.flush();
        } finally {
            fileOutputStream.close();
        }
    } catch (final TransformerException e) {
        LOGGER.log(Level.SEVERE, "Error while generating the forms definition file.", e);
    }
    FileUtils.copyFile(themeDescriptorDefinitionFile, targetFile);
    if (!targetFile.exists()) {
        throw new IOException(String.format("Failed to copy %s to %s",
                themeDescriptorDefinitionFile.getAbsolutePath(), targetFile.getAbsolutePath()));
    }
    return targetFile;
}

From source file:org.broadleafcommerce.common.extensibility.context.merge.ImportProcessor.java

public ResourceInputStream[] extract(ResourceInputStream[] sources) throws MergeException {
    if (sources == null) {
        return null;
    }/*from   ww  w  .j  a  va2 s.  c  o  m*/
    try {
        DynamicResourceIterator resourceList = new DynamicResourceIterator();
        resourceList.addAll(Arrays.asList(sources));
        while (resourceList.hasNext()) {
            ResourceInputStream myStream = resourceList.nextResource();
            Document doc = builder.parse(myStream);
            NodeList nodeList = (NodeList) xPath.evaluate(IMPORT_PATH, doc, XPathConstants.NODESET);
            int length = nodeList.getLength();
            for (int j = 0; j < length; j++) {
                Element element = (Element) nodeList.item(j);
                Resource resource = loader.getResource(element.getAttribute("resource"));
                ResourceInputStream ris = new ResourceInputStream(resource.getInputStream(),
                        resource.getURL().toString());
                resourceList.addEmbeddedResource(ris);
                element.getParentNode().removeChild(element);
            }
            if (length > 0) {
                TransformerFactory tFactory = TransformerFactory.newInstance();
                Transformer xmlTransformer = tFactory.newTransformer();
                xmlTransformer.setOutputProperty(OutputKeys.VERSION, "1.0");
                xmlTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
                xmlTransformer.setOutputProperty(OutputKeys.METHOD, "xml");
                xmlTransformer.setOutputProperty(OutputKeys.INDENT, "yes");

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

                byte[] itemArray = baos.toByteArray();

                resourceList.set(resourceList.getPosition() - 1, new ResourceInputStream(
                        new ByteArrayInputStream(itemArray), null, myStream.getNames()));
            } else {
                myStream.reset();
            }
        }

        return resourceList.toArray(new ResourceInputStream[resourceList.size()]);
    } catch (Exception e) {
        throw new MergeException(e);
    }
}

From source file:org.broadleafcommerce.common.extensibility.context.merge.MergeManager.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.//from w  w w.ja  va2 s  . com
 *
 * @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);
            Node[] list = point.merge(exhaustedNodes);
            if (list != null) {
                Collections.addAll(exhaustedNodes, list);
            }
        }

        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer xmlTransformer = tFactory.newTransformer();
        xmlTransformer.setOutputProperty(OutputKeys.VERSION, "1.0");
        xmlTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        xmlTransformer.setOutputProperty(OutputKeys.METHOD, "xml");
        xmlTransformer.setOutputProperty(OutputKeys.INDENT, "yes");

        DOMSource source = new DOMSource(doc1);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(baos, "UTF-8"));
        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:org.codice.ddf.catalog.transformer.html.RecordViewHelpers.java

public CharSequence buildMetadata(String metadata, Options options) {
    if (metadata == null) {
        return "";
    }//from w  w  w.  j a v a2 s  .  c o m
    try {
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        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");

        DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
        StreamResult result = new StreamResult(new StringWriter());

        transformer.transform(new DOMSource(builder.parse(new InputSource(new StringReader(metadata)))),
                result);
        StringBuilder sb = new StringBuilder();
        sb.append("<pre>").append(escapeHtml(result.getWriter().toString())).append("</pre>");
        return new Handlebars.SafeString(sb.toString());
    } catch (TransformerConfigurationException e) {
        LOGGER.warn("Failed to convert metadata to a pretty string", e);
    } catch (TransformerException e) {
        LOGGER.warn("Failed to convert metadata to a pretty string", e);
    } catch (SAXException e) {
        LOGGER.warn("Failed to convert metadata to a pretty string", e);
    } catch (ParserConfigurationException e) {
        LOGGER.warn("Failed to convert metadata to a pretty string", e);
    } catch (IOException e) {
        LOGGER.warn("Failed to convert metadata to a pretty string", e);
    }
    return metadata;
}

From source file:org.codice.opendx.NITFInputTransformer.java

private static String toString(Node doc) {
    if (doc == null)
        return "";

    try {/*www  . jav a 2 s  .  c  om*/
        StringWriter sw = 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(doc), new StreamResult(sw));
        return sw.toString();
    } catch (Exception ex) {
        throw new RuntimeException("Error converting to String", ex);
    }
}

From source file:org.commonjava.maven.ext.io.XMLIO.java

public XMLIO() {
    try {/*  ww w. j av  a  2 s  . co m*/
        builder = builderFactory.newDocumentBuilder();

        transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    } catch (ParserConfigurationException e) {
        logger.error("Unable to create new DocumentBuilder", e);
        throw new RuntimeException("Unable to create new DocumentBuilder");
    } catch (TransformerConfigurationException e) {
        logger.error("Unable to create new Transformer", e);
        throw new RuntimeException("Unable to create new Transformer");
    }
}

From source file:org.commonjava.maven.galley.maven.model.view.JXPathContextAncestryTest.java

@Before
public void setup() throws Exception {
    docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();

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

    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    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", "2");
}

From source file:org.commonjava.maven.galley.maven.parse.XMLInfrastructure.java

public String toXML(final Node node, final boolean printXmlDeclaration) {
    String result;//from w ww. ja v  a 2s.  c o m
    try {
        final StringWriter sw = new StringWriter();

        final Transformer transformer = transformerFactory.newTransformer();

        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, printXmlDeclaration ? "no" : "yes");
        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", "2");

        final DocumentBuilder docBuilder = dbFactory.newDocumentBuilder();

        Node doc;
        if (node instanceof Document) {
            doc = node;
        } else {
            doc = docBuilder.newDocument().importNode(node, true);
        }

        transformer.transform(new DOMSource(doc), new StreamResult(sw));

        result = sw.toString();
    } catch (final TransformerException | ParserConfigurationException | DOMException e) {
        throw new GalleyMavenRuntimeException("Failed to render to XML: %s. Reason: %s", e, node,
                e.getMessage());
    }

    return result;
}

From source file:org.corpus_tools.pepper.cli.PepperStarter.java

/**
 * This method writes a module configuration of GroupId, ArtifactId and
 * Maven repository back to the modules.xml file
 *///from   ww w  .  j ava  2  s . c  o  m
private boolean write2ConfigFile(String groupId, String artifactId, String repository) {
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    try {
        boolean changes = false;
        File configFile = new File(MODULES_XML_PATH);
        DocumentBuilder docBuilder = dbFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(configFile);
        NodeList configuredModules = doc.getElementsByTagName(ModuleTableReader.TAG_ARTIFACTID);
        if (configuredModules.getLength() == 0) {
            return false;
        }
        /* check, if the module is already in the modules.xml file */
        Node item = configuredModules.item(0);
        int j = 0;
        while (j + 1 < configuredModules.getLength() && !artifactId.equals(item.getTextContent())) {
            item = configuredModules.item(++j);
        }
        if (artifactId.equals(item.getTextContent())) {// already contained
            // -> edit
            Node itemGroupId = null;
            Node itemRepo = null;
            Node node = null;
            for (int i = 0; i < item.getParentNode().getChildNodes().getLength()
                    && (itemGroupId == null || itemRepo == null); i++) {
                node = item.getParentNode().getChildNodes().item(i);
                if (ModuleTableReader.TAG_GROUPID.equals(node.getLocalName())) {
                    itemGroupId = node;
                }
                if (ModuleTableReader.TAG_REPO.equals(node.getLocalName())) {
                    itemRepo = node;
                }
            }
            if (itemGroupId != null) {
                itemGroupId.setTextContent(groupId);
                changes = true;
            } else {
                if (!groupId.equals(doc.getElementsByTagName(ModuleTableReader.ATT_DEFAULTGROUPID).item(0)
                        .getTextContent())) {
                    itemGroupId = doc.createElement(ModuleTableReader.TAG_GROUPID);
                    itemGroupId.setTextContent(groupId);
                    item.getParentNode().appendChild(itemGroupId);
                    changes = true;
                }
            }
            if (itemRepo != null) {
                itemRepo.setTextContent(repository);
                changes = true;
            } else {
                // if
                // (!repository.equals(doc.getElementsByTagName(ModuleTableReader.ATT_DEFAULTREPO).item(0).getTextContent()))
                // {
                // itemRepo = doc.createElement(ModuleTableReader.TAG_REPO);
                // itemRepo.setTextContent(repository);
                // item.getParentNode().appendChild(itemRepo);
                // changes = true;
                // }
            }
            itemGroupId = null;
            itemRepo = null;
            node = null;
        } else {// not contained yet -> insert
            changes = true;
            Node listNode = doc.getElementsByTagName(ModuleTableReader.TAG_LIST).item(0);
            Node newModule = doc.createElement(ModuleTableReader.TAG_ITEM);
            Node groupIdNode = doc.createElement(ModuleTableReader.TAG_GROUPID);
            groupIdNode.appendChild(doc.createTextNode(groupId));
            Node artifactIdNode = doc.createElement(ModuleTableReader.TAG_ARTIFACTID);
            artifactIdNode.appendChild(doc.createTextNode(artifactId));
            Node repositoryNode = doc.createElement(ModuleTableReader.TAG_REPO);
            repositoryNode.appendChild(doc.createTextNode(repository));
            newModule.appendChild(groupIdNode);
            newModule.appendChild(artifactIdNode);
            newModule.appendChild(repositoryNode);
            listNode.appendChild(newModule);

            listNode = null;
            newModule = null;
            groupIdNode = null;
            artifactIdNode = null;
            repository = null;
        }

        if (changes) {
            // write back to file
            TransformerFactory trFactory = TransformerFactory.newInstance();
            // trFactory.setAttribute("indent-number", 2);
            Transformer transformer = trFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            DOMSource src = new DOMSource(doc);
            StreamResult result = new StreamResult(configFile);
            transformer.transform(src, result);

            trFactory = null;
            transformer = null;
            src = null;
            result = null;
        }

        docBuilder = null;
        doc = null;
        configuredModules = null;
        item = null;

    } catch (ParserConfigurationException | SAXException | IOException | FactoryConfigurationError
            | TransformerFactoryConfigurationError | TransformerException e) {
        logger.error("Could not read module table.");
        logger.trace(" ", e);
        return false;
    }
    return true;
}

From source file:org.cruk.genologics.api.jaxb.JaxbAnnotationTest.java

@SuppressWarnings("unused")
private String reformat(String xml) throws Exception {
    byte[] xmlBytes = xml.getBytes("UTF8");
    Document doc = docBuilder.parse(new ByteArrayInputStream(xmlBytes));

    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(OutputKeys.STANDALONE, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

    StringWriter writer = new StringWriter();
    transformer.transform(new DOMSource(doc), new StreamResult(writer));
    return writer.toString();
}