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:com.google.enterprise.connector.salesforce.BaseTraversalManager.java

private DocumentList traverse(String checkpoint) {

    // count the number of times the traverse() was called
    second_counter++;//from  w  w w .  j  av a 2  s.c o m
    if (second_counter == 10) {
        // every 10 seconds print a message
        logger.log(Level.INFO, "[" + connector.getInstanceName() + "] Traverse after [" + checkpoint + "]");
        second_counter = 0;
    }
    // set the current crawled checkpoint
    System.setProperty(this.getConnector().getInstanceName() + "_lcheckpoint", checkpoint);

    // initialize the basedocument list to return
    BaseDocumentList sdl = null;

    try {
        // convert a Date object into a 'numeric' format like
        // 200906010641010
        Date conv_checkpoint = Util.getNumericDate_from_String(checkpoint);

        // if its the first time we're doing this...create the checkpoint
        // for now
        if (conv_checkpoint == null || checkpoint.equalsIgnoreCase("")) {
            Date now = new Date();
            // hmmm...we could set the checkpoint here as either
            checkpoint = this.getConnector().getLastsync();
            // or
            // checkpoint = Util.getNumericString_from_Date(now);
        }

        // initialize a document list with 0 items and now as the checkpoint
        sdl = new BaseDocumentList(0, checkpoint);

        // if your xslt is not processable, return nothing
        if (this.XSLTDoc == null) {
            logger.log(Level.SEVERE, "[" + connector.getInstanceName()
                    + "] Response XSLT not compiled, not proceeded with transforms.");
            return sdl;
        }

        // ok...so our document list has nothing in it so lets go ask the
        // store if we
        // have any more docs to process...
        if (docListIndex.size() == 0) {
            getDocListAfter(checkpoint);
        }

        // now we have some docs in the document array we need to process
        if (docListIndex.size() > 0) {
            // get a doclist from the queue
            DocListEntry de = (DocListEntry) docListIndex.poll();

            // now convert the doclistentry (which is a SOAP response doc)
            // XML to <document><document>
            logger.log(Level.FINE,
                    "Attempting to convert string row to DOM object  [" + de.getCheckpoint() + "]");
            Document doc_in_xml = Util.XMLStringtoDoc(de.getResponseXML());
            logger.log(Level.FINE,
                    "Attempting to Transform DOM object  to <document/> [" + de.getCheckpoint() + "]");
            Document transformed_QueryResult = Util.TransformDoctoDoc(doc_in_xml, this.XSLTDoc);

            // TODO: DTD Validate the transformed SOAP query result

            logger.log(Level.FINE, "Extracting <document> objects from transformed response");

            NodeList nl_documents = transformed_QueryResult.getElementsByTagName("documents");
            // get the NodeList under <document>
            Node n_documents = nl_documents.item(0);
            Vector v_batch = new Vector();
            for (int i = 0; i < n_documents.getChildNodes().getLength(); i++) {
                Node n_doc = n_documents.getChildNodes().item(i);

                if (n_doc.getNodeType() == Node.ELEMENT_NODE) {
                    TransformerFactory transfac = TransformerFactory.newInstance();
                    Transformer trans = transfac.newTransformer();
                    trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
                    trans.setOutputProperty(OutputKeys.INDENT, "yes");

                    if (n_doc.getNodeName().equalsIgnoreCase("document")) {

                        DOMResult dr = new DOMResult();
                        trans.transform(new DOMSource(n_doc), dr);
                        Document newDoc = (Document) dr.getNode();
                        newDoc.getDocumentElement().normalize();
                        v_batch.add(newDoc);
                    }
                }
            }
            logger.log(Level.FINE, "Found " + v_batch.size() + "  documents in batch response");

            // so now we've populated a vector (v_batch) with XML elements
            // of <document></document>
            // objects

            sdl = new BaseDocumentList(v_batch.size(), de.getCheckpoint());
            for (int i = 0; i < v_batch.size(); i++) {

                // now convert each entry in the vector to a basedocument
                BaseSimpleDocument bdoc = this.convertXMLtoBaseDocument((Document) v_batch.get(i));
                SimpleDocument sd = (SimpleDocument) bdoc;
                sdl.add(sd);
            }
        }

        if (sdl.size() > 0) {
            this.running_doc_counter = this.running_doc_counter + sdl.size();
            logger.log(Level.INFO, "[" + connector.getInstanceName() + "]" + "  Returning " + sdl.size()
                    + " documents to the connector manager.  ");
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "traverse() error " + ex);
    }

    // return the doclist
    return sdl;
}

From source file:com.vmware.identity.samlservice.Shared.java

/**
 * Print out XML node to a stream/*from  www. j a  va2 s  . c om*/
 *
 * @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:com.hpe.application.automation.tools.octane.executor.TestExecutionJobCreatorService.java

private static String prepareMtbxData(List<TestExecutionInfo> tests) throws IOException {
    /*<Mtbx>/*  w w w  . j  a v  a 2s . c om*/
    <Test name="test1" path="${WORKSPACE}\${CHECKOUT_SUBDIR}\APITest1">
     <Parameter name="A" value="abc" type="string"/>
     <DataTable path="${WORKSPACE}\aa\bbb.xslx"/>
      .
     </Test>
     <Test name="test2" path="${WORKSPACE}\${CHECKOUT_SUBDIR}\test2">
    <Parameter name="p1" value="123" type="int"/>
    <Parameter name="p4" value="123.4" type="float"/>
     .
     </Test>
    </Mtbx>*/

    try {
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement("Mtbx");
        doc.appendChild(rootElement);

        for (TestExecutionInfo test : tests) {
            Element testElement = doc.createElement("Test");
            String packageAndTestName = (StringUtils.isNotEmpty(test.getPackageName())
                    ? test.getPackageName() + "\\"
                    : "") + test.getTestName();
            testElement.setAttribute("name", packageAndTestName);
            String path = "${WORKSPACE}\\${CHECKOUT_SUBDIR}"
                    + (StringUtils.isEmpty(test.getPackageName()) ? ""
                            : OctaneConstants.General.WINDOWS_PATH_SPLITTER + test.getPackageName())
                    + OctaneConstants.General.WINDOWS_PATH_SPLITTER + test.getTestName();
            testElement.setAttribute("path", path);

            if (StringUtils.isNotEmpty(test.getDataTable())) {
                Element dataTableElement = doc.createElement("DataTable");
                dataTableElement.setAttribute("path", "${WORKSPACE}\\${CHECKOUT_SUBDIR}"
                        + OctaneConstants.General.WINDOWS_PATH_SPLITTER + test.getDataTable());
                testElement.appendChild(dataTableElement);
            }

            rootElement.appendChild(testElement);
        }

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

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

        return writer.toString();
    } catch (Exception e) {
        throw new IOException("Failed to build MTBX content : " + e.getMessage());
    }

}

From source file:com.microfocus.application.automation.tools.octane.executor.TestExecutionJobCreatorService.java

private static String prepareMtbxData(List<TestExecutionInfo> tests) throws IOException {
    /*<Mtbx>/*  ww  w  . j  a  v a  2  s. c om*/
    <Test name="test1" path="${WORKSPACE}\${CHECKOUT_SUBDIR}\APITest1">
     <Parameter name="A" value="abc" type="string"/>
     <DataTable path="${WORKSPACE}\aa\bbb.xslx"/>
      .
     </Test>
     <Test name="test2" path="${WORKSPACE}\${CHECKOUT_SUBDIR}\test2">
    <Parameter name="p1" value="123" type="int"/>
    <Parameter name="p4" value="123.4" type="float"/>
     .
     </Test>
    </Mtbx>*/

    try {
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement("Mtbx");
        doc.appendChild(rootElement);

        for (TestExecutionInfo test : tests) {
            Element testElement = doc.createElement("Test");
            String packageAndTestName = (StringUtils.isNotEmpty(test.getPackageName())
                    ? test.getPackageName() + "\\"
                    : "") + test.getTestName();
            testElement.setAttribute("name", packageAndTestName);
            String path = "${WORKSPACE}\\${CHECKOUT_SUBDIR}"
                    + (StringUtils.isEmpty(test.getPackageName()) ? ""
                            : SdkConstants.FileSystem.WINDOWS_PATH_SPLITTER + test.getPackageName())
                    + SdkConstants.FileSystem.WINDOWS_PATH_SPLITTER + test.getTestName();
            testElement.setAttribute("path", path);

            if (StringUtils.isNotEmpty(test.getDataTable())) {
                Element dataTableElement = doc.createElement("DataTable");
                dataTableElement.setAttribute("path", "${WORKSPACE}\\${CHECKOUT_SUBDIR}"
                        + SdkConstants.FileSystem.WINDOWS_PATH_SPLITTER + test.getDataTable());
                testElement.appendChild(dataTableElement);
            }

            rootElement.appendChild(testElement);
        }

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

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

        return writer.toString();
    } catch (Exception e) {
        throw new IOException("Failed to build MTBX content : " + e.getMessage());
    }

}

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);
    }/*from   www  .  j a 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:com.photon.phresco.plugin.commons.PluginUtils.java

public void encryptConfigFile(String fileName) throws PhrescoException {
    InputStream inputStream = null;
    try {// ww  w.j a v a 2s . co m
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        inputStream = new FileInputStream(new File(fileName));
        Document doc = documentBuilderFactory.newDocumentBuilder().parse(inputStream);
        StringWriter stw = new StringWriter();
        Transformer serializer = TransformerFactory.newInstance().newTransformer();
        serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.transform(new DOMSource(doc), new StreamResult(stw));
        EncryptString encryptstring = new EncryptString();
        encryptstring.Crypto("D4:6E:AC:3F:F0:BE");
        String encryptXmlString = encryptstring.encrypt(stw.toString());
        writeXml(encryptXmlString, fileName);
    } catch (Exception e) {
        throw new PhrescoException(e);
    } finally {
        try {
            if (inputStream != null) {
                inputStream.close();
            }
        } catch (IOException e) {
            throw new PhrescoException(e);
        }
    }
}

From source file:com.sonyericsson.hudson.plugins.gerrit.trigger.spec.DuplicateGerritListenersPreloadedProjectHudsonTestCase.java

/**
 * Transforms the xml document into an xml string.
 *
 * @param doc the document// w  w w  .  j a  v  a2  s .  co  m
 * @return the xml
 * @throws TransformerException if so.
 */
String xmlToString(Document doc) throws TransformerException {
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    StringWriter writer = new StringWriter();
    transformer.transform(new DOMSource(doc), new StreamResult(writer));
    return writer.getBuffer().toString();
}

From source file:com.krawler.portal.tools.ServiceBuilder.java

public void createModuleDef(com.krawler.utils.json.base.JSONArray jsonData, String classname) {
    String result = "";
    try {//w ww . ja v  a  2s .co m

        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();

        Document doc = docBuilder.parse((new ClassPathResource("logic/moduleEx.xml").getFile()));
        //Document doc = docBuilder.newDocument();
        NodeList modules = doc.getElementsByTagName("modules");
        Node modulesNode = modules.item(0);
        Element module_ex = doc.getElementById(classname);
        if (module_ex != null) {
            modulesNode.removeChild(module_ex);
        }
        Element module = doc.createElement("module");
        Element property_list = doc.createElement("property-list");
        module.setAttribute("class", "com.krawler.esp.hibernate.impl." + classname);
        module.setAttribute("type", "pojo");
        module.setAttribute("id", classname);
        for (int cnt = 0; cnt < jsonData.length(); cnt++) {
            Element propertyNode = doc.createElement("property");
            JSONObject jsonObj = jsonData.optJSONObject(cnt);

            propertyNode.setAttribute("name", jsonObj.optString("varname"));
            propertyNode.setAttribute("type", jsonObj.optString("modulename").toLowerCase());
            property_list.appendChild(propertyNode);

        }

        module.appendChild(property_list);
        modulesNode.appendChild(module);
        TransformerFactory transfac = TransformerFactory.newInstance();
        Transformer trans = transfac.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        trans.setOutputProperty(OutputKeys.INDENT, "yes");
        trans.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//KRAWLER//DTD BUSINESSRULES//EN");
        trans.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "http://localhost/dtds/module.dtd");
        trans.setOutputProperty(OutputKeys.VERSION, "1.0");
        trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        // create string from xml tree
        File outputFile = (new ClassPathResource("logic/moduleEx.xml").getFile());
        outputFile.setWritable(true);
        // StringWriter sw = new StringWriter();
        StreamResult sresult = new StreamResult(outputFile);

        DOMSource source = new DOMSource(doc);
        trans.transform(source, sresult);
        //       result  = sw.toString();

    } catch (SAXException ex) {
        logger.warn(ex.getMessage(), ex);
    } catch (IOException ex) {
        logger.warn(ex.getMessage(), ex);
    } catch (TransformerException ex) {
        logger.warn(ex.getMessage(), ex);
    } catch (ParserConfigurationException ex) {
        logger.warn(ex.getMessage(), ex);
    }
}

From source file:com.photon.phresco.service.util.ServerUtil.java

/**
 * To create pom.xml file for artifact upload
 * /*from  w ww  .  ja v  a 2s .c  o  m*/
 * @param info
 * @return
 * @throws PhrescoException
 */
public static File createPomFile(ArtifactGroup info) throws PhrescoException {
    FileWriter writer = null;
    File pomFile = getPomFile();
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    try {
        DocumentBuilder domBuilder = domFactory.newDocumentBuilder();

        org.w3c.dom.Document newDoc = domBuilder.newDocument();
        Element rootElement = newDoc.createElement(ServerConstants.POM_PROJECT);
        newDoc.appendChild(rootElement);

        Element modelVersion = newDoc.createElement(ServerConstants.POM_MODELVERSION);
        modelVersion.setTextContent(ServerConstants.POM_MODELVERSION_VAL);
        rootElement.appendChild(modelVersion);

        Element groupId = newDoc.createElement(ServerConstants.POM_GROUPID);
        groupId.setTextContent(info.getGroupId());
        rootElement.appendChild(groupId);

        Element artifactId = newDoc.createElement(ServerConstants.POM_ARTIFACTID);
        artifactId.setTextContent(info.getArtifactId());
        rootElement.appendChild(artifactId);

        Element version = newDoc.createElement(ServerConstants.POM_VERSION);
        version.setTextContent(info.getVersions().get(0).getVersion());
        rootElement.appendChild(version);

        Element packaging = newDoc.createElement(ServerConstants.POM_PACKAGING);
        packaging.setTextContent(info.getPackaging());
        rootElement.appendChild(packaging);

        Element description = newDoc.createElement(ServerConstants.POM_DESC);
        description.setTextContent(ServerConstants.POM_DESC_VAL);
        rootElement.appendChild(description);

        TransformerFactory transfac = TransformerFactory.newInstance();
        Transformer trans = transfac.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, ServerConstants.POM_OMMIT);
        trans.setOutputProperty(OutputKeys.INDENT, ServerConstants.POM_DESC);

        StringWriter sw = new StringWriter();
        StreamResult result = new StreamResult(sw);
        DOMSource source = new DOMSource(newDoc);
        trans.transform(source, result);
        String xmlString = sw.toString();
        writer = new FileWriter(pomFile);
        writer.write(xmlString);
        writer.close();
    } catch (Exception e) {
        throw new PhrescoException(e);
    } finally {
        Utility.closeStream(writer);
    }

    return pomFile;
}

From source file:io.cloudslang.content.xml.utils.XmlUtils.java

private static String transformElementNode(Node node) throws TransformerException {
    StringWriter stringWriter = new StringWriter();

    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, Constants.YES);
    transformer.setOutputProperty(OutputKeys.INDENT, Constants.YES);
    transformer.transform(new DOMSource(node), new StreamResult(stringWriter));

    return stringWriter.toString().trim();
}