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.pentaho.di.trans.steps.webservices.WebService.java

private void processRows(InputStream anXml, Object[] rowData, RowMetaInterface rowMeta,
        boolean ignoreNamespacePrefix, String encoding) throws KettleException {
    // Just to make sure the old transformations keep working...
    ///*from ww w  . j a va2s. c om*/
    if (meta.isCompatible()) {
        compatibleProcessRows(anXml, rowData, rowMeta, ignoreNamespacePrefix, encoding);
        return;
    }

    // First we should get the complete string
    // The problem is that the string can contain XML or any other format such as HTML saying the service is no longer
    // available.
    // We're talking about a WEB service here.
    // As such, to keep the original parsing scheme, we first read the content.
    // Then we create an input stream from the content again.
    // It's elaborate, but that way we can report on the failure more correctly.
    //
    String response = readStringFromInputStream(anXml, encoding);

    try {

        // What is the expected response object for the operation?
        //
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);

        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

        Document doc = documentBuilder.parse(new InputSource(new StringReader(response)));

        Node envelopeNode = doc.getFirstChild();
        String nsPrefix = envelopeNode.getPrefix();
        Node bodyNode = XMLHandler.getSubNode(envelopeNode, nsPrefix + ":Body");
        if (bodyNode == null) {
            XMLHandler.getSubNode(envelopeNode, nsPrefix + ":body"); // retry, just in case!
        }

        // Create a few objects to help do the layout of XML snippets we find along the way
        //
        Transformer transformer = null;
        try {
            Class<?> clazz = Class.forName("org.apache.xalan.processor.TransformerFactoryImpl");
            TransformerFactory transformerFactory = (TransformerFactory) clazz.newInstance();
            transformer = transformerFactory.newTransformer();
        } catch (Throwable t) {
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            transformer = transformerFactory.newTransformer();
        }
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        if (log.isDetailed()) {
            StringWriter bodyXML = new StringWriter();
            transformer.transform(new DOMSource(bodyNode), new StreamResult(bodyXML));

            logDetailed(bodyXML.toString());
        }

        // The node directly below the body is the response node
        // It's apparently a hassle to get the name in a consistent way, but we know it's the first element node
        //
        Node responseNode = null;
        NodeList nodeList = null;
        if (!Const.isEmpty(meta.getRepeatingElementName())) {

            // We have specified the repeating element name : use it
            //
            nodeList = ((Element) bodyNode).getElementsByTagName(meta.getRepeatingElementName());

        } else {

            if (meta.isReturningReplyAsString()) {

                // Just return the body node as an XML string...
                //
                StringWriter nodeXML = new StringWriter();
                transformer.transform(new DOMSource(bodyNode), new StreamResult(nodeXML));
                String xml = response; // nodeXML.toString();
                Object[] outputRowData = createNewRow(rowData);
                int index = rowData == null ? 0 : getInputRowMeta().size();
                outputRowData[index++] = xml;
                putRow(data.outputRowMeta, outputRowData);

            } else {

                // We just grab the list of nodes from the children of the body
                // Look for the first element node (first real child) and take that one.
                // For that child-element, we consider all the children below
                //
                NodeList responseChildren = bodyNode.getChildNodes();
                for (int i = 0; i < responseChildren.getLength(); i++) {
                    Node responseChild = responseChildren.item(i);
                    if (responseChild.getNodeType() == Node.ELEMENT_NODE) {
                        responseNode = responseChild;
                        break;
                    }
                }

                // See if we want the whole block returned as XML...
                //
                if (meta.getFieldsOut().size() == 1) {
                    WebServiceField field = meta.getFieldsOut().get(0);
                    if (field.getWsName().equals(responseNode.getNodeName())) {
                        // Pass the data as XML
                        //
                        StringWriter nodeXML = new StringWriter();
                        transformer.transform(new DOMSource(responseNode), new StreamResult(nodeXML));
                        String xml = nodeXML.toString();

                        Object[] outputRowData = createNewRow(rowData);
                        int index = rowData == null ? 0 : getInputRowMeta().size();
                        outputRowData[index++] = xml;
                        putRow(data.outputRowMeta, outputRowData);

                    } else {
                        if (responseNode != null) {
                            nodeList = responseNode.getChildNodes();
                        }
                    }

                } else {
                    if (responseNode != null) {
                        nodeList = responseNode.getChildNodes();
                    }
                }
            }
        }

        // The section below is just for repeating nodes. If we don't have those it ends here.
        //
        if (nodeList == null || meta.isReturningReplyAsString()) {
            return;
        }

        // Allocate a result row in case we are dealing with a single result row
        //
        Object[] outputRowData = createNewRow(rowData);

        // Now loop over the node list found above...
        //
        boolean singleRow = false;
        int fieldsFound = 0;
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);

            if (meta.isReturningReplyAsString()) {

                // Just return the body node as an XML string...
                //
                StringWriter nodeXML = new StringWriter();
                transformer.transform(new DOMSource(bodyNode), new StreamResult(nodeXML));
                String xml = nodeXML.toString();
                outputRowData = createNewRow(rowData);
                int index = rowData == null ? 0 : getInputRowMeta().size();
                outputRowData[index++] = xml;
                putRow(data.outputRowMeta, outputRowData);

            } else {

                // This node either contains the data for a single row or it contains the first element of a single result
                // response
                // If we find the node name in out output result fields list, we are going to consider it a single row result.
                //
                WebServiceField field = meta.getFieldOutFromWsName(node.getNodeName(), ignoreNamespacePrefix);
                if (field != null) {
                    if (getNodeValue(outputRowData, node, field, transformer, true)) {
                        // We found a match.
                        // This means that we are dealing with a single row
                        // It also means that we need to update the output index pointer
                        //
                        singleRow = true;
                        fieldsFound++;
                    }
                } else {
                    // If we didn't already get data in the previous block we'll assume multiple rows coming back.
                    //
                    if (!singleRow) {
                        // Sticking with the multiple-results scenario...
                        //

                        // TODO: remove next 2 lines, added for debug reasons.
                        //
                        if (log.isDetailed()) {
                            StringWriter nodeXML = new StringWriter();
                            transformer.transform(new DOMSource(node), new StreamResult(nodeXML));
                            logDetailed(BaseMessages.getString(PKG, "WebServices.Log.ResultRowDataFound",
                                    nodeXML.toString()));
                        }

                        // Allocate a new row...
                        //
                        outputRowData = createNewRow(rowData);

                        // Let's see what's in there...
                        //
                        NodeList childNodes = node.getChildNodes();
                        for (int j = 0; j < childNodes.getLength(); j++) {
                            Node childNode = childNodes.item(j);

                            field = meta.getFieldOutFromWsName(childNode.getNodeName(), ignoreNamespacePrefix);
                            if (field != null) {

                                if (getNodeValue(outputRowData, childNode, field, transformer, false)) {
                                    // We found a match.
                                    // This means that we are dealing with a single row
                                    // It also means that we need to update the output index pointer
                                    //
                                    fieldsFound++;
                                }
                            }
                        }

                        // Prevent empty rows from being sent out.
                        //
                        if (fieldsFound > 0) {
                            // Send a row in a series of rows on its way.
                            //
                            putRow(data.outputRowMeta, outputRowData);
                        }
                    }
                }
            }
        }

        if (singleRow && fieldsFound > 0) {
            // Send the single row on its way.
            //
            putRow(data.outputRowMeta, outputRowData);
        }
    } catch (Exception e) {
        throw new KettleStepException(
                BaseMessages.getString(PKG, "WebServices.ERROR0010.OutputParsingError", response.toString()),
                e);
    }
}

From source file:org.pentaho.di.ui.i18n.MessagesSourceCrawler.java

private void addLabelOccurrences(String sourceFolder, FileObject fileObject, NodeList nodeList,
        String keyPrefix, String tag, String attribute, String defaultPackage,
        List<SourceCrawlerPackageException> packageExcpeptions) throws Exception {
    if (nodeList == null) {
        return;//  w w  w  . j  a  v a2  s .  co m
    }

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);
        String labelString = null;

        if (!Const.isEmpty(attribute)) {
            labelString = XMLHandler.getTagAttribute(node, attribute);
        } else if (!Const.isEmpty(tag)) {
            labelString = XMLHandler.getTagValue(node, tag);
        }

        // TODO : Set the prefix in the right place
        keyPrefix = "$";

        if (labelString != null && labelString.startsWith(keyPrefix)) {
            String key = labelString.substring(1);
            // TODO : maybe not the right place ...
            // just removed ${} around the key
            key = labelString.substring(2, labelString.length() - 1).trim();

            String messagesPackage = defaultPackage;
            for (SourceCrawlerPackageException packageException : packageExcpeptions) {
                if (key.startsWith(packageException.getStartsWith())) {
                    messagesPackage = packageException.getPackageName();
                }
            }

            StringWriter bodyXML = new StringWriter();
            transformer.transform(new DOMSource(node), new StreamResult(bodyXML));
            String xml = bodyXML.getBuffer().toString();

            KeyOccurrence keyOccurrence = new KeyOccurrence(fileObject, sourceFolder, messagesPackage, -1, -1,
                    key, "?", xml);
            addKeyOccurrence(keyOccurrence);
        }
    }
}

From source file:org.pentaho.reporting.platform.plugin.ParameterXmlContentHandlerTest.java

private String toString(final Document doc) {
    try {//w ww .  j  a va  2s. c o m
        final StringWriter stringWriter = new StringWriter();
        final TransformerFactory factory = TransformerFactory.newInstance();
        final Transformer transformer = factory.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.transform(new DOMSource(doc), new StreamResult(stringWriter));
        return stringWriter.toString();
    } catch (final Exception ex) {
        // no op
        return "fail";
    }
}

From source file:org.plasma.provisioning.xsd.AbstractAssembler.java

protected String serializeElement(ElementNSImpl nsElem) {
    String result = "";
    TransformerFactory transFactory = TransformerFactory.newInstance();
    log.debug("transformer factory: " + transFactory.getClass().getName());
    //transFactory.setAttribute("indent-number", 2);
    Transformer idTransform = null;
    ByteArrayOutputStream stream = null;
    try {/*  ww  w  .  j a  va2  s.c o m*/
        idTransform = transFactory.newTransformer();
        idTransform.setOutputProperty(OutputKeys.METHOD, "xml");
        idTransform.setOutputProperty(OutputKeys.INDENT, "yes");
        idTransform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        Source input = new DOMSource(nsElem.getOwnerDocument());
        stream = new ByteArrayOutputStream();
        Result output = new StreamResult(stream);
        idTransform.transform(input, output);
        stream.flush();
        result = new String(stream.toByteArray());
        return result;
    } catch (TransformerConfigurationException e1) {
        log.error(e1.getMessage(), e1);
    } catch (TransformerException e) {
        log.error(e.getMessage(), e);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    } finally {
        if (stream != null)
            try {
                stream.close();
            } catch (Throwable t) {
            }

    }
    return result;
}

From source file:org.plasma.provisioning.xsd.ConverterSupport.java

public String serializeElement(ElementNSImpl nsElem) {
    String result = "";
    TransformerFactory transFactory = TransformerFactory.newInstance();
    log.debug("transformer factory: " + transFactory.getClass().getName());
    //transFactory.setAttribute("indent-number", 2);
    Transformer idTransform = null;
    ByteArrayOutputStream stream = null;
    try {/*from  ww w  . j  ava  2  s .co  m*/
        idTransform = transFactory.newTransformer();
        idTransform.setOutputProperty(OutputKeys.METHOD, "xml");
        idTransform.setOutputProperty(OutputKeys.INDENT, "yes");
        idTransform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        Source input = new DOMSource(nsElem.getOwnerDocument());
        stream = new ByteArrayOutputStream();
        Result output = new StreamResult(stream);
        idTransform.transform(input, output);
        stream.flush();
        result = new String(stream.toByteArray());
        return result;
    } catch (TransformerConfigurationException e1) {
        log.error(e1.getMessage(), e1);
    } catch (TransformerException e) {
        log.error(e.getMessage(), e);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    } finally {
        if (stream != null)
            try {
                stream.close();
            } catch (Throwable t) {
            }

    }
    return result;
}

From source file:org.protempa.dest.xml.XmlQueryResultsHandler.java

private void printDocument(Document doc) throws IOException, TransformerException {
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.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");

    transformer.transform(new DOMSource(doc), new StreamResult(this.out));
    this.out.flush();
}

From source file:org.regenstrief.util.XMLUtil.java

/**
 * does "pretty" format on XML to produce XML as text
 * //from   w w  w . ja  v a 2  s .c  o m
 * @param elem XML Element to be formated into text
 * @param omitXMLDeclaration set to <code>true</code> to prevent <?xml...?> declaration line
 *            from being included in output
 * @param indent set to <code>true</code> to indent output
 * @param lineWidth the XML line width
 * @return returns formated XML as text
 **/
public static final String xmlToString(final Element elem, final boolean omitXMLDeclaration,
        final boolean indent, final int lineWidth) {
    final StringWriter w = new StringWriter();

    //io.serialize(elem, w, omitXMLDeclaration);
    final Properties prop = new Properties();
    prop.setProperty(OutputKeys.OMIT_XML_DECLARATION, toOutputPropertyValue(omitXMLDeclaration));
    prop.setProperty(OutputKeys.INDENT, toOutputPropertyValue(indent));
    io.serialize(elem, w, prop);

    return w.toString();
    //return XercesUtil.xmlToString(elem, omitXMLDeclaration, indent, lineWidth);
}

From source file:org.regenstrief.util.XMLUtil.java

public final static void convertReportXMLToPlainText(final String reportXML, final Writer out)
        throws Exception {
    if (reportTransform == null) {
        reportTransform = getTransformer("strip.xsl");
        reportTransform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, OUTPUT_PROPERTY_YES);
        reportTransform.setOutputProperty(OutputKeys.INDENT, OUTPUT_PROPERTY_NO);
    }//from   www.  j  av  a  2  s  .c  o  m

    reportTransform.transform(new StreamSource(new StringReader(reportXML)), new StreamResult(out));
}

From source file:org.sakaiproject.citation.impl.BaseConfigurationService.java

protected void saveServletClientMappings(Document document) {

    Element clientElement = document.getElementById("saveciteClients");

    if (clientElement == null) {
        NodeList mapNodes = document.getElementsByTagName("map");
        if (mapNodes != null) {
            for (int i = 0; i < mapNodes.getLength(); i++) {
                Element mapElement = (Element) mapNodes.item(i);
                if (mapElement.hasAttribute("id") && mapElement.getAttribute("id").equals("saveciteClients")) {
                    clientElement = mapElement;
                    break;
                }//from   ww w  .  ja v  a2  s  .c om
            }
        }
    }

    if (clientElement != null) {
        try {
            XStream xstream = new XStream();
            TransformerFactory transFactory = TransformerFactory.newInstance();
            Transformer transformer = transFactory.newTransformer();
            StringWriter buffer = new StringWriter();
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            transformer.transform(new DOMSource(clientElement), new StreamResult(buffer));
            String str = buffer.toString();
            //           DOMImplementationLS domImplLS = (DOMImplementationLS) document.getImplementation();
            //           LSSerializer serializer = domImplLS.createLSSerializer();
            //           String str = serializer.writeToString(clientElement);
            this.saveciteClients = (Map<String, List<Map<String, String>>>) xstream.fromXML(str);
        } catch (Exception e) {
            m_log.warn("Exception trying to read saveciteClients from config XML", e);
        }
    }

}

From source file:org.servalproject.maps.indexgenerator.IndexWriter.java

public static boolean writeXmlIndex(File outputFile, ArrayList<MapInfo> mapInfoList) {

    // create the xml document builder factory object
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    // create the xml document builder object and get the DOMImplementation object
    DocumentBuilder builder = null;
    try {/*from w  w w.j av  a  2 s  .co m*/
        builder = factory.newDocumentBuilder();
    } catch (javax.xml.parsers.ParserConfigurationException e) {
        System.err.println("ERROR: unable to build the XML data. " + e.getMessage());
        return false;
    }

    DOMImplementation domImpl = builder.getDOMImplementation();

    // start to build the document
    Document document = domImpl.createDocument(null, "maps", null);

    // get the root element
    Element rootElement = document.getDocumentElement();

    // add the basic metadata
    Element element = document.createElement("version");
    element.setTextContent(VERSION);
    rootElement.appendChild(element);

    element = document.createElement("generated");
    element.setTextContent(Long.toString(System.currentTimeMillis()));
    rootElement.appendChild(element);

    element = document.createElement("author");
    element.setTextContent(AUTHOR);
    rootElement.appendChild(element);

    element = document.createElement("data_source");
    element.setTextContent(DATA_SOURCE);
    rootElement.appendChild(element);

    element = document.createElement("data_format");
    element.setTextContent(DATA_FORMAT);
    rootElement.appendChild(element);

    element = document.createElement("data_format_info");
    element.setTextContent(DATA_FORMAT_INFO);
    rootElement.appendChild(element);

    element = document.createElement("data_format_version");
    element.setTextContent(DATA_FORMAT_VERSION);
    rootElement.appendChild(element);

    element = document.createElement("more_info");
    element.setTextContent(MORE_INFO);
    rootElement.appendChild(element);

    // add the map file information
    Element mapInfoElement = document.createElement("map-info");
    rootElement.appendChild(mapInfoElement);

    for (MapInfo info : mapInfoList) {
        mapInfoElement.appendChild(info.toXml(document.createElement("map")));
    }

    // output the xml
    try {
        // create a transformer 
        TransformerFactory transFactory = TransformerFactory.newInstance();
        Transformer transformer = transFactory.newTransformer();

        // set some options on the transformer
        transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

        // get a transformer and supporting classes
        StreamResult result = new StreamResult(new PrintWriter(outputFile));
        DOMSource source = new DOMSource(document);

        // transform the internal objects into XML and print it
        transformer.transform(source, result);

    } catch (javax.xml.transform.TransformerException e) {
        System.err.println("ERROR: unable to write the XML data. " + e.getMessage());
        return false;
    } catch (FileNotFoundException e) {
        System.err.println("ERROR: unable to write the XML data. " + e.getMessage());
        return false;
    }

    return true;
}