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.apache.ws.security.message.TestMessageTransformer.java

private static void moveReferenceList(Element saaj) {
    Element sh = getFirstChildElement(saaj, new QName("http://schemas.xmlsoap.org/soap/envelope/", "Header"),
            true);/*  w w  w . j a  va  2s. c om*/
    Element encKey = getFirstChildElement(sh, new QName("http://www.w3.org/2001/04/xmlenc#", "EncryptedKey"),
            true);
    Element refList = getFirstChildElement(encKey,
            new QName("http://www.w3.org/2001/04/xmlenc#", "ReferenceList"), true);

    Node wsseHeader = encKey.getParentNode();
    encKey.removeChild(refList);
    wsseHeader.appendChild(refList);
}

From source file:org.apache.ws.security.saml.SamlReferenceTest.java

/**
 * WS-Security Test Case for WSS-178 - "signature verification failure of signed saml token
 * due to "The Reference for URI (bst-saml-uri) has no XMLSignatureInput".
 * /*  w w  w .  ja va2 s  .  co m*/
 * The problem is that the signature is referring to a SecurityTokenReference via the 
 * STRTransform, which in turn is referring to the SAML Assertion. The request is putting 
 * the SAML Assertion below the SecurityTokenReference, and this is causing 
 * SecurityTokenReference.getTokenElement to fail.
 */
@org.junit.Test
public void testAssertionBelowSTR() throws Exception {
    Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(doc);

    SAMLIssuer saml = SAMLIssuerFactory.getInstance("saml_sv.properties");
    AssertionWrapper assertion = saml.newAssertion();
    Crypto crypto = CryptoFactory.getInstance("crypto.properties");
    WSSecSignatureSAML wsSign = new WSSecSignatureSAML();
    wsSign.setKeyIdentifierType(WSConstants.BST_DIRECT_REFERENCE);
    Document samlDoc = wsSign.build(doc, null, assertion, crypto, "16c73ab6-b892-458f-abf5-2f875f74882e",
            "security", 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.getElementsByTagNameNS(WSConstants.SAML_NS, "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);
    }
    assertTrue(outputString.contains(WSConstants.WSS_SAML_KI_VALUE_TYPE));
    assertTrue(outputString.contains(WSConstants.WSS_SAML_TOKEN_TYPE));

    verify(encryptedDoc, crypto, crypto);
}

From source file:org.apereo.portal.layout.dlm.DeleteManager.java

/**
   Get the delete set if any from the plf and process each delete command
   removing any that fail from the delete set so that the delete set is
   self cleaning./*from   w  w  w.  j  av a 2s .  c  om*/
*/
static void applyAndUpdateDeleteSet(Document plf, Document ilf, IntegrationResult result) {

    Element dSet = null;
    try {
        dSet = getDeleteSet(plf, null, false);
    } catch (Exception e) {
        LOG.error("Exception occurred while getting user's DLM delete-set.", e);
    }

    if (dSet == null)
        return;

    NodeList deletes = dSet.getChildNodes();

    for (int i = deletes.getLength() - 1; i >= 0; i--) {
        if (applyDelete((Element) deletes.item(i), ilf) == false) {
            dSet.removeChild(deletes.item(i));
            result.setChangedPLF(true);
        } else {
            result.setChangedILF(true);
        }
    }

    if (dSet.getChildNodes().getLength() == 0) {
        plf.getDocumentElement().removeChild(dSet);
        result.setChangedPLF(true);
    }
}

From source file:org.apereo.portal.layout.dlm.DeleteManager.java

/**
   Attempt to apply a single delete command and return true if it succeeds
   or false otherwise. If the delete is disallowed or the target element
   no longer exists in the document the delete command fails and returns
   false.//w  ww.  ja v a2  s .  com
*/
private static boolean applyDelete(Element delete, Document ilf) {
    String nodeID = delete.getAttribute(Constants.ATT_NAME);

    Element e = ilf.getElementById(nodeID);

    if (e == null)
        return false;

    String deleteAllowed = e.getAttribute(Constants.ATT_DELETE_ALLOWED);
    if (deleteAllowed.equals("false"))
        return false;

    Element p = (Element) e.getParentNode();
    e.setIdAttribute(Constants.ATT_ID, false);
    p.removeChild(e);
    return true;
}

From source file:org.apereo.portal.layout.dlm.DistributedLayoutManager.java

protected DistributedUserLayout getDistributedUserLayout() {
    DistributedUserLayout userLayout = this.layoutCachingService.getCachedLayout(owner, profile);
    if (null == userLayout) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Load from store for " + owner.getAttribute(IPerson.USERNAME));
        }/*  w w w .j  a  v a 2s .  com*/
        userLayout = this.distributedLayoutStore.getUserLayout(this.owner, this.profile);

        final Document userLayoutDocument = userLayout.getLayout();

        // DistributedLayoutManager shall gracefully remove channels 
        // that the user isn't authorized to render from folders of type 
        // 'header' and 'footer'.
        IAuthorizationPrincipal principal = authorizationService.newPrincipal(owner.getUserName(),
                IPerson.class);
        NodeList nodes = userLayoutDocument.getElementsByTagName("folder");
        for (int i = 0; i < nodes.getLength(); i++) {
            Element fd = (Element) nodes.item(i);
            String type = fd.getAttribute("type");
            if (type != null && (type.equals("header") || type.equals("footer") || type.equals("sidebar"))) {
                // Here's where we do the work...
                if (LOG.isDebugEnabled()) {
                    LOG.debug("RDBMUserLayoutStore examining the '" + type + "' folder of user '"
                            + owner.getUserName() + "' for non-authorized channels.");
                }
                NodeList channels = fd.getElementsByTagName("channel");
                for (int j = 0; j < channels.getLength(); j++) {
                    Element ch = (Element) channels.item(j);
                    try {
                        String chanId = ch.getAttribute("chanID");
                        if (!principal.canRender(chanId)) {
                            fd.removeChild(ch);
                            if (LOG.isDebugEnabled()) {
                                LOG.debug("RDBMUserLayoutStore removing channel '" + ch.getAttribute("fname")
                                        + "' from the header or footer of user '" + owner.getUserName()
                                        + "' because he/she isn't authorized to render it.");
                            }
                        }
                    } catch (Throwable t) {
                        // Log this...
                        LOG.warn("RDBMUserLayoutStore was unable to analyze channel element with Id="
                                + ch.getAttribute("chanID"), t);
                    }
                }
            }
        }

        setUserLayoutDOM(userLayout);
    }
    return userLayout;
}

From source file:org.apereo.portal.layout.dlm.EditManager.java

/**
   Evaluate whether attribute changes exist in the ilfChild and if so
   apply them. Returns true if some changes existed. If changes existed
   but matched those in the original node then they are not applicable,
   are removed from the editSet, and false is returned.
*/// w  w w  . ja  v  a2 s.c o m
public static boolean applyEditSet(Element plfChild, Element original) {
    // first get edit set if it exists
    Element editSet = null;
    try {
        editSet = getEditSet(plfChild, null, null, false);
    } catch (Exception e) {
        // should never occur unless problem during create in getEditSet
        // and we are telling it not to create.
        return false;
    }

    if (editSet == null || editSet.getChildNodes().getLength() == 0)
        return false;

    if (original.getAttribute(Constants.ATT_EDIT_ALLOWED).equals("false")) {
        // can't change anymore so discard changes
        plfChild.removeChild(editSet);
        return false;
    }

    Document ilf = original.getOwnerDocument();
    boolean attributeChanged = false;
    Element edit = (Element) editSet.getFirstChild();

    while (edit != null) {
        String attribName = edit.getAttribute(Constants.ATT_NAME);
        Attr attr = plfChild.getAttributeNode(attribName);

        // preferences are only updated at preference storage time so
        // if a preference change exists in the edit set assume it is
        // still valid so that the node being edited will persist in
        // the PLF.
        if (edit.getNodeName().equals(Constants.ELM_PREF))
            attributeChanged = true;
        else if (attr == null) {
            // attribute removed. See if needs removing in original.
            attr = original.getAttributeNode(attribName);
            if (attr == null) // edit irrelevant,
                editSet.removeChild(edit);
            else {
                // edit differs, apply to original
                original.removeAttribute(attribName);
                attributeChanged = true;
            }
        } else {
            // attribute there, see if original is also there
            Attr origAttr = original.getAttributeNode(attribName);
            if (origAttr == null) {
                // original attribute isn't defined so need to add
                origAttr = (Attr) ilf.importNode(attr, true);
                original.setAttributeNode(origAttr);
                attributeChanged = true;
            } else {
                // original attrib found, see if different
                if (attr.getValue().equals(origAttr.getValue())) {
                    // they are the same, edit irrelevant
                    editSet.removeChild(edit);
                } else {
                    // edit differs, apply to original
                    origAttr.setValue(attr.getValue());
                    attributeChanged = true;
                }
            }
        }
        edit = (Element) edit.getNextSibling();
    }
    return attributeChanged;
}

From source file:org.apereo.portal.layout.dlm.EditManager.java

/**
 * Searches for a command of the passed-in type and if found removes it from
 * the user's PLF./* w  w  w. j ava2s.com*/
 */
private static void removeDirective(String elementId, String attributeName, String type, IPerson person) {
    Document plf = (Document) person.getAttribute(Constants.PLF);
    Element node = plf.getElementById(elementId);
    if (node == null)
        return;

    Element editSet = null;

    try {
        editSet = getEditSet(node, plf, person, false);
    } catch (Exception e) {
        /*
         * we should never get here since we are calling getEditSet passing
         * create=false meaning that the only portion of that method that
         * tosses an exception will not be reached with this call. But if a
         * runtime exception somehow occurs we will log it so that we don't
         * lose the information.
         */
        LOG.error(e, e);
        return;
    }

    // if no edit set then the edit can't be there either
    if (editSet == null)
        return;

    Node child = editSet.getFirstChild();

    while (child != null) {
        if (child.getNodeName().equals(type)) {
            Attr attr = ((Element) child).getAttributeNode(Constants.ATT_NAME);
            if (attr != null && attr.getValue().equals(attributeName)) {
                // we found it, remove it
                editSet.removeChild(child);
                break;
            }
        }
        child = child.getNextSibling();
    }
    // if that was the last on in the edit set then delete it
    if (editSet.getFirstChild() == null)
        node.removeChild(editSet);
}

From source file:org.apereo.portal.layout.dlm.FragmentActivator.java

/**
 * Removes unwanted and hidden folders, then changes all node ids to their 
 * globally safe incorporated version./*from ww w.ja v  a2s. c om*/
 */
private void fragmentizeLayout(UserView view, FragmentDefinition fragment) {
    // if fragment not bound to user or layout empty due to error, return
    if (view.getUserId() == -1 || view.getLayout() == null) {
        return;
    }

    // Choose what types of content to apply from the fragment
    Pattern contentPattern = STANDARD_PATTERN; // default
    boolean allowExpandedContent = Boolean
            .parseBoolean(PropertiesManager.getProperty(PROPERTY_ALLOW_EXPANDED_CONTENT));
    if (allowExpandedContent) {
        contentPattern = EXPANDED_PATTERN;
    }

    // remove all non-regular or hidden top level folders
    // skip root folder that is only child of top level layout element
    Element layout = view.getLayout().getDocumentElement();
    Element root = (Element) layout.getFirstChild();
    NodeList children = root.getChildNodes();

    // process the children backwards since as we delete some the indices
    // shift around
    for (int i = children.getLength() - 1; i >= 0; i--) {
        Node node = children.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE && node.getNodeName().equals("folder")) {
            Element folder = (Element) node;

            // strip out folder types 'header', 'footer' and regular, 
            // hidden folder "User Preferences" since users have their own
            boolean isApplicable = contentPattern.matcher(folder.getAttribute("type")).matches();
            if (!isApplicable || folder.getAttribute("hidden").equals("true")) {
                try {
                    root.removeChild(folder);
                } catch (Exception e) {
                    throw new RuntimeException("Anomaly occurred while stripping out "
                            + " portions of layout for fragment '" + fragment.getName()
                            + "'. The fragment will not be available for " + "inclusion into user layouts.", e);
                }
            }
        }
    }
    // now re-lable all remaining nodes below root to have a safe system
    // wide id.

    setIdsAndAttribs(layout, layout.getAttribute(Constants.ATT_ID), "" + fragment.getIndex(),
            "" + fragment.getPrecedence());
}

From source file:org.apereo.portal.layout.dlm.ParameterEditManager.java

/**
   Get the parm edit set if any from the plf and process each edit command
   removing any that fail from the set so that the set is self cleaning.
 * @throws Exception/* ww w  .j  av a  2 s . c om*/
*/
static void applyAndUpdateParmEditSet(Document plf, Document ilf, IntegrationResult result) {

    Element pSet = null;
    try {
        pSet = getParmEditSet(plf, null, false);
    } catch (Exception e) {
        LOG.error("Exception occurred while getting user's DLM " + "paramter-edit-set.", e);
    }

    if (pSet == null)
        return;

    NodeList edits = pSet.getChildNodes();

    for (int i = edits.getLength() - 1; i >= 0; i--) {
        if (applyEdit((Element) edits.item(i), ilf) == false) {
            pSet.removeChild(edits.item(i));
            result.setChangedPLF(true);
        } else {
            result.setChangedILF(true);
        }
    }

    if (pSet.getChildNodes().getLength() == 0) {
        plf.getDocumentElement().removeChild(pSet);
        result.setChangedPLF(true);
    }
}

From source file:org.apereo.portal.layout.dlm.ParameterEditManager.java

/**
 * Remove a parameter edit directive from the parameter edits set for
 * applying user specified values to a named parameter of an incorporated
 * channel represented by the passed-in target id. If one doesn't exists
 * for that node and that name then this call returns without any effects.
 */// w  w  w . jav a  2 s .  c  o  m
public static void removeParmEditDirective(String targetId, String name, IPerson person)
        throws PortalException {
    Document plf = (Document) person.getAttribute(Constants.PLF);
    Element parmSet = getParmEditSet(plf, person, false);

    if (parmSet == null)
        return; // no set so no edit to remove

    NodeList edits = parmSet.getChildNodes();

    for (int i = 0; i < edits.getLength(); i++) {
        Element edit = (Element) edits.item(i);
        if (edit.getAttribute(Constants.ATT_TARGET).equals(targetId)
                && edit.getAttribute(Constants.ATT_NAME).equals(name)) {
            parmSet.removeChild(edit);
            break;
        }
    }
    if (parmSet.getChildNodes().getLength() == 0) // no more edits, remove
    {
        Node parent = parmSet.getParentNode();
        parent.removeChild(parmSet);
    }
}