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.enonic.vertical.adminweb.MenuHandlerServlet.java

private void addMenusXML(AdminService admin, User user, int selectedSiteParameter, Document doc) {
    Document menusDoc = XMLTool//from  www  .  j a  v  a 2  s . c  o  m
            .domparse(admin.getAdminMenuIncludeReadOnlyAccessRights(user, selectedSiteParameter));

    Element[] menuTops = XMLTool.selectElements(menusDoc.getDocumentElement(), "menu");

    for (Element menuTop : menuTops) {
        menuTop = XMLTool.renameElement(menuTop, "menutop");
    }

    Node newMenusDocRootNode = doc.importNode(menusDoc.getDocumentElement(), true);
    doc.getDocumentElement().appendChild(newMenusDocRootNode);
}

From source file:com.enonic.vertical.adminweb.MenuHandlerServlet.java

private void moveMenuItemUp(HttpServletRequest request, HttpServletResponse response, HttpSession session,
        ExtendedMap formItems) throws VerticalAdminException {

    String menuXML = (String) session.getAttribute("menuxml");
    Document doc = XMLTool.domparse(menuXML);

    String xpath = "//menuitem[@key = '" + formItems.getString("key") + "']";
    Element elem = (Element) XMLTool.selectNode(doc, xpath);

    Element parent = (Element) elem.getParentNode();
    Element previousSibling = (Element) elem.getPreviousSibling();
    elem = (Element) parent.removeChild(elem);
    doc.importNode(elem, true);

    if (previousSibling == null)
    // This is the top element, move it to the bottom
    {//from   www  . ja  v a2 s . c  o  m
        parent.appendChild(elem);
    } else {
        parent.insertBefore(elem, previousSibling);
    }

    session.setAttribute("menuxml", XMLTool.documentToString(doc));

    MultiValueMap queryParams = new MultiValueMap();
    queryParams.put("page", formItems.get("page"));
    queryParams.put("op", "browse");
    queryParams.put("keepxml", "yes");
    queryParams.put("highlight", formItems.get("key"));
    queryParams.put("menukey", formItems.get("menukey"));
    queryParams.put("parentmi", formItems.get("parentmi"));
    queryParams.put("subop", "shiftmenuitems");

    queryParams.put("move_menuitem", formItems.getString("move_menuitem", ""));
    queryParams.put("move_from_parent", formItems.getString("move_from_parent", ""));
    queryParams.put("move_to_parent", formItems.getString("move_to_parent", ""));

    redirectClientToAdminPath("adminpage", queryParams, request, response);
}

From source file:cz.mzk.editor.server.fedora.utils.FedoraUtils.java

/**
 * @param foxmlDocument/* www. j  ava 2s.c  o  m*/
 * @param streamToModify
 * @param newContent
 */
private static void modifyStream(Document foxmlDocument, String streamToModify, String newContent) {

    if (newContent != null) {
        try {
            Element versionElement = foxmlDocument.createElement("foxml:datastreamVersion");

            if (streamToModify.equals(RELS_EXT.getValue())) {
                versionElement.setAttribute("LABEL", "RDF Statements about this object");
                versionElement.setAttribute("FORMAT_URI", RELS_EXT_NAMESPACE_URI);
                versionElement.setAttribute("MIMETYPE", "application/rdf+xml");

            } else {
                versionElement.setAttribute("MIMETYPE", "text/xml");

                if (streamToModify.equals(DC.getValue())) {
                    versionElement.setAttribute("LABEL", "Dublin Core Record for this object");
                    versionElement.setAttribute("FORMAT_URI", OAI_DC_NAMESPACE_URI);

                } else if (streamToModify.equals(BIBLIO_MODS.getValue())) {
                    versionElement.setAttribute("LABEL", "BIBLIO_MODS description of current object");
                    versionElement.setAttribute("FORMAT_URI", BIBILO_MODS_URI);

                } else if (streamToModify.equals(TEXT_OCR.getValue())) {
                    versionElement.setAttribute("LABEL", "");
                    Element contLocElement = foxmlDocument.createElement("foxml:contentLocation");
                    contLocElement.setAttribute("TYPE", "INTERNAL_ID");
                    contLocElement.setAttribute("REF", "LOCAL");
                    Element localContElement = foxmlDocument.createElement("foxml:content");
                    localContElement.setTextContent(newContent);
                    contLocElement.appendChild(localContElement);
                    versionElement.appendChild(contLocElement);
                }
            }

            String lastStreamXPath = "//foxml:datastream[@ID=\'" + streamToModify
                    + "\']/foxml:datastreamVersion[last()]";
            Element element = FoxmlUtils.getElement(foxmlDocument, lastStreamXPath);

            int versionNumber = 0;
            if (element != null) {
                versionNumber = getVersionNumber(element.getAttribute("ID"));
            }

            versionElement.setAttribute("ID", streamToModify + "." + (versionNumber + 1));
            versionElement.setAttribute("CREATED", "NOT YET");
            versionElement.setAttribute("SIZE", "0");

            Element contentElement = foxmlDocument.createElement("foxml:xmlContent");

            try {
                InputStream is = new ByteArrayInputStream(newContent.getBytes("UTF-8"));
                Document newStreamDocument = FoxmlUtils.getFoxmlDocument(is);
                NodeList streamNodeList = newStreamDocument.getChildNodes();
                for (int i = 0; i < streamNodeList.getLength(); i++) {
                    Node myNewNode = foxmlDocument.importNode(streamNodeList.item(i), true);
                    contentElement.appendChild(myNewNode);
                }
            } catch (IOException e) {
                System.err.println("IO fauilure" + e);
            }

            versionElement.appendChild(contentElement);

            String streamXPath = "//foxml:datastream[@ID=\'" + streamToModify + "\']";
            Element parentOfStream = FoxmlUtils.getElement(foxmlDocument, streamXPath);

            if (parentOfStream == null) {
                String digObjXPath = "//foxml:digitalObject";
                Element digObjElement = FoxmlUtils.getElement(foxmlDocument, digObjXPath);

                parentOfStream = foxmlDocument.createElement("datastream");
                parentOfStream.setAttribute("ID", streamToModify);
                parentOfStream.setAttribute("STATE", "A");
                //TODO for other streams if necessary
                if (streamToModify.equals(TEXT_OCR.getValue()))
                    parentOfStream.setAttribute("CONTROL_GROUP", "M");
                parentOfStream.setAttribute("VERSIONABLE", "false");
                digObjElement.appendChild(parentOfStream);
            }

            parentOfStream.appendChild(versionElement);

        } catch (XPathExpressionException e) {
            LOGGER.warn("XPath failure", e);
        }
    }
}

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

/**
 * Add a new <bean/> to jasper-views.xml file with the name of the new
 * report/*from  w ww  . j a  v a 2s. c o m*/
 * 
 * @param reportName the name of the report
 * @return jasperReportBeanId
 */
private void addNewJasperReportBean(JavaType entity, String reportName, String format) {
    PathResolver pathResolver = projectOperations.getPathResolver();

    // Install CustomJasperReportsMultiFormatView into
    // top.level.package.<web controllers
    // sub-package>.servlet.view.jasperreports
    // if it is not already installed
    String classMultiFormatView = installCustomJasperReportMultiFormatView();

    // The bean id will be entity_reportName
    String reportBeanId = entity.getSimpleTypeName().toLowerCase().concat("_").concat(reportName.toLowerCase());

    // Add config to jasper-views.xml
    String jasperReportsConfig = pathResolver.getIdentifier(LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""),
            "WEB-INF/spring/jasper-views.xml");
    MutableFile mutableJasperViewsConfigFile = fileManager.updateFile(jasperReportsConfig);
    Document jasperViewsConfigDocument;

    try {
        jasperViewsConfigDocument = XmlUtils.getDocumentBuilder()
                .parse(mutableJasperViewsConfigFile.getInputStream());
    } catch (Exception ex) {
        throw new IllegalStateException(
                "Could not open jasper-views.xml config file '".concat(jasperReportsConfig).concat("'"), ex);
    }

    Element beans = jasperViewsConfigDocument.getDocumentElement();

    if (null != XmlUtils.findFirstElement("/beans/bean[@id='".concat(reportBeanId).concat("']"), beans)) {
        // logger.warning("A report with the name " + reportBeanId +
        // " is already defined");
        return; // There is a bean with the reportName already
                // defined, nothing to do
    }

    // Create a DOM element defining the new bean for the JasperReport view
    InputStream templateInputStream = null;
    OutputStream jasperViewsConfigOutStream = null;
    try {
        templateInputStream = FileUtils.getInputStream(getClass(), "jasperreports-bean-config-template.xml");
        Document reportBeanConfigDocument;
        try {
            reportBeanConfigDocument = XmlUtils.getDocumentBuilder().parse(templateInputStream);
        } catch (Exception ex) {
            throw new IllegalStateException("Could not open jasperreports-bean-config-template.xml file", ex);
        }

        Element configElement = (Element) reportBeanConfigDocument.getDocumentElement();
        Element bean = XmlUtils.findFirstElement("/config/bean", configElement);

        // Set the right attributes dynamically
        bean.setAttribute("id", reportBeanId);
        bean.setAttribute("class", classMultiFormatView);
        bean.setAttribute("p:url", "/WEB-INF/reports/".concat(reportBeanId).concat(".jrxml"));
        bean.setAttribute("p:reportDataKey", reportName.concat("List"));

        // Add the new bean handling the new report view
        Element rootElement = (Element) jasperViewsConfigDocument.getFirstChild();
        Node importedBean = jasperViewsConfigDocument.importNode(bean, true);
        rootElement.appendChild(importedBean);
        jasperViewsConfigOutStream = mutableJasperViewsConfigFile.getOutputStream();
        XmlUtils.writeXml(jasperViewsConfigOutStream, jasperViewsConfigDocument);

    } finally {
        IOUtils.closeQuietly(templateInputStream);
        IOUtils.closeQuietly(jasperViewsConfigOutStream);
    }

    fileManager.scan();
}

From source file:com.enonic.vertical.adminweb.MenuHandlerServlet.java

private void moveMenuItemDown(HttpServletRequest request, HttpServletResponse response, HttpSession session,
        ExtendedMap formItems) throws VerticalAdminException {

    String menuXML = (String) session.getAttribute("menuxml");
    Document doc = XMLTool.domparse(menuXML);

    String xpath = "/model/menuitems-to-list//menuitem[@key = '" + formItems.getString("key") + "']";
    Element movingMenuItemElement = (Element) XMLTool.selectNode(doc, xpath);

    Element parentElement = (Element) movingMenuItemElement.getParentNode();
    Node nextSiblingElement = movingMenuItemElement.getNextSibling();

    movingMenuItemElement = (Element) parentElement.removeChild(movingMenuItemElement);
    doc.importNode(movingMenuItemElement, true);

    if (nextSiblingElement != null) {
        // spool forward...
        for (nextSiblingElement = nextSiblingElement.getNextSibling(); (nextSiblingElement != null
                && nextSiblingElement
                        .getNodeType() != Node.ELEMENT_NODE); nextSiblingElement = nextSiblingElement
                                .getNextSibling()) {

        }//from   w  w  w.j a v a2  s.c  o m

        if (nextSiblingElement != null) {
            parentElement.insertBefore(movingMenuItemElement, nextSiblingElement);
        } else {
            parentElement.appendChild(movingMenuItemElement);
        }
    } else {
        // This is the bottom element, move it to the top
        parentElement.insertBefore(movingMenuItemElement, parentElement.getFirstChild());
    }

    session.setAttribute("menuxml", XMLTool.documentToString(doc));

    MultiValueMap queryParams = new MultiValueMap();
    queryParams.put("page", formItems.get("page"));
    queryParams.put("op", "browse");
    queryParams.put("keepxml", "yes");
    queryParams.put("highlight", formItems.get("key"));
    queryParams.put("menukey", formItems.get("menukey"));
    queryParams.put("parentmi", formItems.get("parentmi"));
    queryParams.put("subop", "shiftmenuitems");

    queryParams.put("move_menuitem", formItems.getString("move_menuitem", ""));
    queryParams.put("move_from_parent", formItems.getString("move_from_parent", ""));
    queryParams.put("move_to_parent", formItems.getString("move_to_parent", ""));

    redirectClientToAdminPath("adminpage", queryParams, request, response);
}

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

/**
 * Queries the CoNE service and transforms the result into a DOM node.
 * //from  w ww  .  j a  v a 2s  .  com
 * @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 {
        logger.info("queryConeExactWithIdentifier: " + model + " identifier: " + identifier + " ou: " + ou);

        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/" + URLEncoder.encode("rdf:value", "UTF-8") + "="
                + URLEncoder.encode("\"" + identifier + "\"", "UTF-8") + "&"
                + URLEncoder.encode("escidoc:position/eprints:affiliatedInstitution", "UTF-8") + "="
                + URLEncoder.encode("\"*" + ou + "*\"", "UTF-8");
        String detailsUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model
                + "/resource/$1?format=rdf";
        HttpClient client = new HttpClient();
        client.getParams().setParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);
        GetMethod method = new GetMethod(queryUrl);

        String coneSession = getConeSession();

        if (coneSession != null) {
            method.setRequestHeader("Cookie", "JSESSIONID=" + coneSession);
        }
        ProxyHelper.executeMethod(client, method);
        if (logger.isDebugEnabled()) {
            logger.debug("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)) {
                        // TODO "&redirect=true" must be reinserted again
                        GetMethod detailMethod = new GetMethod(id + "?format=rdf&eSciDocUserHandle="
                                + Base64.encode(AdminHelper.getAdminUserHandle().getBytes("UTF-8")));
                        detailMethod.setFollowRedirects(true);

                        ProxyHelper.setProxy(client, detailsUrl.replace("$1", id));
                        client.executeMethod(detailMethod);
                        // TODO "&redirect=true" must be reinserted again
                        if (logger.isDebugEnabled()) {
                            logger.debug("CoNE query: " + id + "?format=rdf&eSciDocUserHandle="
                                    + Base64.encode(AdminHelper.getAdminUserHandle().getBytes("UTF-8"))
                                    + " 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.", e);
        return null;
        //throw new RuntimeException(e);
    }
}

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

/**
 * Queries the CoNE service and transforms the result into a DOM node.
 * //from  w w w . ja v  a 2 s .  c o m
 * @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 queryConeExact(String model, String name, 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:title=\"" + URLEncoder.encode(name, "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")));
            queryUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model
                    + "/query?format=jquery&dcterms:alternative=\"" + URLEncoder.encode(name, "UTF-8")
                    + "\"&escidoc:position/eprints:affiliatedInstitution=" + URLEncoder.encode(ou, "UTF-8");
            client = new HttpClient();
            method = new GetMethod(queryUrl);
            if (coneSession != null) {
                method.setRequestHeader("Cookie", "JSESSIONID=" + coneSession);
            }
            ProxyHelper.executeMethod(client, method);
            logger.info("CoNE query: " + queryUrl + " returned " + method.getResponseBodyAsString());
            if (method.getStatusCode() == 200) {
                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);
    }
}

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

private Document createPageTemplatesDocument(Collection<PageTemplateEntity> pageTemplates) {
    Document doc = XMLTool.createDocument("pagetemplates");
    if (pageTemplates == null) {
        return doc;
    }/* w  w w  .  j  av  a 2s. c  o  m*/

    for (PageTemplateEntity pageTemplate : pageTemplates) {
        Element root = doc.getDocumentElement();
        Document ptdDoc = null;

        org.jdom.Document pageTemplateXmlDataAsJdomDoc = pageTemplate.getXmlData();
        if (pageTemplateXmlDataAsJdomDoc != null) {
            ptdDoc = XMLDocumentFactory.create(pageTemplateXmlDataAsJdomDoc).getAsDOMDocument();
            Element docElem = XMLTool.getElement(ptdDoc.getDocumentElement(), "document");
            if (docElem != null) {
                Node firstChild = docElem.getFirstChild();
                if (firstChild == null || firstChild.getNodeType() != Node.CDATA_SECTION_NODE) {
                    docElem.setAttribute("mode", "xhtml");
                }
            }
        }

        Element elem = XMLTool.createElement(doc, root, "pagetemplate");
        elem.setAttribute("key", String.valueOf(pageTemplate.getKey()));
        elem.setAttribute("menukey", String.valueOf(pageTemplate.getSite().getKey()));

        // sub-elements
        XMLTool.createElement(doc, elem, "name", pageTemplate.getName());
        XMLTool.createElement(doc, elem, "description", pageTemplate.getDescription());
        Element tmp = XMLTool.createElement(doc, elem, "stylesheet");
        tmp.setAttribute("stylesheetkey", pageTemplate.getStyleKey().toString());
        tmp.setAttribute("exists",
                resourceDao.getResourceFile(pageTemplate.getStyleKey()) != null ? "true" : "false");

        // element conobjects for pagetemplate
        Document contentobj = getPageTemplateCO(pageTemplate);
        elem.appendChild(doc.importNode(contentobj.getDocumentElement(), true));

        // get page template parameters
        Document ptpDoc = getPageTemplParams(pageTemplate);
        Node ptpNode = doc.importNode(ptpDoc.getDocumentElement(), true);
        elem.appendChild(ptpNode);

        // element timestamp
        XMLTool.createElement(doc, elem, "timestamp",
                CalendarUtil.formatTimestamp(pageTemplate.getTimestamp(), true));

        // element: pagetemplatedata
        if (ptdDoc != null) {
            elem.appendChild(doc.importNode(ptdDoc.getDocumentElement(), true));
        }

        // element: css
        ResourceKey cssKey = pageTemplate.getCssKey();
        if (cssKey != null) {
            tmp = XMLTool.createElement(doc, elem, "css");
            tmp.setAttribute("stylesheetkey", cssKey.toString());
            tmp.setAttribute("exists", resourceDao.getResourceFile(cssKey) != null ? "true" : "false");
        }

        // attribute: runAs & defaultRunAsUser
        elem.setAttribute("runAs", pageTemplate.getRunAs().toString());
        UserEntity defaultRunAsUser = pageTemplate.getSite().resolveDefaultRunAsUser();
        String defaultRunAsUserName = "NA";
        if (defaultRunAsUser != null) {
            defaultRunAsUserName = defaultRunAsUser.getDisplayName();
        }
        elem.setAttribute("defaultRunAsUser", defaultRunAsUserName);

        // attribute: type
        elem.setAttribute("type", pageTemplate.getType().getName());

        // contenttypes
        int[] contentTypes = getContentTypesByPageTemplate(pageTemplate);
        Document contentTypesDoc = getContentHandler().getContentTypesDocument(contentTypes);
        XMLTool.mergeDocuments(elem, contentTypesDoc, true);
    }

    return doc;
}

From source file:edu.uams.clara.webapp.xml.processor.impl.DefaultXmlProcessorImpl.java

/**
 * Thread-safety tested//from  w  w w  . ja v  a 2s . c  o m
 */
@Override
public Map<String, Object> updateElementByPathById(String path, final String originalXml, String elementId,
        final String elementXml) throws SAXException, IOException {

    Assert.hasText(path);
    Assert.hasText(elementId);
    Assert.hasText(originalXml);
    Assert.hasText(elementId);

    Document originalDom = parse(originalXml);

    Document elementDom = parse(elementXml);

    Document finalDom = originalDom;

    Element finalDomRoot = (Element) finalDom.getFirstChild();

    Element elementRoot = (Element) elementDom.getFirstChild();

    List<String> nodeList = getNodeList(path);
    logger.trace("nodeList: " + nodeList + " =? ");

    // the root node of the path should be the same as the root node of
    // the originalXml
    Assert.isTrue(nodeList.size() > 0 && nodeList.get(0).equals(finalDomRoot.getNodeName()));

    // remove first one, should be protocol
    nodeList.remove(0);

    String elementToDeleteName = nodeList.get(nodeList.size() - 1);

    logger.trace("adding <" + elementToDeleteName + ">");
    // remove last one, should be <drug>, we are attaching the drug into
    // drugs... so we want the rightmost element to be drugs...
    nodeList.remove(nodeList.size() - 1);

    Element currentNode = finalDomRoot;
    int c = 0;
    for (String n : nodeList) {
        NodeList cur = currentNode.getElementsByTagName(n);

        c = cur.getLength();

        if (c > 1) {
            throw new RuntimeException("illeagl xml structure; find " + c + " elements with name " + n);
        }

        if (c == 0) {
            throw new RuntimeException("illeagl xml structure; " + n + " doesn't exist");
        }

        currentNode = (Element) cur.item(0);

    }

    logger.trace("rightmost element: " + currentNode.getNodeName());

    elementRoot.setAttribute("id", elementId);

    Node newChild = finalDom.importNode(elementRoot, true);
    NodeList nodes = currentNode.getChildNodes();

    int l = nodes.getLength();

    logger.trace("lenght: " + l);

    for (int i = 0; i < l; i++) {
        Element cc = (Element) nodes.item(i);

        if (cc.getAttribute("id").equals(elementId)) {
            currentNode.replaceChild(newChild, cc);
            break;
        }
    }

    Map<String, Object> resultMap = new HashMap<String, Object>(3);
    resultMap.put("finalXml", DomUtils.elementToString(finalDom));
    resultMap.put("elementXml", DomUtils.elementToString(elementDom));
    resultMap.put("elementId", elementId);
    return resultMap;
}

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

private Document getContentObject(String sql, int[] paramValue) {
    Connection con = null;/*from  www .j  a  va 2  s.com*/
    PreparedStatement preparedStmt = null;
    ResultSet resultSet = null;
    Document doc = XMLTool.createDocument("contentobjects");

    try {
        con = getConnection();
        preparedStmt = con.prepareStatement(sql);
        int length = (paramValue != null ? paramValue.length : 0);
        for (int i = 0; i < length; i++) {
            preparedStmt.setInt(i + 1, paramValue[i]);
        }

        resultSet = preparedStmt.executeQuery();
        Element root = doc.getDocumentElement();
        while (resultSet.next()) {

            // pre-fetch content object data
            Document contentdata = XMLTool.domparse(resultSet.getBinaryStream("cob_xmlData"));

            Element elem = XMLTool.createElement(doc, root, "contentobject");
            elem.setAttribute("key", resultSet.getString("cob_lKey"));
            elem.setAttribute("menukey", resultSet.getString("cob_men_lKey"));

            String style = resultSet.getString("cob_sStyle");
            Element subelem = XMLTool.createElement(doc, elem, "objectstylesheet", style);
            subelem.setAttribute("key", style);
            boolean styleExist = false;
            if (style != null && style.length() > 0) {
                styleExist = null != resourceDao.getResourceFile(new ResourceKey(style));
            }
            subelem.setAttribute("exists", styleExist ? "true" : "false");
            resultSet.getInt("cob_men_lKey");
            if (resultSet.wasNull()) {
                subelem.setAttribute("shared", "true");
            }

            String border = resultSet.getString("cob_sBorder");
            if (!resultSet.wasNull()) {
                subelem = XMLTool.createElement(doc, elem, "borderstylesheet", border);
                subelem.setAttribute("key", border);
                boolean borderExist = false;
                if (border != null && border.length() > 0) {
                    borderExist = null != resourceDao.getResourceFile(new ResourceKey(border));
                }
                subelem.setAttribute("exists", borderExist ? "true" : "false");
                resultSet.getInt("cob_men_lKey");
                if (resultSet.wasNull()) {
                    subelem.setAttribute("shared", "true");
                }
            }

            // element: name
            XMLTool.createElement(doc, elem, "name", resultSet.getString("cob_sName"));

            // element: contentobjectdata
            Node xmldata_root = doc.importNode(contentdata.getDocumentElement(), true);
            elem.appendChild(xmldata_root);

            Timestamp timestamp = resultSet.getTimestamp("cob_dteTimestamp");
            XMLTool.createElement(doc, elem, "timestamp", CalendarUtil.formatTimestamp(timestamp, true));

            elem.setAttribute("runAs", RunAsType.get(resultSet.getInt("cob_lRunAs")).toString());
        }

        resultSet.close();
        resultSet = null;
        preparedStmt.close();
        preparedStmt = null;
    } catch (SQLException sqle) {
        String message = "Failed to get content object(s): %t";
        VerticalEngineLogger.error(this.getClass(), 0, message, sqle);
    } finally {
        close(resultSet);
        close(preparedStmt);
        close(con);
    }

    return doc;
}