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.springframework.ide.eclipse.boot.core.internal.MavenSpringBootProject.java

@Override
public void removeMavenDependency(final MavenId mavenId) {
    IFile file = getPomFile();/* w ww .ja v  a2  s . co m*/
    try {
        performOnDOMDocument(new OperationTuple(file, new Operation() {
            @Override
            public void process(Document pom) {
                Element depsEl = getChild(pom.getDocumentElement(), DEPENDENCIES);
                if (depsEl != null) {
                    Element dep = findChild(depsEl, DEPENDENCY, childEquals(GROUP_ID, mavenId.getGroupId()),
                            childEquals(ARTIFACT_ID, mavenId.getArtifactId()));
                    if (dep != null) {
                        depsEl.removeChild(dep);
                    }
                }
            }
        }));
    } catch (Exception e) {
        BootActivator.log(e);
    }
}

From source file:org.unitime.commons.hibernate.util.HibernateUtil.java

private static void removeProperty(org.w3c.dom.Document document, String name) {
    org.w3c.dom.Element hibConfiguration = (org.w3c.dom.Element) document
            .getElementsByTagName("hibernate-configuration").item(0);
    org.w3c.dom.Element sessionFactoryConfig = (org.w3c.dom.Element) hibConfiguration
            .getElementsByTagName("session-factory").item(0);
    org.w3c.dom.NodeList properties = sessionFactoryConfig.getElementsByTagName("property");
    for (int i = 0; i < properties.getLength(); i++) {
        org.w3c.dom.Element property = (org.w3c.dom.Element) properties.item(i);
        if (name.equals(property.getAttribute("name"))) {
            sessionFactoryConfig.removeChild(property);
            return;
        }//from   w  w w. j  a v  a2 s  . c om
    }
}

From source file:org.wso2.carbon.apimgt.migration.client._200Specific.ResourceModifier200.java

private static void updateInSequence(Element resourceElement, Document doc) {
    // Find the inSequence
    Element inSequenceElement = (Element) resourceElement
            .getElementsByTagName(Constants.SYNAPSE_API_ELEMENT_INSEQUENCE).item(0);

    // Find the property element in the inSequence
    NodeList filters = inSequenceElement.getElementsByTagName(Constants.SYNAPSE_API_ELEMENT_FILTER);

    for (int j = 0; j < filters.getLength(); ++j) {
        Element filterElement = (Element) filters.item(j);
        if (Constants.SYNAPSE_API_VALUE_AM_KEY_TYPE
                .equals(filterElement.getAttribute(Constants.SYNAPSE_API_ATTRIBUTE_SOURCE))) {
            // Only one <then> element can exist in filter mediator
            Element thenElement = (Element) filterElement
                    .getElementsByTagNameNS(Constants.SYNAPSE_API_XMLNS, Constants.SYNAPSE_API_ELEMENT_THEN)
                    .item(0);/* w w w  .j  ava  2 s  . co  m*/
            NodeList properties = thenElement.getElementsByTagName(Constants.SYNAPSE_API_ELEMENT_PROPERTY);
            for (int i = 0; i < properties.getLength(); ++i) {
                Element propertyElement = (Element) properties.item(i);
                if (propertyElement.hasAttribute(Constants.SYNAPSE_API_ATTRIBUTE_NAME)) {
                    if (Constants.SYNAPSE_API_VALUE_BACKEND_REQUEST_TIME
                            .equals(propertyElement.getAttribute(Constants.SYNAPSE_API_ATTRIBUTE_NAME))) {
                        thenElement.removeChild(propertyElement);
                        break;
                    }
                }
            }

            //removing bam mediator
            //for production url
            NodeList thenFilterElement = thenElement.getElementsByTagName(Constants.SYNAPSE_API_ELEMENT_FILTER);
            if (thenFilterElement != null && thenFilterElement.getLength() > 0) {
                for (int i = 0; i < thenFilterElement.getLength(); ++i) {
                    Element filterNode = (Element) thenFilterElement.item(i);
                    if (filterNode.getAttribute(Constants.SYNAPSE_API_ATTRIBUTE_SOURCE)
                            .contains(Constants.SYNAPSE_IS_STAT_ENABLED_PROPERTY_NAME)) {
                        thenElement.removeChild(filterNode);
                    }
                }
            }
            //for sandbox url
            Element elseElement = (Element) filterElement
                    .getElementsByTagNameNS(Constants.SYNAPSE_API_XMLNS, "else").item(0);
            NodeList elseFilterElement = elseElement.getElementsByTagName(Constants.SYNAPSE_API_ELEMENT_FILTER);
            if (elseFilterElement != null && elseFilterElement.getLength() > 0) {
                for (int i = 0; i < elseFilterElement.getLength(); ++i) {
                    Element filterNode = (Element) elseFilterElement.item(i);
                    if (filterNode.getAttribute(Constants.SYNAPSE_API_ATTRIBUTE_SOURCE)
                            .contains(Constants.SYNAPSE_IS_STAT_ENABLED_PROPERTY_NAME)) {
                        elseElement.removeChild(filterNode);
                    }
                }
            }

            //adding endpoint_address property, only for production
            Element sendElement = (Element) thenElement
                    .getElementsByTagNameNS(Constants.SYNAPSE_API_XMLNS, Constants.SYNAPSE_API_ELEMENT_SEND)
                    .item(0);
            Element endpointElement = (Element) sendElement
                    .getElementsByTagNameNS(Constants.SYNAPSE_API_XMLNS, Constants.SYNAPSE_ENDPOINT_XML_ELEMENT)
                    .item(0);

            if (endpointElement != null) {
                NodeList failOverElements = endpointElement
                        .getElementsByTagName(Constants.SYNAPSE_FAIL_OVER_XML_ELEMENT);
                NodeList loadBalanceElements = endpointElement
                        .getElementsByTagName(Constants.SYNAPSE_LOAD_BALANCE_XML_ELEMENT);
                if (failOverElements.getLength() > 0) {
                    Element failOverElement = (Element) failOverElements.item(0);
                    NodeList endpointElements = failOverElement
                            .getElementsByTagName(Constants.SYNAPSE_ENDPOINT_XML_ELEMENT);
                    for (int i = 0; i < endpointElements.getLength(); i++) {
                        addingAddressPropertyToEndpoint((Element) endpointElements.item(i), doc);
                    }
                } else if (loadBalanceElements.getLength() > 0) {
                    Element loadBalanceElement = (Element) loadBalanceElements.item(0);
                    NodeList endpointElements = loadBalanceElement
                            .getElementsByTagName(Constants.SYNAPSE_ENDPOINT_XML_ELEMENT);
                    for (int i = 0; i < endpointElements.getLength(); i++) {
                        addingAddressPropertyToEndpoint((Element) endpointElements.item(i), doc);
                    }
                } else {
                    addingAddressPropertyToEndpoint(endpointElement, doc);
                }
            }
        }
    }

    boolean isExistProp = false;
    NodeList properties = inSequenceElement.getElementsByTagName(Constants.SYNAPSE_API_ELEMENT_PROPERTY);
    for (int i = 0; i < properties.getLength(); ++i) {
        Element propertyElement = (Element) properties.item(i);
        if (propertyElement.hasAttribute(Constants.SYNAPSE_API_ATTRIBUTE_NAME)) {
            if (Constants.SYNAPSE_API_VALUE_BACKEND_REQUEST_TIME
                    .equals(propertyElement.getAttribute(Constants.SYNAPSE_API_ATTRIBUTE_NAME))) {
                isExistProp = true;
                log.info("Property '" + Constants.SYNAPSE_API_VALUE_BACKEND_REQUEST_TIME + "' already exist");
                break;
            }
        }
    }

    if (!isExistProp) {
        Element propertyElement = doc.createElementNS(Constants.SYNAPSE_API_XMLNS,
                Constants.SYNAPSE_API_ELEMENT_PROPERTY);
        propertyElement.setAttribute(Constants.SYNAPSE_API_ATTRIBUTE_EXPRESSION,
                Constants.SYNAPSE_API_VALUE_EXPRESSION);
        propertyElement.setAttribute(Constants.SYNAPSE_API_ATTRIBUTE_NAME,
                Constants.SYNAPSE_API_VALUE_BACKEND_REQUEST_TIME);
        if (filters.getLength() > 0) {
            inSequenceElement.insertBefore(propertyElement, filters.item(0));
        } else {
            inSequenceElement.appendChild(propertyElement);
        }
    }
}

From source file:org.wso2.carbon.dataservices.core.DBUtils.java

private static void removeWhitespaceInMixedContentElements(Element element) {
    List<Element> childEls = getChildElements(element);
    if (childEls.size() > 0) {
        for (Node node : getWhitespaceNodes(element)) {
            element.removeChild(node);
        }/*from w w  w.j  a v a 2 s  .c om*/
        for (Element childEl : childEls) {
            removeWhitespaceInMixedContentElements(childEl);
        }
    }
}

From source file:org.wso2.developerstudio.eclipse.esb.impl.MediatorSequenceImpl.java

/**
 * {@inheritDoc}//from  www.  j a v a 2s.  c  o m
 */
public void doLoad(Element self) throws Exception {
    // Extract the name attribute.
    if (self.hasAttribute("name")) {
        setSequenceName(self.getAttribute("name"));
    } else {
        setAnonymous(true);
    }

    // Extract the on error attribute
    if (self.hasAttribute("onError")) {
        getOnError().setKeyValue(self.getAttribute("onError"));
    }

    Element descriptionElem = getChildElement(self, "description");
    if (null != descriptionElem) {
        if (getDescription() == null) {
            Description description = getEsbFactory().createDescription();
            description.setValue(descriptionElem.getTextContent());
            setDescription(description);
        } else {
            getDescription().setValue(descriptionElem.getTextContent());
        }

    } else {
        //TODO
    }

    //Description tag will be unrecognized since it is not a mediator. So we remove it now and we add description tag manually.
    Node node = null;
    Element elementForMedator = (Element) self.cloneNode(true);
    NodeList list = elementForMedator.getChildNodes();

    for (int i = 0; i < list.getLength(); ++i) {
        node = list.item(i);
        if ("description".equals(node.getLocalName())) {
            elementForMedator.removeChild(node);
            break;
        }
    }

    // Load all the children.
    loadObjects(elementForMedator, Mediator.class, new ObjectHandler<Mediator>() {
        public void handle(Mediator object) {
            getMediators().add(object);
        }
    });

    super.doLoad(self);
}

From source file:org.wyona.yanel.core.map.RealmManager.java

/**
 * Copies a realm by creating a physical copy of the realm, changing its name/id,
 * and registering it in this RealmManager.
 * A realm can only be copied if it has a <root-dir> element in its config file and
 * if this directory contains the complete realm. 
 * @param srcRealmID//from w w  w . ja  va 2 s. c  o m
 * @param destRealmID
 * @param destRealmName
 * @param destMountPoint
 * @param destDir directory where the new realm will be created (if null, the realm
 *                will be created in the same directory as the src realm).
 * @throws Exception
 */
public void copyRealm(String srcRealmID, String destRealmID, String destRealmName, String destMountPoint,
        File destDir) throws Exception {
    if (getRealm(destRealmID) != null) {
        log.warn("Cannot add realm: " + destRealmID + " (realm with this ID exists already)");
        throw new Exception("Cannot add realm: " + destRealmID + " (realm with this ID exists already)");
    }
    DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder();

    Realm srcRealm = getRealm(srcRealmID);
    if (srcRealm == null) {
        throw new Exception(
                "cannot create realm '" + destRealmID + "': source realm '" + srcRealmID + "' does not exist.");
    }
    String srcConfigSrc = srcRealm.getConfigFile().getAbsolutePath();

    File realmConfigFile = resolveFile(new File(srcConfigSrc), _realmsConfigFile);
    Configuration realmConfig = builder.buildFromFile(realmConfigFile);
    Configuration srcRootConfig = realmConfig.getChild("root-dir", false);
    if (srcRootConfig == null) {
        throw new Exception("cannot copy realm '" + srcRealmID + "' no root dir specified in config file");
    }
    File srcRootDir = new File(srcRootConfig.getValue());
    if (!srcRootDir.isAbsolute()) {
        srcRootDir = resolveFile(srcRootDir, realmConfigFile).getCanonicalFile();
    }

    // copy realm directory:
    File destRootDir;
    if (destDir != null) {
        if (!destDir.exists() || !destDir.isDirectory()) {
            if (!new File(destDir.getAbsolutePath()).mkdirs()) {
                throw new Exception("cannot create directory: " + destDir);
            }
        }
        destRootDir = new File(destDir, destRealmID);
    } else {
        destRootDir = new File(srcRootDir.getParentFile(), destRealmID);
    }
    log.debug("copying realm " + srcRootDir + " to " + destRootDir);
    byte[] buffer = new byte[8192];
    String[] filter = { ".svn", ".cvs" };
    FileUtil.copyDirectory(srcRootDir, destRootDir, buffer, filter);

    // patch new realm:
    if (!srcConfigSrc.startsWith(srcRootDir.getAbsolutePath())) {
        throw new Exception(srcConfigSrc + " does not start with " + srcRootDir);
    }

    String configPath = srcConfigSrc.substring(srcRootDir.getAbsolutePath().length());
    if (!configPath.startsWith(File.separator)) {
        configPath = File.separator + configPath;
    }
    String destConfigSrc = destRootDir.getAbsolutePath() + configPath;
    log.debug("destConfigSrc: " + destConfigSrc);

    realmConfigFile = resolveFile(new File(destConfigSrc), _realmsConfigFile);
    realmConfig = builder.buildFromFile(realmConfigFile);
    Element realmDocument = ConfigurationUtil.toElement(realmConfig);

    Element nameElement = (Element) realmDocument.getElementsByTagName("name").item(0);
    Node text = realmDocument.getOwnerDocument().createTextNode(destRealmName);
    nameElement.removeChild(nameElement.getFirstChild());
    nameElement.appendChild(text);
    Element rootDirElement = (Element) realmDocument.getElementsByTagName("root-dir").item(0);
    text = realmDocument.getOwnerDocument().createTextNode(destRootDir.getAbsolutePath());
    rootDirElement.removeChild(rootDirElement.getFirstChild());
    rootDirElement.appendChild(text);

    realmConfig = ConfigurationUtil.toConfiguration(realmDocument);
    DefaultConfigurationSerializer configSerializer = new DefaultConfigurationSerializer();
    configSerializer.setIndent(true);
    configSerializer.serializeToFile(realmConfigFile, realmConfig);

    // add realm to realms.xml and register it:
    addRealm(destRealmID, destRealmName, destMountPoint, destConfigSrc);
}

From source file:org.wyona.yanel.servlet.YanelServlet.java

/**
 * Clean meta document//from ww  w .  j  av  a 2 s.co m
 */
private void cleanMetaDoc(Document doc) {
    Element rootElem = doc.getDocumentElement();
    org.w3c.dom.NodeList children = rootElem.getChildNodes();
    for (int i = children.getLength() - 1; i >= 0; i--) {
        rootElem.removeChild(children.item(i));
    }
}

From source file:ua.utility.kfsdbupgrade.MaintainableXMLConversionServiceImpl.java

/**
 * Does the following:// w w w .j  a  va2s . c o m
 * <ol>
 * <li>Recursively calls this method on all child elements of
 * <code>talist</code> to handle any child lists first
 * <li>Remove the attributes {@link #SERIALIZATION_ATTRIBUTE} and
 * {@link #CLASS_ATTRIBUTE} of <code>talist</code></li>
 * <li>If
 * <code>//[talist.getNodeName()]/org.apache.ojb.broker.core.proxy.ListProxyDefaultImpl/default/size/</code>
 * evaluates to a value >1, indicating elements in this list, call
 * {@link #transformClassNode(Document, Node)} on that element and store to
 * readd</li>
 * <li>Remove all child elements of <code>talist</code></li>
 * <li>Readd list elements calculated and transformed above</li>
 * </ol>
 * 
 * @param document
 *            Root {@link Document}
 * @param xpath
 *            {@link XPath} to use during evaluation
 * @param talist
 *            {@link Element} to process typed array lists on
 * @throws XPathExpressionException
 * @throws ClassNotFoundException
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 * @throws InvocationTargetException
 * @throws NoSuchMethodException
 * @throws InstantiationException
 */
private void handleTypedArrayList(Document document, XPath xpath, Element talist)
        throws XPathExpressionException, ClassNotFoundException, IllegalAccessException,
        InvocationTargetException, InvocationTargetException, NoSuchMethodException, InstantiationException {
    LOGGER.trace("Handling typed array list: " + talist.getNodeName());
    XPathExpression getChildTypedArrayLists = xpath
            .compile(".//*[@class='org.kuali.rice.kns.util.TypedArrayList']");
    NodeList nodeList = (NodeList) getChildTypedArrayLists.evaluate(talist, XPathConstants.NODESET);
    // handle any child lists first
    for (int i = 0; i < nodeList.getLength(); ++i) {
        Node item = nodeList.item(i);
        handleTypedArrayList(document, xpath, (Element) item);
    }

    talist.removeAttribute(SERIALIZATION_ATTRIBUTE);
    talist.removeAttribute(CLASS_ATTRIBUTE);
    XPathExpression listSizeExpression = xpath.compile("//" + talist.getNodeName()
            + "/org.apache.ojb.broker.core.proxy.ListProxyDefaultImpl/default/size/text()");
    String size = (String) listSizeExpression.evaluate(talist, XPathConstants.STRING);
    List<Node> nodesToAdd = new ArrayList<Node>();
    if (StringUtils.isNotBlank(size) && Integer.valueOf(size) > 0) {
        XPathExpression listTypeExpression = xpath.compile("//" + talist.getNodeName()
                + "/org.kuali.rice.kns.util.TypedArrayList/default/listObjectType/text()");
        String listType = (String) listTypeExpression.evaluate(talist, XPathConstants.STRING);
        XPathExpression listContentsExpression = xpath.compile("//" + talist.getNodeName()
                + "/org.apache.ojb.broker.core.proxy.ListProxyDefaultImpl/" + listType);
        NodeList listContents = (NodeList) listContentsExpression.evaluate(talist, XPathConstants.NODESET);
        for (int i = 0; i < listContents.getLength(); i++) {
            Node tempNode = listContents.item(i);
            transformClassNode(document, tempNode);
            nodesToAdd.add(tempNode);
        }
    }
    for (Node removeNode = talist.getFirstChild(); removeNode != null;) {
        Node nextRemoveNode = removeNode.getNextSibling();
        talist.removeChild(removeNode);
        removeNode = nextRemoveNode;
    }
    for (Node nodeToAdd : nodesToAdd) {
        talist.appendChild(nodeToAdd);
    }
}

From source file:ucar.unidata.idv.ui.ImageGenerator.java

/**
 * process the given node/*from   w  w  w.  ja  v  a2 s.  c  o  m*/
 *
 * @param node Node to process
 *
 * @return keep going
 *
 * @throws Throwable On badness
 */
protected boolean processTagImport(Element node) throws Throwable {
    Element parent = (Element) node.getParentNode();
    String file = applyMacros(node, ATTR_FILE);
    Element root = XmlUtil.findRoot(node);
    Element newRoot = XmlUtil.getRoot(file, getClass());
    newRoot = (Element) root.getOwnerDocument().importNode(newRoot, true);
    parent.insertBefore(newRoot, node);
    parent.removeChild(node);
    if (!processNode(newRoot)) {
        return false;
    }
    return true;
}

From source file:wssec.TestWSSecurityWSS178.java

/**
 * Test where the Assertion is referenced using a Key Identifier 
 * (from the SecurityTokenReference)./*w w w  . j ava 2s  .  c o m*/
 */
public void testKeyIdentifier() throws Exception {
    SOAPEnvelope unsignedEnvelope = message.getSOAPEnvelope();
    Document doc = unsignedEnvelope.getAsDocument();
    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(doc);

    SAMLIssuer saml = SAMLIssuerFactory.getInstance("saml.properties");
    SAMLAssertion assertion = saml.newAssertion();
    String issuerKeyName = saml.getIssuerKeyName();
    String issuerKeyPW = saml.getIssuerKeyPassword();
    Crypto issuerCrypto = saml.getIssuerCrypto();
    WSSecSignatureSAML wsSign = new WSSecSignatureSAML();
    wsSign.setKeyIdentifierType(WSConstants.X509_KEY_IDENTIFIER);
    Document samlDoc = wsSign.build(doc, null, assertion, issuerCrypto, issuerKeyName, issuerKeyPW, secHeader);

    WSSecEncrypt builder = new WSSecEncrypt();
    builder.setUserInfo("16c73ab6-b892-458f-abf5-2f875f74882e");
    builder.setKeyIdentifierType(WSConstants.BST_DIRECT_REFERENCE);
    Document encryptedDoc = builder.build(samlDoc, crypto, secHeader);

    //
    // Remove the assertion its place in the security header and then append it
    //
    org.w3c.dom.Element secHeaderElement = secHeader.getSecurityHeader();
    org.w3c.dom.Node assertionNode = secHeaderElement.getElementsByTagName("Assertion").item(0);
    secHeaderElement.removeChild(assertionNode);
    secHeaderElement.appendChild(assertionNode);

    String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(encryptedDoc);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Encrypted message:");
        LOG.debug(outputString);
    }

    verify(encryptedDoc);
}