Example usage for javax.xml.parsers DocumentBuilder newDocument

List of usage examples for javax.xml.parsers DocumentBuilder newDocument

Introduction

In this page you can find the example usage for javax.xml.parsers DocumentBuilder newDocument.

Prototype


public abstract Document newDocument();

Source Link

Document

Obtain a new instance of a DOM Document object to build a DOM tree with.

Usage

From source file:com.zimbra.cs.service.AutoDiscoverServlet.java

private static String createResponseDocForEws(String displayName, String email, String serviceUrl, Account acct)
        throws Exception {

    Provisioning prov = Provisioning.getInstance();
    Server server = prov.getServer(acct);

    String cn = server.getCn();/*from w  w w . j  a va2s.c  o m*/
    String name = server.getName();
    String acctId = acct.getId();

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document xmlDoc = builder.newDocument();

    Element root = xmlDoc.createElementNS(NS, "Autodiscover");
    root.setAttribute("xmlns", NS);
    root.setAttribute("xmlns:xsi", XSI_NS);
    root.setAttribute("xmlns:xsd", XSD_NS);
    xmlDoc.appendChild(root);

    //Add the response element.
    Element response = xmlDoc.createElementNS(NS_OUTLOOK, "Response");
    root.appendChild(response);

    //User
    Element user = xmlDoc.createElement("User");
    Element displayNameElm = xmlDoc.createElement("DisplayName");
    displayNameElm.appendChild(xmlDoc.createTextNode(displayName));
    user.appendChild(displayNameElm);
    Element emailAddr = xmlDoc.createElement("EmailAddress");
    emailAddr.appendChild(xmlDoc.createTextNode(email));
    user.appendChild(emailAddr);

    Element depId = xmlDoc.createElement("DeploymentId");
    depId.appendChild(xmlDoc.createTextNode(acctId));
    user.appendChild(depId);

    response.appendChild(user);

    //Action
    Element account = xmlDoc.createElement("Account");
    Element acctType = xmlDoc.createElement("AccountType");
    acctType.appendChild(xmlDoc.createTextNode("email"));
    account.appendChild(acctType);
    response.appendChild(account);

    Element action = xmlDoc.createElement("Action");
    action.appendChild(xmlDoc.createTextNode("settings"));
    account.appendChild(action);

    Element protocol = xmlDoc.createElement("Protocol");
    account.appendChild(protocol);

    Element type = xmlDoc.createElement("Type");
    type.appendChild(xmlDoc.createTextNode("EXCH"));
    protocol.appendChild(type);

    Element ews = xmlDoc.createElement("EwsUrl");
    protocol.appendChild(ews);
    ews.appendChild(xmlDoc.createTextNode(serviceUrl));

    Element as = xmlDoc.createElement("ASUrl");
    protocol.appendChild(as);
    as.appendChild(xmlDoc.createTextNode(serviceUrl));

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    DOMSource source = new DOMSource(xmlDoc);
    StringWriter writer = new StringWriter();
    StreamResult result = new StreamResult(writer);
    transformer.transform(source, result);
    writer.flush();
    String xml = writer.toString();
    writer.close();
    return "<?xml version=\"1.0\"?>\n" + xml;
}

From source file:com.adaptris.core.util.XmlHelper.java

/**
 * Create a document from an {@code InputStream}.
 * //  w ww  .j av  a 2 s  .c  o m
 * @param in the inputstream
 * @param builder configuration for the underlying {@link DocumentBuilderFactory} instance.
 * @param newDocOnFailure return a new document if the input stream failed to parse.
 * @return the Document element
 */
public static Document createDocument(InputStream in, DocumentBuilderFactoryBuilder builder,
        boolean newDocOnFailure) throws ParserConfigurationException, IOException, SAXException {
    DocumentBuilder docBuilder = newDocumentBuilder(builder);
    Document result = null;
    try (InputStream docIn = in) {
        result = docBuilder.parse(new InputSource(docIn));
    } catch (IOException | SAXException e) {
        if (newDocOnFailure) {
            result = docBuilder.newDocument();
        } else {
            throw e;
        }
    }
    return result;
}

From source file:com.msopentech.odatajclient.engine.data.ODataBinder.java

private static Element newEntryContent() {
    Element properties = null;/*from   w  ww  .  jav a2  s  . com*/
    try {
        final DocumentBuilder builder = ODataConstants.DOC_BUILDER_FACTORY.newDocumentBuilder();
        final Document doc = builder.newDocument();
        properties = doc.createElement(ODataConstants.ELEM_PROPERTIES);
        properties.setAttribute(ODataConstants.XMLNS_METADATA, ODataConstants.NS_METADATA);
        properties.setAttribute(ODataConstants.XMLNS_DATASERVICES, ODataConstants.NS_DATASERVICES);
        properties.setAttribute(ODataConstants.XMLNS_GML, ODataConstants.NS_GML);
        properties.setAttribute(ODataConstants.XMLNS_GEORSS, ODataConstants.NS_GEORSS);
    } catch (ParserConfigurationException e) {
        LOG.error("Failure building entry content", e);
    }

    return properties;
}

From source file:com.granule.json.utils.XML.java

/**
 * Method to do the transform from an JSON input stream to a XML stream.
 * Neither input nor output streams are closed.  Closure is left up to the caller.
 *
 * @param JSONStream The XML stream to convert to JSON
 * @param XMLStream The stream to write out JSON to.  The contents written to this stream are always in UTF-8 format.
 * @param verbose Flag to denote whether or not to render the XML text in verbose (indented easy to read), or compact (not so easy to read, but smaller), format.
 *
 * @throws IOException Thrown if an IO error occurs.
 */// w  w w. ja  v a  2s .  c om
public static void toXml(InputStream JSONStream, OutputStream XMLStream, boolean verbose) throws IOException {
    if (logger.isLoggable(Level.FINER)) {
        logger.entering(className, "toXml(InputStream, OutputStream)");
    }

    if (XMLStream == null) {
        throw new NullPointerException("XMLStream cannot be null");
    } else if (JSONStream == null) {
        throw new NullPointerException("JSONStream cannot be null");
    } else {

        if (logger.isLoggable(Level.FINEST)) {
            logger.logp(Level.FINEST, className, "transform", "Parsing the JSON and a DOM builder.");
        }

        try {
            //Get the JSON from the stream.
            JSONObject jObject = new JSONObject(JSONStream);

            //Create a new document

            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbf.newDocumentBuilder();
            Document doc = dBuilder.newDocument();

            if (logger.isLoggable(Level.FINEST)) {
                logger.logp(Level.FINEST, className, "transform", "Parsing the JSON content to XML");
            }

            convertJSONObject(doc, doc.getDocumentElement(), jObject, "jsonObject");

            //Serialize it.
            TransformerFactory tfactory = TransformerFactory.newInstance();
            Transformer serializer = null;
            if (verbose) {
                serializer = tfactory.newTransformer(new StreamSource(new StringReader(styleSheet)));
                ;
            } else {
                serializer = tfactory.newTransformer();
            }
            Properties oprops = new Properties();
            oprops.put(OutputKeys.METHOD, "xml");
            oprops.put(OutputKeys.OMIT_XML_DECLARATION, "yes");
            oprops.put(OutputKeys.VERSION, "1.0");
            oprops.put(OutputKeys.INDENT, "true");
            serializer.setOutputProperties(oprops);
            serializer.transform(new DOMSource(doc), new StreamResult(XMLStream));

        } catch (Exception ex) {
            IOException iox = new IOException("Problem during conversion");
            iox.initCause(ex);
            throw iox;
        }
    }

    if (logger.isLoggable(Level.FINER)) {
        logger.exiting(className, "toXml(InputStream, OutputStream)");
    }
}

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

private static String prepareMtbxData(List<TestExecutionInfo> tests) throws IOException {
    /*<Mtbx>//from ww  w  . j  ava  2s.  co  m
    <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:Examples.java

/**
 * A fuller example showing how the TrAX interface can be used 
 * to serialize a DOM tree./*w w  w. java2s.  c o m*/
 */
public static void exampleAsSerializer(String sourceID, String xslID) throws TransformerException,
        TransformerConfigurationException, SAXException, IOException, ParserConfigurationException {
    DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = dfactory.newDocumentBuilder();
    org.w3c.dom.Document outNode = docBuilder.newDocument();
    Node doc = docBuilder.parse(new InputSource(sourceID));

    TransformerFactory tfactory = TransformerFactory.newInstance();

    // This creates a transformer that does a simple identity transform, 
    // and thus can be used for all intents and purposes as a serializer.
    Transformer serializer = tfactory.newTransformer();

    Properties oprops = new Properties();
    oprops.put("method", "html");
    serializer.setOutputProperties(oprops);
    serializer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(System.out)));
}

From source file:Examples.java

/**
 * Show how to transform a DOM tree into another DOM tree.
 * This uses the javax.xml.parsers to parse an XML file into a
 * DOM, and create an output DOM.//from w ww.j a v a  2  s .c om
 */
public static Node exampleDOM2DOM(String sourceID, String xslID) throws TransformerException,
        TransformerConfigurationException, SAXException, IOException, ParserConfigurationException {
    TransformerFactory tfactory = TransformerFactory.newInstance();

    if (tfactory.getFeature(DOMSource.FEATURE)) {
        Templates templates;

        {
            DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
            dfactory.setNamespaceAware(true);
            DocumentBuilder docBuilder = dfactory.newDocumentBuilder();
            org.w3c.dom.Document outNode = docBuilder.newDocument();
            Node doc = docBuilder.parse(new InputSource(xslID));

            DOMSource dsource = new DOMSource(doc);
            // If we don't do this, the transformer won't know how to 
            // resolve relative URLs in the stylesheet.
            dsource.setSystemId(xslID);

            templates = tfactory.newTemplates(dsource);
        }

        Transformer transformer = templates.newTransformer();
        DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
        // Note you must always setNamespaceAware when building .xsl stylesheets
        dfactory.setNamespaceAware(true);
        DocumentBuilder docBuilder = dfactory.newDocumentBuilder();
        org.w3c.dom.Document outNode = docBuilder.newDocument();
        Node doc = docBuilder.parse(new InputSource(sourceID));

        transformer.transform(new DOMSource(doc), new DOMResult(outNode));

        Transformer serializer = tfactory.newTransformer();
        serializer.transform(new DOMSource(outNode), new StreamResult(new OutputStreamWriter(System.out)));

        return outNode;
    } else {
        throw new org.xml.sax.SAXNotSupportedException("DOM node processing not supported!");
    }
}

From source file:Examples.java

/**
 * Show the Transformer using SAX events in and DOM nodes out.
 *///from   w w w. java2s  .c  om
public static void exampleContentHandler2DOM(String sourceID, String xslID) throws TransformerException,
        TransformerConfigurationException, SAXException, IOException, ParserConfigurationException {
    TransformerFactory tfactory = TransformerFactory.newInstance();

    // Make sure the transformer factory we obtained supports both
    // DOM and SAX.
    if (tfactory.getFeature(SAXSource.FEATURE) && tfactory.getFeature(DOMSource.FEATURE)) {
        // We can now safely cast to a SAXTransformerFactory.
        SAXTransformerFactory sfactory = (SAXTransformerFactory) tfactory;

        // Create an Document node as the root for the output.
        DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dfactory.newDocumentBuilder();
        org.w3c.dom.Document outNode = docBuilder.newDocument();

        // Create a ContentHandler that can liston to SAX events 
        // and transform the output to DOM nodes.
        TransformerHandler handler = sfactory.newTransformerHandler(new StreamSource(xslID));
        handler.setResult(new DOMResult(outNode));

        // Create a reader and set it's ContentHandler to be the 
        // transformer.
        XMLReader reader = null;

        // Use JAXP1.1 ( if possible )
        try {
            javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance();
            factory.setNamespaceAware(true);
            javax.xml.parsers.SAXParser jaxpParser = factory.newSAXParser();
            reader = jaxpParser.getXMLReader();

        } catch (javax.xml.parsers.ParserConfigurationException ex) {
            throw new org.xml.sax.SAXException(ex);
        } catch (javax.xml.parsers.FactoryConfigurationError ex1) {
            throw new org.xml.sax.SAXException(ex1.toString());
        } catch (NoSuchMethodError ex2) {
        }
        if (reader == null)
            reader = XMLReaderFactory.createXMLReader();
        reader.setContentHandler(handler);
        reader.setProperty("http://xml.org/sax/properties/lexical-handler", handler);

        // Send the SAX events from the parser to the transformer,
        // and thus to the DOM tree.
        reader.parse(sourceID);

        // Serialize the node for diagnosis.
        exampleSerializeNode(outNode);
    } else {
        System.out.println(
                "Can't do exampleContentHandlerToContentHandler because tfactory is not a SAXTransformerFactory");
    }
}

From source file:org.openmrs.module.atomfeed.AtomFeedUtil.java

/**
 * Updates content of atom feed header file by re-creating new xml header block and writing it
 * into given file. Actually, if given atom feed header file does not exists, it creates it.
 * Otherwise, it changes values of "updated", "versionId" and "entriesSize" elements within
 * header xml tree./*from w w  w . j av  a 2s .  c  o m*/
 * 
 * @param atomfeedheader the file target to be updated
 * @param entriesSize the size in bytes of entries payload, which is related to given feed
 *            header
 */
private static void updateFeedFileHeader(File atomfeedheader, long entriesSize) {
    try {
        // We need a Document
        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
        Document doc = docBuilder.newDocument();

        // //////////////////////
        // Creating the XML tree

        // create the root element and add it to the document
        Element root = doc.createElement("feed");
        root.setAttribute("xmlns", "http://www.w3.org/2005/Atom");
        doc.appendChild(root);

        // create title element, add its text, and add to root
        Element title = doc.createElement("title");
        Text titleText = doc.createTextNode(AtomFeedConstants.ATOM_FEED_TITLE);
        title.appendChild(titleText);
        root.appendChild(title);

        // create title element, add its attrs, and add to root
        Element selflink = doc.createElement("link");
        selflink.setAttribute("href", AtomFeedUtil.getFeedUrl());
        selflink.setAttribute("rel", "self");
        root.appendChild(selflink);

        Element serverlink = doc.createElement("link");
        serverlink.setAttribute("href", getWebServiceUrl());
        root.appendChild(serverlink);

        // create title element, add its text, and add to root
        Element id = doc.createElement("id");
        Text idText = doc.createTextNode(AtomFeedConstants.ATOM_FEED_ID);
        id.appendChild(idText);
        root.appendChild(id);

        // create updated element, add its text, and add to root
        Element updated = doc.createElement("updated");
        Date lastModified = new Date();
        Text updatedText = doc.createTextNode(dateToRFC3339(lastModified));
        updated.appendChild(updatedText);
        root.appendChild(updated);

        // create versionId element, add its text, and add to root
        Element versionId = doc.createElement("versionId");
        Text versionIdText = doc.createTextNode(String.valueOf(lastModified.getTime()));
        versionId.appendChild(versionIdText);
        root.appendChild(versionId);

        // create versionId element, add its text, and add to root
        Element entriesSizeElement = doc.createElement("entriesSize");
        Text entriesSizeText = doc.createTextNode(String.valueOf(entriesSize));
        entriesSizeElement.appendChild(entriesSizeText);
        root.appendChild(entriesSizeElement);

        /*
         * Print the xml to the file
         */

        // set up a transformer
        TransformerFactory transfac = TransformerFactory.newInstance();
        Transformer trans = transfac.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        trans.setOutputProperty(OutputKeys.INDENT, "no");

        // create string from xml tree
        FileWriter fw = new FileWriter(atomfeedheader);
        StreamResult result = new StreamResult(fw);
        DOMSource source = new DOMSource(doc);
        trans.transform(source, result);

        // print xml for debugging purposes
        if (log.isTraceEnabled()) {
            StringWriter sw = new StringWriter();
            result = new StreamResult(sw);
            trans.transform(source, result);
            log.trace("Here's the initial xml:\n\n" + sw.toString());
        }

    } catch (Exception e) {
        log.error("unable to initialize feed at: " + atomfeedheader.getAbsolutePath(), e);
    }
}

From source file:org.openmrs.module.atomfeed.AtomFeedUtil.java

/**
 * Converts the given object to an xml entry
 * //  w w  w  .  j  a  v a2  s  .c o m
 * @param action what is happenening
 * @param object the object being changed
 * @return atom feed xml entry string
 * @should return valid entry xml data
 */
protected static String getEntry(String action, OpenmrsObject object) {
    try {
        // We need a Document
        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
        Document doc = docBuilder.newDocument();

        // //////////////////////
        // Creating the XML tree

        // create the root element and add it to the document
        Element root = doc.createElement("entry");
        doc.appendChild(root);

        // the title element is REQUIRED
        // create title element, add object class, and add to root
        Element title = doc.createElement("title");
        Text titleText = doc.createTextNode(action + ":" + object.getClass().getName());
        title.appendChild(titleText);
        root.appendChild(title);

        // create link to view object details
        Element link = doc.createElement("link");
        link.setAttribute("href", AtomFeedUtil.getViewUrl(object));
        root.appendChild(link);

        // the id element is REQUIRED
        // create id element
        Element id = doc.createElement("id");
        Text idText = doc.createTextNode("urn:uuid:" + object.getUuid());
        id.appendChild(idText);
        root.appendChild(id);

        // the updated element is REQUIRED
        // create updated element, set current date
        Element updated = doc.createElement("updated");
        // TODO: try to discover dateChanged/dateCreated from object -- ATOM-2
        // instead?
        Text updatedText = doc.createTextNode(dateToRFC3339(getUpdatedValue(object)));
        updated.appendChild(updatedText);
        root.appendChild(updated);

        // the author element is REQUIRED
        // add author element, find creator
        Element author = doc.createElement("author");
        Element name = doc.createElement("name");
        Text nameText = doc.createTextNode(getAuthor(object));

        name.appendChild(nameText);
        author.appendChild(name);
        root.appendChild(author);

        // the summary element is REQUIRED
        // add a summary
        Element summary = doc.createElement("summary");
        Text summaryText = doc.createTextNode(object.getClass().getSimpleName() + " -- " + action);
        summary.appendChild(summaryText);
        root.appendChild(summary);

        Element classname = doc.createElement("classname");
        Text classnameText = doc.createTextNode(object.getClass().getName());
        classname.appendChild(classnameText);
        root.appendChild(classname);

        Element actionElement = doc.createElement("action");
        Text actionText = doc.createTextNode(action);
        actionElement.appendChild(actionText);
        root.appendChild(actionElement);

        /*
         * Print the xml to the string
         */

        // set up a transformer
        TransformerFactory transfac = TransformerFactory.newInstance();
        Transformer trans = transfac.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        trans.setOutputProperty(OutputKeys.INDENT, "no");

        StringWriter sw = new StringWriter();
        StreamResult result = new StreamResult(sw);
        DOMSource source = new DOMSource(doc);
        trans.transform(source, result);

        return sw.toString();
    } catch (Exception e) {
        log.error("unable to create entry string for: " + object);
        return "";
    }
}