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:nl.b3p.kaartenbalie.service.requesthandler.WMSRequestHandler.java

/**
 * Method which copies information from one XML document to another
 * document. It adds information to an document and with this method it's
 * possible to create one document from several other documents as used to
 * create an GetFeatureInfo document.//w ww . ja  va  2  s .  c  om
 *
 * @param source Document object
 * @param destination Document object
 */
private static void copyElements(Document source, Document destination) {
    Element root_source = source.getDocumentElement();
    NodeList nodelist_source = root_source.getChildNodes();
    int size_source = nodelist_source.getLength();

    for (int i = 0; i < size_source; i++) {
        Node node_source = nodelist_source.item(i);
        if (node_source instanceof Element) {
            Element element_source = (Element) node_source;
            String tagName = element_source.getTagName();
            if (!tagName.equalsIgnoreCase("ServiceException")) {
                Node importedNode = destination.importNode(element_source, true);
                Element root_destination = destination.getDocumentElement();
                root_destination.appendChild(importedNode);
            }
        }
    }
}

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

public static Element renameElement(Element elem, String newName) {
    Document doc = elem.getOwnerDocument();

    // Create an element with the new name
    Element elem2 = doc.createElement(newName);

    // Copy the attributes to the new element
    NamedNodeMap attrs = elem.getAttributes();
    for (int i = 0; i < attrs.getLength(); i++) {
        Attr attr2 = (Attr) doc.importNode(attrs.item(i), true);
        elem2.getAttributes().setNamedItem(attr2);
    }//  w  w w.  j ava  2s .co  m

    // Move all the children
    while (elem.hasChildNodes()) {
        elem2.appendChild(elem.getFirstChild());
    }

    // Replace the old node with the new node
    elem.getParentNode().replaceChild(elem2, elem);

    return elem2;
}

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

/**
 * Process study import request./*from   ww w.  j  a  v  a 2 s.  co  m*/
 *
 * @param body the body
 * @return the sOAP message
 * @throws DOMException the dOM exception
 * @throws RuntimeException the runtime exception
 * @throws ParserConfigurationException the parser configuration exception
 * @throws C3PRCodedException the c3 pr coded exception
 * @throws SOAPException the sOAP exception
 */
private SOAPMessage processStudyImportRequest(SOAPBody body)
        throws DOMException, RuntimeException, ParserConfigurationException, C3PRCodedException, SOAPException {
    NodeList nodes = body.getElementsByTagNameNS(SERVICE_NS, IMPORT_STUDY_REQUEST);
    Node importStudyRequestNode = nodes.item(0);
    NodeList studyNodes = ((Element) importStudyRequestNode).getElementsByTagNameNS(C3PR_NS, STUDY_ELEMENT);
    if (studyNodes.getLength() != 1) {
        throw new RuntimeException("Malformed SOAP request. Please check the WSDL.");
    }
    Element study = (Element) studyNodes.item(0);

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.newDocument();
    doc.appendChild(doc.importNode(study, true));
    List<Study> studies = studyXMLImporterService.importStudies(doc, new ErrorsImpl());
    if (CollectionUtils.isEmpty(studies)) {
        throw new RuntimeException("No studies have been imported.");
    }
    return createImportStudyResponse();

}

From source file:nl.b3p.kaartenbalie.service.requesthandler.WMSRequestHandler.java

private static void prefixElements(Document source, Document destination, String spAbbr) {
    Element root_source = source.getDocumentElement();
    NodeList nodelist_source = root_source.getChildNodes();
    int size_source = nodelist_source.getLength();

    for (int i = 0; i < size_source; i++) {
        Node node_source = nodelist_source.item(i);

        if (node_source instanceof Element) {
            Element element_source = (Element) node_source;
            String tagName = element_source.getTagName();

            if (!tagName.equalsIgnoreCase("ServiceException")) {
                Node importedNode = destination.importNode(element_source, true);
                Node newNode = destination.renameNode(importedNode, importedNode.getNamespaceURI(),
                        OGCCommunication.attachSp(spAbbr, tagName));

                Element root_destination = destination.getDocumentElement();
                root_destination.appendChild(newNode);
            }/*from  www  .ja va  2  s  .c om*/
        }
    }
}

From source file:com.twinsoft.convertigo.engine.admin.services.database_objects.Set.java

protected void getServiceResult(HttpServletRequest request, Document document) throws Exception {
    Element root = document.getDocumentElement();
    Document post = null;/*from   ww  w.  ja  v  a 2s  .  c  o  m*/
    Element response = document.createElement("response");

    try {
        Map<String, DatabaseObject> map = com.twinsoft.convertigo.engine.admin.services.projects.Get
                .getDatabaseObjectByQName(request);

        xpath = new TwsCachedXPathAPI();
        post = XMLUtils.parseDOM(request.getInputStream());
        postElt = document.importNode(post.getFirstChild(), true);

        String objectQName = xpath.selectSingleNode(postElt, "./@qname").getNodeValue();
        DatabaseObject object = map.get(objectQName);

        //         String comment = getPropertyValue(object, "comment").toString();
        //         object.setComment(comment);

        if (object instanceof Project) {
            Project project = (Project) object;

            String objectNewName = getPropertyValue(object, "name").toString();

            Engine.theApp.databaseObjectsManager.renameProject(project, objectNewName);

            map.remove(objectQName);
            map.put(project.getQName(), project);
        }

        BeanInfo bi = CachedIntrospector.getBeanInfo(object.getClass());

        PropertyDescriptor[] propertyDescriptors = bi.getPropertyDescriptors();

        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            String propertyName = propertyDescriptor.getName();

            Method setter = propertyDescriptor.getWriteMethod();

            Class<?> propertyTypeClass = propertyDescriptor.getReadMethod().getReturnType();
            if (propertyTypeClass.isPrimitive()) {
                propertyTypeClass = ClassUtils.primitiveToWrapper(propertyTypeClass);
            }

            try {
                String propertyValue = getPropertyValue(object, propertyName).toString();

                Object oPropertyValue = createObject(propertyTypeClass, propertyValue);

                if (object.isCipheredProperty(propertyName)) {

                    Method getter = propertyDescriptor.getReadMethod();
                    String initialValue = (String) getter.invoke(object, (Object[]) null);

                    if (oPropertyValue.equals(initialValue)
                            || DatabaseObject.encryptPropertyValue(initialValue).equals(oPropertyValue)) {
                        oPropertyValue = initialValue;
                    } else {
                        object.hasChanged = true;
                    }
                }

                if (oPropertyValue != null) {
                    Object args[] = { oPropertyValue };
                    setter.invoke(object, args);
                }

            } catch (IllegalArgumentException e) {
            }
        }

        Engine.theApp.databaseObjectsManager.exportProject(object.getProject());
        response.setAttribute("state", "success");
        response.setAttribute("message", "Project have been successfully updated!");
    } catch (Exception e) {
        Engine.logAdmin.error("Error during saving the properties!\n" + e.getMessage());
        response.setAttribute("state", "error");
        response.setAttribute("message", "Error during saving the properties!");
        Element stackTrace = document.createElement("stackTrace");
        stackTrace.setTextContent(e.getMessage());
        root.appendChild(stackTrace);
    } finally {
        xpath.resetCache();
    }

    root.appendChild(response);
}

From source file:com.adaptris.core.services.jdbc.XmlPayloadTranslator.java

private DocumentWrapper toDocument(JdbcResult rs, AdaptrisMessage msg)
        throws ParserConfigurationException, SQLException {
    XmlUtils xu = createXmlUtils(msg);/*from  w  ww  .  jav  a2 s . c  o  m*/
    DocumentBuilderFactoryBuilder factoryBuilder = documentFactoryBuilder(msg);
    DocumentBuilderFactory factory = factoryBuilder.configure(DocumentBuilderFactory.newInstance());
    DocumentBuilder builder = factoryBuilder.configure(factory.newDocumentBuilder());
    Document doc = builder.newDocument();
    DocumentWrapper result = new DocumentWrapper(doc, 0);
    ColumnStyle elementNameStyle = getColumnNameStyle();

    Element results = doc.createElement(elementNameStyle.format(ELEMENT_NAME_RESULTS));
    doc.appendChild(results);

    if (isPreserveOriginalMessage()) {
        Element originalMessage = doc.createElement(elementNameStyle.format(ORIGINAL_MESSAGE_ELEMENT));

        if (xu.isDocumentValid()) {
            Node n = xu.getSingleNode("/").getFirstChild();
            originalMessage.appendChild(doc.importNode(n, true));
        } else {
            // Not XML, so let's add it in as a CDATA node.
            originalMessage.appendChild(createTextNode(doc, msg.getContent(), true));
        }
        results.appendChild(originalMessage);
    }
    for (JdbcResultSet rSet : rs.getResultSets()) {
        List<Element> elements = createListFromResultSet(builder, doc, rSet);
        for (Element element : elements) {
            results.appendChild(element);
        }
        result.resultSetCount += elements.size();
    }
    return result;
}

From source file:org.openmhealth.shim.healthvault.HealthvaultShim.java

@Override
public ShimDataResponse getData(final ShimDataRequest shimDataRequest) throws ShimException {
    final HealthVaultDataType healthVaultDataType;
    try {//  ww  w. j  ava  2  s.  c  o m
        healthVaultDataType = HealthVaultDataType
                .valueOf(shimDataRequest.getDataTypeKey().trim().toUpperCase());
    } catch (NullPointerException | IllegalArgumentException e) {
        throw new ShimException("Null or Invalid data type parameter: " + shimDataRequest.getDataTypeKey()
                + " in shimDataRequest, cannot retrieve data.");
    }

    final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'hh:mm:ss");

    /***
     * Setup default date parameters
     */
    DateTime today = new DateTime();

    DateTime startDate = shimDataRequest.getStartDate() == null ? today.minusDays(1)
            : shimDataRequest.getStartDate();
    String dateStart = startDate.toString(formatter);

    DateTime endDate = shimDataRequest.getEndDate() == null ? today.plusDays(1) : shimDataRequest.getEndDate();
    String dateEnd = endDate.toString(formatter);

    long numToReturn = shimDataRequest.getNumToReturn() == null || shimDataRequest.getNumToReturn() <= 0 ? 100
            : shimDataRequest.getNumToReturn();

    Request request = new Request();
    request.setMethodName("GetThings");
    request.setInfo("<info>" + "<group max=\"" + numToReturn + "\">" + "<filter>" + "<type-id>"
            + healthVaultDataType.getDataTypeId() + "</type-id>" + "<eff-date-min>" + dateStart
            + "</eff-date-min>" + "<eff-date-max>" + dateEnd + "</eff-date-max>" + "</filter>" + "<format>"
            + "<section>core</section>" + "<xml/>" + "</format>" + "</group>" + "</info>");

    RequestTemplate template = new RequestTemplate(connection);
    return template.makeRequest(shimDataRequest.getAccessParameters(), request,
            new Marshaller<ShimDataResponse>() {
                public ShimDataResponse marshal(InputStream istream) throws Exception {

                    /**
                     * XML Document mappings to JSON don't respect repeatable
                     * tags, they don't get properly serialized into collections.
                     * Thus, we pickup the 'things' via the 'group' root tag
                     * and create a new JSON document out of each 'thing' node.
                     */
                    XmlMapper xmlMapper = new XmlMapper();
                    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder builder = factory.newDocumentBuilder();
                    Document doc = builder.parse(istream);
                    NodeList nodeList = doc.getElementsByTagName("thing");

                    /**
                     * Collect JsonNode from each 'thing' xml node.
                     */
                    List<JsonNode> thingList = new ArrayList<>();
                    for (int i = 0; i < nodeList.getLength(); i++) {
                        Node node = nodeList.item(i);
                        Document thingDoc = builder.newDocument();
                        Node newNode = thingDoc.importNode(node, true);
                        thingDoc.appendChild(newNode);
                        thingList.add(xmlMapper.readTree(convertDocumentToString(thingDoc)));
                    }

                    /**
                     * Rebuild JSON document structure to pass to deserializer.
                     */
                    String thingsJson = "{\"things\":[";
                    String thingsContent = "";
                    for (JsonNode thingNode : thingList) {
                        thingsContent += thingNode.toString() + ",";
                    }
                    thingsContent = "".equals(thingsContent) ? thingsContent
                            : thingsContent.substring(0, thingsContent.length() - 1);
                    thingsJson += thingsContent;
                    thingsJson += "]}";

                    /**
                     * Return raw re-built 'things' or a normalized JSON document.
                     */
                    ObjectMapper objectMapper = new ObjectMapper();
                    if (shimDataRequest.getNormalize()) {
                        SimpleModule module = new SimpleModule();
                        module.addDeserializer(ShimDataResponse.class, healthVaultDataType.getNormalizer());
                        objectMapper.registerModule(module);
                        return objectMapper.readValue(thingsJson, ShimDataResponse.class);
                    } else {
                        return ShimDataResponse.result(HealthvaultShim.SHIM_KEY,
                                objectMapper.readTree(thingsJson));
                    }
                }
            });
}

From source file:com.jaspersoft.studio.data.querydesigner.xpath.XPathQueryDesigner.java

private void createContextualMenu() {
    Menu contextMenu = new Menu(treeViewer.getTree());
    final MenuItem setRecordNodeItem = new MenuItem(contextMenu, SWT.PUSH);
    setRecordNodeItem.setText(Messages.XPathQueryDesigner_SetRecordItem);
    setRecordNodeItem.addSelectionListener(new SelectionAdapter() {
        @Override/* w w w.j ava2  s.co m*/
        public void widgetSelected(SelectionEvent e) {
            Object sel = ((IStructuredSelection) treeViewer.getSelection()).getFirstElement();
            if (sel instanceof XMLNode) {
                String xPathExpression = documentManager.getXPathExpression(null, (XMLNode) sel);
                queryTextArea.setText((xPathExpression != null) ? xPathExpression : ""); //$NON-NLS-1$
            }
        }
    });
    final MenuItem setDocumentRootItem = new MenuItem(contextMenu, SWT.PUSH);
    setDocumentRootItem.setText(Messages.XPathQueryDesigner_SetDocRootItem);
    setDocumentRootItem.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            Object sel = ((IStructuredSelection) treeViewer.getSelection()).getFirstElement();
            try {
                Document newDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
                Node originalNode = documentManager.getDocumentNodesMap().get(sel);
                Node importedNode = newDocument.importNode(originalNode, true);
                newDocument.appendChild(importedNode);
                documentManager.setDocument(newDocument);
                treeViewer.setInput(documentManager.getXMLDocumentModel());
            } catch (Exception e1) {
                UIUtils.showError(e1);
            }
        }
    });
    new MenuItem(contextMenu, SWT.SEPARATOR);
    final MenuItem addNodeAsFieldItem1 = new MenuItem(contextMenu, SWT.PUSH);
    addNodeAsFieldItem1.setText(Messages.XPathQueryDesigner_AddAsFieldItem);
    addNodeAsFieldItem1.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            Object sel = ((IStructuredSelection) treeViewer.getSelection()).getFirstElement();
            if (sel instanceof XMLNode) {
                String xPathExpression = documentManager.getXPathExpression(queryTextArea.getText(),
                        (XMLNode) sel);
                ((XMLNode) sel).setXPathExpression(xPathExpression);
                createField((XMLNode) sel);
            }
        }
    });
    final MenuItem addNodeAsFieldItem2 = new MenuItem(contextMenu, SWT.PUSH);
    addNodeAsFieldItem2.setText(Messages.XPathQueryDesigner_AddAsFieldAbsoluteItem);
    addNodeAsFieldItem2.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            Object sel = ((IStructuredSelection) treeViewer.getSelection()).getFirstElement();
            if (sel instanceof XMLNode) {
                String xPathExpression = documentManager.getXPathExpression(null, (XMLNode) sel);
                ((XMLNode) sel).setXPathExpression(xPathExpression);
                createField((XMLNode) sel);
            }
        }
    });
    new MenuItem(contextMenu, SWT.SEPARATOR);
    final MenuItem expandAllItem = new MenuItem(contextMenu, SWT.PUSH);
    expandAllItem.setText(Messages.XPathQueryDesigner_ExpandAllItem);
    expandAllItem.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            treeViewer.expandAll();
        }
    });
    final MenuItem collapseAllItem = new MenuItem(contextMenu, SWT.PUSH);
    collapseAllItem.setText(Messages.XPathQueryDesigner_CollapseAllItem);
    collapseAllItem.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            treeViewer.collapseAll();
        }
    });
    final MenuItem resetRefreshDocItem = new MenuItem(contextMenu, SWT.PUSH);
    resetRefreshDocItem.setText(Messages.XPathQueryDesigner_RefreshItem);
    resetRefreshDocItem.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            refreshTreeViewerContent(container.getDataAdapter());
        }
    });
    treeViewer.getTree().setMenu(contextMenu);

    contextMenu.addMenuListener(new MenuListener() {
        @Override
        public void menuShown(MenuEvent e) {
            Object selEl = ((IStructuredSelection) treeViewer.getSelection()).getFirstElement();
            if (selEl instanceof XMLNode) {
                addNodeAsFieldItem1.setEnabled(true);
                addNodeAsFieldItem2.setEnabled(true);
                if (selEl instanceof XMLAttributeNode) {
                    setRecordNodeItem.setEnabled(false);
                    setDocumentRootItem.setEnabled(false);
                } else {
                    setRecordNodeItem.setEnabled(true);
                    setDocumentRootItem.setEnabled(true);
                }
            } else {
                setRecordNodeItem.setEnabled(false);
                setDocumentRootItem.setEnabled(false);
                addNodeAsFieldItem1.setEnabled(false);
                addNodeAsFieldItem2.setEnabled(false);
            }
        }

        @Override
        public void menuHidden(MenuEvent e) {

        }
    });
}

From source file:com.adaptris.util.XmlUtils.java

/**
 * Convenience method which appends a new Node to the children of a parent
 *
 * @param newNode the Node to be added//  w w  w  . j  av a  2  s  . c om
 * @param parent the parent Node
 * @throws Exception on error.
 */
public void appendNode(Node newNode, Node parent) throws Exception {
    Document parentDoc = parent.getOwnerDocument();
    Document newDoc = newNode.getOwnerDocument();

    if (!parentDoc.equals(newDoc)) {
        newNode = parentDoc.importNode(newNode, true);
    }

    parent.appendChild(newNode);
}

From source file:com.inbravo.scribe.rest.service.crm.ms.MSCRMMessageFormatUtils.java

public static final List<Element> createEntityFromBusinessObject(final BusinessEntity businessEntity)
        throws Exception {

    /* Create list of elements */
    final List<Element> elementList = new ArrayList<Element>();

    if (businessEntity != null) {
        final Node node = businessEntity.getDomNode();
        if (node.hasChildNodes()) {
            final NodeList nodeList = node.getChildNodes();
            for (int i = 0; i < nodeList.getLength(); i++) {

                /* To avoid : 'DOM Level 3 Not implemented' error */
                final DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                final Document document = builder.newDocument();
                final Element element = (Element) document.importNode(nodeList.item(i), true);

                if (element.getNodeName() != null && element.getNodeName().contains(":")) {
                    final String nodeName = element.getNodeName().split(":")[1];

                    /* Check for attributes */
                    final NamedNodeMap attributes = element.getAttributes();

                    if (attributes != null && attributes.getLength() != 0) {

                        /* Create new map for attributes */
                        final Map<String, String> attributeMap = new HashMap<String, String>();

                        for (int j = 0; j < attributes.getLength(); j++) {
                            final Attr attr = (Attr) attributes.item(j);

                            /* Set node name and value in map */
                            attributeMap.put(attr.getNodeName(), attr.getNodeValue());
                        }//from   w  w  w.j ava 2s  . c  om

                        /* Create node with attributes */
                        elementList.add(MSCRMMessageFormatUtils.createMessageElement(nodeName,
                                element.getTextContent(), attributeMap));
                    } else {

                        /* Create node without attributes */
                        elementList.add(MSCRMMessageFormatUtils.createMessageElement(nodeName,
                                element.getTextContent()));
                    }
                }
            }
        }
        return elementList;
    } else {
        return null;
    }
}