Example usage for org.w3c.dom Document adoptNode

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

Introduction

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

Prototype

public Node adoptNode(Node source) throws DOMException;

Source Link

Document

Attempts to adopt a node from another document to this document.

Usage

From source file:Main.java

/**
 * //from w w  w.  j a va 2  s  . c  o m
 * <i>Description:</i> append a node into specified <code>parent</code> node
 * 
 * @param doc
 * @param parent
 * @param node
 */
public static void appendNode(Document doc, Node parent, Node node) {
    Node txt = doc.createTextNode("\n    ");
    parent.appendChild(txt);
    Node comment = doc.createComment(" Created by FM GUI @ " + (new Date()) + " ");
    parent.appendChild(comment);
    doc.adoptNode(node);
    parent.appendChild(node);
    formatNode(doc, parent, node);
    txt = doc.createTextNode("\n\n  ");
    parent.appendChild(txt);
}

From source file:net.padaf.xmpbox.SaveMetadataHelper.java

/**
 * Serialize a schema into an Output stream
 * /* ww w  .  ja v  a 2s  .com*/
 * @param schema
 *            Schema concerned by the serialization processing
 * @param os
 *            Stream to save serialized schema
 * @throws TransformException
 *             When couldn't parse data to XML/RDF
 */
public static void serialize(XMPSchema schema, OutputStream os) throws TransformException {
    try {
        Document doc = XMLUtil.newDocument();
        Element rdf = doc.createElementNS("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdf:RDF");
        Node schemContent = schema.getElement().cloneNode(true);
        doc.adoptNode(schemContent);
        rdf.appendChild(schemContent);
        XMLUtil.save(rdf, os, "UTF-8");
    } catch (TransformerException e) {
        throw new TransformException("Failed to parse defined XMP");
    } catch (IOException e) {
        throw new TransformException("Failed to create Document to contain Schema representation ",
                e.getCause());
    }

}

From source file:de.ingrid.interfaces.csw.domain.encoding.impl.XMLEncoding.java

protected static Document extractFromDocument(Node node) throws Exception {
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);/*from  www . j a  v a  2 s  .  c  om*/
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document doc = builder.newDocument();
    Node copy = node.cloneNode(true);
    Node adopted = doc.adoptNode(copy);
    doc.appendChild(adopted);
    return doc;
}

From source file:net.padaf.xmpbox.SaveMetadataHelper.java

/**
 * Prepare XMP Saving Put data necessary to make a well-formed XMP
 * //from  w  w  w  .  j a  v a2  s.co  m
 * @param metadata
 *            metadata concerned by the serialization processing
 * @param intoXPacket
 *            true if Processing instruction must be embedded
 * @return The DOM Document which will represent the serialized metadata
 */
protected static Document prepareSaving(XMPMetadata metadata, boolean intoXPacket) {
    Document newdoc = (Document) metadata.getFuturOwner().cloneNode(true);
    if (intoXPacket) {
        ProcessingInstruction beginXPacket = newdoc.createProcessingInstruction("xpacket",
                "begin=\"" + metadata.getXpacketBegin() + "\" id=\"" + metadata.getXpacketId() + "\"");
        newdoc.appendChild(beginXPacket);
    }

    Element xmpMeta = newdoc.createElementNS("adobe:ns:meta/", "x:xmpmeta");
    xmpMeta.setAttributeNS(XMPSchema.NS_NAMESPACE, "xmlns:x", "adobe:ns:meta/");

    newdoc.appendChild(xmpMeta);
    Element elem = (Element) metadata.getContainerElement().cloneNode(true);
    newdoc.adoptNode(elem);
    xmpMeta.appendChild(elem);

    if (intoXPacket) {
        ProcessingInstruction endXPacket = newdoc.createProcessingInstruction("xpacket",
                metadata.getEndXPacket());
        newdoc.appendChild(endXPacket);
    }
    return newdoc;
}

From source file:eu.europa.esig.dss.DSSXMLUtils.java

/**
 * Creates a DOM Document object of the specified type with its document element.
 *
 * @param namespaceURI  the namespace URI of the document element to create or null
 * @param qualifiedName the qualified name of the document element to be created or null
 * @param element       document {@code Element}
 * @return {@code Document}//from w w  w .  ja v a 2  s  . c o m
 */
public static Document createDocument(final String namespaceURI, final String qualifiedName,
        final Element element) {
    ensureDocumentBuilder();

    DOMImplementation domImpl;
    try {
        domImpl = dbFactory.newDocumentBuilder().getDOMImplementation();
    } catch (ParserConfigurationException e) {
        throw new DSSException(e);
    }
    final Document newDocument = domImpl.createDocument(namespaceURI, qualifiedName, null);
    final Element newElement = newDocument.getDocumentElement();
    newDocument.adoptNode(element);
    newElement.appendChild(element);

    return newDocument;
}

From source file:eu.europa.esig.dss.DSSXMLUtils.java

/**
 * Creates a DOM Document object of the specified type with its document elements.
 *
 * @param namespaceURI//from  ww  w.ja v a 2 s .c om
 * @param qualifiedName
 * @param element1
 * @param element2
 * @return {@code Document}
 */
public static Document createDocument(final String namespaceURI, final String qualifiedName,
        final Element element1, final Element element2) {
    ensureDocumentBuilder();

    DOMImplementation domImpl;
    try {
        domImpl = dbFactory.newDocumentBuilder().getDOMImplementation();
    } catch (ParserConfigurationException e) {
        throw new DSSException(e);
    }
    final Document newDocument = domImpl.createDocument(namespaceURI, qualifiedName, null);
    final Element newElement = newDocument.getDocumentElement();
    newDocument.adoptNode(element1);
    newElement.appendChild(element1);

    newDocument.adoptNode(element2);
    newElement.appendChild(element2);

    return newDocument;
}

From source file:eu.apenet.dpt.standalone.gui.hgcreation.LevelTreeActions.java

private Node stringToNode(Document originalDoc, ReaderInputStream readerInputStream) throws Exception {
    Document doc = DOMUtil.createDocument(readerInputStream);
    return originalDoc.adoptNode(doc.getFirstChild());
}

From source file:cz.incad.kramerius.service.replication.ExternalReferencesFormat.java

private void original(Document document, Element element)
        throws DOMException, MalformedURLException, URISyntaxException {
    Element original = document.createElementNS(FedoraNamespaces.KRAMERIUS_URI, "replicatedFrom");
    document.adoptNode(original);
    original.setTextContent(makeHANDLE(document).toURI().toString());

    List<Element> rdfversions = XMLUtils.getElementsRecursive(element, new XMLUtils.ElementsFilter() {

        @Override//from   w w  w  .  j  a  va 2 s  .c o m
        public boolean acceptElement(Element el) {
            String localName = el.getLocalName();
            String namespace = el.getNamespaceURI();
            if (namespace.equals(FedoraNamespaces.RDF_NAMESPACE_URI)) {
                return localName.equals("Description");
            }
            return false;
        }
    });

    for (Element desc : rdfversions) {
        desc.appendChild(original);
    }
}

From source file:com.bstek.dorado.idesupport.resolver.RobotResolver.java

protected void assembleContent(Document document, Element responseElement, List<Element> elements) {
    Element contentElenment = document.createElement("Content");
    responseElement.appendChild(contentElenment);
    for (Element element : elements) {
        contentElenment.appendChild(document.adoptNode(element));
    }/*from w  w  w. j a va 2  s .c o m*/
}

From source file:act.installer.HMDBParser.java

/**
 * Convert an HMDB XML document into a Chemical object.  Expects one chemical per document.
 * @param doc A parsed HMDB XML doc./*from ww w  .  ja  va2 s.c  o  m*/
 * @return The corresponding chemical to store in the DB.
 * @throws JaxenException
 * @throws JSONException
 */
protected Chemical extractChemicalFromXMLDocument(Document doc) throws JaxenException, JSONException {
    String hmdbId = getText(HMDB_XPATH.HMDB_ID_TEXT, doc);

    String primaryName = getText(HMDB_XPATH.PRIMARY_NAME_TEXT, doc);
    String iupacName = getText(HMDB_XPATH.IUPAC_NAME_TEXT, doc);
    List<String> synonyms = getTextFromNodes(HMDB_XPATH.SYNONYMS_NODES, doc);

    String inchi = getText(HMDB_XPATH.INCHI_TEXT, doc);
    String smiles = getText(HMDB_XPATH.SMILES_TEXT, doc);

    // Require an InChI if we're going to consume this molecule.
    if (inchi == null || inchi.isEmpty()) {
        LOGGER.warn("No InChI found for HMDB chemical %s, aborting", hmdbId);
        return null;
    }

    String ontologyStatus = getText(HMDB_XPATH.ONTOLOGY_STATUS_TEXT, doc);
    List<String> ontologyOrigins = getTextFromNodes(HMDB_XPATH.ONTOLOGY_ORIGINS_NODES, doc);
    List<String> ontologyFunctions = getTextFromNodes(HMDB_XPATH.ONTOLOGY_FUNCTIONS_NODES, doc);
    List<String> ontologyApplications = getTextFromNodes(HMDB_XPATH.ONTOLOGY_APPLICATIONS_NODES, doc);
    List<String> ontologyLocations = getTextFromNodes(HMDB_XPATH.ONTOLOGY_LOCATIONS_NODES, doc);

    List<String> locationFluids = getTextFromNodes(HMDB_XPATH.LOCATIONS_FLUID_NODES, doc);
    List<String> locationTissues = getTextFromNodes(HMDB_XPATH.LOCATIONS_TISSUE_NODES, doc);

    List<String> pathwayNames = getTextFromNodes(HMDB_XPATH.PATHWAY_NAME_NODES, doc);

    List<String> diseaseNames = getTextFromNodes(HMDB_XPATH.DISEASE_NAME_NODES, doc);

    String metlinId = getText(HMDB_XPATH.METLIN_ID_TEXT, doc);
    String pubchemId = getText(HMDB_XPATH.PUBCHEM_ID_TEXT, doc);
    String chebiId = getText(HMDB_XPATH.CHEBI_ID_TEXT, doc);

    List<Node> proteins = getNodes(HMDB_XPATH.PROTEIN_L1_NODES, doc);
    // Simple triples of name, uniprot id, gene name.
    List<Triple<String, String, String>> proteinAttributes = new ArrayList<>(proteins.size());

    for (Node n : proteins) {
        /* In order to run XPath on a sub-document, we have to Extract the relevant nodes into their own document object.
         * If we try to run evaluate on `n` instead of this new document, we'll get matching paths for the original
         * document `d` but not for the nodes we're looking at right now.  Very weird. */
        Document proteinDoc = documentBuilder.newDocument();
        proteinDoc.adoptNode(n);
        proteinDoc.appendChild(n);
        String name = getText(HMDB_XPATH.PROTEIN_L2_NAME_TEXT, proteinDoc);
        String uniprotId = getText(HMDB_XPATH.PROTEIN_L2_UNIPROT_ID_TEXT, proteinDoc);
        String geneName = getText(HMDB_XPATH.PROTEIN_L2_GENE_NAME_TEXT, proteinDoc);
        proteinAttributes.add(Triple.of(name, uniprotId, geneName));
    }

    // Assumption: when we reach this point there will always be an InChI.
    Chemical chem = new Chemical(inchi);
    chem.setSmiles(smiles);

    chem.setCanon(primaryName);

    if (pubchemId != null && !pubchemId.isEmpty()) {
        chem.setPubchem(Long.valueOf(pubchemId));
    }

    synonyms.forEach(chem::addSynonym);
    chem.addSynonym(iupacName); // TODO: is there a better place for this?

    JSONObject meta = new JSONObject().put("hmdb_id", hmdbId).put("ontology",
            new JSONObject().put("status", ontologyStatus).put("origins", new JSONArray(ontologyOrigins))
                    .put("functions", new JSONArray(ontologyFunctions))
                    .put("applications", new JSONArray(ontologyApplications))
                    .put("locations", new JSONArray(ontologyLocations)))
            .put("location",
                    new JSONObject().put("fluid", new JSONArray(locationFluids)).put("tissue",
                            new JSONArray(locationTissues)))
            .put("pathway_names", new JSONArray(pathwayNames)).put("disease_names", new JSONArray(diseaseNames))
            .put("metlin_id", metlinId).put("chebi_id", chebiId).put("proteins",
                    new JSONArray(proteinAttributes
                            .stream().map(t -> new JSONObject().put("name", t.getLeft())
                                    .put("uniprot_id", t.getMiddle()).put("gene_name", t.getRight()))
                            .collect(Collectors.toList())));

    chem.putRef(Chemical.REFS.HMDB, meta);

    return chem;
}