Example usage for org.w3c.dom Document importNode

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

Introduction

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

Prototype

public Node importNode(Node importedNode, boolean deep) throws DOMException;

Source Link

Document

Imports a node from another document to this document, without altering or removing the source node from the original document; this method creates a new copy of the source node.

Usage

From source file:de.mpg.escidoc.services.transformation.Util.java

public static Node querySSRNId(String conePersonUrl) {
    DocumentBuilder documentBuilder;
    HttpClient client = new HttpClient();

    logger.info("querySSRNId: " + conePersonUrl);

    try {//from  ww  w.j a va2s.  c  om
        documentBuilder = DocumentBuilderFactoryImpl.newInstance().newDocumentBuilder();

        Document document = documentBuilder.newDocument();
        Element element = document.createElement("cone");
        document.appendChild(element);
        GetMethod detailMethod = new GetMethod(conePersonUrl + "?format=rdf");
        ProxyHelper.setProxy(client, conePersonUrl);
        client.executeMethod(detailMethod);
        if (detailMethod.getStatusCode() == 200) {
            Document details = documentBuilder.parse(detailMethod.getResponseBodyAsStream());
            element.appendChild(document.importNode(details.getFirstChild(), true));
            return document;
        } else {
            logger.error("Error querying CoNE: Status " + detailMethod.getStatusCode() + "\n"
                    + detailMethod.getResponseBodyAsString());
            return null;
        }

    } catch (Exception e) {
        logger.error("Error querying CoNE service. This is normal during unit tests. "
                + "Otherwise it should be clarified if any measures have to be taken.", e);
        return null;
    }

}

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

private static Element feed(final AtomFeed feed) throws ParserConfigurationException {
    final DocumentBuilder builder = ODataConstants.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, ODataConstants.NS_METADATA);
    feedElem.setAttribute(ODataConstants.XMLNS_DATASERVICES, ODataConstants.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());
    }//  w  ww  .  j  a  v  a2s.c o m
    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;
}

From source file:de.uni_potsdam.hpi.bpt.promnicat.importer.sap_rm.SapReferenceModelImporter.java

public void splitEPML(File file)
        throws ParserConfigurationException, SAXException, IOException, TransformerException, JSONException {
    DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = fac.newDocumentBuilder();
    Document doc = builder.parse(file);
    NodeList epcNodes = doc.getElementsByTagName("epc");
    for (int i = 0; i < epcNodes.getLength(); i++) {
        String epcName = epcNodes.item(i).getAttributes().getNamedItem("name").getNodeValue();

        Model model = this.persistenceApi.loadCompleteModelWithImportedId(epcName);
        if (model != null) {
            continue;
        }/* www .j  a v  a 2 s .  co  m*/

        Document newEpcDoc = builder.newDocument();
        Element epml = newEpcDoc.createElement("epml:epml");
        Element directory = newEpcDoc.createElement("directory");
        newEpcDoc.appendChild(epml);
        epml.appendChild(directory);
        directory.setAttribute("name", "ROOT");
        Node epcNode = newEpcDoc.importNode(epcNodes.item(i), true);
        directory.appendChild(epcNode);

        DOMSource epmlSource = new DOMSource(newEpcDoc);
        final File epml2eRDFxsltFile = new File("resources/xslt/EPML2eRDF.xslt");
        final Source epml2eRDFxsltSource = new StreamSource(epml2eRDFxsltFile);

        // Transformer Factory
        final TransformerFactory transformerFactory = TransformerFactory.newInstance();

        // Get the epml source
        Transformer transformer = transformerFactory.newTransformer(epml2eRDFxsltSource);
        StringWriter writer = new StringWriter();
        transformer.transform(epmlSource, new StreamResult(writer));
        String erdf = writer.toString();
        String rdf = erdfToRdf(erdf);
        rdf = rdf.replaceAll("ns[0-9]+:", "");
        rdf = rdf.replace("#resource", "#");
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        Document rdfDoc = builder.parse(new ByteArrayInputStream(rdf.getBytes("UTF-8")));
        String json = RdfJsonTransformation.toJson(rdfDoc, "").toString();

        //Diagram diagram = DiagramBuilder.parseJson(json);
        Representation representation = new Representation(Constants.FORMAT_BPMAI_JSON, Constants.NOTATION_EPC);
        Diagram parseJson = DiagramBuilder.parseJson(json);
        representation.setDataContent(json.getBytes());
        model = new Model(epcName, Constants.ORIGIN_SAP_RM);
        model.setImportedId(epcName);
        Revision revision = new Revision(0);
        revision.connectRepresentation(representation);
        model.connectLatestRevision(revision);
        revision.connectModel(model);
        model.connectLatestRevision(revision);
        persistenceApi.savePojo(model);

    }

}

From source file:SVGJUnitTest.java

@Test
public void merge() throws IOException, TranscoderException {

    String data = FileUtils.readFileToString(new File("target/out1.svg"), "UTF-8");
    InputStream inputStream = new ByteArrayInputStream(data.getBytes());
    String parser = XMLResourceDescriptor.getXMLParserClassName();
    SAXSVGDocumentFactory f = new SAXSVGDocumentFactory(parser);

    Document doc = f.createDocument("http://www.w3.org/2000/svg", inputStream);

    String data2 = FileUtils.readFileToString(new File("target/out2.svg"), "UTF-8");
    InputStream inputStream2 = new ByteArrayInputStream(data2.getBytes());

    Document doc2 = f.createDocument("http://www.w3.org/2000/svg", inputStream2);

    Node n = doc.importNode(doc2.getDocumentElement(), true);
    doc.getDocumentElement().appendChild(n);

    PNGTranscoder t = new PNGTranscoder();

    TranscoderInput input = new TranscoderInput(doc);

    OutputStream ostream = new FileOutputStream("target/merged.png");
    TranscoderOutput output = new TranscoderOutput(ostream);

    // Perform the transcoding.
    t.transcode(input, output);/*  ww  w .  ja v a2s .  c om*/
    ostream.flush();
    ostream.close();

}

From source file:com.portfolio.data.utils.DomUtils.java

private static void insererXML(Connection connexion, Document xmlSourceDoc, String partageableId,
        StringBuffer outTrace, boolean trace) throws Exception {
    //  ---------------------------------------------------
    if (trace)//w  ww  .jav  a 2 s  .  c  om
        outTrace.append("<br>insererPartageable -- entre");
    if (trace)
        outTrace.append("<br>partageableId=" + partageableId);
    // ===============chargement du document source ========================================

    if (trace)
        outTrace.append("<br>lecture du document xml :" + partageableId + "...");
    Document xmlPartageable = buildDOM(readXmlString(connexion, partageableId, outTrace));
    if (trace)
        outTrace.append(" ok");

    DocumentFragment aInserer = xmlSourceDoc.createDocumentFragment();

    NodeList liste = xmlPartageable.getDocumentElement().getChildNodes();
    int nbListe = liste.getLength();
    if (trace)
        outTrace.append("<br> nbListe=" + nbListe);
    for (int i = 0; i < nbListe; i++) {
        aInserer.appendChild(xmlSourceDoc.importNode(liste.item(i), true));
    }

    xmlSourceDoc.getFirstChild().insertBefore(aInserer, xmlSourceDoc.getFirstChild().getFirstChild());
    if (trace)
        outTrace.append("<br>insererPartageable -- sortie");
}

From source file:com.enonic.esl.xml.XMLTool.java

public static void mergeDocuments(Document destDoc, Document srcDoc, boolean copyRoot) {
    Element destDocElem = destDoc.getDocumentElement();

    if (copyRoot) {
        Element element = srcDoc.getDocumentElement();
        destDocElem.appendChild(destDoc.importNode(element, true));
    } else {//from w  ww  .  ja v  a 2  s .  c om
        NodeList nodes = srcDoc.getDocumentElement().getChildNodes();

        for (int i = 0; i < nodes.getLength(); i++) {
            destDocElem.appendChild(destDoc.importNode(nodes.item(i), true));
        }
    }

}

From source file:com.jkoolcloud.tnt4j.streams.parsers.ActivityXmlParser.java

private Document cropDocumentForNode(Node xmlDoc) throws ParseException {
    if (xmlDoc.getParentNode() != null) { // if node is not document root node
        try {//from w  w  w  . j av  a 2s  .  com
            Document nodeXmlDoc;
            synchronized (builder) {
                nodeXmlDoc = builder.newDocument();
            }
            Node importedNode = nodeXmlDoc.importNode(xmlDoc, true);
            nodeXmlDoc.appendChild(importedNode);

            return nodeXmlDoc;
        } catch (Exception exc) {
            ParseException pe = new ParseException(StreamsResources.getString(
                    StreamsResources.RESOURCE_BUNDLE_NAME, "ActivityXmlParser.xmlDocument.parse.error"), 0);
            pe.initCause(exc);

            throw pe;
        }
    }

    return null;
}

From source file:eionet.gdem.qa.QAResultPostProcessor.java

/**
 * Parses div nodes and adds warning node to result
 * @param divElements Div elements/*  ww w. ja v  a 2 s  .c o  m*/
 * @param warnMessage Warning message
 * @return true if feedbacktext class is found
 * @throws XmlException If an error occurs.
 */
private boolean parseDivNodes(NodeList divElements, String warnMessage) throws XmlException {
    boolean feedBackDivFound = false;
    try {
        for (int i = 0; divElements != null && i < divElements.getLength(); i++) {
            Node divNode = divElements.item(i);
            Node classNode = divNode.getAttributes().getNamedItem("class");

            if (classNode != null && classNode.getNodeValue().equalsIgnoreCase("feedbacktext")) {
                // found feedback div
                feedBackDivFound = true;

                Node firstChild = divNode.getFirstChild();
                Document doc = divNode.getOwnerDocument();

                Node warningNode = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                        .parse(new InputSource(
                                new StringReader("<div class=\"error-msg\">" + warnMessage + "</div>")))
                        .getFirstChild();
                warningNode = doc.importNode(warningNode, true);
                if (firstChild == null) {
                    divNode.appendChild(warningNode);
                } else {
                    warningNode = divNode.insertBefore(warningNode, firstChild);
                }
                //
                break;
            }
        }
    } catch (Exception e) {
        LOGGER.error("Error processing divNodes " + e);
    }
    return feedBackDivFound;
}

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

/**
 * Xpath performance degrades on large documents so this workaround was needed to improve performance. See link inline in the code.
 * /*w  w  w. j a v a2  s .co m*/
 * @param entityElement
 * @return
 * @throws ParserConfigurationException
 */
private Element createOrphanElement(Element entityElement) throws ParserConfigurationException {

    // this is necessary to avoid a performance bottleneck in the Xalan xpath engine
    // see http://stackoverflow.com/questions/6340802/java-xpath-apache-jaxp-implementation-performance

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document dummyDocument = db.newDocument();
    dummyDocument.appendChild(dummyDocument.importNode(entityElement, true));
    entityElement = dummyDocument.getDocumentElement();

    return entityElement;

}

From source file:edu.duke.cabig.c3pr.webservice.studyimportexport.impl.StudyImportExportImpl.java

/**
 * Convert to oai./*from w ww  . j  av a 2 s .  com*/
 *
 * @param studyId the study id
 * @return the organization assigned identifier
 * @throws XMLUtilityException the xML utility exception
 * @throws ParserConfigurationException the parser configuration exception
 */
private OrganizationAssignedIdentifier convertToOAI(Element studyId)
        throws XMLUtilityException, ParserConfigurationException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.newDocument();
    doc.appendChild(doc.importNode(studyId, true));

    DOMBuilder jdomBuilder = new DOMBuilder();
    org.jdom.Document jdomDoc = jdomBuilder.build(doc);
    String xmlRep = new XMLOutputter().outputString(jdomDoc);
    OrganizationAssignedIdentifier oai = (OrganizationAssignedIdentifier) marshaller
            .fromXML(new StringReader(xmlRep));
    return oai;
}