Example usage for org.w3c.dom Element getParentNode

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

Introduction

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

Prototype

public Node getParentNode();

Source Link

Document

The parent of this node.

Usage

From source file:org.apache.ws.security.message.TestMessageTransformer.java

private static void updateEncryptedKeyRefList(Node wsseHeader, String newId) {
    Element encryptedKey = getFirstChildElement(wsseHeader,
            new QName("http://www.w3.org/2001/04/xmlenc#", "EncryptedKey"), true);
    Element ref = getFirstChildElement(encryptedKey,
            new QName("http://www.w3.org/2001/04/xmlenc#", "DataReference"), true);
    Element newRef = (Element) ref.cloneNode(true);
    newRef.setAttributeNS(null, "URI", "#" + newId);
    ref.getParentNode().appendChild(newRef);
}

From source file:org.apache.ws.security.message.WSSecEncrypt.java

private Vector doEncryption(Document doc, SecretKey secretKey, KeyInfo keyInfo, Vector references)
        throws WSSecurityException {

    XMLCipher xmlCipher = null;/*from   w ww. java 2s .  c  o  m*/
    try {
        xmlCipher = XMLCipher.getInstance(symEncAlgo);
    } catch (XMLEncryptionException e3) {
        throw new WSSecurityException(WSSecurityException.UNSUPPORTED_ALGORITHM, null, null, e3);
    }

    Vector encDataRef = new Vector();

    boolean cloneKeyInfo = false;
    for (int part = 0; part < references.size(); part++) {
        WSEncryptionPart encPart = (WSEncryptionPart) references.get(part);

        String idToEnc = encPart.getId();
        String elemName = encPart.getName();
        String nmSpace = encPart.getNamespace();
        String modifier = encPart.getEncModifier();
        //
        // Third step: get the data to encrypt.
        //
        Element body = null;
        if (idToEnc != null) {
            body = WSSecurityUtil.findElementById(document.getDocumentElement(), idToEnc, WSConstants.WSU_NS);
            if (body == null) {
                body = WSSecurityUtil.findElementById(document.getDocumentElement(), idToEnc, null);
            }
        } else {
            body = (Element) WSSecurityUtil.findElement(document, elemName, nmSpace);
        }
        if (body == null) {
            throw new WSSecurityException(WSSecurityException.FAILURE, "noEncElement",
                    new Object[] { "{" + nmSpace + "}" + elemName });
        }

        boolean content = modifier.equals("Content") ? true : false;
        String xencEncryptedDataId = wssConfig.getIdAllocator().createId("EncDataId-", body);
        encPart.setEncId(xencEncryptedDataId);

        cloneKeyInfo = true;

        if (keyInfo == null) {
            keyInfo = new KeyInfo(document);
            SecurityTokenReference secToken = new SecurityTokenReference(document);

            if (useKeyIdentifier && SecurityTokenReference.SAML_ID_URI.equals(customReferenceValue)) {
                secToken.setSAMLKeyIdentifier((encKeyIdDirectId ? "" : "#") + encKeyId);
            } else {
                Reference ref = new Reference(document);
                if (encKeyIdDirectId) {
                    ref.setURI(encKeyId);
                } else {
                    ref.setURI("#" + encKeyId);
                }
                if (encKeyValueType != null) {
                    ref.setValueType(encKeyValueType);
                }
                secToken.setReference(ref);
            }

            keyInfo.addUnknownElement(secToken.getElement());
            Element keyInfoElement = keyInfo.getElement();
            keyInfoElement.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:" + WSConstants.SIG_PREFIX,
                    WSConstants.SIG_NS);
        }
        //
        // Fourth step: encrypt data, and set necessary attributes in
        // xenc:EncryptedData
        //
        try {
            if (modifier.equals("Header")) {

                Element elem = doc.createElementNS(WSConstants.WSSE11_NS,
                        "wsse11:" + WSConstants.ENCRYPTED_HEADER);
                WSSecurityUtil.setNamespace(elem, WSConstants.WSSE11_NS, WSConstants.WSSE11_PREFIX);
                String wsuPrefix = WSSecurityUtil.setNamespace(elem, WSConstants.WSU_NS,
                        WSConstants.WSU_PREFIX);
                elem.setAttributeNS(WSConstants.WSU_NS, wsuPrefix + ":Id",
                        wssConfig.getIdAllocator().createId("EncHeader-", body));

                NamedNodeMap map = body.getAttributes();

                for (int i = 0; i < map.getLength(); i++) {
                    Attr attr = (Attr) map.item(i);
                    if (attr.getNamespaceURI().equals(WSConstants.URI_SOAP11_ENV)
                            || attr.getNamespaceURI().equals(WSConstants.URI_SOAP12_ENV)) {
                        String soapEnvPrefix = WSSecurityUtil.setNamespace(elem, attr.getNamespaceURI(),
                                WSConstants.DEFAULT_SOAP_PREFIX);
                        elem.setAttributeNS(attr.getNamespaceURI(), soapEnvPrefix + ":" + attr.getLocalName(),
                                attr.getValue());
                    }
                }

                xmlCipher.init(XMLCipher.ENCRYPT_MODE, secretKey);
                EncryptedData encData = xmlCipher.getEncryptedData();
                encData.setId(xencEncryptedDataId);
                encData.setKeyInfo(keyInfo);
                xmlCipher.doFinal(doc, body, content);

                Element encDataElem = WSSecurityUtil.findElementById(document.getDocumentElement(),
                        xencEncryptedDataId, null);
                Node clone = encDataElem.cloneNode(true);
                elem.appendChild(clone);
                encDataElem.getParentNode().appendChild(elem);
                encDataElem.getParentNode().removeChild(encDataElem);
            } else {
                xmlCipher.init(XMLCipher.ENCRYPT_MODE, secretKey);
                EncryptedData encData = xmlCipher.getEncryptedData();
                encData.setId(xencEncryptedDataId);
                encData.setKeyInfo(keyInfo);
                xmlCipher.doFinal(doc, body, content);
            }
            if (cloneKeyInfo) {
                keyInfo = new KeyInfo((Element) keyInfo.getElement().cloneNode(true), null);
            }
        } catch (Exception e2) {
            throw new WSSecurityException(WSSecurityException.FAILED_ENCRYPTION, null, null, e2);
        }
        encDataRef.add("#" + xencEncryptedDataId);
    }
    return encDataRef;
}

From source file:org.apache.ws.security.processor.EncryptedDataProcessor.java

public List<WSSecurityEngineResult> handleToken(Element elem, RequestData request, WSDocInfo wsDocInfo)
        throws WSSecurityException {
    if (log.isDebugEnabled()) {
        log.debug("Found EncryptedData element");
    }//from  w  w w.j  a v a  2  s  .co m
    Element kiElem = WSSecurityUtil.getDirectChildElement(elem, "KeyInfo", WSConstants.SIG_NS);
    // KeyInfo cannot be null
    if (kiElem == null) {
        throw new WSSecurityException(WSSecurityException.UNSUPPORTED_ALGORITHM, "noKeyinfo");
    }

    String symEncAlgo = X509Util.getEncAlgo(elem);
    // Check BSP compliance
    if (request.getWssConfig().isWsiBSPCompliant()) {
        checkBSPCompliance(symEncAlgo);
    }

    // Get the Key either via a SecurityTokenReference or an EncryptedKey
    Element secRefToken = WSSecurityUtil.getDirectChildElement(kiElem, "SecurityTokenReference",
            WSConstants.WSSE_NS);
    Element encryptedKeyElement = WSSecurityUtil.getDirectChildElement(kiElem, WSConstants.ENC_KEY_LN,
            WSConstants.ENC_NS);

    if (elem != null && request.isRequireSignedEncryptedDataElements()) {
        WSSecurityUtil.verifySignedElement(elem, elem.getOwnerDocument(), wsDocInfo.getSecurityHeader());
    }

    SecretKey key = null;
    List<WSSecurityEngineResult> encrKeyResults = null;
    Principal principal = null;
    if (secRefToken != null) {
        STRParser strParser = new SecurityTokenRefSTRParser();
        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put(SecurityTokenRefSTRParser.SIGNATURE_METHOD, symEncAlgo);
        strParser.parseSecurityTokenReference(secRefToken, request, wsDocInfo, parameters);
        byte[] secretKey = strParser.getSecretKey();
        principal = strParser.getPrincipal();
        key = WSSecurityUtil.prepareSecretKey(symEncAlgo, secretKey);
    } else if (encryptedKeyElement != null) {
        EncryptedKeyProcessor encrKeyProc = new EncryptedKeyProcessor();
        encrKeyResults = encrKeyProc.handleToken(encryptedKeyElement, request, wsDocInfo);
        byte[] symmKey = (byte[]) encrKeyResults.get(0).get(WSSecurityEngineResult.TAG_SECRET);
        key = WSSecurityUtil.prepareSecretKey(symEncAlgo, symmKey);
    } else {
        throw new WSSecurityException(WSSecurityException.UNSUPPORTED_ALGORITHM, "noEncKey");
    }

    // Check for compliance against the defined AlgorithmSuite
    AlgorithmSuite algorithmSuite = request.getAlgorithmSuite();
    if (algorithmSuite != null) {
        AlgorithmSuiteValidator algorithmSuiteValidator = new AlgorithmSuiteValidator(algorithmSuite);

        if (principal instanceof WSDerivedKeyTokenPrincipal) {
            algorithmSuiteValidator
                    .checkDerivedKeyAlgorithm(((WSDerivedKeyTokenPrincipal) principal).getAlgorithm());
            algorithmSuiteValidator
                    .checkEncryptionDerivedKeyLength(((WSDerivedKeyTokenPrincipal) principal).getLength());
        }
        algorithmSuiteValidator.checkSymmetricKeyLength(key.getEncoded().length);
        algorithmSuiteValidator.checkSymmetricEncryptionAlgorithm(symEncAlgo);
    }

    // initialize Cipher ....
    XMLCipher xmlCipher = null;
    try {
        xmlCipher = XMLCipher.getInstance(symEncAlgo);
        xmlCipher.setSecureValidation(true);
        xmlCipher.init(XMLCipher.DECRYPT_MODE, key);
    } catch (XMLEncryptionException ex) {
        throw new WSSecurityException(WSSecurityException.UNSUPPORTED_ALGORITHM, null, null, ex);
    }
    Node previousSibling = elem.getPreviousSibling();
    Node parent = elem.getParentNode();
    try {
        xmlCipher.doFinal(elem.getOwnerDocument(), elem, false);
    } catch (Exception e) {
        throw new WSSecurityException(WSSecurityException.FAILED_CHECK, null, null, e);
    }

    WSDataRef dataRef = new WSDataRef();
    dataRef.setWsuId(elem.getAttributeNS(null, "Id"));
    dataRef.setAlgorithm(symEncAlgo);
    dataRef.setContent(false);

    Node decryptedNode;
    if (previousSibling == null) {
        decryptedNode = parent.getFirstChild();
    } else {
        decryptedNode = previousSibling.getNextSibling();
    }
    if (decryptedNode != null && Node.ELEMENT_NODE == decryptedNode.getNodeType()) {
        dataRef.setProtectedElement((Element) decryptedNode);
    }
    dataRef.setXpath(ReferenceListProcessor.getXPath(decryptedNode));

    WSSecurityEngineResult result = new WSSecurityEngineResult(WSConstants.ENCR,
            Collections.singletonList(dataRef));
    result.put(WSSecurityEngineResult.TAG_ID, elem.getAttributeNS(null, "Id"));
    wsDocInfo.addResult(result);
    wsDocInfo.addTokenElement(elem);

    WSSConfig wssConfig = request.getWssConfig();
    if (wssConfig != null) {
        // Get hold of the plain text element
        Element decryptedElem;
        if (previousSibling == null) {
            decryptedElem = (Element) parent.getFirstChild();
        } else {
            decryptedElem = (Element) previousSibling.getNextSibling();
        }
        QName el = new QName(decryptedElem.getNamespaceURI(), decryptedElem.getLocalName());
        Processor proc = request.getWssConfig().getProcessor(el);
        if (proc != null) {
            if (log.isDebugEnabled()) {
                log.debug("Processing decrypted element with: " + proc.getClass().getName());
            }
            List<WSSecurityEngineResult> results = proc.handleToken(decryptedElem, request, wsDocInfo);
            List<WSSecurityEngineResult> completeResults = new ArrayList<WSSecurityEngineResult>();
            if (encrKeyResults != null) {
                completeResults.addAll(encrKeyResults);
            }
            completeResults.add(result);
            completeResults.addAll(0, results);
            return completeResults;
        }
    }
    encrKeyResults.add(result);
    return encrKeyResults;
}

From source file:org.apache.ws.security.processor.ReferenceListProcessor.java

/**
 * Decrypt the EncryptedData argument using a SecretKey.
 * @param doc The (document) owner of EncryptedData
 * @param dataRefURI The URI of EncryptedData
 * @param encData The EncryptedData element
 * @param symmetricKey The SecretKey with which to decrypt EncryptedData
 * @param symEncAlgo The symmetric encryption algorithm to use
 * @throws WSSecurityException/*  w w  w  . j  ava  2  s  . c  o m*/
 */
public static WSDataRef decryptEncryptedData(Document doc, String dataRefURI, Element encData,
        SecretKey symmetricKey, String symEncAlgo) throws WSSecurityException {
    XMLCipher xmlCipher = null;
    try {
        xmlCipher = XMLCipher.getInstance(symEncAlgo);
        xmlCipher.init(XMLCipher.DECRYPT_MODE, symmetricKey);
    } catch (XMLEncryptionException ex) {
        throw new WSSecurityException(WSSecurityException.UNSUPPORTED_ALGORITHM, null, null, ex);
    }

    WSDataRef dataRef = new WSDataRef(dataRefURI);
    dataRef.setWsuId(dataRefURI);
    dataRef.setAlgorithm(symEncAlgo);
    boolean content = X509Util.isContent(encData);
    dataRef.setContent(content);

    Node parent = encData.getParentNode();
    Node previousSibling = encData.getPreviousSibling();
    if (content) {
        encData = (Element) encData.getParentNode();
        parent = encData.getParentNode();
    }

    try {
        xmlCipher.doFinal(doc, encData, content);
    } catch (Exception ex) {
        throw new WSSecurityException(WSSecurityException.FAILED_CHECK, null, null, ex);
    }

    if (parent.getLocalName().equals(WSConstants.ENCRYPTED_HEADER)
            && parent.getNamespaceURI().equals(WSConstants.WSSE11_NS)) {

        Node decryptedHeader = parent.getFirstChild();
        Element decryptedHeaderClone = (Element) decryptedHeader.cloneNode(true);
        parent.getParentNode().appendChild(decryptedHeaderClone);
        parent.getParentNode().removeChild(parent);
        dataRef.setProtectedElement(decryptedHeaderClone);
        dataRef.setXpath(getXPath(decryptedHeaderClone));
    } else if (content) {
        dataRef.setProtectedElement(encData);
        dataRef.setXpath(getXPath(encData));
    } else {
        Node decryptedNode;
        if (previousSibling == null) {
            decryptedNode = parent.getFirstChild();
        } else {
            decryptedNode = previousSibling.getNextSibling();
        }
        if (decryptedNode != null && Node.ELEMENT_NODE == decryptedNode.getNodeType()) {
            dataRef.setProtectedElement((Element) decryptedNode);
        }
        dataRef.setXpath(getXPath(decryptedNode));
    }

    return dataRef;
}

From source file:org.apache.xml.security.encryption.XMLCipher.java

/**
 * Encrypts an <code>Element</code> and replaces it with its encrypted
 * counterpart in the context <code>Document</code>, that is, the
 * <code>Document</code> specified when one calls
 * {@link #getInstance(String) getInstance}.
 *
 * @param element the <code>Element</code> to encrypt.
 * @return the context <code>Document</code> with the encrypted
 *   <code>Element</code> having replaced the source <code>Element</code>.
 *  @throws Exception/*from w ww  . j  a  va2 s.co m*/
 */
private Document encryptElement(Element element) throws Exception {
    if (log.isDebugEnabled()) {
        log.debug("Encrypting element...");
    }
    if (null == element) {
        log.error("Element unexpectedly null...");
    }
    if (cipherMode != ENCRYPT_MODE && log.isDebugEnabled()) {
        log.debug("XMLCipher unexpectedly not in ENCRYPT_MODE...");
    }

    if (algorithm == null) {
        throw new XMLEncryptionException("XMLCipher instance without transformation specified");
    }
    encryptData(contextDocument, element, false);

    Element encryptedElement = factory.toElement(ed);

    Node sourceParent = element.getParentNode();
    sourceParent.replaceChild(encryptedElement, element);

    return contextDocument;
}

From source file:org.apache.xml.security.encryption.XMLCipher.java

/**
 * Decrypts <code>EncryptedData</code> in a single-part operation.
 *
 * @param element the <code>EncryptedData</code> to decrypt.
 * @return the <code>Node</code> as a result of the decrypt operation.
 * @throws XMLEncryptionException//  ww w. j  a va2 s.com
 */
private Document decryptElement(Element element) throws XMLEncryptionException {
    if (log.isDebugEnabled()) {
        log.debug("Decrypting element...");
    }

    if (cipherMode != DECRYPT_MODE) {
        log.error("XMLCipher unexpectedly not in DECRYPT_MODE...");
    }

    String octets;
    try {
        octets = new String(decryptToByteArray(element), "UTF-8");
    } catch (UnsupportedEncodingException uee) {
        throw new XMLEncryptionException("empty", uee);
    }

    if (log.isDebugEnabled()) {
        log.debug("Decrypted octets:\n" + octets);
    }

    Node sourceParent = element.getParentNode();
    Node decryptedNode = serializer.deserialize(octets, sourceParent);

    // The de-serialiser returns a node whose children we need to take on.
    if (sourceParent != null && Node.DOCUMENT_NODE == sourceParent.getNodeType()) {
        // If this is a content decryption, this may have problems
        contextDocument.removeChild(contextDocument.getDocumentElement());
        contextDocument.appendChild(decryptedNode);
    } else if (sourceParent != null) {
        sourceParent.replaceChild(decryptedNode, element);
    }

    return contextDocument;
}

From source file:org.apache.xml.security.keys.keyresolver.implementations.RetrievalMethodResolver.java

private static Element getDocumentElement(Set<Node> set) {
    Iterator<Node> it = set.iterator();
    Element e = null;
    while (it.hasNext()) {
        Node currentNode = it.next();
        if (currentNode != null && Node.ELEMENT_NODE == currentNode.getNodeType()) {
            e = (Element) currentNode;
            break;
        }/*www . ja v a  2  s.c  o m*/
    }
    List<Node> parents = new ArrayList<Node>();

    // Obtain all the parents of the elemnt
    while (e != null) {
        parents.add(e);
        Node n = e.getParentNode();
        if (n == null || Node.ELEMENT_NODE != n.getNodeType()) {
            break;
        }
        e = (Element) n;
    }
    // Visit them in reverse order.
    ListIterator<Node> it2 = parents.listIterator(parents.size() - 1);
    Element ele = null;
    while (it2.hasPrevious()) {
        ele = (Element) it2.previous();
        if (set.contains(ele)) {
            return ele;
        }
    }
    return null;
}

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  w  w.j  a  v  a  2s  . co m*/
*/
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

public boolean deleteNode(String nodeId) throws PortalException {
    if (canDeleteNode(nodeId)) {
        IUserLayoutNodeDescription nodeDescription = this.getNode(nodeId);
        String parentNodeId = this.getParentId(nodeId);

        Document uld = this.getUserLayoutDOM();
        Element ilfNode = uld.getElementById(nodeId);
        Node parent = ilfNode.getParentNode();
        if (parent != null) {
            parent.removeChild(ilfNode);
        } else {//from w w  w .  j a  v a2 s .  c  om
            throw new PortalException("Node \"" + nodeId + "\" has a NULL parent for layout of "
                    + owner.getAttribute(IPerson.USERNAME) + ".");
        }
        this.updateCacheKey();

        // now push into the PLF
        TabColumnPrefsHandler.deleteNode(ilfNode, (Element) parent, owner);
        // inform the listeners
        final int layoutId = this.getLayoutId();
        if (nodeDescription instanceof IUserLayoutChannelDescription) {
            final IUserLayoutChannelDescription userLayoutChannelDescription = (IUserLayoutChannelDescription) nodeDescription;
            this.portalEventFactory.publishPortletDeletedFromLayoutPortalEvent(this, this.owner, layoutId,
                    parentNodeId, userLayoutChannelDescription.getFunctionalName());
        } else {
            this.portalEventFactory.publishFolderDeletedFromLayoutPortalEvent(this, this.owner, layoutId,
                    parentNodeId, nodeDescription.getId(), nodeDescription.getName());
        }

        return true;
    }
    return false;
}

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

public String getParentId(String nodeId) throws PortalException {
    Document uld = this.getUserLayoutDOM();
    Element nelement = uld.getElementById(nodeId);
    if (nelement != null) {
        Node parent = nelement.getParentNode();
        if (parent != null) {
            if (parent.getNodeType() != Node.ELEMENT_NODE) {
                throw new PortalException(
                        "Node with id=\"" + nodeId + "\" is attached to something other then an element node.");
            }/*from  w  w w.j a  v  a 2  s . c  om*/
            Element e = (Element) parent;
            return e.getAttribute("ID");
        }
        return null;
    }
    throw new PortalException("Node with id=\"" + nodeId + "\" doesn't exist. Occurred in layout for "
            + owner.getAttribute(IPerson.USERNAME) + ".");
}