Example usage for org.w3c.dom Node appendChild

List of usage examples for org.w3c.dom Node appendChild

Introduction

In this page you can find the example usage for org.w3c.dom Node appendChild.

Prototype

public Node appendChild(Node newChild) throws DOMException;

Source Link

Document

Adds the node newChild to the end of the list of children of this node.

Usage

From source file:org.infoglue.cms.controllers.kernel.impl.simple.ContentVersionController.java

public void updateAttributeValue(Integer contentVersionId, String attributeName, String attributeValue,
        InfoGluePrincipal infogluePrincipal, boolean skipValidate, Database db,
        boolean skipSiteNodeVersionUpdate) throws SystemException, Bug {
    ContentVersionVO contentVersionVO = null;
    try {//from w  w  w  .ja  v a2s. c  o m
        contentVersionVO = getContentVersionVOWithId(contentVersionId);
    } catch (Exception e) {
        logger.warn("Problem finding version: " + e.getMessage() + " - skipping - was probably deleted");
    }

    if (contentVersionVO != null) {
        try {
            InputSource inputSource = new InputSource(new StringReader(contentVersionVO.getVersionValue()));

            DOMParser parser = new DOMParser();
            parser.parse(inputSource);
            Document document = parser.getDocument();

            NodeList nl = document.getDocumentElement().getChildNodes();
            Node attributesNode = nl.item(0);

            boolean existed = false;
            nl = attributesNode.getChildNodes();
            for (int i = 0; i < nl.getLength(); i++) {
                Node n = nl.item(i);
                if (n.getNodeName().equalsIgnoreCase(attributeName)) {
                    if (n.getFirstChild() != null && n.getFirstChild().getNodeValue() != null) {
                        n.getFirstChild().setNodeValue(attributeValue);
                        existed = true;
                        break;
                    } else {
                        CDATASection cdata = document.createCDATASection(attributeValue);
                        n.appendChild(cdata);
                        existed = true;
                        break;
                    }
                }
            }

            if (existed == false) {
                org.w3c.dom.Element attributeElement = document.createElement(attributeName);
                attributesNode.appendChild(attributeElement);
                CDATASection cdata = document.createCDATASection(attributeValue);
                attributeElement.appendChild(cdata);
            }

            StringBuffer sb = new StringBuffer();
            org.infoglue.cms.util.XMLHelper.serializeDom(document.getDocumentElement(), sb);
            logger.info("sb:" + sb);
            contentVersionVO.setVersionValue(sb.toString());
            contentVersionVO.setVersionModifier(infogluePrincipal.getName());
            update(contentVersionVO.getContentId(), contentVersionVO.getLanguageId(), contentVersionVO,
                    infogluePrincipal, skipValidate, db, skipSiteNodeVersionUpdate);
        } catch (Exception e) {
            logger.error("Error updating version value: " + e.getMessage(), e);
        }
    }
}

From source file:org.infoscoop.request.filter.HTMLFragmentFilter.java

public byte[] fragmentHTML(Document doc, String xpath, String encoding) {
    if (log.isDebugEnabled())
        log.debug("start fragmentHTML : xpath=" + xpath);

    Element root = doc.getDocumentElement();
    if (!"html".equalsIgnoreCase(root.getNodeName())) {
        NodeList htmlList = root.getElementsByTagName("html");
        if (htmlList.getLength() == 0) {
            log.error("document do not have html tag.");

            return null;
        }/*from  w w  w .java2  s .  c o m*/
        root = (Element) htmlList.item(0);
    }

    if (log.isDebugEnabled())
        log.debug("before html : \n" + document2String(doc));

    // remove scriptTags
    /*
    NodeList scriptTags = XPathAPI.selectNodeList(root, "//script");
    int tagsLength = scriptTags.getLength();
    for(int i=0;i<tagsLength;i++){
       scriptTags.item(i).getParentNode().removeChild(scriptTags.item(i));;
    }
    */

    NodeList headTags = root.getElementsByTagName("head");
    for (int j = 0; j < headTags.getLength(); j++) {
        Element headTag = (Element) headTags.item(j);
        NodeList metas = headTag.getElementsByTagName("meta");
        for (int i = 0; i < metas.getLength(); i++) {
            Element tmpTag = (Element) metas.item(i);
            if (!"Content-Type".equalsIgnoreCase(tmpTag.getAttribute("http-equiv")))
                headTag.removeChild(tmpTag);
        }
    }

    Node targetNode = null;
    Node body = null;
    byte[] fragmentHTML = null;
    try {
        targetNode = XPathAPI.selectSingleNode(root, xpath);
        body = XPathAPI.selectSingleNode(root, "//body");
    } catch (Exception ex) {
        log.error("fragment failed.", ex);
    }

    if (log.isDebugEnabled())
        log.debug("target:" + targetNode + " : body:" + body);

    if (targetNode != null && body != null) {
        if ("body".equals(targetNode.getNodeName().toLowerCase())) {
            // No processing
        } else {
            NodeList childNodes = body.getChildNodes();
            int childLength = childNodes.getLength();
            for (int i = childLength - 1; 0 <= i; i--) {
                body.removeChild(childNodes.item(i));
            }
            body.appendChild(targetNode);
        }

        String resultHTML = document2String(doc);
        //FIXME
        resultHTML = resultHTML.replaceAll("&amp;", "&");

        if (log.isDebugEnabled()) {
            log.debug("result html : \n" + resultHTML);
        }

        try {
            fragmentHTML = resultHTML.getBytes(encoding);
        } catch (UnsupportedEncodingException ex) {
            log.error("Invalid encoding is specified.", ex);

            throw new IllegalArgumentException("unsupported encoding :[" + encoding + "]");
        }
    } else {
        log.error("target is null : " + targetNode + " : " + body + " @" + xpath);

        throw new IllegalArgumentException("node not found :[" + xpath + "]");
    }

    return fragmentHTML;
}

From source file:org.infoscoop.service.ProxyConfService.java

/**
 * @param elementName/*from w w  w . j ava 2 s  .  c om*/
 * @param id
 * @param cacheLifeTime
 * @param type
 * @param pattern
 * @param replacement
 * @param host
 * @param port
 * @throws Exception
 */
public synchronized void addProxyConf(String elementName, String id, String cacheLifeTime, String type,
        String pattern, String replacement, String host, String port, Collection<String> headers)
        throws Exception {
    if (log.isInfoEnabled()) {
        log.info("addProxyConf: id=" + id + ", cacheLifeTime=" + cacheLifeTime + ", type=" + type + ", pattern="
                + pattern + ", replacement=" + replacement + ", host=" + host + ", port=" + port);
    }

    try {
        // Obtain data and transfer the result to Document.
        Proxyconf entity = this.proxyConfDAO.select();
        Document document = entity.getElement().getOwnerDocument();

        // Search for top Node.
        Node topNode = null;
        topNode = AdminServiceUtil.getNodeById(document, "/proxy-config", null);

        // Error
        if (topNode == null)
            throw new Exception("element not found [/proxy-config]");

        // Search for default
        Node defaultNode = null;
        defaultNode = AdminServiceUtil.getNodeById(document, "/proxy-config/default", null);

        // Create the Element to insert.
        if (id == null || id.length() == 0)
            id = String.valueOf(System.currentTimeMillis());
        Element element;
        element = document.createElement(elementName);
        element.setAttribute("id", id);
        if (type != null && type.length() > 0)
            element.setAttribute("type", type);
        if (cacheLifeTime != null && cacheLifeTime.length() > 0)
            element.setAttribute("cacheLifeTime", cacheLifeTime);
        if (pattern != null && pattern.length() > 0)
            element.setAttribute("pattern", pattern);
        if (replacement != null && replacement.length() > 0)
            element.setAttribute("replacement", replacement);
        if (host != null && host.length() > 0)
            element.setAttribute("host", host);
        if (port != null && port.length() > 0)
            element.setAttribute("port", port);

        if ("default".equals(elementName)) {
            // Added to the end of top Node.
            topNode.appendChild(element);
        } else if ("case".equals(elementName)) {
            if (defaultNode != null) {
                // Insert before default
                topNode.insertBefore(element, defaultNode);
            } else {
                // Added to the end of top Node.
                topNode.appendChild(element);
            }
        } else {
            throw new Exception("No elementname");
        }

        if (headers.size() > 0) {
            Node headersNode = document.createElement("headers");
            element.appendChild(headersNode);

            for (String header : headers) {
                Element headerNode = document.createElement("header");
                headerNode.appendChild(document.createTextNode(header));
                headersNode.appendChild(headerNode);
            }
        }
        entity.setElement(document.getDocumentElement());
        // Update
        proxyConfDAO.update(entity);
    } catch (Exception e) {
        log.error("Unexpected error occurred.", e);
        throw e;
    }
}

From source file:org.infoscoop.service.ProxyConfService.java

public void updateProxyConfHeaders(String id, Collection<String> headers, Collection<String> sendingCookies) {
    Proxyconf proxyconf = proxyConfDAO.select();

    try {/*  ww w  .j  a v  a  2  s .co m*/
        XPath xpath = XPathFactory.newInstance().newXPath();
        Element element = proxyconf.getElement();
        Document document = element.getOwnerDocument();

        Element caseNode = (Element) xpath.evaluate("*[@id='" + id + "']", element, XPathConstants.NODE);
        if (caseNode == null)
            throw new RuntimeException("proxyConf[@id=" + id + "] not found");

        Node headersNode = (Node) xpath.evaluate("headers", caseNode, XPathConstants.NODE);
        if (headersNode != null)
            caseNode.removeChild(headersNode);

        if (headers != null) {
            headersNode = document.createElement("headers");
            caseNode.appendChild(headersNode);

            for (String header : headers) {
                Element headerNode = document.createElement("header");
                headerNode.appendChild(document.createTextNode(header));
                headersNode.appendChild(headerNode);
            }
        }

        Node sendingCookiesNode = (Node) xpath.evaluate("sendingcookies", caseNode, XPathConstants.NODE);
        if (sendingCookiesNode != null)
            caseNode.removeChild(sendingCookiesNode);

        if (sendingCookies != null) {
            sendingCookiesNode = document.createElement("sendingcookies");
            caseNode.appendChild(sendingCookiesNode);

            for (String cookie : sendingCookies) {
                Element sendingCookieNode = document.createElement("cookie");
                sendingCookieNode.appendChild(document.createTextNode(cookie));
                sendingCookiesNode.appendChild(sendingCookieNode);
            }
        }

        proxyconf.setElement(element);

        proxyConfDAO.update(proxyconf);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.infoscoop.service.SearchEngineService.java

/**
 * @param parent/*from   w ww .j  a va  2 s  .  c om*/
 * @param id
 * @param title
 * @param retrieveUrl
 * @param encoding
 * @return
 * @throws Exception
 */
public synchronized String addSearchEngine(String parent, String id, String title, String retrieveUrl,
        String encoding, boolean defaultSelected) throws Exception {
    if (log.isInfoEnabled()) {
        log.info("addSearchEngine: id=" + id + ", title=" + title + ", retrieveUrl=" + retrieveUrl
                + ", encoding=" + encoding);
    }

    // Obtain data and transfer the result to Document.
    Searchengine temp = (Searchengine) this.searchEngineDAO.selectTemp();
    Document document = temp.getDocument();

    // Search for child node.
    Node node = AdminServiceUtil.getNodeById(document, "/searchEngines/" + parent, null);

    // Error
    if (node == null)
        throw new Exception("element not found [/searchEngines/" + parent + "]");

    // Create element to insert.
    if (id == null || id.length() == 0)
        id = String.valueOf(System.currentTimeMillis());
    Element element;
    element = document.createElement("searchEngine");
    element.setAttribute("id", id);
    element.setAttribute("title", title);
    element.setAttribute("retrieveUrl", retrieveUrl);
    element.setAttribute("defaultSelected", String.valueOf(defaultSelected));
    if (encoding != null && encoding.length() > 0)
        element.setAttribute("encoding", encoding);

    // Added to the end of node
    node.appendChild(element);

    temp.setDocument(document);
    // Update
    this.searchEngineDAO.update(temp);

    return id;
}

From source file:org.infoscoop.service.SiteAggregationMenuService.java

public synchronized void addMenuItem(String id, String parentId, String title, String href, String display,
        String type, Map props, String alert, String menuType, Collection auths, Boolean linkDisabled,
        String directoryTitle, String sitetopId, boolean multi) throws Exception {

    href = StringUtil.getTruncatedString(href, 1024, "UTF-8");

    if (log.isInfoEnabled()) {
        log.info("AddMenuItem: title=" + title + ", href=" + href + ", display=" + display + ", type=" + type
                + ", alert" + alert + ", properties=" + props);
    }/*  ww  w . j  a va  2 s .c  om*/
    // Obtain data and transfer the result to Document.
    Siteaggregationmenu_temp entity = this.siteAggregationMenuTempDAO.selectBySitetopId(menuType, sitetopId);

    Node node = getTargetElement(entity, parentId);

    // Error
    if (node == null)
        throw new Exception("element not found [//site],[//site-top]");

    Document document = node.getOwnerDocument();

    Element element;
    element = document.createElement("site");
    element.setAttribute("id", id);
    element.setAttribute("title", title);
    element.setAttribute("href", href);
    element.setAttribute("display", display);
    element.setAttribute("link_disabled", linkDisabled.toString());
    element.setAttribute("multi", String.valueOf(multi));
    element.setAttribute("type", type);
    if (alert != null && !"".equals(alert))
        element.setAttribute("alert", alert);
    if (directoryTitle != null && !"".equals(directoryTitle))
        element.setAttribute("directory_title", directoryTitle);

    element.appendChild(recreatePropertiesNode(document, element, props));

    if (auths != null) {
        element.appendChild(MenuAuthorization.createAuthsElement(document, auths));
    }

    // Added at last
    node.appendChild(element);

    // Update
    entity.setElement(document.getDocumentElement());
    this.siteAggregationMenuTempDAO.update(entity);
}

From source file:org.iobserve.mobile.instrument.core.APKToolProxy.java

/**
 * Adjust the manifest file of the application.
 * /*from  w w  w. jav a  2  s .  c o  m*/
 * @param rights
 *            the rights which are mandatory
 * @param modifiedManifest
 *            the file where the adjusted manifest can be stored
 * @return true if success - false otherwise
 */
public boolean adjustManifest(final List<String> rights, final File modifiedManifest) {
    if (folderName == null) {
        return false;
    }

    // read all rights
    final File manifestFile = new File(folderName + "/" + MANIFEST_FILE);
    if (!manifestFile.exists()) {
        return false;
    }

    final Set<String> exRights = new HashSet<String>();

    // PARSING XML
    final Document dom;
    // Make an instance of the DocumentBuilderFactory
    final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    try {
        final DocumentBuilder db = dbf.newDocumentBuilder();

        dom = db.parse(manifestFile);
    } catch (ParserConfigurationException | SAXException | IOException e) {
        return false;
    }

    final Node manifestNode = dom.getElementsByTagName("manifest").item(0);
    this.packageName = manifestNode.getAttributes().getNamedItem("package").getTextContent();
    final NodeList permissionNodes = manifestNode.getChildNodes();

    for (int k = 0; k < permissionNodes.getLength(); k++) {
        final Node permNode = permissionNodes.item(k);
        if (permNode.getNodeName().equals("uses-permission")) {
            exRights.add(permNode.getAttributes().getNamedItem("android:name").getTextContent());
        }
    }

    // determine which to add
    for (String right : rights) {
        if (!exRights.contains(right)) {
            final Element nNode = dom.createElement("uses-permission");
            nNode.setAttribute("android:name", right);
            manifestNode.appendChild(nNode);
        }
    }

    // write content back to file
    try {
        final TransformerFactory transformerFactory = TransformerFactory.newInstance();
        final Transformer transformer = transformerFactory.newTransformer();
        final DOMSource source = new DOMSource(dom);
        final StreamResult result = new StreamResult(manifestFile);
        transformer.transform(source, result);
    } catch (TransformerException e) {
        return false;
    }

    // RECOMPILE
    // apktool b bar -o new_bar.apk
    final File rebuildFile = new File(folderName + "/rebuild.apk");
    final ProcessBuilder pb = new ProcessBuilder("java", "-jar", LIB_PATH, "b", folderName, "-o",
            rebuildFile.getAbsolutePath());

    pb.redirectOutput(Redirect.INHERIT);
    pb.redirectError(Redirect.INHERIT);

    try {
        pb.start().waitFor();
    } catch (InterruptedException | IOException e) {
        LOG.error("Failed to rebuild apk with APKTool.");
        return false;
    }

    // UNZIP IT
    try {
        final ZipFile rebuildZip = new ZipFile(rebuildFile);
        rebuildZip.extractFile(MANIFEST_FILE, folderName + "/" + "manifest_new");
        Files.copy(new File(folderName + "/" + "manifest_new" + "/" + MANIFEST_FILE).toPath(),
                modifiedManifest.toPath());
    } catch (ZipException | IOException e) {
        LOG.error("Failed to extract the manifest from the rebuilt application.");
        return false;
    }

    return true;
}

From source file:org.jahia.services.importexport.ExternalUsersImportUpdater.java

private boolean transform(InputStream inputStream, OutputStream outputStream, Map<String, String> pathMapping)
        throws IOException, ParserConfigurationException, SAXException, XPathExpressionException,
        TransformerException {//from   w  w w  .j  a  v  a2 s .  c  o m
    Document doc = JahiaDocumentBuilderFactory.newInstance().newDocumentBuilder()
            .parse(new InputSource(inputStream));

    XPath xpath = XPathFactory.newInstance().newXPath();
    NodeList nodes = (NodeList) xpath.evaluate(
            "//*[@*[name()='jcr:primaryType'] = 'jnt:user' and @*[name()='j:external'] = 'true']", doc,
            XPathConstants.NODESET);

    for (int i = 0; i < nodes.getLength(); i++) {
        Node legacyExtUser = nodes.item(i);
        ArrayList<Node> tree = new ArrayList<Node>();
        Element extUser = (Element) legacyExtUser.cloneNode(true);
        extUser.setAttribute("jcr:primaryType", "jnt:externalUser");
        String externalSource = extUser.getAttribute("j:externalSource");
        extUser.setAttribute("j:externalSource", externalSource + ".users");
        tree.add(extUser);

        Node parent = legacyExtUser.getParentNode();
        parent.removeChild(legacyExtUser);
        boolean removeParent = !hasChildElement(parent);
        while (parent != null && !"users".equals(parent.getNodeName())) {
            tree.add(0, parent.cloneNode(false));
            Node n = parent.getParentNode();
            if (removeParent) {
                n.removeChild(parent);
                removeParent = !hasChildElement(n);
            }
            parent = n;
        }
        if (parent == null)
            continue;
        StringBuilder mappingSrc = new StringBuilder(getNodePath(parent));
        StringBuilder mappingDst = new StringBuilder(getNodePath(parent));

        NodeList nodeList = ((Element) parent).getElementsByTagName("providers");
        if (nodeList.getLength() == 0) {
            Element e = doc.createElement("providers");
            e.setAttribute("jcr:primaryType", "jnt:usersFolder");
            e.setAttribute("jcr:mixinTypes", "jmix:hasExternalProviderExtension");
            e.setAttribute("j:published", "true");
            e.setAttribute("j:publicationStatus", "1");
            parent.appendChild(e);
            parent = e;
        } else {
            parent = nodeList.item(0);
        }
        mappingDst.append("/").append(parent.getNodeName());

        nodeList = ((Element) parent).getElementsByTagName(externalSource);
        if (nodeList.getLength() == 0) {
            Element e = doc.createElement(externalSource);
            e.setAttribute("jcr:primaryType", "jnt:usersFolder");
            e.setAttribute("provider", externalSource + ".users");
            e.setAttribute("j:publicationStatus", "4");
            parent.appendChild(e);
            parent = e;
        } else {
            parent = nodeList.item(0);
        }
        mappingDst.append("/").append(parent.getNodeName());

        for (Node n : tree) {
            String nodeName = n.getNodeName();
            mappingSrc.append("/").append(nodeName);
            mappingDst.append("/").append(nodeName);
            nodeList = ((Element) parent).getElementsByTagName(nodeName);
            if (nodeList.getLength() == 0) {
                Node node = parent.appendChild(n);
                parent = node;
            } else {
                parent = nodeList.item(0);
            }
        }
        pathMapping.put(mappingSrc.toString(), mappingDst.toString());
    }

    Transformer xformer = TransformerFactory.newInstance().newTransformer();
    xformer.transform(new DOMSource(doc), new StreamResult(outputStream));

    return nodes.getLength() > 0;
}

From source file:org.jboss.pressgang.ccms.contentspec.builder.DocBookBuilder.java

/**
 * Adds a Topics contents as the introduction text for a Level.
 *
 * @param docBookVersion//from  www .  ja va2 s  .c o  m
 * @param level          The level the intro topic is being added for.
 * @param specTopic      The Topic that contains the introduction content.
 * @param parentNode     The DOM parent node the intro content is to be appended to.
 * @param doc            The DOM Document the content is to be added to.
 */
protected void addTopicContentsToLevelDocument(final DocBookVersion docBookVersion, final Level level,
        final SpecTopic specTopic, final Element parentNode, final Document doc, final boolean includeInfo) {
    final Node section = doc.importNode(specTopic.getXMLDocument().getDocumentElement(), true);

    final String infoName;
    if (docBookVersion == DocBookVersion.DOCBOOK_50) {
        infoName = "info";
    } else {
        infoName = DocBookUtilities.TOPIC_ROOT_SECTIONINFO_NODE_NAME;
    }

    if (includeInfo && (level.getLevelType() != LevelType.PART)) {
        // Reposition the sectioninfo
        final List<Node> sectionInfoNodes = XMLUtilities.getDirectChildNodes(section, infoName);
        if (sectionInfoNodes.size() != 0) {
            final String parentInfoName;
            if (docBookVersion == DocBookVersion.DOCBOOK_50) {
                parentInfoName = "info";
            } else {
                parentInfoName = parentNode.getNodeName() + "info";
            }

            // Check if the parent already has a info node
            final List<Node> infoNodes = XMLUtilities.getDirectChildNodes(parentNode, parentInfoName);
            final Node infoNode;
            if (infoNodes.size() == 0) {
                infoNode = doc.createElement(parentInfoName);
                DocBookUtilities.setInfo(docBookVersion, (Element) infoNode, parentNode);
            } else {
                infoNode = infoNodes.get(0);
            }

            // Merge the info text
            final NodeList sectionInfoChildren = sectionInfoNodes.get(0).getChildNodes();
            final Node firstNode = infoNode.getFirstChild();
            while (sectionInfoChildren.getLength() > 0) {
                if (firstNode != null) {
                    infoNode.insertBefore(sectionInfoChildren.item(0), firstNode);
                } else {
                    infoNode.appendChild(sectionInfoChildren.item(0));
                }
            }
        }
    }

    // Remove the title and sectioninfo
    final List<Node> titleNodes = XMLUtilities.getDirectChildNodes(section,
            DocBookUtilities.TOPIC_ROOT_TITLE_NODE_NAME, infoName);
    for (final Node removeNode : titleNodes) {
        section.removeChild(removeNode);
    }

    // Move the contents of the section to the chapter/level
    final NodeList sectionChildren = section.getChildNodes();
    while (sectionChildren.getLength() > 0) {
        parentNode.appendChild(sectionChildren.item(0));
    }
}

From source file:org.jboss.pressgang.ccms.contentspec.builder.DocBookBuilder.java

/**
 * Adds a revision element to the list of revisions in a revhistory element. This method ensures that the new revision is at
 * the top of the revhistory list.//from   www. j a  v a  2s . c  om
 *
 * @param revHistory The revhistory element to add the revision to.
 * @param revision   The revision element to be added into the revisionhistory element.
 */
private void addRevisionToRevHistory(final Node revHistory, final Node revision) {
    if (revHistory.hasChildNodes()) {
        revHistory.insertBefore(revision, revHistory.getFirstChild());
    } else {
        revHistory.appendChild(revision);
    }
}