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:com.bstek.dorado.view.config.XmlDocumentPreprocessor.java

protected void mergeMetaData(Document templateDocument, Element templteElement, Element element) {
    if (element.getAttributeNode(ViewXmlConstants.ATTRIBUTE_METADATA) != null) {
        templteElement.setAttribute(ViewXmlConstants.ATTRIBUTE_METADATA,
                element.getAttribute(ViewXmlConstants.ATTRIBUTE_METADATA));
    }// w  w  w.j  a  va  2  s . co m

    Element templateMetaDataElement = findPropertyElement(templteElement, ViewXmlConstants.ATTRIBUTE_METADATA);
    Element metaDataElement = findPropertyElement(element, ViewXmlConstants.ATTRIBUTE_METADATA);
    if (metaDataElement != null) {
        if (templateMetaDataElement == null) {
            templateMetaDataElement = templateDocument.createElement(XmlConstants.PROPERTY);
            templateMetaDataElement.setAttribute(XmlConstants.ATTRIBUTE_NAME,
                    ViewXmlConstants.ATTRIBUTE_METADATA);
            templteElement.appendChild(templateMetaDataElement);
        }

        for (Element metaPropertyElement : DomUtils.getChildrenByTagName(metaDataElement,
                XmlConstants.PROPERTY)) {
            Element clonedElement = (Element) templateDocument.importNode(metaPropertyElement, true);
            templateMetaDataElement.appendChild(clonedElement);
        }
    }
}

From source file:edu.stanford.epad.epadws.aim.AIMUtil.java

public static void returnImageAnnotationsXMLV4(PrintWriter responseStream, List<ImageAnnotationCollection> aims)
        throws ParserConfigurationException, edu.stanford.hakan.aim4api.base.AimException {
    long starttime = System.currentTimeMillis();
    DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
    Document doc = docBuilder.newDocument();
    Element root = doc.createElement("imageAnnotations");
    doc.appendChild(root);//from w  w w.  jav a2  s. co  m

    for (ImageAnnotationCollection aim : aims) {
        Node node = aim.getXMLNode(docBuilder.newDocument());
        Node copyNode = doc.importNode(node, true);
        Element res = (Element) copyNode; // Copy the node
        res.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:rdf",
                "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
        res.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsi",
                "http://www.w3.org/2001/XMLSchema-instance");
        res.setAttribute("xsi:schemaLocation",
                "gme://caCORE.caCORE/4.4/edu.northwestern.radiology.AIM AIM_v4_rv44_XML.xsd");
        res.setAttribute("xmlns", "gme://caCORE.caCORE/4.4/edu.northwestern.radiology.AIM");
        Node n = renameNodeNS(res, "ImageAnnotationCollection",
                "gme://caCORE.caCORE/4.4/edu.northwestern.radiology.AIM");
        root.appendChild(n); // Adding to the root
    }
    String queryResults = XmlDocumentToString(doc, "gme://caCORE.caCORE/4.4/edu.northwestern.radiology.AIM");
    long xmltime = System.currentTimeMillis();
    log.info("Time taken create xml:" + (xmltime - starttime) + " msecs for " + aims.size() + " annotations");
    responseStream.print(queryResults);
    long resptime = System.currentTimeMillis();
    log.info("" + aims.size() + " annotations returned to client, time to write resp:" + (resptime - xmltime)
            + " msecs");
}

From source file:com.bstek.dorado.view.config.XmlDocumentPreprocessor.java

private void mergeArguments(Document templateDocument, TemplateContext templateContext) throws Exception {
    Document document = templateContext.getSourceDocument();
    Map<String, Element> argumentMap = getArgumentElements(document, templateContext.getSourceContext());
    Map<String, Element> templateArgumentMap = getArgumentElements(templateDocument, templateContext);

    if (!argumentMap.isEmpty()) {
        Element templateDocumentElement = templateDocument.getDocumentElement();
        Element argumentsElement = ViewConfigParserUtils.findArgumentsElement(templateDocumentElement,
                templateContext.getResource());
        if (argumentsElement == null) {
            argumentsElement = templateDocument.createElement(ViewXmlConstants.ARGUMENTS);
            templateDocumentElement.insertBefore(argumentsElement, templateDocumentElement.getFirstChild());
        }/*  w  w w  .j  a v a2s .c  om*/

        for (Map.Entry<String, Element> entry : argumentMap.entrySet()) {
            String name = entry.getKey();
            if (templateArgumentMap == null || !templateArgumentMap.containsKey(name)) {
                Element element = entry.getValue();
                Element clonedElement = (Element) templateDocument.importNode(element, true);
                argumentsElement.appendChild(clonedElement);
            }
        }
    }
}

From source file:com.bstek.dorado.view.config.XmlDocumentPreprocessor.java

private void mergeModels(Document templateDocument, TemplateContext templateContext) throws Exception {
    Element templateDocumentElement = templateDocument.getDocumentElement();
    Element templateModelElement = ViewConfigParserUtils.findModelElement(templateDocumentElement,
            templateContext.getResource());

    Document document = templateContext.getSourceDocument();
    Element modelElement = ViewConfigParserUtils.findModelElement(document.getDocumentElement(),
            templateContext.getSourceContext().getResource());

    if (modelElement != null) {
        List<Element> modelElements = DomUtils.getChildElements(modelElement);
        if (!modelElements.isEmpty()) {
            if (templateModelElement == null) {
                templateModelElement = templateDocument.createElement(ViewXmlConstants.MODEL);
                Element viewElement = ViewConfigParserUtils.findViewElement(templateDocumentElement,
                        templateContext.getResource());
                templateDocumentElement.insertBefore(templateModelElement, viewElement);
            }//from w  w w  .  j  a  v a2 s. c o  m

            for (Element model : modelElements) {
                Element clonedElement = (Element) templateDocument.importNode(model, true);
                templateModelElement.appendChild(clonedElement);
            }
        }
    }
}

From source file:org.gvnix.web.report.roo.addon.addon.ReportConfigServiceImpl.java

/**
 * Add the ViewResolver config to webmvc-config.xml
 *//*w  w  w . java  2  s  . c o  m*/
public final void addJasperReportsViewResolver() {
    PathResolver pathResolver = projectOperations.getPathResolver();

    // Add config to MVC app context
    String mvcConfig = pathResolver.getIdentifier(LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""),
            "WEB-INF/spring/webmvc-config.xml");
    MutableFile mutableMvcConfigFile = fileManager.updateFile(mvcConfig);
    Document mvcConfigDocument;
    try {
        mvcConfigDocument = XmlUtils.getDocumentBuilder().parse(mutableMvcConfigFile.getInputStream());
    } catch (Exception ex) {
        throw new IllegalStateException("Could not open Spring MVC config file '" + mvcConfig + "'", ex);
    }

    Element beans = mvcConfigDocument.getDocumentElement();

    if (null == XmlUtils.findFirstElement("/beans/bean[@id='jasperReportsXmlViewResolver']", beans)) {
        InputStream configTemplateInputStream = null;
        OutputStream mutableMvcConfigFileOutput = null;
        try {
            configTemplateInputStream = FileUtils.getInputStream(getClass(),
                    "jasperreports-mvc-config-template.xml");
            Validate.notNull(configTemplateInputStream,
                    "Could not acquire jasperreports-mvc-config-template.xml file");
            Document configDoc;
            try {
                configDoc = XmlUtils.getDocumentBuilder().parse(configTemplateInputStream);
            } catch (Exception e) {
                throw new IllegalStateException(e);
            }

            Element configElement = (Element) configDoc.getFirstChild();
            Element jasperReportsBeanConfig = XmlUtils.findFirstElement("/config/bean", configElement);

            Node importedElement = mvcConfigDocument.importNode(jasperReportsBeanConfig, true);
            beans.appendChild(importedElement);

            mutableMvcConfigFileOutput = mutableMvcConfigFile.getOutputStream();
            XmlUtils.writeXml(mutableMvcConfigFileOutput, mvcConfigDocument);
        } finally {
            IOUtils.closeQuietly(mutableMvcConfigFileOutput);
            IOUtils.closeQuietly(configTemplateInputStream);
        }
    }

    if (fileManager.exists(
            pathResolver.getIdentifier(LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""), JASPER_VIEWS_XML))) {
        fileManager.scan();
        // This file already exists, nothing to do
        return;
    }

    // Add jasper-views.xml file
    MutableFile mutableFile;
    InputStream jRepTInStrm;

    try {
        jRepTInStrm = FileUtils.getInputStream(getClass(), "jasperreports-views-config-template.xml");
    } catch (Exception ex) {
        throw new IllegalStateException("Unable to load jasperreports-views-config-template.xml", ex);
    }

    String jasperViesFileDestination = pathResolver
            .getIdentifier(LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""), JASPER_VIEWS_XML);
    if (!fileManager.exists(jasperViesFileDestination)) {
        mutableFile = fileManager.createFile(jasperViesFileDestination);
        Validate.notNull(mutableFile, "Could not create JasperReports views definition file '"
                .concat(jasperViesFileDestination).concat("'"));
    } else {
        mutableFile = fileManager.updateFile(jasperViesFileDestination);
    }

    InputStream inputStream = null;
    OutputStream outputStream = null;
    try {
        inputStream = jRepTInStrm;
        outputStream = mutableFile.getOutputStream();
        IOUtils.copy(inputStream, outputStream);
    } catch (IOException ioe) {
        throw new IllegalStateException("Could not output '".concat(mutableFile.getCanonicalPath()).concat("'"),
                ioe);
    } finally {
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(outputStream);
    }

    fileManager.scan();
}

From source file:com.bstek.dorado.view.config.XmlDocumentPreprocessor.java

private void gothroughPlaceHolders(Document templateDocument, TemplateContext templateContext)
        throws Exception {
    Element templteViewElement = ViewConfigParserUtils.findViewElement(templateDocument.getDocumentElement(),
            templateContext.getResource());

    Document document = templateContext.getSourceDocument();
    Element viewElement = ViewConfigParserUtils.findViewElement(document.getDocumentElement(),
            templateContext.getSourceContext().getResource());

    NamedNodeMap attributes = viewElement.getAttributes();
    int len = attributes.getLength();
    for (int i = 0; i < len; i++) {
        Node item = attributes.item(i);
        String nodeName = item.getNodeName();
        if (!specialMergeProperties.contains(nodeName)) {
            templteViewElement.setAttribute(nodeName, item.getNodeValue());
        }//from   w w w.  ja va2s. com
    }

    List<Element> viewProperties = DomUtils.getChildrenByTagName(viewElement, XmlConstants.PROPERTY);
    for (Element propertyElement : viewProperties) {
        String propertyName = propertyElement.getAttribute(XmlConstants.ATTRIBUTE_NAME);
        if (!specialMergeProperties.contains(propertyName)) {
            Element clonedElement = (Element) templateDocument.importNode(propertyElement, true);
            templteViewElement.appendChild(clonedElement);
        }
    }

    mergeMetaData(templateDocument, templteViewElement, viewElement);
    mergeTemplateProperty(templteViewElement, viewElement, ViewXmlConstants.ATTRIBUTE_PACKAGES);
    mergeTemplateProperty(templteViewElement, viewElement, ViewXmlConstants.ATTRIBUTE_JAVASCRIPT_FILE);
    mergeTemplateProperty(templteViewElement, viewElement, ViewXmlConstants.ATTRIBUTE_STYLESHEET_FILE);

    for (Element element : DomUtils.getChildElements(viewElement)) {
        String nodeName = element.getNodeName();
        if (nodeName.equals(XmlConstants.PROPERTY) || nodeName.equals(XmlConstants.GROUP_START)
                || nodeName.equals(XmlConstants.GROUP_END) || nodeName.equals(XmlConstants.IMPORT)
                || nodeName.equals(XmlConstants.GROUP_END) || nodeName.equals(XmlConstants.PLACE_HOLDER_START)
                || nodeName.equals(XmlConstants.PLACE_HOLDER_END)) {
            continue;
        }
        if (componentTypeRegistry.getRegisterInfo(nodeName) == null) {
            Element clonedElement = (Element) templateDocument.importNode(element, true);
            templteViewElement.appendChild(clonedElement);
        }
    }

    processPlaceHolders(templteViewElement, templateContext);
}

From source file:cc.siara.csv_ml_demo.MultiLevelCSVSwingDemo.java

/**
 * Evaluates given XPath from Input box against Document generated by
 * parsing csv_ml in input box and sets value or node list to output box.
 *//*w  ww.j a v a2s  .c  o  m*/
private void processXPath() {
    XPath xpath = XPathFactory.newInstance().newXPath();
    Document doc = parseInputToDOM();
    if (doc == null)
        return;
    StringBuffer out_str = new StringBuffer();
    try {
        XPathExpression expr = xpath.compile(tfXPath.getText());
        try {
            Document outDoc = Util.parseXMLToDOM("<output></output>");
            Element rootElement = outDoc.getDocumentElement();
            NodeList ret = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
            for (int i = 0; i < ret.getLength(); i++) {
                Object o = ret.item(i);
                if (o instanceof String) {
                    out_str.append(o);
                } else if (o instanceof Node) {
                    Node n = (Node) o;
                    short nt = n.getNodeType();
                    switch (nt) {
                    case Node.TEXT_NODE:
                    case Node.ATTRIBUTE_NODE:
                    case Node.CDATA_SECTION_NODE: // Only one value gets
                                                  // evaluated?
                        if (out_str.length() > 0)
                            out_str.append(',');
                        if (nt == Node.ATTRIBUTE_NODE)
                            out_str.append(n.getNodeValue());
                        else
                            out_str.append(n.getTextContent());
                        break;
                    case Node.ELEMENT_NODE:
                        rootElement.appendChild(outDoc.importNode(n, true));
                        break;
                    }
                }
            }
            if (out_str.length() > 0) {
                rootElement.setTextContent(out_str.toString());
                out_str.setLength(0);
            }
            out_str.append(Util.docToString(outDoc, true));
        } catch (Exception e) {
            // Thrown most likely because the given XPath evaluates to a
            // string
            out_str.append(expr.evaluate(doc));
        }
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }
    taOutput.setText(out_str.toString());
    tfOutputSize.setText(String.valueOf(out_str.length()));
}

From source file:com.enonic.vertical.engine.handlers.ContentObjectHandler.java

private Document createContentObjectsDoc(List<PortletEntity> list) {
    Document doc = XMLTool.createDocument("contentobjects");
    if (list == null) {
        return doc;
    }//from   ww w .ja  va  2 s .  c o m

    Element root = doc.getDocumentElement();
    for (PortletEntity entity : list) {
        Element elem = XMLTool.createElement(doc, root, "contentobject");
        elem.setAttribute("key", String.valueOf(entity.getKey()));
        elem.setAttribute("menukey", String.valueOf(entity.getSite().getKey()));

        Element subelem = XMLTool.createElement(doc, elem, "objectstylesheet", entity.getStyleKey().toString());
        subelem.setAttribute("key", entity.getStyleKey().toString());

        String borderstylesheetkey = entity.getBorderKey() != null ? entity.getBorderKey().toString() : null;
        if (borderstylesheetkey != null) {
            subelem = XMLTool.createElement(doc, elem, "borderstylesheet", borderstylesheetkey);
            subelem.setAttribute("key", borderstylesheetkey);
        }

        XMLTool.createElement(doc, elem, "name", entity.getName());

        Document contentdata = XMLDocumentFactory.create(entity.getXmlDataAsJDOMDocument()).getAsDOMDocument();
        Node xmldata_root = doc.importNode(contentdata.getDocumentElement(), true);
        elem.appendChild(xmldata_root);

        XMLTool.createElement(doc, elem, "timestamp", CalendarUtil.formatTimestamp(entity.getCreated(), true));

        elem.setAttribute("runAs", entity.getRunAs().toString());
    }

    return doc;
}

From source file:net.bpelunit.framework.SpecificationLoader.java

private Element copyAsRootWithNamespaces(XmlObject xmlData) throws SpecificationException {
    final Element rawDataRoot = BPELUnitUtil.generateDummyElementNode();
    final Document rawDataDoc = rawDataRoot.getOwnerDocument();

    final XmlCursor dataCursor = xmlData.newCursor();
    if (dataCursor.toFirstChild()) {
        do {//  w w  w.  j  ava 2  s . c o m
            // Skip comments
            if (dataCursor.isComment()) {
                continue;
            }

            if (dataCursor.isContainer()) {
                // Import elements, including their namespace nodes
                final Node original = dataCursor.getDomNode();
                final Node imported = rawDataDoc.importNode(original, true);
                rawDataRoot.appendChild(imported);
            }
        } while (dataCursor.toNextSibling());
    }

    dataCursor.dispose();
    return rawDataRoot;
}

From source file:de.mpg.escidoc.services.common.util.Util.java

/**
 * Queries the CoNE service and transforms the result into a DOM node.
 * /*from  ww  w  . j av a2  s.  c  om*/
 * @param model The type of object (e.g. "persons")
 * @param name The query string.
 * @param ou Specialty for persons
 * @param coneSession A JSESSIONID to not produce a new session with each call.
 * @return A DOM node containing the results.
 */
public static Node queryConeExactWithIdentifier(String model, String identifier, String ou) {
    DocumentBuilder documentBuilder;

    try {
        System.out.println("queryConeExact: " + model);

        documentBuilder = DocumentBuilderFactoryImpl.newInstance().newDocumentBuilder();

        Document document = documentBuilder.newDocument();
        Element element = document.createElement("cone");
        document.appendChild(element);

        String queryUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model
                + "/query?format=jquery&dc:identifier/rdf:value=\"" + URLEncoder.encode(identifier, "UTF-8")
                + "\"&escidoc:position/eprints:affiliatedInstitution=" + URLEncoder.encode(ou, "UTF-8") + "";
        String detailsUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model
                + "/resource/$1?format=rdf";
        HttpClient client = new HttpClient();
        GetMethod method = new GetMethod(queryUrl);

        String coneSession = getConeSession();

        if (coneSession != null) {
            method.setRequestHeader("Cookie", "JSESSIONID=" + coneSession);
        }
        ProxyHelper.executeMethod(client, method);
        logger.info("CoNE query: " + queryUrl + " returned " + method.getResponseBodyAsString());
        if (method.getStatusCode() == 200) {
            ArrayList<String> results = new ArrayList<String>();
            results.addAll(Arrays.asList(method.getResponseBodyAsString().split("\n")));
            Set<String> oldIds = new HashSet<String>();
            for (String result : results) {
                if (!"".equals(result.trim())) {
                    String id = result.split("\\|")[1];
                    if (!oldIds.contains(id)) {
                        GetMethod detailMethod = new GetMethod(id + "?format=rdf&eSciDocUserHandle=" + "TODO");

                        ProxyHelper.setProxy(client, detailsUrl.replace("$1", id));
                        client.executeMethod(detailMethod);
                        logger.info("CoNE query: " + id + "?format=rdf&eSciDocUserHandle=" + "TODO"
                                + " returned " + detailMethod.getResponseBodyAsString());
                        if (detailMethod.getStatusCode() == 200) {
                            Document details = documentBuilder.parse(detailMethod.getResponseBodyAsStream());
                            element.appendChild(document.importNode(details.getFirstChild(), true));
                        } else {
                            logger.error("Error querying CoNE: Status " + detailMethod.getStatusCode() + "\n"
                                    + detailMethod.getResponseBodyAsString());
                        }
                        oldIds.add(id);
                    }
                }
            }
        } else {
            logger.error("Error querying CoNE: Status " + method.getStatusCode() + "\n"
                    + method.getResponseBodyAsString());
        }
        return document;
    } 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.");
        return null;
        //throw new RuntimeException(e);
    }
}