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:com.mirth.connect.model.util.ImportConverter.java

public static Document convertServerConfiguration(String serverConfiguration) throws Exception {
    serverConfiguration = convertPackageNames(serverConfiguration);

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    Document document;//from   ww  w .  j  a v  a  2s.com
    DocumentBuilder builder;

    builder = factory.newDocumentBuilder();
    document = builder.parse(new InputSource(new StringReader(serverConfiguration)));

    // Remove users from the server configuration file if they were there.
    Element documentElement = document.getDocumentElement();
    NodeList users = documentElement.getElementsByTagName("users");
    if (users != null && users.getLength() > 0) {
        documentElement.removeChild(users.item(0));
    }

    Element channelsRoot = (Element) document.getElementsByTagName("channels").item(0);
    NodeList channels = getElements(document, "channel", "com.mirth.connect.model.Channel");
    List<Element> channelList = new ArrayList<Element>();
    int length = channels.getLength();

    for (int i = 0; i < length; i++) {
        // Must get node 0 because the first channel is removed each
        // iteration
        Element channel = (Element) channels.item(0);

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer trans = tf.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        StringWriter sw = new StringWriter();
        trans.transform(new DOMSource(channel), new StreamResult(sw));
        String channelDocXML = sw.toString();

        channelList.add(new DonkeyElement(convertChannelString(channelDocXML)).getElement());
        channelsRoot.removeChild(channel);
    }

    for (Element channel : channelList) {
        channelsRoot.appendChild(document.importNode(channel, true));
    }

    NodeList codeTemplates = documentElement.getElementsByTagName("codeTemplates");
    int codeTemplateCount = codeTemplates.getLength();

    for (int i = 0; i < codeTemplateCount; i++) {
        Element codeTemplate = (Element) codeTemplates.item(i);
        Element convertedCodeTemplate = convertCodeTemplates(new DonkeyElement(codeTemplate).toXml())
                .getDocumentElement();
        documentElement.replaceChild(document.importNode(convertedCodeTemplate, true), codeTemplate);
    }

    return document;
}

From source file:com.mirth.connect.model.util.ImportConverter.java

private static void updateFilterFor1_4(Element filterElement) {
    Element filterTemplate = null;

    if (filterElement.getElementsByTagName("template").getLength() > 0) {
        filterTemplate = (Element) filterElement.getElementsByTagName("template").item(0);
        if (filterTemplate != null)
            filterElement.removeChild(filterElement.getElementsByTagName("template").item(0));
    }//from  w  w  w  . j ava  2 s.  c  o  m
}

From source file:com.springsource.hq.plugin.tcserver.plugin.serverconfig.AbstractXmlElementConverter.java

protected void updateServletInitParam(Document document, Element servlet, String attributeName,
        Object attributeValue, Properties catalinaProperties) {
    List<Element> initParams = getChildElements(servlet, "init-param");
    boolean paramFound = false;
    for (int i = 0; i < initParams.size(); i++) {
        Element initParam = (Element) initParams.get(i);
        final String paramName = getChildElements(initParam, "param-name").get(0).getTextContent();
        if (paramName.equals(attributeName)) {
            paramFound = true;//from   ww w .  j ava 2  s .  c  o  m
            if (attributeValue != null && !("".equals(attributeValue))) {
                Element paramValue = getChildElements(initParam, "param-value").get(0);
                paramValue.setTextContent(
                        determineNewValue(paramValue.getTextContent(), attributeValue, catalinaProperties));
            } else {
                servlet.removeChild(initParam);
            }
            break;
        }
    }
    if (!(paramFound) && attributeValue != null && !("".equals(attributeValue))) {
        Element newInitParam = document.createElement("init-param");
        Element paramName = document.createElement("param-name");
        Element paramValue = document.createElement("param-value");
        newInitParam.appendChild(paramName);
        newInitParam.appendChild(paramValue);
        paramName.setTextContent(attributeName);
        paramValue.setTextContent(
                determineNewValue(paramValue.getTextContent(), attributeValue, catalinaProperties));
        // This list contains all the elements that are required by the XSD to occur after init-param node
        List<String> orderedTypes = Arrays.asList("load-on-startup", "enabled", "async-supported", "run-as",
                "security-role-ref", "multipart-config");
        boolean elementInserted = false;
        for (String orderedType : orderedTypes) {
            List<Element> foundElement = getChildElements(servlet, orderedType);
            if (!foundElement.isEmpty()) {
                servlet.insertBefore(newInitParam, foundElement.get(0));
                elementInserted = true;
                break;
            }
        }
        if (!elementInserted) {
            servlet.appendChild(newInitParam);
        }

    }
}

From source file:com.wfreitas.camelsoap.SoapClient.java

private void injectParameters(Element element, Map params, String soapNs) {
    NodeList children = element.getChildNodes();
    int childCount = children.getLength();

    for (int i = 0; i < childCount; i++) {
        Node node = children.item(i);

        if (childCount == 1 && node.getNodeType() == Node.TEXT_NODE) {
            if (node.getNodeValue().equals("?")) {
                String ognl = OGNLUtils.getOGNLExpression(element, soapNs);
                Object param;/*from w w w  .  j  a  v a2  s .  c  o m*/

                param = OGNLUtils.getParameter(ognl, params);

                element.removeChild(node);
                element.appendChild(element.getOwnerDocument().createTextNode(param.toString()));
            }
        } else if (node.getNodeType() == Node.ELEMENT_NODE) {
            injectParameters((Element) node, params, soapNs);
        }
    }

    element.removeAttributeNS(OGNLUtils.JBOSSESB_SOAP_NS, IS_CLONE_ATTRIB);
    element.removeAttributeNS(OGNLUtils.JBOSSESB_SOAP_NS, OGNLUtils.OGNL_ATTRIB);
}

From source file:com.springsource.hq.plugin.tcserver.plugin.serverconfig.general.GeneralConfigConverter.java

/**
 * This method sifts through server.xml to find the AprLifecycleListener. If it exists, but is not defined in the
 * locally cached copy of GeneralConfig, it is stripped out when pushing a new copy of server.xml. If it exists,
 * then the className is forced to the correct fully qualified class name. If it doesn't exist, and IS defined in
 * GeneralConfig, it is added to server.xml.
 *///from   w  ww.  ja  va2s  .c o  m
private void convertAprLifecycleListener(Document document, Element server,
        AprLifecycleListener configuredAprLifecycleListener) {
    Element aprLifecycleListenerXmlElementInServerXml = null;
    Element lastListener = null;
    boolean foundAprLifecycleXmlElementInServerXml = false;

    List<Element> listeners = DomUtils.getChildElementsByTagName(server, TAG_NAME_LISTENER);

    for (Element listener : listeners) {
        lastListener = listener; // We need to catch the last listener, so we can insert before its nextSibling.
        if (isAprLifecycleListener(listener)) {
            foundAprLifecycleXmlElementInServerXml = true;
            aprLifecycleListenerXmlElementInServerXml = listener;
            if (configuredAprLifecycleListener == null) {
                server.removeChild(aprLifecycleListenerXmlElementInServerXml);
            }
        }
    }

    if (configuredAprLifecycleListener != null) {
        if (!foundAprLifecycleXmlElementInServerXml) {
            aprLifecycleListenerXmlElementInServerXml = document.createElement(TAG_NAME_LISTENER);
        }
        aprLifecycleListenerXmlElementInServerXml.setAttribute(ATTRIBUTE_CLASS_NAME,
                CLASS_NAME_APR_LIFECYCLE_LISTENER);
        if (!foundAprLifecycleXmlElementInServerXml) {
            if (lastListener != null) {
                // Strangely, there doesn't appear to be any sort of insertAfter() call, so we have to fetch the
                // next sibling.
                server.insertBefore(aprLifecycleListenerXmlElementInServerXml, lastListener.getNextSibling());
            } else {
                Element globalNamingResources = DomUtils.getChildElementByTagName(server,
                        "GlobalNamingResources");
                server.insertBefore(aprLifecycleListenerXmlElementInServerXml, globalNamingResources);
            }

        }
    }
}

From source file:com.springsource.hq.plugin.tcserver.plugin.serverconfig.resources.jdbc.DataSourcesConverter.java

public void convert(final Document document, Element server, Set<DataSource> from,
        Properties catalinaProperties) {
    final List<Element> globalNamingResourcesList = getChildElements(server, "GlobalNamingResources");
    if (globalNamingResourcesList.size() > 1) {
        throw new InvalidNodeException(
                "Unable to determine existing DataSources.  Found multiple GlobalNamingResource Elements in server.xml");
    }//from   ww w  .  j  ava2s  .c o m
    final Set<String> dataSourceIds = new HashSet<String>(from.size());
    for (DataSource dataSource : from) {
        dataSourceIds.add(dataSource.getId());
    }
    final Map<String, Element> dataSourceElements = new HashMap<String, Element>();
    Element globalNamingResources;
    if (globalNamingResourcesList.isEmpty()) {
        globalNamingResources = document.createElement("GlobalNamingResources");
        server.appendChild(globalNamingResources);
    } else {
        globalNamingResources = globalNamingResourcesList.get(0);
        final List<Element> resources = getChildElements(globalNamingResources, "Resource");
        for (int i = 0; i < resources.size(); i++) {
            Element resource = (Element) resources.get(i);
            if (DATA_SOURCE_TYPE.equals(resource.getAttribute("type"))) {
                final String name = parseProperties(resource.getAttribute("name"), catalinaProperties);
                if (dataSourceIds.contains(name)) {
                    dataSourceElements.put(name, resource);
                } else if (dataSourceConverter.isDataSourceFactorySupported(resource, catalinaProperties)) {
                    globalNamingResources.removeChild(resource);
                }
            }
        }
    }
    for (DataSource dataSource : from) {
        if (dataSourceElements.get(dataSource.getId()) == null) {
            final Element dataSourceElement = document.createElement("Resource");
            dataSourceElement.setAttribute("type", DATA_SOURCE_TYPE);
            dataSourceConverter.convert(document, dataSourceElement, dataSource, catalinaProperties);
            globalNamingResources.appendChild(dataSourceElement);
        } else {
            dataSourceConverter.convert(document, dataSourceElements.get(dataSource.getId()), dataSource,
                    catalinaProperties);
        }
    }
}

From source file:com.enonic.vertical.userservices.FormHandlerController.java

@Override
protected void buildContentTypeXML(UserServicesService userServices, Element contentdataElem,
        ExtendedMap formItems, boolean skipElements) throws VerticalUserServicesException {

    int menuItemKey = formItems.getInt("_form_id");

    // Elements in the old form XML are prefixed with an underscore
    Element _formElement = (Element) formItems.get("__form");

    Document doc = contentdataElem.getOwnerDocument();
    Element formElement = XMLTool.createElement(doc, contentdataElem, "form");
    formElement.setAttribute("categorykey", _formElement.getAttribute("categorykey"));

    // Set title element:
    Element _titleElement = XMLTool.getElement(_formElement, "title");
    XMLTool.createElement(doc, formElement, "title", XMLTool.getElementText(_titleElement));

    // There may be multiple error states/codes, so we have to keep track of them.
    // When errors occurr, XML is inserted into the resulting document, and sent
    // back to the user client.
    // TIntArrayList errorCodes = new TIntArrayList(5);
    List<Integer> errorCodes = new ArrayList<Integer>(5);

    // The people that will recieve the form mail:
    Element recipientsElem = XMLTool.getElement(_formElement, "recipients");
    if (recipientsElem != null) {
        formElement.appendChild(doc.importNode(recipientsElem, true));
    }/* w  ww. java2 s  .  com*/

    // Loop all form items and insert the data from the form:
    int fileattachmentCount = 0;
    Element[] _formItems = XMLTool.getElements(_formElement, "item");
    for (int i = 0; i < _formItems.length; i++) {
        String formName = menuItemKey + "_form_" + (i + 1);

        Element itemElement = (Element) doc.importNode(_formItems[i], true);
        formElement.appendChild(itemElement);

        String type = itemElement.getAttribute("type");

        if ("text".equals(type)) {
            // Remove default data:
            Element tmpElement = XMLTool.getElement(itemElement, "data");
            if (tmpElement != null) {
                itemElement.removeChild(tmpElement);
            }
        }

        if ("text".equals(type) || "textarea".equals(type) || "checkbox".equals(type)) {
            String value = formItems.getString(formName, "");

            // If a regular expression is specified, it should be verified that
            // the data entered in the form conforms to this:
            String regexp = itemElement.getAttribute("validation");
            if ("text".equals(type) && regexp != null && regexp.length() > 0) {
                final boolean valueIsNonEmpty = value.length() > 0;
                if (!value.matches(regexp) && valueIsNonEmpty) {
                    XMLTool.createElement(doc, itemElement, "error", ERR_MSG_VALIDATION_FAILED)
                            .setAttribute("id", String.valueOf(ERR_VALIDATION_FAILED));

                    if (!errorCodes.contains(ERR_VALIDATION_FAILED)) {
                        errorCodes.add(ERR_VALIDATION_FAILED);
                    }
                }
            }

            // If the form element is required, we must test that the user actually
            // entered data:
            if (itemElement.getAttribute("required").equals("true") && value.length() == 0) {
                XMLTool.createElement(doc, itemElement, "error", ERR_MSG_MISSING_REQ).setAttribute("id",
                        String.valueOf(ERR_MISSING_REQ));

                if (!errorCodes.contains(ERR_MISSING_REQ)) {
                    errorCodes.add(ERR_MISSING_REQ);
                }
            }

            XMLTool.createElement(doc, itemElement, "data", value);
        } else if ("checkbox".equals(type)) {
            String value;
            if (formItems.getString(formName, "").equals("on")) {
                value = "1";
            } else {
                value = "0";
            }

            XMLTool.createElement(doc, itemElement, "data", value);
        } else if ("radiobuttons".equals(type) || "dropdown".equals(type)) {
            String value = formItems.getString(formName, null);

            boolean selected = false;
            Element tmpElement = XMLTool.getElement(itemElement, "data");
            Element[] options = XMLTool.getElements(tmpElement, "option");
            for (Element option : options) {
                tmpElement = option;
                if (tmpElement.getAttribute("value").equals(value)) {
                    tmpElement.setAttribute("selected", "true");
                    selected = true;
                    break;
                }
            }

            // If the form element is required, we must test that the user actually
            // checked on of the radiobuttons:
            if (itemElement.getAttribute("required").equals("true") && !selected) {
                XMLTool.createElement(doc, itemElement, "error", ERR_MSG_MISSING_REQ).setAttribute("id",
                        String.valueOf(ERR_MISSING_REQ));

                if (!errorCodes.contains(ERR_MISSING_REQ)) {
                    errorCodes.add(ERR_MISSING_REQ);
                }
            }
        } else if ("checkboxes".equals(type)) {
            String[] values = formItems.getStringArray(formName);

            Element tmpElement = XMLTool.getElement(itemElement, "data");
            Element[] options = XMLTool.getElements(tmpElement, "option");
            for (Element option : options) {
                tmpElement = option;

                for (String currentValue : values) {
                    if (tmpElement.getAttribute("value").equals(currentValue)) {
                        tmpElement.setAttribute("selected", "true");
                        break;
                    }
                }
            }
        } else if ("fileattachment".equals(type)) {
            FileItem fileItem = formItems.getFileItem(formName, null);

            // If the form element is required, we must test that the user actually
            // entered data:
            if ("true".equals(itemElement.getAttribute("required")) && fileItem == null) {
                XMLTool.createElement(doc, itemElement, "error", ERR_MSG_MISSING_REQ).setAttribute("id",
                        String.valueOf(ERR_MISSING_REQ));

                if (!errorCodes.contains(ERR_MISSING_REQ)) {
                    errorCodes.add(ERR_MISSING_REQ);
                }
            } else if (fileItem != null) {
                String fileName = FileUtil.getFileName(fileItem);
                Element binaryDataElem = XMLTool.createElement(doc, itemElement, "binarydata", fileName);
                binaryDataElem.setAttribute("key", "%" + fileattachmentCount++);
            }
        }

    }

    HttpServletRequest request = ServletRequestAccessor.getRequest();

    try {
        Boolean captchaOk = captchaService.validateCaptcha(formItems, request, "form", "create");
        if ((captchaOk != null) && (!captchaOk)) {
            errorCodes.add(ERR_INVALID_CAPTCHA);
        }
    } catch (CaptchaServiceException e) {
        String message = "Failed during captcha validation: %t";
        VerticalUserServicesLogger.error(this.getClass(), 0, message, e);
        errorCodes.add(ERR_OPERATION_BACKEND);
    }

    // If one or more errors occurred, an exception is thrown, containing the errorcodes
    // and the resulting document (that now should include error XML):
    if (errorCodes.size() > 0) {
        throw new FormException(doc, errorCodes.toArray(new Integer[errorCodes.size()]));
    }

    VerticalUserServicesLogger.debug(this.getClass(), 10, doc);
}

From source file:com.alfaariss.oa.util.configuration.ConfigurationManager.java

/**
 * Remove a configuration section./*w w w .ja v a 2s.  c om*/
 * @see IConfigurationManager#removeSection(org.w3c.dom.Element, java.lang.String)
 */
public synchronized boolean removeSection(Element eRootSection, String sName) throws ConfigurationException {
    if (sName == null)
        throw new IllegalArgumentException("Suplied name is empty");

    boolean bRet = false;
    try {
        //rootSection can be null if the first section is requested
        if (eRootSection == null)
            eRootSection = _oDomDocument.getDocumentElement();

        Node nSection = getSubSection(eRootSection, sName);
        if (nSection == null)
            _logger.debug("Section not found: " + sName);
        else {
            //remove section
            eRootSection.removeChild(nSection);
            bRet = true;
        }
    } catch (DOMException e) {
        _logger.error("Error removing section: " + sName, e);
        throw new ConfigurationException(SystemErrors.ERROR_CONFIG_DELETE);
    }
    return bRet;
}

From source file:com.enonic.cms.web.portal.services.FormServicesProcessor.java

@Override
protected void buildContentTypeXML(UserServicesService userServices, Element contentdataElem,
        ExtendedMap formItems, boolean skipElements) throws VerticalUserServicesException {

    int menuItemKey = formItems.getInt("_form_id");

    // Elements in the old form XML are prefixed with an underscore
    Element _formElement = (Element) formItems.get("__form");

    Document doc = contentdataElem.getOwnerDocument();
    Element formElement = XMLTool.createElement(doc, contentdataElem, "form");
    formElement.setAttribute("categorykey", _formElement.getAttribute("categorykey"));

    // Set title element:
    Element _titleElement = XMLTool.getElement(_formElement, "title");
    XMLTool.createElement(doc, formElement, "title", XMLTool.getElementText(_titleElement));

    // There may be multiple error states/codes, so we have to keep track of them.
    // When errors occurr, XML is inserted into the resulting document, and sent
    // back to the user client.
    // TIntArrayList errorCodes = new TIntArrayList(5);
    List<Integer> errorCodes = new ArrayList<Integer>(5);

    // The people that will recieve the form mail:
    Element recipientsElem = XMLTool.getElement(_formElement, "recipients");
    if (recipientsElem != null) {
        formElement.appendChild(doc.importNode(recipientsElem, true));
    }/*from  w  w w  .j  a va2  s.  com*/

    // Loop all form items and insert the data from the form:
    int fileattachmentCount = 0;
    Element[] _formItems = XMLTool.getElements(_formElement, "item");
    for (int i = 0; i < _formItems.length; i++) {
        String formName = menuItemKey + "_form_" + (i + 1);

        Element itemElement = (Element) doc.importNode(_formItems[i], true);
        formElement.appendChild(itemElement);

        String type = itemElement.getAttribute("type");

        if ("text".equals(type)) {
            // Remove default data:
            Element tmpElement = XMLTool.getElement(itemElement, "data");
            if (tmpElement != null) {
                itemElement.removeChild(tmpElement);
            }
        }

        if ("text".equals(type) || "textarea".equals(type) || "checkbox".equals(type)) {
            String value = formItems.getString(formName, "");

            // If a regular expression is specified, it should be verified that
            // the data entered in the form conforms to this:
            String regexp = itemElement.getAttribute("validation");
            if ("text".equals(type) && regexp != null && regexp.length() > 0) {
                final boolean valueIsNonEmpty = value.length() > 0;
                if (!value.matches(regexp) && valueIsNonEmpty) {
                    XMLTool.createElement(doc, itemElement, "error", ERR_MSG_VALIDATION_FAILED)
                            .setAttribute("id", String.valueOf(ERR_VALIDATION_FAILED));

                    if (!errorCodes.contains(ERR_VALIDATION_FAILED)) {
                        errorCodes.add(ERR_VALIDATION_FAILED);
                    }
                }
            }

            // If the form element is required, we must test that the user actually
            // entered data:
            if (itemElement.getAttribute("required").equals("true") && value.length() == 0) {
                XMLTool.createElement(doc, itemElement, "error", ERR_MSG_MISSING_REQ).setAttribute("id",
                        String.valueOf(ERR_MISSING_REQ));

                if (!errorCodes.contains(ERR_MISSING_REQ)) {
                    errorCodes.add(ERR_MISSING_REQ);
                }
            }

            XMLTool.createElement(doc, itemElement, "data", value);
        } else if ("checkbox".equals(type)) {
            String value;
            if (formItems.getString(formName, "").equals("on")) {
                value = "1";
            } else {
                value = "0";
            }

            XMLTool.createElement(doc, itemElement, "data", value);
        } else if ("radiobuttons".equals(type) || "dropdown".equals(type)) {
            String value = formItems.getString(formName, null);

            boolean selected = false;
            Element tmpElement = XMLTool.getElement(itemElement, "data");
            Element[] options = XMLTool.getElements(tmpElement, "option");
            for (Element option : options) {
                tmpElement = option;
                if (tmpElement.getAttribute("value").equals(value)) {
                    tmpElement.setAttribute("selected", "true");
                    selected = true;
                    break;
                }
            }

            // If the form element is required, we must test that the user actually
            // checked on of the radiobuttons:
            if (itemElement.getAttribute("required").equals("true") && !selected) {
                XMLTool.createElement(doc, itemElement, "error", ERR_MSG_MISSING_REQ).setAttribute("id",
                        String.valueOf(ERR_MISSING_REQ));

                if (!errorCodes.contains(ERR_MISSING_REQ)) {
                    errorCodes.add(ERR_MISSING_REQ);
                }
            }
        } else if ("checkboxes".equals(type)) {
            String[] values = formItems.getStringArray(formName);

            Element tmpElement = XMLTool.getElement(itemElement, "data");
            Element[] options = XMLTool.getElements(tmpElement, "option");
            for (Element option : options) {
                tmpElement = option;

                for (String currentValue : values) {
                    if (tmpElement.getAttribute("value").equals(currentValue)) {
                        tmpElement.setAttribute("selected", "true");
                        break;
                    }
                }
            }
        } else if ("fileattachment".equals(type)) {
            FileItem fileItem = formItems.getFileItem(formName, null);

            // If the form element is required, we must test that the user actually
            // entered data:
            if ("true".equals(itemElement.getAttribute("required")) && fileItem == null) {
                XMLTool.createElement(doc, itemElement, "error", ERR_MSG_MISSING_REQ).setAttribute("id",
                        String.valueOf(ERR_MISSING_REQ));

                if (!errorCodes.contains(ERR_MISSING_REQ)) {
                    errorCodes.add(ERR_MISSING_REQ);
                }
            } else if (fileItem != null) {
                String fileName = FileUtil.getFileName(fileItem);
                Element binaryDataElem = XMLTool.createElement(doc, itemElement, "binarydata", fileName);
                binaryDataElem.setAttribute("key", "%" + fileattachmentCount++);
            }
        }

    }

    HttpServletRequest request = ServletRequestAccessor.getRequest();

    Boolean captchaOk = captchaService.validateCaptcha(formItems, request, "form", "create");
    if ((captchaOk != null) && (!captchaOk)) {
        errorCodes.add(ERR_INVALID_CAPTCHA);
    }

    // If one or more errors occurred, an exception is thrown, containing the errorcodes
    // and the resulting document (that now should include error XML):
    if (errorCodes.size() > 0) {
        throw new FormException(doc, errorCodes.toArray(new Integer[errorCodes.size()]));
    }
}