Example usage for javax.xml.transform OutputKeys OMIT_XML_DECLARATION

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

Introduction

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

Prototype

String OMIT_XML_DECLARATION

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

Click Source Link

Document

omit-xml-declaration = "yes" | "no".

Usage

From source file:org.cauldron.einstein.ri.core.model.data.xml.dom.DOMUtil.java

@Post
@Pre//from   w  w  w. j av  a  2s .com
public static DocumentFragment buildFragmentFromNode(DocumentBuilder docBuilder, Node node)
        throws IOException, TransformerException, SAXException {
    Document doc;
    DocumentFragment fragment;
    /*
    I know this is convoluted but it's very difficult to actually add a bunch of random nodes to
    a document fragment without getting errors. XML DOM APIs are bloomin sketchy so this guarantees
    that the node can be added.  Need to throw this rubbish away and use a better XML API really.
     */
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    byteArrayOutputStream.write("<dummy>".getBytes());
    Transformer xformer = transformerFactory.newTransformer();
    xformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    Source source = new DOMSource(node);
    Result result = new StreamResult(byteArrayOutputStream);
    xformer.transform(source, result);
    byteArrayOutputStream.write("</dummy>".getBytes());

    log.debug("Dumy node {0}.", byteArrayOutputStream);

    doc = docBuilder.parse(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));
    fragment = doc.createDocumentFragment();
    final Element element = doc.getDocumentElement();
    if (element.hasChildNodes()) {
        //has child nodes, not text.
        NodeList nodeList = element.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            log.debug("Moving temporary node.");
            final Node newNode = nodeList.item(i);
            doc.adoptNode(newNode);
            fragment.appendChild(newNode);
        }
    }

    log.debug("Fragment is now {0}.", ReflectionToStringBuilder.reflectionToString(fragment));
    return fragment;
}

From source file:org.cauldron.einstein.ri.core.model.data.xml.dom.XMLDOMDataObject.java

@Post
public String asString() {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    try {//w  ww.  java2 s  . c om
        Transformer xformer = transformerFactory.newTransformer();
        xformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        //            for (Node node : list) {
        Source source = new DOMSource(node);
        Result result = new StreamResult(byteArrayOutputStream);
        xformer.transform(source, result);
        //            }
    } catch (TransformerConfigurationException e) {
        throw new DataConversionRuntimeException(e);
    } catch (TransformerException e) {
        throw new DataConversionRuntimeException(e);
    }
    return byteArrayOutputStream.toString();
}

From source file:org.codice.ddf.catalog.transformer.html.RecordViewHelpers.java

public CharSequence buildMetadata(String metadata, Options options) {
    if (metadata == null) {
        return "";
    }/*  www  . j ava2s .co 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.ddf.security.claims.attributequery.common.AttributeQueryClient.java

/**
 * Sends the request to the external attribute store via a Dispatch client.
 *
 * @param requestDocument of the request.
 * @return Document of the response or null if the response is empty.
 * @throws AttributeQueryException/*from   w  w  w  .  j  a va2s.c o  m*/
 */
protected Document sendRequest(Document requestDocument) {
    TransformerProperties transformerProperties = new TransformerProperties();
    transformerProperties.addOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    String request = XMLUtils.format(requestDocument, transformerProperties);

    StreamSource streamSource;
    try {
        streamSource = dispatch.invoke(new StreamSource(new StringReader(request)));
    } catch (Exception e) {
        throw new AttributeQueryException(
                String.format("Could not connect to: %s", this.externalAttributeStoreUrl), e);
    }
    String response = XMLUtils.format(streamSource, transformerProperties);
    if (StringUtils.isBlank(response)) {
        LOGGER.warn("Response is empty.");
        return null;
    }

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder;
    Document responseDoc;
    try {
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        responseDoc = documentBuilder.parse(new InputSource(new StringReader(response)));
    } catch (ParserConfigurationException | SAXException | IOException e) {
        throw new AttributeQueryException("Unable to parse response string into an XML document.", e);
    }
    return responseDoc;
}

From source file:org.codice.ddf.security.claims.attributequery.common.AttributeQueryClient.java

/**
 * Prints the given XML./*from  w w  w  . j  av  a2 s . c  om*/
 *
 * @param xmlNode Node to transform.
 * @param message Message to display.
 */
private void printXML(String message, Node xmlNode) {
    TransformerProperties transformerProperties = new TransformerProperties();
    transformerProperties.addOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    LOGGER.trace(message, XMLUtils.format(xmlNode, transformerProperties));
}

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

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

    try {/*from  w ww. j a  va2 s  .c  o  m*/
        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 {/*from w w  w.  j  a  va2 s.c om*/
        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. j a va  2s  .  co 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.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();
}