List of usage examples for org.w3c.dom Node getNextSibling
public Node getNextSibling();
From source file:org.apache.openaz.xacml.std.dom.DOMUtil.java
/** * Gets the first child {@link org.w3c.dom.Element} of the given <code>Node</code>. * * @param node the <code>Node</code> to search * @return the first child <code>Element</code> of the given <code>Node</code> *//*from w ww . j av a 2 s.c o m*/ public static Element getFirstChildElement(Node rootNode) { if (rootNode == null) { return null; } Node node = rootNode.getFirstChild(); while (node != null && node.getNodeType() != Node.ELEMENT_NODE) { node = node.getNextSibling(); } if (node != null && node.getNodeType() == Node.ELEMENT_NODE) { return (Element) node; } return null; }
From source file:org.apache.shindig.gadgets.parse.nekohtml.NekoSimplifiedHtmlParser.java
private void fixNekoWeirdness(Document document) { // Neko as of versions > 1.9.13 stuffs all leading <script> nodes into <head>. // This breaks all sorts of assumptions in gadgets, notably the existence of document.body. // We can't tell Neko to avoid putting <script> into <head> however, since gadgets // like <Content><script>...</script><style>...</style> will break due to both // <script> and <style> ending up in <body> -- at which point Neko unceremoniously // drops the <style> (and <link>) elements. // Therefore we just search for <script> elements in <head> and stuff them all into // the top of <body>. // This method assumes a normalized document as input. Node html = DomUtil.getFirstNamedChildNode(document, "html"); if (html.getNextSibling() != null && html.getNextSibling().getNodeName().equalsIgnoreCase("html")) { // if a doctype is specified, then the desired root <html> node is wrapped by an <HTML> node // Pull out the <html> root. html = html.getNextSibling();//from w ww . j a v a2s . com } Node head = DomUtil.getFirstNamedChildNode(html, "head"); if (head == null) { head = document.createElement("head"); html.insertBefore(head, html.getFirstChild()); } NodeList headNodes = head.getChildNodes(); Stack<Node> headScripts = new Stack<Node>(); for (int i = 0; i < headNodes.getLength(); ++i) { Node headChild = headNodes.item(i); if (headChild.getNodeName().equalsIgnoreCase("script")) { headScripts.add(headChild); } } // Remove from head, add to top of <body> in <head> order. Node body = DomUtil.getFirstNamedChildNode(html, "body"); if (body == null) { body = document.createElement("body"); html.insertBefore(body, head.getNextSibling()); } Node bodyFirst = body.getFirstChild(); while (!headScripts.isEmpty()) { Node headScript = headScripts.pop(); head.removeChild(headScript); body.insertBefore(headScript, bodyFirst); bodyFirst = headScript; } }
From source file:org.apache.shindig.gadgets.rewrite.ConcatVisitor.java
private Node getNext(Node node, boolean isPrev) { return isPrev ? node.getPreviousSibling() : node.getNextSibling(); }
From source file:org.apache.tika.parser.image.ImageParser.java
private static void loadNode(Metadata metadata, Node node, String parents, boolean addThisNodeName) { if (addThisNodeName) { if (parents.length() > 0) { parents += " "; }//from ww w. ja va2 s. c o m parents += node.getNodeName(); } NamedNodeMap map = node.getAttributes(); if (map != null) { int length = map.getLength(); if (length == 1) { metadata.add(parents, normalize(map.item(0).getNodeValue())); } else if (length > 1) { StringBuilder value = new StringBuilder(); for (int i = 0; i < length; i++) { if (i > 0) { value.append(", "); } Node attr = map.item(i); value.append(attr.getNodeName()); value.append("="); value.append(normalize(attr.getNodeValue())); } metadata.add(parents, value.toString()); } } Node child = node.getFirstChild(); while (child != null) { // print children recursively loadNode(metadata, child, parents, true); child = child.getNextSibling(); } }
From source file:org.apache.tuscany.sca.implementation.bpel.ode.TuscanyProcessConfImpl.java
/** * Insert an initializer which supplies the value of an SCA property as specified by the * SCA Component using the BPEL process/*from w w w . j av a2 s . c o m*/ * @param bpelDOM - a DOM model representation of the BPEL process * @param property - an SCA ComponentProperty element for the property * This DOM model is updated, with an initializer being added for the BPEL variable * corresponding to the SCA property */ private void insertSCAPropertyInitializer(Document bpelDOM, ComponentProperty property) { // Only insert a Property initializer where there is a value for the Property if (property.getValue() == null) return; Element insertionElement = findInitializerInsertionPoint(bpelDOM); if (insertionElement == null) return; Element initializer = getInitializerSequence(bpelDOM, property); if (initializer == null) return; // Insert the initializer sequence as the next sibling element of the insertion point Element parent = (Element) insertionElement.getParentNode(); // Get the next sibling element, if there is one Node sibling = insertionElement.getNextSibling(); while (sibling != null && sibling.getNodeType() != Node.ELEMENT_NODE) { sibling = sibling.getNextSibling(); } // end while // Either insert at the end or before the next element if (sibling == null) { parent.appendChild(initializer); } else { parent.insertBefore(initializer, sibling); } // end if }
From source file:org.apache.ws.security.message.TestMessageTransformer.java
private static Node copyHeadersAndUpdateRefList(Node cur, Node dest, String newId) { Node temp = cur.cloneNode(true); dest.appendChild(temp);/*from w w w. ja v a 2 s .c o m*/ if (newId != null && temp.getNodeType() == Node.ELEMENT_NODE) { Element t = (Element) temp; if (t.getLocalName().equals("ReferenceList")) { Element ref = getFirstChildElement(t, new QName("http://www.w3.org/2001/04/xmlenc#", "DataReference"), true); Element newRef = (Element) ref.cloneNode(true); newRef.setAttributeNS(null, "URI", "#" + newId); t.appendChild(newRef); } } return cur.getNextSibling(); }
From source file:org.apache.ws.security.message.token.BinarySecurity.java
/** * get the byte array containing token information. * // w ww. java 2 s.co m * @return the byte array containing token information */ public byte[] getToken() { Node node = element.getFirstChild(); StringBuffer buffer = new StringBuffer(); while (node != null) { if (Node.TEXT_NODE == node.getNodeType()) { buffer.append(((Text) node).getData()); } node = node.getNextSibling(); } try { return Base64.decode(buffer.toString()); } catch (Exception ex) { if (LOG.isDebugEnabled()) { LOG.debug(ex.getMessage(), ex); } return null; } }
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 ww w . j a va 2 s . c o 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.EncryptedKeyProcessor.java
public ArrayList handleEncryptedKey(Element xencEncryptedKey, CallbackHandler cb, Crypto crypto, PrivateKey privateKey) throws WSSecurityException { long t0 = 0, t1 = 0, t2 = 0; if (tlog.isDebugEnabled()) { t0 = System.currentTimeMillis(); }/*from w w w. ja v a 2s .c o m*/ // need to have it to find the encrypted data elements in the envelope Document doc = xencEncryptedKey.getOwnerDocument(); // lookup xenc:EncryptionMethod, get the Algorithm attribute to determine // how the key was encrypted. Then check if we support the algorithm Node tmpE = null; // short living Element used for lookups only tmpE = (Element) WSSecurityUtil.getDirectChild((Node) xencEncryptedKey, "EncryptionMethod", WSConstants.ENC_NS); if (tmpE != null) { this.encryptedKeyTransportMethod = ((Element) tmpE).getAttribute("Algorithm"); } if (this.encryptedKeyTransportMethod == null) { throw new WSSecurityException(WSSecurityException.UNSUPPORTED_ALGORITHM, "noEncAlgo"); } Cipher cipher = WSSecurityUtil.getCipherInstance(this.encryptedKeyTransportMethod); // // Well, we can decrypt the session (symmetric) key. Now lookup CipherValue, this is the // value of the encrypted session key (session key usually is a symmetrical key that encrypts // the referenced content). This is a 2-step lookup // Element xencCipherValue = null; tmpE = (Element) WSSecurityUtil.getDirectChild((Node) xencEncryptedKey, "CipherData", WSConstants.ENC_NS); if (tmpE != null) { xencCipherValue = (Element) WSSecurityUtil.getDirectChild(tmpE, "CipherValue", WSConstants.ENC_NS); } if (xencCipherValue == null) { throw new WSSecurityException(WSSecurityException.INVALID_SECURITY, "noCipher"); } if (privateKey == null) { Element keyInfo = (Element) WSSecurityUtil.getDirectChild((Node) xencEncryptedKey, "KeyInfo", WSConstants.SIG_NS); String alias; if (keyInfo != null) { Element secRefToken = (Element) WSSecurityUtil.getDirectChild(keyInfo, "SecurityTokenReference", WSConstants.WSSE_NS); // // EncryptedKey must a a STR as child of KeyInfo, KeyName // valid only for EncryptedData // // if (secRefToken == null) { // secRefToken = (Element) WSSecurityUtil.getDirectChild(keyInfo, // "KeyName", WSConstants.SIG_NS); // } if (secRefToken == null) { throw new WSSecurityException(WSSecurityException.INVALID_SECURITY, "noSecTokRef"); } SecurityTokenReference secRef = new SecurityTokenReference(secRefToken); // // Well, at this point there are several ways to get the key. // Try to handle all of them :-). // alias = null; // // handle X509IssuerSerial here. First check if all elements are available, // get the appropriate data, check if all data is available. // If all is ok up to that point, look up the certificate alias according // to issuer name and serial number. // This method is recommended by OASIS WS-S specification, X509 profile // if (secRef.containsX509Data() || secRef.containsX509IssuerSerial()) { alias = secRef.getX509IssuerSerialAlias(crypto); if (log.isDebugEnabled()) { log.debug("X509IssuerSerial alias: " + alias); } } // // If wsse:KeyIdentifier found, then the public key of the attached cert was used to // encrypt the session (symmetric) key that encrypts the data. Extract the certificate // using the BinarySecurity token (was enhanced to handle KeyIdentifier too). // This method is _not_ recommended by OASIS WS-S specification, X509 profile // else if (secRef.containsKeyIdentifier()) { X509Certificate[] certs = null; if (WSConstants.WSS_SAML_KI_VALUE_TYPE.equals(secRef.getKeyIdentifierValueType())) { Element token = secRef.getKeyIdentifierTokenElement(doc, docInfo, cb); if (crypto == null) { throw new WSSecurityException(WSSecurityException.FAILURE, "noSigCryptoFile"); } SAMLKeyInfo samlKi = SAMLUtil.getSAMLKeyInfo(token, crypto, cb); certs = samlKi.getCerts(); } else if (WSConstants.WSS_SAML2_KI_VALUE_TYPE.equals(secRef.getKeyIdentifierValueType())) { Element token = secRef.getKeyIdentifierTokenElement(doc, docInfo, cb); if (crypto == null) { throw new WSSecurityException(0, "noSigCryptoFile"); } SAML2KeyInfo samlKi = SAML2Util.getSAML2KeyInfo(token, crypto, cb); certs = samlKi.getCerts(); } else { certs = secRef.getKeyIdentifier(crypto); } if (certs == null || certs.length < 1 || certs[0] == null) { throw new WSSecurityException(WSSecurityException.FAILURE, "noCertsFound", new Object[] { "decryption (KeyId)" }); } // // Here we have the certificate. Now find the alias for it. Needed to identify // the private key associated with this certificate // alias = crypto.getAliasForX509Cert(certs[0]); cert = certs[0]; if (log.isDebugEnabled()) { log.debug("cert: " + certs[0]); log.debug("KeyIdentifier Alias: " + alias); } } else if (secRef.containsReference()) { Element bstElement = secRef.getTokenElement(doc, null, cb); // at this point ... check token type: Binary QName el = new QName(bstElement.getNamespaceURI(), bstElement.getLocalName()); if (el.equals(WSSecurityEngine.binaryToken)) { X509Security token = new X509Security(bstElement); String value = bstElement.getAttribute(WSSecurityEngine.VALUE_TYPE); if (!X509Security.X509_V3_TYPE.equals(value) || (token == null)) { throw new WSSecurityException(WSSecurityException.UNSUPPORTED_SECURITY_TOKEN, "unsupportedBinaryTokenType", new Object[] { "for decryption (BST)" }); } cert = token.getX509Certificate(crypto); if (cert == null) { throw new WSSecurityException(WSSecurityException.FAILURE, "noCertsFound", new Object[] { "decryption" }); } // // Here we have the certificate. Now find the alias for it. Needed to identify // the private key associated with this certificate // alias = crypto.getAliasForX509Cert(cert); if (log.isDebugEnabled()) { log.debug("BST Alias: " + alias); } } else { throw new WSSecurityException(WSSecurityException.UNSUPPORTED_SECURITY_TOKEN, "unsupportedBinaryTokenType", null); } // // The following code is somewhat strange: the called crypto method gets // the keyname and searches for a certificate with an issuer's name that is // equal to this keyname. No serialnumber is used - IMHO this does // not identifies a certificate. In addition neither the WSS4J encryption // nor signature methods use this way to identify a certificate. Because of that // the next lines of code are disabled. // // } else if (secRef.containsKeyName()) { // alias = crypto.getAliasForX509Cert(secRef.getKeyNameValue()); // if (log.isDebugEnabled()) { // log.debug("KeyName alias: " + alias); // } } else { throw new WSSecurityException(WSSecurityException.INVALID_SECURITY, "unsupportedKeyId"); } } else if (crypto.getDefaultX509Alias() != null) { alias = crypto.getDefaultX509Alias(); } else { throw new WSSecurityException(WSSecurityException.INVALID_SECURITY, "noKeyinfo"); } // // At this point we have all information necessary to decrypt the session // key: // - the Cipher object intialized with the correct methods // - The data that holds the encrypted session key // - the alias name for the private key // // Now use the callback here to get password that enables // us to read the private key // WSPasswordCallback pwCb = new WSPasswordCallback(alias, WSPasswordCallback.DECRYPT); try { Callback[] callbacks = new Callback[] { pwCb }; cb.handle(callbacks); } catch (IOException e) { throw new WSSecurityException(WSSecurityException.FAILURE, "noPassword", new Object[] { alias }, e); } catch (UnsupportedCallbackException e) { throw new WSSecurityException(WSSecurityException.FAILURE, "noPassword", new Object[] { alias }, e); } String password = pwCb.getPassword(); if (password == null) { throw new WSSecurityException(WSSecurityException.FAILURE, "noPassword", new Object[] { alias }); } try { privateKey = crypto.getPrivateKey(alias, password); } catch (Exception e) { throw new WSSecurityException(WSSecurityException.FAILED_CHECK, null, null, e); } } try { cipher.init(Cipher.DECRYPT_MODE, privateKey); } catch (Exception e1) { throw new WSSecurityException(WSSecurityException.FAILED_CHECK, null, null, e1); } try { encryptedEphemeralKey = getDecodedBase64EncodedData(xencCipherValue); decryptedBytes = cipher.doFinal(encryptedEphemeralKey); } catch (IllegalStateException e2) { throw new WSSecurityException(WSSecurityException.FAILED_CHECK, null, null, e2); } catch (Exception e2) { decryptedBytes = getRandomKey(getDataRefURIs(xencCipherValue), xencEncryptedKey.getOwnerDocument(), docInfo); } if (tlog.isDebugEnabled()) { t1 = System.currentTimeMillis(); } // At this point we have the decrypted session (symmetric) key. According // to W3C XML-Enc this key is used to decrypt _any_ references contained in // the reference list // Now lookup the references that are encrypted with this key // Element refList = (Element) WSSecurityUtil.getDirectChild((Node) xencEncryptedKey, "ReferenceList", WSConstants.ENC_NS); ArrayList dataRefs = new ArrayList(); if (refList != null) { for (tmpE = refList.getFirstChild(); tmpE != null; tmpE = tmpE.getNextSibling()) { if (tmpE.getNodeType() != Node.ELEMENT_NODE) { continue; } if (!tmpE.getNamespaceURI().equals(WSConstants.ENC_NS)) { continue; } if (tmpE.getLocalName().equals("DataReference")) { String dataRefURI = ((Element) tmpE).getAttribute("URI"); if (dataRefURI.charAt(0) == '#') { dataRefURI = dataRefURI.substring(1); } WSDataRef dataRef = decryptDataRef(doc, dataRefURI, decryptedBytes); dataRefs.add(dataRef); } } return dataRefs; } if (tlog.isDebugEnabled()) { t2 = System.currentTimeMillis(); tlog.debug( "XMLDecrypt: total= " + (t2 - t0) + ", get-sym-key= " + (t1 - t0) + ", decrypt= " + (t2 - t1)); } return null; }
From source file:org.apache.ws.security.processor.ReferenceListProcessor.java
/** * Dereferences and decodes encrypted data elements. * /*from w w w . j a v a2 s .co m*/ * @param elem contains the <code>ReferenceList</code> to the encrypted * data elements * @param cb the callback handler to get the key for a key name stored if * <code>KeyInfo</code> inside the encrypted data elements */ private ArrayList handleReferenceList(Element elem, CallbackHandler cb, Crypto crypto) throws WSSecurityException { Node tmpE = null; ArrayList dataRefUris = new ArrayList(); for (tmpE = elem.getFirstChild(); tmpE != null; tmpE = tmpE.getNextSibling()) { if (tmpE.getNodeType() != Node.ELEMENT_NODE) { continue; } if (!tmpE.getNamespaceURI().equals(WSConstants.ENC_NS)) { continue; } if (tmpE.getLocalName().equals("DataReference")) { String dataRefURI = ((Element) tmpE).getAttribute("URI"); if (dataRefURI.charAt(0) == '#') { dataRefURI = dataRefURI.substring(1); } WSDataRef dataRef = decryptDataRefEmbedded(elem.getOwnerDocument(), dataRefURI, cb, crypto); dataRefUris.add(dataRef); } } return dataRefUris; }