Example usage for org.w3c.dom Element removeChild

List of usage examples for org.w3c.dom Element removeChild

Introduction

In this page you can find the example usage for org.w3c.dom Element removeChild.

Prototype

public Node removeChild(Node oldChild) throws DOMException;

Source Link

Document

Removes the child node indicated by oldChild from the list of children, and returns it.

Usage

From source file:org.infoglue.cms.applications.managementtool.actions.ViewContentTypeDefinitionAction.java

public String doUpdateAttributeValidatorArguments() throws Exception {
    this.initialize(getContentTypeDefinitionId());

    try {//www  .  j  a v  a 2 s  .c  o m
        Document document = createDocumentFromDefinition();

        int i = 0;
        //String attributeValidatorName = this.getRequest().getParameter("attributeValidatorName");
        String attributeValidatorIndex = this.getRequest().getParameter("attributeValidatorIndex");
        Integer attributeValidatorIndexInteger = new Integer(attributeValidatorIndex);

        String argumentName = this.getRequest().getParameter(i + "_argumentName");
        while (argumentName != null && !argumentName.equalsIgnoreCase("")) {
            String argumentValue = this.getRequest().getParameter(i + "_argumentValue");

            //String validatorsXPath = "/xs:schema/xs:complexType[@name = 'Validation']/xs:annotation/xs:appinfo/form-validation/formset/form/field[@property = '" + attributeName + "'][@depends = '" + attributeValidatorName + "']";
            String validatorsXPath = "/xs:schema/xs:complexType[@name = 'Validation']/xs:annotation/xs:appinfo/form-validation/formset/form/field[@property = '"
                    + attributeName + "'][" + attributeValidatorIndexInteger + "]";
            Node fieldNode = org.apache.xpath.XPathAPI.selectSingleNode(document.getDocumentElement(),
                    validatorsXPath);
            if (fieldNode != null) {
                Element element = (Element) fieldNode;
                NodeList nl = element.getElementsByTagName("var");
                for (int nlIndex = 0; nlIndex < nl.getLength(); nlIndex++) {
                    Node node = (Node) nl.item(nlIndex);
                    element.removeChild(node);
                }

                Element newVar = document.createElement("var");

                Element varNameElement = createTextElement(document, "var-name", argumentName);
                Element varValueElement = createTextElement(document, "var-value", argumentValue);
                newVar.appendChild(varNameElement);
                newVar.appendChild(varValueElement);

                element.appendChild(newVar);
            }

            i++;
            argumentName = this.getRequest().getParameter(i + "_argumentName");
        }

        //Sets the message part
        String msgText = this.getRequest().getParameter("errorMessage");
        logger.info("msgText:" + msgText);
        msgText = StringEscapeUtils.escapeXml(msgText);
        logger.info("msgText:" + msgText);
        //se=Du fr inte 'ladda' innehllet med "snt"!<b>NU</b>;en=You cannot do 'this' or "that"

        //String validatorsXPath = "/xs:schema/xs:complexType[@name = 'Validation']/xs:annotation/xs:appinfo/form-validation/formset/form/field[@property = '" + attributeName + "'][@depends = '" + attributeValidatorName + "']";
        String validatorsXPath = "/xs:schema/xs:complexType[@name = 'Validation']/xs:annotation/xs:appinfo/form-validation/formset/form/field[@property = '"
                + attributeName + "'][" + attributeValidatorIndexInteger + "]";
        Node fieldNode = org.apache.xpath.XPathAPI.selectSingleNode(document.getDocumentElement(),
                validatorsXPath);
        logger.info("fieldNode:" + fieldNode);
        if (fieldNode != null) {
            Element element = (Element) fieldNode;
            NodeList nl1 = element.getElementsByTagName("msg");
            for (int nlIndex = 0; nlIndex < nl1.getLength(); nlIndex++) {
                Element messageElement = (Element) nl1.item(nlIndex);
                if (currentContentTypeEditorViewLanguageCode != null
                        && !currentContentTypeEditorViewLanguageCode.equals(""))
                    messageElement.setAttribute("key_" + currentContentTypeEditorViewLanguageCode, msgText);
                else
                    messageElement.setAttribute("key", msgText);
            }
        }

        saveUpdatedDefinition(document);
    } catch (Exception e) {
        e.printStackTrace();
    }

    this.initialize(getContentTypeDefinitionId());
    return USE_EDITOR;
}

From source file:org.infoglue.cms.applications.structuretool.actions.ViewSiteNodePageComponentsAction.java

/**
 * This method shows the user a list of Components(HTML Templates). 
 *//*from   w  ww  . j a  v a 2 s .c  o m*/

public String doAddComponentPropertyBinding() throws Exception {
    initialize();
    //logger.info("************************************************************");
    //logger.info("* doAddComponentPropertyBinding                            *");
    //logger.info("************************************************************");
    //logger.info("siteNodeId:" + this.siteNodeId);
    //logger.info("languageId:" + this.languageId);
    //logger.info("contentId:" + this.contentId);
    //logger.info("componentId:" + this.componentId);
    //logger.info("slotId:" + this.slotId);
    //logger.info("specifyBaseTemplate:" + this.specifyBaseTemplate);
    //logger.info("assetKey:" + assetKey);

    Integer siteNodeId = new Integer(this.getRequest().getParameter("siteNodeId"));
    Integer languageId = new Integer(this.getRequest().getParameter("languageId"));

    Locale locale = LanguageController.getController().getLocaleWithId(languageId);

    String entity = this.getRequest().getParameter("entity");
    Integer entityId = new Integer(this.getRequest().getParameter("entityId"));
    String propertyName = this.getRequest().getParameter("propertyName");

    String componentXML = getPageComponentsString(siteNodeId, this.masterLanguageVO.getId());

    Document document = XMLHelper.readDocumentFromByteArray(componentXML.getBytes("UTF-8"));
    String componentPropertyXPath = "//component[@id=" + this.componentId + "]/properties/property[@name='"
            + propertyName + "']";
    //logger.info("componentPropertyXPath:" + componentPropertyXPath);
    NodeList anl = org.apache.xpath.XPathAPI.selectNodeList(document.getDocumentElement(),
            componentPropertyXPath);
    if (anl.getLength() == 0) {
        String componentXPath = "//component[@id=" + this.componentId + "]/properties";
        //logger.info("componentXPath:" + componentXPath);
        NodeList componentNodeList = org.apache.xpath.XPathAPI.selectNodeList(document.getDocumentElement(),
                componentXPath);
        if (componentNodeList.getLength() > 0) {
            Element componentProperties = (Element) componentNodeList.item(0);
            if (entity.equalsIgnoreCase("SiteNode"))
                addPropertyElement(componentProperties, propertyName, path, "siteNodeBinding", locale);
            else if (entity.equalsIgnoreCase("Content"))
                addPropertyElement(componentProperties, propertyName, path, "contentBinding", locale);
            else if (entity.equalsIgnoreCase("Category"))
                addPropertyElement(componentProperties, propertyName, path, "categoryBinding", locale);

            anl = org.apache.xpath.XPathAPI.selectNodeList(document.getDocumentElement(),
                    componentPropertyXPath);
        }
    }

    //logger.info("anl:" + anl);
    if (anl.getLength() > 0) {
        Element component = (Element) anl.item(0);
        if (entity.equalsIgnoreCase("SiteNode")) {
            SiteNodeVO siteNodeVO = SiteNodeController.getController().getSiteNodeVOWithId(entityId);
            path = siteNodeVO.getName();
        } else if (entity.equalsIgnoreCase("Content")) {
            ContentVO contentVO = ContentController.getContentController().getContentVOWithId(entityId);
            path = contentVO.getName();
        } else if (entity.equalsIgnoreCase("Category")) {
            CategoryVO categoryVO = CategoryController.getController().findById(entityId);
            path = categoryVO.getDisplayName();
        }

        component.setAttribute("path", path);
        NamedNodeMap attributes = component.getAttributes();
        logger.debug("NumberOfAttributes:" + attributes.getLength() + ":" + attributes);

        List removableAttributes = new ArrayList();
        for (int i = 0; i < attributes.getLength(); i++) {
            Node node = attributes.item(i);
            logger.debug("Node:" + node.getNodeName());
            if (node.getNodeName().startsWith("path_")) {
                removableAttributes.add("" + node.getNodeName());
            }
        }

        Iterator removableAttributesIterator = removableAttributes.iterator();
        while (removableAttributesIterator.hasNext()) {
            String attributeName = (String) removableAttributesIterator.next();
            logger.debug("Removing node:" + attributeName);
            component.removeAttribute(attributeName);
        }

        NodeList children = component.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            Node node = children.item(i);
            component.removeChild(node);
        }

        if (assetKey != null) {
            logger.debug("assetKey:" + assetKey);
            String fromEncoding = CmsPropertyHandler.getUploadFromEncoding();
            if (fromEncoding == null)
                fromEncoding = "iso-8859-1";

            String toEncoding = CmsPropertyHandler.getUploadToEncoding();
            if (toEncoding == null)
                toEncoding = "utf-8";

            this.assetKey = new String(this.assetKey.getBytes(fromEncoding), toEncoding);
            logger.debug("assetKey:" + assetKey);
        }

        Element newComponent = addBindingElement(component, entity, entityId, assetKey);
        String modifiedXML = XMLHelper.serializeDom(document, new StringBuffer()).toString();
        //logger.info("modifiedXML:" + modifiedXML);

        ContentVO contentVO = NodeDeliveryController
                .getNodeDeliveryController(siteNodeId, languageId, contentId)
                .getBoundContent(this.getInfoGluePrincipal(), siteNodeId, languageId, true, "Meta information",
                        DeliveryContext.getDeliveryContext());
        ContentVersionVO contentVersionVO = ContentVersionController.getContentVersionController()
                .getLatestActiveContentVersionVO(contentVO.getId(), this.masterLanguageVO.getId());

        ContentVersionController.getContentVersionController().updateAttributeValue(
                contentVersionVO.getContentVersionId(), "ComponentStructure", modifiedXML,
                this.getInfoGluePrincipal());
    }

    Boolean hideComponentPropertiesOnLoad = (Boolean) getHttpSession()
            .getAttribute("" + siteNodeId + "_hideComponentPropertiesOnLoad");
    if (hideComponentPropertiesOnLoad == null)
        hideComponentPropertiesOnLoad = false;
    else
        getHttpSession().removeAttribute("" + siteNodeId + "_hideComponentPropertiesOnLoad");

    if (showDecorated == null || !showDecorated.equalsIgnoreCase("false"))
        this.url = getComponentRendererUrl() + getComponentRendererAction() + "?siteNodeId=" + this.siteNodeId
                + "&languageId=" + this.languageId + "&contentId=" + this.contentId + "&focusElementId="
                + this.componentId
                + (!hideComponentPropertiesOnLoad ? "&activatedComponentId=" + this.componentId : "")
                + "&showSimple=" + this.showSimple;
    else
        this.url = getComponentRendererUrl() + "ViewPage.action?siteNodeId=" + this.siteNodeId + "&languageId="
                + this.languageId + "&contentId=" + this.contentId + "&focusElementId=" + this.componentId
                + (!hideComponentPropertiesOnLoad ? "&activatedComponentId=" + this.componentId : "")
                + "&showSimple=" + this.showSimple;

    this.url = this.getResponse().encodeURL(url);
    this.getResponse().sendRedirect(url);
    return NONE;
}

From source file:org.infoglue.common.contenttypeeditor.actions.ViewContentTypeDefinitionAction.java

/**
 * This method moves an content type attribute up one step.
 *///w w w  . ja v  a2  s. c o  m

public String doMoveAttributeUp() throws Exception {
    this.initialize(getContentTypeDefinitionId());

    try {
        Document document = createDocumentFromDefinition();

        String attributesXPath = "/xs:schema/xs:complexType/xs:all/xs:element/xs:complexType/xs:all/xs:element";
        NodeList anl = org.apache.xpath.XPathAPI.selectNodeList(document.getDocumentElement(), attributesXPath);
        Element previousElement = null;
        for (int i = 0; i < anl.getLength(); i++) {
            Element element = (Element) anl.item(i);
            if (element.getAttribute("name").equalsIgnoreCase(this.attributeName) && previousElement != null) {
                Element parent = (Element) element.getParentNode();
                parent.removeChild(element);
                parent.insertBefore(element, previousElement);
            }
            previousElement = element;
        }

        saveUpdatedDefinition(document);
    } catch (Exception e) {
        e.printStackTrace();
    }

    this.initialize(getContentTypeDefinitionId());

    return UPDATED;
}

From source file:org.infoglue.common.contenttypeeditor.actions.ViewContentTypeDefinitionAction.java

/**
 * This method moves an content type attribute down one step.
 *///from w  w  w. j  a va 2 s  . c  o m

public String doMoveAttributeDown() throws Exception {
    this.initialize(getContentTypeDefinitionId());

    try {
        Document document = createDocumentFromDefinition();

        String attributesXPath = "/xs:schema/xs:complexType/xs:all/xs:element/xs:complexType/xs:all/xs:element";
        NodeList anl = org.apache.xpath.XPathAPI.selectNodeList(document.getDocumentElement(), attributesXPath);
        Element parent = null;
        Element elementToMove = null;
        boolean isInserted = false;
        int position = 0;
        for (int i = 0; i < anl.getLength(); i++) {
            Element element = (Element) anl.item(i);
            parent = (Element) element.getParentNode();

            if (elementToMove != null) {
                if (position == 2) {
                    parent.insertBefore(elementToMove, element);
                    isInserted = true;
                    break;
                } else
                    position++;
            }

            if (element.getAttribute("name").equalsIgnoreCase(this.attributeName)) {
                elementToMove = element;
                parent.removeChild(elementToMove);
                position++;
            }
        }

        if (!isInserted && elementToMove != null)
            parent.appendChild(elementToMove);

        saveUpdatedDefinition(document);
    } catch (Exception e) {
        e.printStackTrace();
    }

    this.initialize(getContentTypeDefinitionId());

    return UPDATED;
}

From source file:org.infoglue.common.contenttypeeditor.actions.ViewContentTypeDefinitionAction.java

public String doUpdateAttributeValidatorArguments() throws Exception {
    this.initialize(getContentTypeDefinitionId());

    try {/*from ww w  .j a v  a  2 s .  c  o m*/
        Document document = createDocumentFromDefinition();

        int i = 0;
        String attributeValidatorName = ServletActionContext.getRequest()
                .getParameter("attributeValidatorName");
        String argumentName = ServletActionContext.getRequest().getParameter(i + "_argumentName");

        while (argumentName != null && !argumentName.equalsIgnoreCase("")) {
            String argumentValue = ServletActionContext.getRequest().getParameter(i + "_argumentValue");

            String validatorsXPath = "/xs:schema/xs:complexType[@name = 'Validation']/xs:annotation/xs:appinfo/form-validation/formset/form/field[@property = '"
                    + attributeName + "'][@depends = '" + attributeValidatorName + "']";
            Node fieldNode = org.apache.xpath.XPathAPI.selectSingleNode(document.getDocumentElement(),
                    validatorsXPath);
            if (fieldNode != null) {
                Element element = (Element) fieldNode;
                NodeList nl = element.getElementsByTagName("var");
                for (int nlIndex = 0; nlIndex < nl.getLength(); nlIndex++) {
                    Node node = (Node) nl.item(nlIndex);
                    element.removeChild(node);
                }

                Element newVar = document.createElement("var");

                Element varNameElement = createTextElement(document, "var-name", argumentName);
                Element varValueElement = createTextElement(document, "var-value", argumentValue);
                newVar.appendChild(varNameElement);
                newVar.appendChild(varValueElement);

                element.appendChild(newVar);
            }

            i++;
            argumentName = ServletActionContext.getRequest().getParameter(i + "_argumentName");
        }

        saveUpdatedDefinition(document);
    } catch (Exception e) {
        e.printStackTrace();
    }

    this.initialize(getContentTypeDefinitionId());

    return UPDATED;
}

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;
        }//  www.  j  a  v a2s  .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.GadgetService.java

private void updateUserPrefNodes(Document doc, JSONObject json) throws JSONException {
    String prefType = "UserPref";
    if (!json.has(prefType))
        return;// ww  w  .j  a v a2  s .  c o m

    JSONObject prefs = json.getJSONObject(prefType);

    Map<String, Element> prefNodes = new HashMap<String, Element>();
    NodeList prefNodeList = doc.getElementsByTagName(prefType);
    for (int i = 0; i < prefNodeList.getLength(); i++) {
        Element prefNode = (Element) prefNodeList.item(i);

        prefNodes.put(prefNode.getAttribute("name"), prefNode);
    }

    // update the userPref
    for (Iterator<String> prefNames = prefs.keys(); prefNames.hasNext();) {
        String prefName = prefNames.next();
        JSONObject pref = prefs.getJSONObject(prefName);
        if (!pref.has("default_value"))
            continue;

        String value = pref.getString("default_value");
        Element prefNode = prefNodes.get(prefName);
        if (prefNode == null)
            continue;

        if (log.isInfoEnabled())
            log.info("Modify Gadget's " + prefType + " name=" + prefName + " to " + value + ".");

        String datatype = "";
        if (pref.has("datatype"))
            datatype = pref.getString("datatype");

        if ("xml".equals(datatype) || "json".equals(datatype)) {
            prefNode.removeAttribute("default_value");
            while (prefNode.getFirstChild() != null)
                prefNode.removeChild(prefNode.getFirstChild());

            prefNode.appendChild(doc.createTextNode(value));
        } else {
            prefNode.setAttribute("default_value", value);
        }
    }
}

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

/**
 * add and update the property of preference.
 * When a changed value does not change, we return false.
 * //from   w w  w .j a v a 2  s . co  m
 * @param node
 * @param field
 * @param value
 * @return boolean 
 */
public static boolean updateProperty(Element node, String field, String value) {
    NodeList propList = node.getElementsByTagName("property");

    Element property;
    boolean isModified = false;
    for (int i = 0; i < propList.getLength(); i++) {
        property = (Element) propList.item(i);
        if (property.getAttribute("name").equals(field)) {
            // If there is an existing property, we update a value.
            NodeList textNodeList = property.getChildNodes();
            while (textNodeList.getLength() > 0) {
                property.removeChild(textNodeList.item(0));
            }
            Text textNode = node.getOwnerDocument().createTextNode(value);
            property.appendChild(textNode);

            isModified = true;
            break;
        }
    }

    if (!isModified) {
        Element propEl = node.getOwnerDocument().createElement("property");
        propEl.setAttribute("name", field);
        propEl.appendChild(node.getOwnerDocument().createTextNode(value));
        node.appendChild(propEl);
    }

    return true;
}

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

/**
 * Helper of remove property//  w  w  w. j a  va2  s . c  o m
 * @param node
 * @param field
 * @return
 */
public static boolean removeProperty(Element node, String field) {
    NodeList propList = node.getElementsByTagName("property");

    Element property = null;

    for (int i = 0; i < propList.getLength(); i++) {
        property = (Element) propList.item(i);
        if (property.getAttribute("name").equals(field)) {
            node.removeChild(property);
            return true;
        }
    }
    return false;
}

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

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

    try {/*  www  .  j a va  2s .c o  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);
    }
}