List of usage examples for org.w3c.dom Element isSameNode
public boolean isSameNode(Node other);
From source file:Main.java
/** * Gets the parent element.// www. j a va2 s . c om * * @param element * the element * @return the parent element */ public static Element getParentElement(Element element) { if (element == null) { return null; } Element parentElement = null; Node parentNode = element.getParentNode(); while (parentNode != null && parentElement == null) { if (parentNode.getNodeType() == Node.ELEMENT_NODE) { parentElement = (Element) parentNode; } if (parentNode.getNodeType() == Node.DOCUMENT_NODE) { parentElement = ((Document) parentNode).getDocumentElement(); if (element.isSameNode(parentElement)) { parentElement = null; } } parentNode = parentNode.getParentNode(); } return parentElement; }
From source file:org.apache.sling.its.servlets.ItsImportServlet.java
/** * Store the element and its attribute. The child node of global rules are * specially handled so they will not be traversed. * * @param path/*from www. j a v a2 s .c o m*/ * the target path * @param resourceType * the resourceType * @param doc * the document * @param file * the file. * @param isExternalDoc * true if this is for storing global rules for external documents */ private void store(String path, final String resourceType, final Document doc, final File file, final boolean isExternalDoc) { final ITraversal itsEng = applyITSRules(doc, file, null, false); itsEng.startTraversal(); Node node; while ((node = itsEng.nextNode()) != null) { switch (node.getNodeType()) { case Node.ELEMENT_NODE: final Element element = (Element) node; // Use !backTracking() to get to the elements only once // and to include the empty elements (for attributes). if (itsEng.backTracking()) { if (!SlingItsConstants.getGlobalRules().containsKey(element.getLocalName())) { path = backTrack(path); } } else { if (element.isSameNode(doc.getDocumentElement()) && !isExternalDoc) { path += "/" + element.getNodeName(); output(path, null, null); setAttributes(element, path); } else if (SlingItsConstants.getGlobalRules().containsKey(element.getLocalName())) { storeGlobalRule(element, resourceType, itsEng); } else if (!isExternalDoc && !SlingItsConstants.getGlobalRules().containsKey(element.getLocalName()) && !(element.getParentNode().getLocalName().equals(SlingItsConstants.ITS_RULES) && element.getParentNode().getPrefix() != null)) { if (element.getLocalName().equals(SlingItsConstants.ITS_RULES) && element.getPrefix() != null) { this.hasGlobalRules = true; } if (element.getPrefix() != null) { path += String.format("/%s(%d)", element.getLocalName(), getCounter(path + "/" + element.getLocalName())); element.setAttribute(SlingItsConstants.NODE_PREFIX, element.getPrefix()); } else if (element.getNodeName().equals("link") && StringUtils.endsWith(element.getAttribute("rel"), "-rules")) { path += String.format("/%s(%d)", SlingItsConstants.ITS_RULES, getCounter(path + "/" + SlingItsConstants.ITS_RULES)); final String prefix = StringUtils.substringBefore(element.getAttribute("rel"), "-rules"); element.setAttribute(SlingItsConstants.NODE_PREFIX, prefix); element.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, SlingItsConstants.XMLNS + prefix, Namespaces.ITS_NS_URI); element.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns:h", Namespaces.HTML_NS_URI); element.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns:jcr", NamespaceRegistry.NAMESPACE_JCR); this.hasGlobalRules = true; } else { path += String.format("/%s(%d)", element.getNodeName(), getCounter(path + "/" + element.getNodeName())); } output(path, null, null); setAttributes(element, path); if (!element.hasChildNodes()) // Empty elements: { path = backTrack(path); } } } break; case Node.TEXT_NODE: if (StringUtils.isNotBlank(node.getNodeValue()) && !isExternalDoc) { path += String.format("/%s(%d)", SlingItsConstants.TEXT_CONTENT_NODE, getCounter(path + "/" + SlingItsConstants.TEXT_CONTENT_NODE)); output(path, null, node.getNodeValue()); path = backTrack(path); } break; default: break; } } }
From source file:org.jaggeryjs.modules.sso.common.util.Util.java
/** * Validate the Signature's Reference URI. * * First validate the Reference URI against the parent's ID itself. Then validate that the * URI (if non-empty) resolves to the same Element node as is cached by the SignableSAMLObject. * * * @param uri the Signature Reference URI attribute value * @param signableObject the SignableSAMLObject whose signature is being validated * @throws ValidationException if the URI is invalid or doesn't resolve to the expected DOM node *//*from w w w .jav a 2 s.c om*/ private static void validateReferenceURI(String uri, SignableSAMLObject signableObject) throws ValidationException { if (DatatypeHelper.isEmpty(uri)) { return; } String uriID = uri.substring(1); Element expected = signableObject.getDOM(); if (expected == null) { log.error("SignableSAMLObject does not have a cached DOM Element."); throw new ValidationException("SignableSAMLObject does not have a cached DOM Element."); } Document doc = expected.getOwnerDocument(); Element resolved = IdResolver.getElementById(doc, uriID); if (resolved == null) { log.error("Apache xmlsec IdResolver could not resolve the Element for id reference: " + uriID); throw new ValidationException( "Apache xmlsec IdResolver could not resolve the Element for id reference: " + uriID); } if (!expected.isSameNode(resolved)) { log.error("Signature Reference URI " + uri + " did not resolve to the expected parent Element"); throw new ValidationException("Signature Reference URI did not resolve to the expected parent Element"); } }
From source file:ru.codeinside.gws.crypto.cryptopro.CryptoProvider.java
@Override public String signElement(String sourceXML, String elementName, String namespace, boolean removeIdAttribute, boolean signatureAfterElement, boolean inclusive) throws Exception { loadCertificate();/*from ww w . ja va 2s . co m*/ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setIgnoringElementContentWhitespace(true); dbf.setCoalescing(true); dbf.setNamespaceAware(true); DocumentBuilder documentBuilder = dbf.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(sourceXML)); Document doc = documentBuilder.parse(is); Element elementForSign = (Element) doc.getElementsByTagNameNS(namespace, elementName).item(0); Node parentNode = null; Element detachedElementForSign; Document detachedDocument; if (!elementForSign.isSameNode(doc.getDocumentElement())) { parentNode = elementForSign.getParentNode(); parentNode.removeChild(elementForSign); detachedDocument = documentBuilder.newDocument(); Node importedElementForSign = detachedDocument.importNode(elementForSign, true); detachedDocument.appendChild(importedElementForSign); detachedElementForSign = detachedDocument.getDocumentElement(); } else { detachedElementForSign = elementForSign; detachedDocument = doc; } String signatureMethodUri = inclusive ? "urn:ietf:params:xml:ns:cpxmlsec:algorithms:gostr34102001-gostr3411" : "http://www.w3.org/2001/04/xmldsig-more#gostr34102001-gostr3411"; String canonicalizationMethodUri = inclusive ? "http://www.w3.org/TR/2001/REC-xml-c14n-20010315" : "http://www.w3.org/2001/10/xml-exc-c14n#"; XMLSignature sig = new XMLSignature(detachedDocument, "", signatureMethodUri, canonicalizationMethodUri); if (!removeIdAttribute) { detachedElementForSign.setAttribute("Id", detachedElementForSign.getTagName()); } if (signatureAfterElement) detachedElementForSign.insertBefore(sig.getElement(), detachedElementForSign.getLastChild().getNextSibling()); else { detachedElementForSign.insertBefore(sig.getElement(), detachedElementForSign.getFirstChild()); } Transforms transforms = new Transforms(detachedDocument); transforms.addTransform("http://www.w3.org/2000/09/xmldsig#enveloped-signature"); transforms.addTransform(inclusive ? "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments" : "http://www.w3.org/2001/10/xml-exc-c14n#"); String digestURI = inclusive ? "urn:ietf:params:xml:ns:cpxmlsec:algorithms:gostr3411" : "http://www.w3.org/2001/04/xmldsig-more#gostr3411"; sig.addDocument(removeIdAttribute ? "" : "#" + detachedElementForSign.getTagName(), transforms, digestURI); sig.addKeyInfo(cert); sig.sign(privateKey); if ((!elementForSign.isSameNode(doc.getDocumentElement())) && (parentNode != null)) { Node signedNode = doc.importNode(detachedElementForSign, true); parentNode.appendChild(signedNode); } TransformerFactory tf = TransformerFactory.newInstance(); Transformer trans = tf.newTransformer(); trans.setOutputProperty("omit-xml-declaration", "yes"); StringWriter stringWriter = new StringWriter(); StreamResult streamResult = new StreamResult(stringWriter); trans.transform(new DOMSource(doc), streamResult); return stringWriter.toString(); }
From source file:ru.codeinside.gws3572c.GMPClientSignTest.java
@Test public void testSignForEntity() throws Exception { ClientRequest request = client.createClientRequest(createContext()); InputSource is = new InputSource(new StringReader(request.appData)); Document doc = documentBuilder.parse(is); Element elementForSign = (Element) doc.getElementsByTagNameNS(null, "Charge").item(0); Node parentNode;//from w ww . j a v a 2 s .c o m Document detachedDocument; if (!elementForSign.isSameNode(doc.getDocumentElement())) { parentNode = elementForSign.getParentNode(); parentNode.removeChild(elementForSign); detachedDocument = documentBuilder.newDocument(); Node importedElementForSign = detachedDocument.importNode(elementForSign, true); detachedDocument.appendChild(importedElementForSign); } else { detachedDocument = doc; } Element nscontext = detachedDocument.createElementNS(null, "namespaceContext"); nscontext.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" + "ds".trim(), "http://www.w3.org/2000/09/xmldsig#"); Element certificateElement = (Element) XPathAPI.selectSingleNode(detachedDocument, "//ds:X509Certificate[1]", nscontext); Element sigElement = (Element) certificateElement.getParentNode().getParentNode().getParentNode(); XMLSignature signature = new XMLSignature(sigElement, ""); CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate certKey = (X509Certificate) cf.generateCertificate( new ByteArrayInputStream(Base64.decode(certificateElement.getTextContent().trim().getBytes()))); Assert.assertNotNull("There are no information about public key. Verification couldn't be implemented", certKey); Assert.assertTrue("Signature is not valid", signature.checkSignatureValue(certKey)); }