Example usage for org.w3c.dom Document appendChild

List of usage examples for org.w3c.dom Document appendChild

Introduction

In this page you can find the example usage for org.w3c.dom Document appendChild.

Prototype

public Node appendChild(Node newChild) throws DOMException;

Source Link

Document

Adds the node newChild to the end of the list of children of this node.

Usage

From source file:ddf.catalog.services.xsltlistener.XsltResponseQueueTransformer.java

@Override
public ddf.catalog.data.BinaryContent transform(SourceResponse upstreamResponse,
        Map<String, Serializable> arguments) throws CatalogTransformerException {

    LOGGER.debug("Transforming ResponseQueue with XSLT tranformer");

    long grandTotal = -1;

    try {//from  ww  w . ja  v  a  2 s  .c o  m
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();

        Document doc = builder.newDocument();

        Node resultsElement = doc.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "results", null));

        // TODO use streaming XSLT, not DOM
        List<Result> results = upstreamResponse.getResults();
        grandTotal = upstreamResponse.getHits();

        for (Result result : results) {
            Metacard metacard = result.getMetacard();
            String thisMetacard = metacard.getMetadata();
            if (metacard != null && thisMetacard != null) {
                Element metacardElement = createElement(doc, XML_RESULTS_NAMESPACE, "metacard", null);
                if (metacard.getId() != null) {
                    metacardElement
                            .appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "id", metacard.getId()));
                }
                if (metacard.getMetacardType().toString() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "type",
                            metacard.getMetacardType().getName()));
                }
                if (metacard.getTitle() != null) {
                    metacardElement.appendChild(
                            createElement(doc, XML_RESULTS_NAMESPACE, "title", metacard.getTitle()));
                }
                if (result.getRelevanceScore() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "score",
                            result.getRelevanceScore().toString()));
                }
                if (result.getDistanceInMeters() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "distance",
                            result.getDistanceInMeters().toString()));
                }
                if (metacard.getSourceId() != null) {
                    metacardElement.appendChild(
                            createElement(doc, XML_RESULTS_NAMESPACE, "site", metacard.getSourceId()));
                }
                if (metacard.getContentTypeName() != null) {
                    String contentType = metacard.getContentTypeName();
                    Element typeElement = createElement(doc, XML_RESULTS_NAMESPACE, "content-type",
                            contentType);
                    // TODO revisit what to put in the qualifier
                    typeElement.setAttribute("qualifier", "content-type");
                    metacardElement.appendChild(typeElement);
                }
                if (metacard.getResourceURI() != null) {
                    try {
                        metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "product",
                                metacard.getResourceURI().toString()));
                    } catch (DOMException e) {
                        LOGGER.warn(" Unable to create resource uri element", e);
                    }
                }
                if (metacard.getThumbnail() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "thumbnail",
                            Base64.encodeBase64String(metacard.getThumbnail())));
                    try {
                        String mimeType = URLConnection
                                .guessContentTypeFromStream(new ByteArrayInputStream(metacard.getThumbnail()));
                        metacardElement
                                .appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "t_mimetype", mimeType));
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        metacardElement.appendChild(
                                createElement(doc, XML_RESULTS_NAMESPACE, "t_mimetype", "image/png"));
                    }
                }
                DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
                if (metacard.getCreatedDate() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "created",
                            fmt.print(metacard.getCreatedDate().getTime())));
                }
                // looking at the date last modified
                if (metacard.getModifiedDate() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "updated",
                            fmt.print(metacard.getModifiedDate().getTime())));
                }
                if (metacard.getEffectiveDate() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "effective",
                            fmt.print(metacard.getEffectiveDate().getTime())));
                }
                if (metacard.getLocation() != null) {
                    metacardElement.appendChild(
                            createElement(doc, XML_RESULTS_NAMESPACE, "location", metacard.getLocation()));
                }
                Element documentElement = doc.createElementNS(XML_RESULTS_NAMESPACE, "document");
                metacardElement.appendChild(documentElement);
                resultsElement.appendChild(metacardElement);

                Node importedNode = doc.importNode(new XPathHelper(thisMetacard).getDocument().getFirstChild(),
                        true);
                documentElement.appendChild(importedNode);
            } else {
                LOGGER.debug("Null content/document returned to XSLT ResponseQueueTransformer");
                continue;
            }
        }

        if (LOGGER.isDebugEnabled()) {
            DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
            LSSerializer lsSerializer = domImplementation.createLSSerializer();
            LOGGER.debug("Generated XML input for transform: " + lsSerializer.writeToString(doc));
        }

        LOGGER.debug("Starting responsequeue xslt transform.");

        Transformer transformer;

        Map<String, Object> mergedMap = new HashMap<String, Object>();
        mergedMap.put(GRAND_TOTAL, grandTotal);
        if (arguments != null) {
            mergedMap.putAll(arguments);
        }

        BinaryContent resultContent;
        StreamResult resultOutput = null;
        Source source = new DOMSource(doc);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        resultOutput = new StreamResult(baos);

        try {
            transformer = templates.newTransformer();
        } catch (TransformerConfigurationException tce) {
            throw new CatalogTransformerException("Could not perform Xslt transform: " + tce.getException(),
                    tce.getCause());
        }

        if (mergedMap != null && !mergedMap.isEmpty()) {
            for (Map.Entry<String, Object> entry : mergedMap.entrySet()) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug(
                            "Adding parameter to transform {" + entry.getKey() + ":" + entry.getValue() + "}");
                }
                transformer.setParameter(entry.getKey(), entry.getValue());
            }
        }

        try {
            transformer.transform(source, resultOutput);
            byte[] bytes = baos.toByteArray();
            LOGGER.debug("Transform complete.");
            resultContent = new XsltTransformedContent(bytes, mimeType);
        } catch (TransformerException te) {
            LOGGER.error("Could not perform Xslt transform: " + te.getException(), te.getCause());
            throw new CatalogTransformerException("Could not perform Xslt transform: " + te.getException(),
                    te.getCause());
        } finally {
            // transformer.reset();
            // don't need to do that unless we are putting it back into a
            // pool -- which we should do, but that can wait until later.
        }

        return resultContent;
    } catch (ParserConfigurationException e) {
        LOGGER.warn("Error creating new document: " + e.getMessage(), e.getCause());
        throw new CatalogTransformerException("Error merging entries to xml feed.", e);
    }
}

From source file:com.twinsoft.convertigo.engine.util.TwsCachedXPathAPI.java

/**
 * Returns a node list for the specified Xpath and context node. When the result is just a string, a NodeList is 
 * constructed containing one node text containing this string.
 * /*w w  w. j av  a 2s . c o  m*/
 * @param contextNode
 * @param xpath
 * @return null is an error occurs
 * @throws TransformerException
 */
public NodeList selectNodeList(Node contextNode, String xpath) throws TransformerException {
    switch (xpathEngine) {
    case Xalan:
        checkContextNode(contextNode);
        XObject Xobj;

        Xobj = xpathApi.eval(contextNode, xpath);
        switch (Xobj.getType()) {
        case XObject.CLASS_NODESET:
            return (Xobj.nodelist());

        case XObject.CLASS_BOOLEAN:
        case XObject.CLASS_NUMBER:
        case XObject.CLASS_STRING:
            try {
                Document doc = XMLUtils.getDefaultDocumentBuilder().newDocument();
                Element root = (Element) doc.createElement("root");
                doc.appendChild(root);
                root.appendChild(doc.createTextNode(Xobj.str()));
                return (root.getChildNodes());
            } catch (Exception e) {
                return null;
            }
        }
        return null;
    }
    return new JXPathNodeList(selectList(contextNode, xpath));

}

From source file:cn.itcast.fredck.FCKeditor.connector.ConnectorServlet.java

private Node CreateCommonXml(Document doc, String commandStr, String typeStr, String currentPath,
        String currentUrl) {/*from  ww w. ja va 2  s  .  c  om*/

    Element root = doc.createElement("Connector");
    doc.appendChild(root);
    root.setAttribute("command", commandStr);
    root.setAttribute("resourceType", typeStr);

    Element myEl = doc.createElement("CurrentFolder");
    myEl.setAttribute("path", currentPath);
    myEl.setAttribute("url", currentUrl);
    root.appendChild(myEl);

    return root;

}

From source file:com.mirth.connect.connectors.jdbc.DatabaseReceiver.java

/**
 * Convert a resultMap representing a message into XML.
 *///from  ww w  . j  a va  2 s  .c o  m
private String resultMapToXml(Map<String, Object> resultMap) throws Exception {
    Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    Element root = document.createElement("result");
    document.appendChild(root);

    for (Entry<String, Object> entry : resultMap.entrySet()) {
        String value = objectToString(entry.getValue());

        if (value != null) {
            Element child = document.createElement(entry.getKey());
            child.appendChild(document.createTextNode(value));
            root.appendChild(child);
        }
    }

    return new DocumentSerializer().toXML(document);
}

From source file:hoot.services.controllers.osm.MapResource.java

/**
 * Writes a map query response with no element data
 *
 * @return a XML document response/*www .  j a  v a  2  s  .c o m*/
 */
private static Document writeEmptyResponse() {
    Document responseDoc = null;
    try {
        responseDoc = XmlDocumentBuilder.create();
    } catch (ParserConfigurationException e) {
        throw new RuntimeException("Error creating XmlDocumentBuilder!", e);
    }

    Element elementRootXml = OsmResponseHeaderGenerator.getOsmDataHeader(responseDoc);
    responseDoc.appendChild(elementRootXml);
    return responseDoc;
}

From source file:com.adr.mimame.PlatformList.java

private boolean saveList(List<GamesItem> games, File f) {

    try {//from   w  w  w . j av a 2 s .  c o m
        FileUtils.forceMkdir(f);

        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.newDocument();
        Element root = doc.createElement("gameslist");
        doc.appendChild(root);

        for (GamesItem g : games) {
            Element e = doc.createElement("game");
            root.appendChild(e);
            g.toElement(e);
        }

        // write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File(f, "games.xml"));
        transformer.transform(source, result);
        return true;
    } catch (IOException ex) {
        logger.log(Level.SEVERE, null, ex);
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(PlatformList.class.getName()).log(Level.SEVERE, null, ex);
    } catch (TransformerConfigurationException ex) {
        Logger.getLogger(PlatformList.class.getName()).log(Level.SEVERE, null, ex);
    } catch (TransformerException ex) {
        Logger.getLogger(PlatformList.class.getName()).log(Level.SEVERE, null, ex);
    }
    return false;
}

From source file:com.gargoylesoftware.htmlunit.activex.javascript.msxml.XSLProcessor.java

/**
 * @return {@link XMLDOMNode} or {@link String}
 *///from w  w  w .  j  a  va 2s .  co  m
private Object transform(final XMLDOMNode source) {
    try {
        Source xmlSource = new DOMSource(source.getDomNodeOrDie());
        final Source xsltSource = new DOMSource(style_.getDomNodeOrDie());

        final org.w3c.dom.Document containerDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .newDocument();
        final org.w3c.dom.Element containerElement = containerDocument.createElement("container");
        containerDocument.appendChild(containerElement);

        final DOMResult result = new DOMResult(containerElement);

        final Transformer transformer = TransformerFactory.newInstance().newTransformer(xsltSource);
        for (final Map.Entry<String, Object> entry : parameters_.entrySet()) {
            transformer.setParameter(entry.getKey(), entry.getValue());
        }
        transformer.transform(xmlSource, result);

        final org.w3c.dom.Node transformedNode = result.getNode();
        if (transformedNode.getFirstChild().getNodeType() == Node.ELEMENT_NODE) {
            return transformedNode;
        }
        //output is not DOM (text)
        xmlSource = new DOMSource(source.getDomNodeOrDie());
        final StringWriter writer = new StringWriter();
        final Result streamResult = new StreamResult(writer);
        transformer.transform(xmlSource, streamResult);
        return writer.toString();
    } catch (final Exception e) {
        throw Context.reportRuntimeError("Exception: " + e);
    }
}

From source file:com.verisign.epp.codec.verificationcode.EPPEncodedSignedCodeValue.java

/**
 * Encode the encoded signed code to a <code>byte[]</code>. This returns the
 * XML with the wrapping &lt;verificationCode:code&gt; element with the
 * Base64 encoded signed code value./* w w w  . j  a va 2  s.co  m*/
 * 
 * @return Encoded signed code XML
 * @throws EPPEncodeException
 *             Error encoding the signed code
 */
public byte[] encode() throws EPPEncodeException {
    cat.debug("EPPEncodedSignedCodeValue.encode(): enter");

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
        Document doc = new DocumentImpl();
        Element root = this.encode(doc);
        doc.appendChild(root);

        TransformerFactory transFac = TransformerFactory.newInstance();
        Transformer trans = transFac.newTransformer();

        trans.transform(new DOMSource(root), new StreamResult(os));
    } catch (EPPEncodeException ex) {
        throw ex;
    } catch (Exception ex) {
        cat.error("Error encoding tradecode to byte[]: " + ex);
        throw new EPPEncodeException("Error encoding tradecode to byte[]");
    }

    cat.debug("EPPEncodedSignedCodeValue.encode(): exit");
    return os.toByteArray();
}

From source file:net.sourceforge.fullsync.fs.connection.SyncFileBufferedConnection.java

public void saveToBuffer() throws IOException {
    File fsRoot = fs.getRoot();// w w w. j ava 2s. c  o m
    File node = fsRoot.getChild(BUFFER_FILENAME);
    if ((null == node) || !node.exists()) {
        node = root.createChild(BUFFER_FILENAME, false);
    }

    try {
        DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = docBuilder.newDocument();

        Element e = doc.createElement(ELEMENT_SYNC_FILES);
        e.appendChild(serializeFile(root, doc));
        doc.appendChild(e);
        TransformerFactory fac = TransformerFactory.newInstance();
        fac.setAttribute("indent-number", 2); //$NON-NLS-1$
        Transformer tf = fac.newTransformer();
        tf.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
        tf.setOutputProperty(OutputKeys.VERSION, "1.0"); //$NON-NLS-1$
        tf.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
        tf.setOutputProperty(OutputKeys.STANDALONE, "no"); //$NON-NLS-1$
        DOMSource source = new DOMSource(doc);

        try (OutputStreamWriter osw = new OutputStreamWriter(new GZIPOutputStream(node.getOutputStream()),
                StandardCharsets.UTF_8)) {
            tf.transform(source, new StreamResult(osw));
            osw.flush();
        }
    } catch (IOException | ParserConfigurationException | FactoryConfigurationError | TransformerException e) {
        ExceptionHandler.reportException(e);
    }
}

From source file:be.fedict.eid.pkira.xkmsws.util.XMLMarshallingUtil.java

public void addSoapHeaders(Document document) {
    Element envelope = document.createElementNS(NAMESPACE_SOAP, "Envelope");
    Element body = document.createElementNS(NAMESPACE_SOAP, "Body");
    envelope.appendChild(body);/*from   w w w .ja v  a  2s . c om*/
    body.appendChild(document.getDocumentElement());
    document.appendChild(envelope);
}