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:cz.cas.lib.proarc.common.export.cejsh.CejshBuilder.java

/**
 * Builds modsCollection from mods of articles.
 *///from  w  w  w .ja v  a  2s .  c  o  m
Document mergeElements(List<Article> articles) throws DOMException {
    Document doc = db.newDocument();
    Element root = doc.createElementNS(ModsConstants.NS, "modsCollection");
    for (Article article : articles) {
        Element modsElm = article.getModsElement();
        Node n = doc.adoptNode(modsElm);
        root.appendChild(n);
    }
    doc.appendChild(root);
    return doc;
}

From source file:com.igeekinc.indelible.indeliblefs.webaccess.IndelibleWebAccessServlet.java

public void listVolumes(HttpServletRequest req, HttpServletResponse resp, Document buildDoc)
        throws IOException {
    Element rootElem = buildDoc.createElement("volumesList");
    buildDoc.appendChild(rootElem);
    IndelibleFSObjectID[] volumeIDs = connection.listVolumes();
    for (IndelibleFSObjectID curVolumeID : volumeIDs) {
        try {//from w w  w. ja v  a2 s . com
            IndelibleFSVolumeIF curVolume = connection.retrieveVolume(curVolumeID);
            Element volumeElement = buildDoc.createElement("volume");
            XMLUtils.appendSingleValElement(buildDoc, volumeElement, "id", curVolumeID.toString());
            Map<String, Object> volumeResources = curVolume
                    .getMetaDataResource(IndelibleFSVolumeIF.kVolumeResourcesName);
            if (volumeResources != null) {
                String volumeName = (String) volumeResources.get(IndelibleFSVolumeIF.kVolumeNamePropertyName);
                if (volumeName != null) {
                    XMLUtils.appendSingleValElement(buildDoc, volumeElement, "name", volumeName);
                }
            }
            rootElem.appendChild(volumeElement);
        } catch (VolumeNotFoundException e) {
            // TODO Auto-generated catch block
            Logger.getLogger(getClass()).error(new ErrorLogMessage("Caught exception"), e);
        } catch (PermissionDeniedException e) {
            // TODO Auto-generated catch block
            Logger.getLogger(getClass()).error(new ErrorLogMessage("Caught exception"), e);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            Logger.getLogger(getClass()).error(new ErrorLogMessage("Caught exception"), e);
        }

    }
}

From source file:de.betterform.xml.xforms.XFormsProcessorImpl.java

private Document toDocument(Node node) throws XFormsException {
    // ensure xerces dom
    if (node instanceof Document) {
        return (Document) node;
    }/*from  w  w w .  java  2 s .co  m*/

    Document document = getDocumentBuilder().newDocument();
    if (node instanceof Document) {
        node = ((Document) node).getDocumentElement();
    }
    document.appendChild(document.importNode(node, true));

    return document;
}

From source file:com.igeekinc.indelible.indeliblefs.webaccess.IndelibleWebAccessServlet.java

protected void listPath(FilePath reqPath, Document buildDoc) throws IndelibleWebAccessException {
    Element rootElem = buildDoc.createElement("list");
    buildDoc.appendChild(rootElem);
    // Should be an absolute path
    reqPath = reqPath.removeLeadingComponent();
    String fsIDStr = reqPath.getComponent(0);
    IndelibleFSVolumeIF volume = getVolume(fsIDStr);
    if (volume == null)
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kVolumeNotFoundError, null);
    FilePath listPath = reqPath.removeLeadingComponent();
    XMLUtils.appendSingleValElement(buildDoc, rootElem, "path", reqPath.toString());
    XMLUtils.appendSingleValElement(buildDoc, rootElem, "parentPath", reqPath.getParent().toString());
    try {//  w w  w  .  jav a 2s.  c  om
        IndelibleFileNodeIF listFile = volume.getObjectByPath(listPath.makeAbsolute());
        if (listFile.isDirectory()) {
            IndelibleDirectoryNodeIF listDir = (IndelibleDirectoryNodeIF) listFile;
            String[] children = listDir.list();
            Arrays.sort(children);
            for (String curChildName : children) {
                IndelibleFileNodeIF curChild = listDir.getChildNode(curChildName);
                Element curFileElement = listIndelibleFile(reqPath.getChild(curChildName).toString(),
                        curChildName, curChild, buildDoc);
                rootElem.appendChild(curFileElement);
            }
        } else {
            Element curFileElement = listIndelibleFile(listPath.toString(), listPath.getName(), listFile,
                    buildDoc);
            rootElem.appendChild(curFileElement);
        }
    } catch (ObjectNotFoundException e) {
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kPathNotFound, e);
    } catch (PermissionDeniedException e) {
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kPermissionDenied, e);
    } catch (IOException e) {
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kInternalError, e);
    }
    return;
}

From source file:com.ggvaidya.scinames.model.Project.java

public void serializeToDocument(Document doc) {
    // Add top-level element.
    Element project = doc.createElement("project");
    project.setAttribute("name", getName());
    doc.appendChild(project);

    // Set up some properties.
    properties.put(PROP_NAME_EXTRACTORS,
            getNameExtractors().stream().map(lne -> NameExtractorFactory.serializeExtractorsToString(lne))
                    .distinct().sorted().collect(Collectors.joining("; ")));

    // Write out properties.
    Element propertiesElement = doc.createElement("properties");
    for (String key : properties.keySet()) {
        Element p = doc.createElement("property");
        p.setAttribute("name", key);
        p.setTextContent(properties.get(key));
        propertiesElement.appendChild(p);
    }/* w ww .ja va 2s  .  c  o m*/
    project.appendChild(propertiesElement);

    // Add filters.
    Element filtersElement = doc.createElement("filters");
    Deque<ChangeFilter> changeFilters = new LinkedList<>();
    {
        // We need to read the filters inside-out, so they'll be recreated
        // the right way around.
        ChangeFilter cf = getChangeFilter();
        while (cf != null) {
            changeFilters.addLast(cf);
            cf = cf.getPrevChangeFilter();
        }
    }
    changeFilters.forEach(cf -> {
        // Skip any nulls.
        if (cf.getShortName().equals("null"))
            return;

        filtersElement.appendChild(cf.serializeToElement(doc));
    });

    project.appendChild(filtersElement);

    // List all timepoints.
    Element timepointsElement = doc.createElement("datasets");
    for (Dataset tp : getDatasets()) {
        Element t = tp.serializeToElement(doc);
        timepointsElement.appendChild(t);
    }
    project.appendChild(timepointsElement);
}

From source file:ddf.catalog.source.opensearch.CddaOpenSearchSite.java

/**
 * @param is// w w  w  . j a  va2s  .  c  o  m
 * @param queryRequest
 * @return
 * @throws UnsupportedQueryException
 */
private SourceResponseImpl processResponse(InputStream is, QueryRequest queryRequest)
        throws ConversionException {
    List<Result> resultQueue = new ArrayList<Result>();
    Document atomDoc = null;

    try {
        atomDoc = OpenSearchSiteUtil.convertStreamToDocument(is);
        if (logger.isDebugEnabled()) {
            logger.debug("Incoming response from OpenSearch site: " + XPathHelper.xmlToString(atomDoc));
        }
    } finally {
        IOUtils.closeQuietly(is);
    }

    Map<String, String> securityProps = updateDefaultClassification();

    Document ddmsDoc = OpenSearchSiteUtil.normalizeAtomToDDMS(tf, atomDoc, normalizeXslt, securityProps);

    if (logger.isDebugEnabled()) {
        logger.debug("Incoming response from OpenSearch site normalized to DDMS: "
                + XPathHelper.xmlToString(ddmsDoc));
    }
    NodeList list = ddmsDoc.getElementsByTagNameNS("http://metadata.dod.mil/mdr/ns/DDMS/2.0/", "Resource");

    String resultNum = evaluate("//opensearch:totalResults", atomDoc);
    long totalResults = 0;
    if (resultNum != null && !resultNum.isEmpty()) {
        totalResults = Integer.parseInt(resultNum);
    } else {
        // if no openseach:totalResults element, spec says to use list
        // of current items as totalResults
        totalResults = list.getLength();
    }

    // offset always comes in as 0 from DDF federation logic
    for (int i = 0; i < list.getLength(); i++) {
        try {
            Node curNode = list.item(i);
            String relevance = OpenSearchSiteUtil.popAttribute(curNode, "score");
            String id = OpenSearchSiteUtil.popAttribute(curNode, "id");
            String date = OpenSearchSiteUtil.popAttribute(curNode, "date");
            Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
            doc.appendChild(doc.importNode(curNode, true));

            if (logger.isDebugEnabled()) {
                logger.debug(XPathHelper.xmlToString(doc));
            }
            resultQueue.add(createResponse(doc, id, date, relevance));
        } catch (ParserConfigurationException pce) {
            throw new ConversionException("Couldn't convert node to document. ", pce);
        }

        if (logger.isDebugEnabled()) {
            logger.debug("Returning " + list.getLength() + " entries in response.");
        }
    }

    SourceResponseImpl response = new SourceResponseImpl(queryRequest, resultQueue);
    response.setHits(totalResults);

    return response;
}

From source file:gov.nij.bundles.intermediaries.ers.EntityResolutionMessageHandler.java

/**
 * This method takes the ER response and converts the Java objects to the Merge Response XML.
 * //from   www. ja v a  2 s . c  o  m
 * @param entityContainerNode
 * @param results
 * @param recordLimit
 * @param attributeParametersNode
 * @return
 * @throws ParserConfigurationException
 * @throws XPathExpressionException
 * @throws TransformerException
 */
private Document createResponseMessage(Node entityContainerNode, EntityResolutionResults results,
        Node attributeParametersNode, int recordLimit) throws Exception {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);

    Document resultDocument = dbf.newDocumentBuilder().newDocument();

    Element entityMergeResultMessageElement = resultDocument.createElementNS(
            EntityResolutionNamespaceContext.MERGE_RESULT_NAMESPACE, "EntityMergeResultMessage");
    resultDocument.appendChild(entityMergeResultMessageElement);

    Element entityContainerElement = resultDocument
            .createElementNS(EntityResolutionNamespaceContext.MERGE_RESULT_NAMESPACE, "EntityContainer");
    entityMergeResultMessageElement.appendChild(entityContainerElement);

    NodeList inputEntityNodes = (NodeList) xpath.evaluate("er-ext:Entity", entityContainerNode,
            XPathConstants.NODESET);
    Collection<Element> inputEntityElements = null;
    if (attributeParametersNode == null) {
        inputEntityElements = new ArrayList<Element>();
    } else {
        inputEntityElements = TreeMultiset
                .create(new EntityElementComparator((Element) attributeParametersNode));
        //inputEntityElements = new ArrayList<Element>();
    }

    for (int i = 0; i < inputEntityNodes.getLength(); i++) {
        inputEntityElements.add((Element) inputEntityNodes.item(i));
    }

    if (attributeParametersNode == null) {
        LOG.warn("Attribute Parameters element was null, so records will not be sorted");
    }
    //Collections.sort((List<Element>) inputEntityElements, new EntityElementComparator((Element) attributeParametersNode));

    if (inputEntityElements.size() != inputEntityNodes.getLength()) {
        LOG.error("Lost elements in ER output sorting.  Input count=" + inputEntityNodes.getLength()
                + ", output count=" + inputEntityElements.size());
    }

    for (Element e : inputEntityElements) {
        Node clone = resultDocument.adoptNode(e.cloneNode(true));
        resultDocument.renameNode(clone, EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE,
                e.getLocalName());
        entityContainerElement.appendChild(clone);
    }

    Element mergedRecordsElement = resultDocument
            .createElementNS(EntityResolutionNamespaceContext.MERGE_RESULT_NAMESPACE, "MergedRecords");
    entityMergeResultMessageElement.appendChild(mergedRecordsElement);

    if (results != null) {

        List<RecordWrapper> records = results.getRecords();

        // Loop through RecordWrappers to extract info to create merged records
        for (RecordWrapper record : records) {
            LOG.debug("  !#!#!#!# Record 1, id=" + record.getExternalId() + ", externals="
                    + record.getRelatedIds());

            // Create Merged Record Container
            Element mergedRecordElement = resultDocument.createElementNS(
                    EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "MergedRecord");
            mergedRecordsElement.appendChild(mergedRecordElement);

            // Create Original Record Reference for 'first record'
            Element originalRecordRefElement = resultDocument.createElementNS(
                    EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "OriginalRecordReference");
            originalRecordRefElement.setAttributeNS(EntityResolutionNamespaceContext.STRUCTURES_NAMESPACE,
                    "ref", record.getExternalId());
            mergedRecordElement.appendChild(originalRecordRefElement);

            // Loop through and add any related records
            for (String relatedRecordId : record.getRelatedIds()) {
                originalRecordRefElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "OriginalRecordReference");
                originalRecordRefElement.setAttributeNS(EntityResolutionNamespaceContext.STRUCTURES_NAMESPACE,
                        "ref", relatedRecordId);
                mergedRecordElement.appendChild(originalRecordRefElement);
            }

            // Create Merge Quality Element
            Element mergeQualityElement = resultDocument.createElementNS(
                    EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "MergeQuality");
            mergedRecordElement.appendChild(mergeQualityElement);
            Set<AttributeStatistics> stats = results.getStatisticsForRecord(record.getExternalId());
            for (AttributeStatistics stat : stats) {
                Element stringDistanceStatsElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE,
                        "StringDistanceStatistics");
                mergeQualityElement.appendChild(stringDistanceStatsElement);
                Element xpathElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "AttributeXPath");
                stringDistanceStatsElement.appendChild(xpathElement);
                Node contentNode = resultDocument.createTextNode(stat.getAttributeName());
                xpathElement.appendChild(contentNode);
                Element meanElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE,
                        "StringDistanceMeanInRecord");
                stringDistanceStatsElement.appendChild(meanElement);
                contentNode = resultDocument.createTextNode(String.valueOf(stat.getAverageStringDistance()));
                meanElement.appendChild(contentNode);
                Element sdElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE,
                        "StringDistanceStandardDeviationInRecord");
                stringDistanceStatsElement.appendChild(sdElement);
                contentNode = resultDocument
                        .createTextNode(String.valueOf(stat.getStandardDeviationStringDistance()));
                sdElement.appendChild(contentNode);

            }
        }

    } else {

        for (Element e : inputEntityElements) {

            String id = e.getAttributeNS(EntityResolutionNamespaceContext.STRUCTURES_NAMESPACE, "id");

            Element mergedRecordElement = resultDocument.createElementNS(
                    EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "MergedRecord");
            mergedRecordsElement.appendChild(mergedRecordElement);

            Element originalRecordRefElement = resultDocument.createElementNS(
                    EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "OriginalRecordReference");
            originalRecordRefElement.setAttributeNS(EntityResolutionNamespaceContext.STRUCTURES_NAMESPACE,
                    "ref", id);
            mergedRecordElement.appendChild(originalRecordRefElement);

            Element mergeQualityElement = resultDocument.createElementNS(
                    EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "MergeQuality");
            mergedRecordElement.appendChild(mergeQualityElement);
            XPath xp = XPathFactory.newInstance().newXPath();
            xp.setNamespaceContext(new EntityResolutionNamespaceContext());
            NodeList attributeParameterNodes = (NodeList) xp.evaluate("er-ext:AttributeParameter",
                    attributeParametersNode, XPathConstants.NODESET);
            for (int i = 0; i < attributeParameterNodes.getLength(); i++) {
                String attributeName = xp.evaluate("er-ext:AttributeXPath", attributeParametersNode);
                Element stringDistanceStatsElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE,
                        "StringDistanceStatistics");
                mergeQualityElement.appendChild(stringDistanceStatsElement);
                Element xpathElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "AttributeXPath");
                stringDistanceStatsElement.appendChild(xpathElement);
                Node contentNode = resultDocument.createTextNode(attributeName);
                xpathElement.appendChild(contentNode);
                Element meanElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE,
                        "StringDistanceMeanInRecord");
                stringDistanceStatsElement.appendChild(meanElement);
                contentNode = resultDocument.createTextNode("0.0");
                meanElement.appendChild(contentNode);
                Element sdElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE,
                        "StringDistanceStandardDeviationInRecord");
                stringDistanceStatsElement.appendChild(sdElement);
                contentNode = resultDocument.createTextNode("0.0");
                sdElement.appendChild(contentNode);
            }

        }

    }

    Element recordLimitExceededElement = resultDocument.createElementNS(
            EntityResolutionNamespaceContext.MERGE_RESULT_NAMESPACE, "RecordLimitExceededIndicator");
    recordLimitExceededElement.setTextContent(new Boolean(results == null).toString());
    entityMergeResultMessageElement.appendChild(recordLimitExceededElement);

    return resultDocument;

}

From source file:net.solarnetwork.node.support.XmlServiceSupport.java

/**
 * Turn an object into a simple XML Document, supporting custom property
 * editors.// ww  w . ja v a 2  s  .c  o  m
 * 
 * <p>
 * The returned XML will be a document with a single element with all
 * JavaBean properties turned into attributes. For example:
 * <p>
 * 
 * <pre>
 * &lt;powerDatum
 *   id="123"
 *   pvVolts="123.123"
 *   ... /&gt;
 * </pre>
 * 
 * <p>
 * {@link PropertyEditor} instances can be registered with the supplied
 * {@link BeanWrapper} for custom handling of properties, e.g. dates.
 * </p>
 * 
 * @param bean
 *        the object to turn into XML
 * @param elementName
 *        the name of the XML element
 * @return the element, as an XML DOM Document
 */
protected Document getDocument(BeanWrapper bean, String elementName) {
    Document dom = null;
    try {
        dom = getDocBuilderFactory().newDocumentBuilder().newDocument();
        dom.appendChild(getElement(bean, elementName, dom));
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    }
    return dom;
}

From source file:ambit.data.qmrf.QMRFObject.java

protected Document buildDocument() throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    factory.setNamespaceAware(true);//w w w .j a v a2 s. co m
    factory.setValidating(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    builder.setErrorHandler(new SimpleErrorHandler(builder.getClass().getName()));
    Document doc = builder.newDocument();
    Element e = toXML(doc);
    doc.appendChild(e);
    return doc;
}

From source file:com.msopentech.odatajclient.engine.data.impl.v3.AtomSerializer.java

private Element feed(final AtomFeed feed) throws ParserConfigurationException {
    final DocumentBuilder builder = XMLUtils.DOC_BUILDER_FACTORY.newDocumentBuilder();
    final Document doc = builder.newDocument();

    final Element feedElem = doc.createElement(ODataConstants.ATOM_ELEM_FEED);
    feedElem.setAttribute(XMLConstants.XMLNS_ATTRIBUTE, ODataConstants.NS_ATOM);
    feedElem.setAttribute(ODataConstants.XMLNS_METADATA,
            client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_METADATA));
    feedElem.setAttribute(ODataConstants.XMLNS_DATASERVICES,
            client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NS_DATASERVICES));
    feedElem.setAttribute(ODataConstants.XMLNS_GML, ODataConstants.NS_GML);
    feedElem.setAttribute(ODataConstants.XMLNS_GEORSS, ODataConstants.NS_GEORSS);
    if (feed.getBaseURI() != null) {
        feedElem.setAttribute(ODataConstants.ATTR_XMLBASE, feed.getBaseURI().toASCIIString());
    }/*from   ww  w .  j  a v a  2  s  . com*/
    doc.appendChild(feedElem);

    if (StringUtils.isNotBlank(feed.getTitle())) {
        final Element title = doc.createElement(ODataConstants.ATOM_ELEM_TITLE);
        title.appendChild(doc.createTextNode(feed.getTitle()));
        feedElem.appendChild(title);
    }

    if (StringUtils.isNotBlank(feed.getSummary())) {
        final Element summary = doc.createElement(ODataConstants.ATOM_ELEM_SUMMARY);
        summary.appendChild(doc.createTextNode(feed.getSummary()));
        feedElem.appendChild(summary);
    }

    for (AtomEntry entry : feed.getEntries()) {
        feedElem.appendChild(doc.importNode(entry(entry), true));
    }

    return feedElem;
}